-
Notifications
You must be signed in to change notification settings - Fork 346
Expand file tree
/
Copy pathcli.ts
More file actions
223 lines (207 loc) · 6.84 KB
/
Copy pathcli.ts
File metadata and controls
223 lines (207 loc) · 6.84 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
// SPDX-FileCopyrightText: 2024 LiveKit, Inc.
//
// SPDX-License-Identifier: Apache-2.0
import { Command, Option } from 'commander';
import type { EventEmitter } from 'node:events';
import { initializeLogger, log } from './log.js';
import { Plugin } from './plugin.js';
import { version } from './version.js';
import { AgentServer, ServerOptions } from './worker.js';
type CliArgs = {
opts: ServerOptions;
production: boolean;
watch: boolean;
event?: EventEmitter;
room?: string;
participantIdentity?: string;
};
const runServer = async (args: CliArgs) => {
initializeLogger({ pretty: !args.production, level: args.opts.logLevel });
const logger = log();
// though `production` is defined in ServerOptions, it will always be overridden by CLI.
const { production: _, ...opts } = args.opts; // eslint-disable-line @typescript-eslint/no-unused-vars
const server = new AgentServer(new ServerOptions({ production: args.production, ...opts }));
if (args.room) {
server.event.once('worker_registered', () => {
logger.info(`connecting to room ${args.room}`);
server.simulateJob(args.room!, args.participantIdentity);
});
}
process.once('SIGINT', async () => {
logger.debug('SIGINT received in CLI');
// allow C-c C-c for force interrupt
process.once('SIGINT', () => {
console.log('Force exit (Ctrl+C pressed twice)');
process.exit(130); // SIGINT exit code
});
if (args.production) {
try {
await server.drain();
} catch (e) {
logger.error(e);
}
}
await server.close();
logger.debug('worker closed due to SIGINT.');
process.exit(130); // SIGINT exit code
});
process.once('SIGTERM', async () => {
logger.debug('SIGTERM received in CLI.');
if (args.production) {
try {
await server.drain();
} catch (e) {
logger.error(e);
}
}
await server.close();
logger.debug('worker closed due to SIGTERM.');
process.exit(143); // SIGTERM exit code
});
try {
await server.run();
} catch {
logger.fatal('closing worker due to error.');
process.exit(1);
}
};
/**
* Exposes a CLI for creating a new worker, in development or production mode.
*
* @param opts - Options to launch the worker with
* @example
* ```
* if (process.argv[1] === fileURLToPath(import.meta.url)) {
* cli.runApp(new ServerOptions({ agent: import.meta.filename }));
* }
* ```
*/
export const runApp = (opts: ServerOptions) => {
const logLevelOption = (defaultLevel: string) =>
new Option('--log-level <level>', 'Set the logging level')
.choices(['trace', 'debug', 'info', 'warn', 'error', 'fatal'])
.default(defaultLevel)
.env('LOG_LEVEL');
const program = new Command()
.name('agents')
.description('LiveKit Agents CLI')
.version(version)
.addOption(
new Option('--url <string>', 'LiveKit server or Cloud project websocket URL').env(
'LIVEKIT_URL',
),
)
.addOption(
new Option('--api-key <string>', "LiveKit server or Cloud project's API key").env(
'LIVEKIT_API_KEY',
),
)
.addOption(
new Option('--api-secret <string>', "LiveKit server or Cloud project's API secret").env(
'LIVEKIT_API_SECRET',
),
)
.addOption(
new Option('--worker-token <string>', 'Internal use only')
.env('LIVEKIT_WORKER_TOKEN')
.hideHelp(),
)
.action(() => {
if (
// do not run CLI if origin file is agents/ipc/job_main.js
process.argv[1] !== new URL('ipc/job_main.js', import.meta.url).pathname &&
process.argv.length < 3
) {
program.help();
}
});
program
.command('start')
.description('Start the worker in production mode')
.addOption(logLevelOption('info'))
.action((...[, command]) => {
const globalOptions = program.optsWithGlobals();
const commandOptions = command.opts();
opts.wsURL = globalOptions.url || opts.wsURL;
opts.apiKey = globalOptions.apiKey || opts.apiKey;
opts.apiSecret = globalOptions.apiSecret || opts.apiSecret;
opts.logLevel = commandOptions.logLevel;
opts.workerToken = globalOptions.workerToken || opts.workerToken;
runServer({
opts,
production: true,
watch: false,
});
});
program
.command('dev')
.description('Start the worker in development mode')
.addOption(logLevelOption('debug'))
.action((...[, command]) => {
const globalOptions = program.optsWithGlobals();
const commandOptions = command.opts();
opts.wsURL = globalOptions.url || opts.wsURL;
opts.apiKey = globalOptions.apiKey || opts.apiKey;
opts.apiSecret = globalOptions.apiSecret || opts.apiSecret;
opts.logLevel = commandOptions.logLevel;
opts.workerToken = globalOptions.workerToken || opts.workerToken;
process.env.LIVEKIT_DEV_MODE = '1';
runServer({
opts,
production: false,
watch: false,
});
});
program
.command('connect')
.description('Connect to a specific room')
.requiredOption('--room <string>', 'Room name to connect to')
.option('--participant-identity <string>', 'Identity of user to listen to')
.addOption(logLevelOption('info'))
.action((...[, command]) => {
const globalOptions = program.optsWithGlobals();
const commandOptions = command.opts();
opts.wsURL = globalOptions.url || opts.wsURL;
opts.apiKey = globalOptions.apiKey || opts.apiKey;
opts.apiSecret = globalOptions.apiSecret || opts.apiSecret;
opts.logLevel = commandOptions.logLevel;
opts.workerToken = globalOptions.workerToken || opts.workerToken;
process.env.LIVEKIT_DEV_MODE = '1';
runServer({
opts,
production: false,
watch: false,
room: commandOptions.room,
participantIdentity: commandOptions.participantIdentity,
});
});
program
.command('download-files')
.description('Download plugin dependency files')
.addOption(logLevelOption('debug'))
.action((...[, command]) => {
const commandOptions = command.opts();
initializeLogger({ pretty: true, level: commandOptions.logLevel });
const logger = log();
const downloadFiles = async () => {
for (const plugin of Plugin.registeredPlugins) {
logger.info(`Downloading files for ${plugin.title}`);
try {
await plugin.downloadFiles();
logger.info(`Finished downloading files for ${plugin.title}`);
} catch (error) {
logger.error(`Failed to download files for ${plugin.title}: ${error}`);
}
}
};
downloadFiles()
.catch((error) => {
logger.fatal(`Error during file downloads: ${error}`);
process.exit(1);
})
.finally(() => {
process.exit(0);
});
});
program.parse();
};