@livekit/agents 0.1.0 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (133) hide show
  1. package/.turbo/turbo-build.log +1 -1
  2. package/CHANGELOG.md +21 -0
  3. package/LICENSE +201 -0
  4. package/dist/audio.d.ts +12 -0
  5. package/dist/audio.d.ts.map +1 -0
  6. package/dist/audio.js +37 -0
  7. package/dist/audio.js.map +1 -0
  8. package/dist/cli.d.ts +11 -0
  9. package/dist/cli.d.ts.map +1 -1
  10. package/dist/cli.js +68 -8
  11. package/dist/cli.js.map +1 -1
  12. package/dist/generator.d.ts +12 -6
  13. package/dist/generator.d.ts.map +1 -1
  14. package/dist/generator.js +9 -3
  15. package/dist/generator.js.map +1 -1
  16. package/dist/http_server.d.ts +1 -1
  17. package/dist/http_server.js +0 -3
  18. package/dist/http_server.js.map +1 -1
  19. package/dist/index.d.ts +12 -3
  20. package/dist/index.d.ts.map +1 -1
  21. package/dist/index.js +12 -3
  22. package/dist/index.js.map +1 -1
  23. package/dist/ipc/job_executor.d.ts +19 -0
  24. package/dist/ipc/job_executor.d.ts.map +1 -0
  25. package/dist/ipc/job_executor.js +8 -0
  26. package/dist/ipc/job_executor.js.map +1 -0
  27. package/dist/ipc/job_main.d.ts +7 -4
  28. package/dist/ipc/job_main.d.ts.map +1 -1
  29. package/dist/ipc/job_main.js +96 -61
  30. package/dist/ipc/job_main.js.map +1 -1
  31. package/dist/ipc/message.d.ts +41 -0
  32. package/dist/ipc/message.d.ts.map +1 -0
  33. package/dist/ipc/message.js +2 -0
  34. package/dist/ipc/message.js.map +1 -0
  35. package/dist/ipc/proc_job_executor.d.ts +15 -0
  36. package/dist/ipc/proc_job_executor.d.ts.map +1 -0
  37. package/dist/ipc/proc_job_executor.js +150 -0
  38. package/dist/ipc/proc_job_executor.js.map +1 -0
  39. package/dist/ipc/proc_pool.d.ts +26 -0
  40. package/dist/ipc/proc_pool.d.ts.map +1 -0
  41. package/dist/ipc/proc_pool.js +82 -0
  42. package/dist/ipc/proc_pool.js.map +1 -0
  43. package/dist/job.d.ts +99 -0
  44. package/dist/job.d.ts.map +1 -0
  45. package/dist/job.js +197 -0
  46. package/dist/job.js.map +1 -0
  47. package/dist/llm/function_context.d.ts +20 -0
  48. package/dist/llm/function_context.d.ts.map +1 -0
  49. package/dist/llm/function_context.js +37 -0
  50. package/dist/llm/function_context.js.map +1 -0
  51. package/dist/llm/index.d.ts +3 -0
  52. package/dist/llm/index.d.ts.map +1 -0
  53. package/dist/llm/index.js +6 -0
  54. package/dist/llm/index.js.map +1 -0
  55. package/dist/log.d.ts +12 -1
  56. package/dist/log.d.ts.map +1 -1
  57. package/dist/log.js +28 -11
  58. package/dist/log.js.map +1 -1
  59. package/dist/plugin.js +20 -7
  60. package/dist/plugin.js.map +1 -1
  61. package/dist/stt/index.d.ts +1 -1
  62. package/dist/stt/index.d.ts.map +1 -1
  63. package/dist/stt/index.js.map +1 -1
  64. package/dist/stt/stream_adapter.d.ts +2 -11
  65. package/dist/stt/stream_adapter.d.ts.map +1 -1
  66. package/dist/stt/stream_adapter.js +47 -33
  67. package/dist/stt/stream_adapter.js.map +1 -1
  68. package/dist/stt/stt.d.ts +27 -0
  69. package/dist/stt/stt.d.ts.map +1 -1
  70. package/dist/stt/stt.js +32 -5
  71. package/dist/stt/stt.js.map +1 -1
  72. package/dist/tts/stream_adapter.d.ts +4 -11
  73. package/dist/tts/stream_adapter.d.ts.map +1 -1
  74. package/dist/tts/stream_adapter.js +66 -32
  75. package/dist/tts/stream_adapter.js.map +1 -1
  76. package/dist/tts/tts.d.ts +10 -0
  77. package/dist/tts/tts.d.ts.map +1 -1
  78. package/dist/tts/tts.js +48 -7
  79. package/dist/tts/tts.js.map +1 -1
  80. package/dist/utils.d.ts +32 -0
  81. package/dist/utils.d.ts.map +1 -1
  82. package/dist/utils.js +114 -6
  83. package/dist/utils.js.map +1 -1
  84. package/dist/vad.d.ts +29 -0
  85. package/dist/vad.d.ts.map +1 -1
  86. package/dist/vad.js.map +1 -1
  87. package/dist/worker.d.ts +67 -50
  88. package/dist/worker.d.ts.map +1 -1
  89. package/dist/worker.js +379 -214
  90. package/dist/worker.js.map +1 -1
  91. package/package.json +9 -9
  92. package/src/audio.ts +62 -0
  93. package/src/cli.ts +72 -8
  94. package/src/generator.ts +13 -7
  95. package/src/index.ts +13 -3
  96. package/src/ipc/job_executor.ts +25 -0
  97. package/src/ipc/job_main.ts +134 -61
  98. package/src/ipc/message.ts +39 -0
  99. package/src/ipc/proc_job_executor.ts +162 -0
  100. package/src/ipc/proc_pool.ts +108 -0
  101. package/src/job.ts +258 -0
  102. package/src/llm/function_context.ts +61 -0
  103. package/src/llm/index.ts +11 -0
  104. package/src/log.ts +40 -8
  105. package/src/stt/index.ts +1 -1
  106. package/src/stt/stream_adapter.ts +32 -32
  107. package/src/stt/stt.ts +27 -0
  108. package/src/tts/stream_adapter.ts +32 -31
  109. package/src/tts/tts.ts +10 -0
  110. package/src/utils.ts +125 -3
  111. package/src/vad.ts +29 -0
  112. package/src/worker.ts +419 -170
  113. package/tsconfig.json +6 -0
  114. package/dist/ipc/job_process.d.ts +0 -22
  115. package/dist/ipc/job_process.d.ts.map +0 -1
  116. package/dist/ipc/job_process.js +0 -73
  117. package/dist/ipc/job_process.js.map +0 -1
  118. package/dist/ipc/protocol.d.ts +0 -40
  119. package/dist/ipc/protocol.d.ts.map +0 -1
  120. package/dist/ipc/protocol.js +0 -14
  121. package/dist/ipc/protocol.js.map +0 -1
  122. package/dist/job_context.d.ts +0 -16
  123. package/dist/job_context.d.ts.map +0 -1
  124. package/dist/job_context.js +0 -31
  125. package/dist/job_context.js.map +0 -1
  126. package/dist/job_request.d.ts +0 -42
  127. package/dist/job_request.d.ts.map +0 -1
  128. package/dist/job_request.js +0 -79
  129. package/dist/job_request.js.map +0 -1
  130. package/src/ipc/job_process.ts +0 -96
  131. package/src/ipc/protocol.ts +0 -51
  132. package/src/job_context.ts +0 -49
  133. package/src/job_request.ts +0 -118
@@ -0,0 +1,162 @@
1
+ // SPDX-FileCopyrightText: 2024 LiveKit, Inc.
2
+ //
3
+ // SPDX-License-Identifier: Apache-2.0
4
+ import type { ChildProcess } from 'child_process';
5
+ import { once } from 'events';
6
+ import type { RunningJobInfo } from '../job.js';
7
+ import { log, loggerOptions } from '../log.js';
8
+ import { Future } from '../utils.js';
9
+ import type { ProcOpts } from './job_executor.js';
10
+ import { JobExecutor } from './job_executor.js';
11
+ import type { IPCMessage } from './message.js';
12
+
13
+ export class ProcJobExecutor extends JobExecutor {
14
+ #opts: ProcOpts;
15
+ #started = false;
16
+ #closing = false;
17
+ #runningJob?: RunningJobInfo = undefined;
18
+ #proc?: ChildProcess;
19
+ #pingInterval?: ReturnType<typeof setInterval>;
20
+ #pongTimeout?: ReturnType<typeof setTimeout>;
21
+ #init = new Future();
22
+ #join = new Future();
23
+ #logger = log().child({ runningJob: this.#runningJob });
24
+
25
+ constructor(agent: string, initializeTimeout: number, closeTimeout: number) {
26
+ super();
27
+ this.#opts = {
28
+ agent,
29
+ initializeTimeout,
30
+ closeTimeout,
31
+ };
32
+ }
33
+
34
+ get started(): boolean {
35
+ return this.#started;
36
+ }
37
+
38
+ get runningJob(): RunningJobInfo | undefined {
39
+ return this.#runningJob;
40
+ }
41
+
42
+ async start() {
43
+ if (this.#started) {
44
+ throw new Error('runner already started');
45
+ } else if (this.#closing) {
46
+ throw new Error('runner is closed');
47
+ }
48
+
49
+ this.#proc = await import('./job_main.js').then((m) =>
50
+ m.runProcess({
51
+ agentFile: this.#opts.agent,
52
+ }),
53
+ );
54
+
55
+ this.#started = true;
56
+ this.run();
57
+ }
58
+
59
+ async run() {
60
+ await this.#init.await;
61
+
62
+ this.#pingInterval = setInterval(() => {
63
+ this.#proc!.send({ case: 'pingRequest', value: { timestamp: Date.now() } });
64
+ }, this.PING_INTERVAL);
65
+
66
+ this.#pongTimeout = setTimeout(() => {
67
+ this.#logger.warn('job is unresponsive');
68
+ clearTimeout(this.#pongTimeout);
69
+ clearInterval(this.#pingInterval);
70
+ this.#proc!.kill();
71
+ this.#join.resolve();
72
+ }, this.PING_TIMEOUT);
73
+
74
+ const listener = (msg: IPCMessage) => {
75
+ switch (msg.case) {
76
+ case 'pongResponse': {
77
+ const delay = Date.now() - msg.value.timestamp;
78
+ if (delay > this.HIGH_PING_THRESHOLD) {
79
+ this.#logger.child({ delay }).warn('job executor is unresponsive');
80
+ }
81
+ this.#pongTimeout?.refresh();
82
+ break;
83
+ }
84
+ case 'exiting': {
85
+ this.#logger.child({ reason: msg.value.reason }).debug('job exiting');
86
+ break;
87
+ }
88
+ case 'done': {
89
+ this.#closing = true;
90
+ this.#proc!.off('message', listener);
91
+ this.#join.resolve();
92
+ break;
93
+ }
94
+ }
95
+ };
96
+ this.#proc!.on('message', listener);
97
+ this.#proc!.on('error', (err) => {
98
+ if (this.#closing) return;
99
+ this.#logger.child({ err }).warn('job process exited unexpectedly');
100
+ clearTimeout(this.#pongTimeout);
101
+ clearInterval(this.#pingInterval);
102
+ this.#join.resolve();
103
+ });
104
+
105
+ await this.#join.await;
106
+ }
107
+
108
+ async join() {
109
+ if (!this.#started) {
110
+ throw new Error('runner not started');
111
+ }
112
+
113
+ await this.#join.await;
114
+ }
115
+
116
+ async initialize() {
117
+ const timer = setTimeout(() => {
118
+ const err = new Error('runner initialization timed out');
119
+ this.#init.reject(err);
120
+ throw err;
121
+ }, this.#opts.initializeTimeout);
122
+ this.#proc!.send({ case: 'initializeRequest', value: { loggerOptions } });
123
+ await once(this.#proc!, 'message').then(([msg]: IPCMessage[]) => {
124
+ clearTimeout(timer);
125
+ if (msg.case !== 'initializeResponse') {
126
+ throw new Error('first message must be InitializeResponse');
127
+ }
128
+ });
129
+ this.#init.resolve();
130
+ }
131
+
132
+ async close() {
133
+ if (!this.#started) {
134
+ return;
135
+ }
136
+ this.#closing = true;
137
+
138
+ if (!this.#runningJob) {
139
+ this.#proc!.kill();
140
+ this.#join.resolve();
141
+ }
142
+
143
+ this.#proc!.send({ case: 'shutdownRequest' });
144
+
145
+ const timer = setTimeout(() => {
146
+ this.#logger.error('job shutdown is taking too much time');
147
+ }, this.#opts.closeTimeout);
148
+ await this.#join.await.then(() => {
149
+ clearTimeout(timer);
150
+ clearTimeout(this.#pongTimeout);
151
+ clearInterval(this.#pingInterval);
152
+ });
153
+ }
154
+
155
+ async launchJob(info: RunningJobInfo) {
156
+ if (this.#runningJob) {
157
+ throw new Error('executor already has a running job');
158
+ }
159
+ this.#runningJob = info;
160
+ this.#proc!.send({ case: 'startJobRequest', value: { runningJob: info } });
161
+ }
162
+ }
@@ -0,0 +1,108 @@
1
+ // SPDX-FileCopyrightText: 2024 LiveKit, Inc.
2
+ //
3
+ // SPDX-License-Identifier: Apache-2.0
4
+ import type { RunningJobInfo } from '../job.js';
5
+ import { Mutex, Queue } from '../utils.js';
6
+ import type { JobExecutor } from './job_executor.js';
7
+ import { ProcJobExecutor } from './proc_job_executor.js';
8
+
9
+ export class ProcPool {
10
+ agent: string;
11
+ initializeTimeout: number;
12
+ closeTimeout: number;
13
+ executors: JobExecutor[] = [];
14
+ tasks: Promise<void>[] = [];
15
+ started = false;
16
+ closed = false;
17
+ controller = new AbortController();
18
+ initMutex = new Mutex();
19
+ procMutex: Mutex;
20
+ procUnlock?: () => void;
21
+ warmedProcQueue = new Queue<JobExecutor>();
22
+
23
+ constructor(
24
+ agent: string,
25
+ numIdleProcesses: number,
26
+ initializeTimeout: number,
27
+ closeTimeout: number,
28
+ ) {
29
+ this.agent = agent;
30
+ this.procMutex = new Mutex(numIdleProcesses);
31
+ this.initializeTimeout = initializeTimeout;
32
+ this.closeTimeout = closeTimeout;
33
+ }
34
+
35
+ get processes(): JobExecutor[] {
36
+ return this.executors;
37
+ }
38
+
39
+ getByJobId(id: string): JobExecutor | null {
40
+ return this.executors.find((x) => x.runningJob && x.runningJob.job.id === id) || null;
41
+ }
42
+
43
+ async launchJob(info: RunningJobInfo) {
44
+ const proc = await this.warmedProcQueue.get();
45
+ if (this.procUnlock) {
46
+ this.procUnlock();
47
+ this.procUnlock = undefined;
48
+ }
49
+ await proc.launchJob(info);
50
+ }
51
+
52
+ async procWatchTask() {
53
+ const proc = new ProcJobExecutor(this.agent, this.initializeTimeout, this.closeTimeout);
54
+
55
+ try {
56
+ this.executors.push(proc);
57
+
58
+ const unlock = await this.initMutex.lock();
59
+ if (this.closed) {
60
+ return;
61
+ }
62
+
63
+ await proc.start();
64
+ try {
65
+ await proc.initialize();
66
+ await this.warmedProcQueue.put(proc);
67
+ } catch {
68
+ if (this.procUnlock) {
69
+ this.procUnlock();
70
+ this.procUnlock = undefined;
71
+ }
72
+ }
73
+
74
+ unlock();
75
+ await proc.join();
76
+ } finally {
77
+ this.executors.splice(this.executors.indexOf(proc));
78
+ }
79
+ }
80
+
81
+ start() {
82
+ if (this.started) {
83
+ return;
84
+ }
85
+
86
+ this.started = true;
87
+ this.run(this.controller.signal);
88
+ }
89
+
90
+ async run(signal: AbortSignal) {
91
+ while (!signal.aborted) {
92
+ this.procUnlock = await this.procMutex.lock();
93
+ const task = this.procWatchTask();
94
+ this.tasks.push(task);
95
+ task.finally(() => this.tasks.splice(this.tasks.indexOf(task)));
96
+ }
97
+ }
98
+
99
+ async close() {
100
+ if (!this.started) {
101
+ return;
102
+ }
103
+ this.closed = true;
104
+ this.controller.abort();
105
+ this.executors.forEach((e) => e.close());
106
+ await Promise.allSettled(this.tasks);
107
+ }
108
+ }
package/src/job.ts ADDED
@@ -0,0 +1,258 @@
1
+ // SPDX-FileCopyrightText: 2024 LiveKit, Inc.
2
+ //
3
+ // SPDX-License-Identifier: Apache-2.0
4
+ import type * as proto from '@livekit/protocol';
5
+ import type {
6
+ E2EEOptions,
7
+ LocalParticipant,
8
+ RemoteParticipant,
9
+ Room,
10
+ RtcConfiguration,
11
+ } from '@livekit/rtc-node';
12
+ import { RoomEvent, TrackKind } from '@livekit/rtc-node';
13
+ import type { Logger } from 'pino';
14
+ import { log } from './log.js';
15
+
16
+ /** Which tracks, if any, should the agent automatically subscribe to? */
17
+ export enum AutoSubscribe {
18
+ SUBSCRIBE_ALL,
19
+ SUBSCRIBE_NONE,
20
+ VIDEO_ONLY,
21
+ AUDIO_ONLY,
22
+ }
23
+
24
+ export type JobAcceptArguments = {
25
+ name: string;
26
+ identity: string;
27
+ metadata: string;
28
+ };
29
+
30
+ export type RunningJobInfo = {
31
+ acceptArguments: JobAcceptArguments;
32
+ job: proto.Job;
33
+ url: string;
34
+ token: string;
35
+ };
36
+
37
+ /** Attempted to add a function callback, but the function already exists. */
38
+ export class FunctionExistsError extends Error {
39
+ constructor(msg?: string) {
40
+ super(msg);
41
+ Object.setPrototypeOf(this, new.target.prototype);
42
+ }
43
+ }
44
+
45
+ /** The job and environment context as seen by the agent, accessible by the entrypoint function. */
46
+ export class JobContext {
47
+ #proc: JobProcess;
48
+ #info: RunningJobInfo;
49
+ #room: Room;
50
+ #onConnect: () => void;
51
+ #onShutdown: (s: string) => void;
52
+ /** @internal */
53
+ shutdownCallbacks: (() => Promise<void>)[] = [];
54
+ #participantEntrypoints: ((job: JobContext, p: RemoteParticipant) => Promise<void>)[] = [];
55
+ #participantTasks: {
56
+ [id: string]: {
57
+ callback: (job: JobContext, p: RemoteParticipant) => Promise<void>;
58
+ result: Promise<void>;
59
+ };
60
+ } = {};
61
+ #logger: Logger;
62
+
63
+ constructor(
64
+ proc: JobProcess,
65
+ info: RunningJobInfo,
66
+ room: Room,
67
+ onConnect: () => void,
68
+ onShutdown: (s: string) => void,
69
+ ) {
70
+ this.#proc = proc;
71
+ this.#info = info;
72
+ this.#room = room;
73
+ this.#onConnect = onConnect;
74
+ this.#onShutdown = onShutdown;
75
+ this.onParticipantConnected = this.onParticipantConnected.bind(this);
76
+ this.#room.on(RoomEvent.ParticipantConnected, this.onParticipantConnected);
77
+ this.#logger = log().child({ info: this.#info });
78
+ }
79
+
80
+ get proc(): JobProcess {
81
+ return this.#proc;
82
+ }
83
+
84
+ get job(): proto.Job {
85
+ return this.#info.job;
86
+ }
87
+
88
+ /** @returns The room the agent was called into */
89
+ get room(): Room {
90
+ return this.#room;
91
+ }
92
+
93
+ /** @returns The agent's participant if connected to the room, otherwise `undefined` */
94
+ get agent(): LocalParticipant | undefined {
95
+ return this.#room.localParticipant;
96
+ }
97
+
98
+ /** Adds a promise to be awaited when {@link JobContext.shutdown | shutdown} is called. */
99
+ addShutdownCallback(callback: () => Promise<void>) {
100
+ this.shutdownCallbacks.push(callback);
101
+ }
102
+
103
+ /**
104
+ * Connects the agent to the room.
105
+ *
106
+ * @remarks
107
+ * It is recommended to run this command as early in the function as possible, as executing it
108
+ * later may cause noticeable delay between user and agent joins.
109
+ *
110
+ * @see {@link https://github.com/livekit/node-sdks/tree/main/packages/livekit-rtc#readme |
111
+ * @livekit/rtc-node} for more information about the parameters.
112
+ */
113
+ async connect(
114
+ e2ee?: E2EEOptions,
115
+ autoSubscribe: AutoSubscribe = AutoSubscribe.SUBSCRIBE_ALL,
116
+ rtcConfig?: RtcConfiguration,
117
+ ) {
118
+ const opts = {
119
+ e2ee,
120
+ autoSubscribe: autoSubscribe == AutoSubscribe.SUBSCRIBE_ALL,
121
+ rtcConfig,
122
+ dynacast: false,
123
+ };
124
+
125
+ await this.#room.connect(this.#info.url, this.#info.token, opts);
126
+ this.#onConnect();
127
+
128
+ this.#room.remoteParticipants.forEach(this.onParticipantConnected);
129
+
130
+ if ([AutoSubscribe.AUDIO_ONLY, AutoSubscribe.VIDEO_ONLY].includes(autoSubscribe)) {
131
+ this.#room.remoteParticipants.forEach((p) => {
132
+ p.trackPublications.forEach((pub) => {
133
+ if (
134
+ (autoSubscribe === AutoSubscribe.AUDIO_ONLY && pub.kind === TrackKind.KIND_AUDIO) ||
135
+ (autoSubscribe === AutoSubscribe.VIDEO_ONLY && pub.kind === TrackKind.KIND_VIDEO)
136
+ ) {
137
+ pub.setSubscribed(true);
138
+ }
139
+ });
140
+ });
141
+ }
142
+ }
143
+
144
+ /**
145
+ * Gracefully shuts down the job, and runs all shutdown promises.
146
+ *
147
+ * @param reason - Optional reason for shutdown
148
+ */
149
+ shutdown(reason = '') {
150
+ this.#onShutdown(reason);
151
+ }
152
+
153
+ /** @internal */
154
+ onParticipantConnected(p: RemoteParticipant) {
155
+ for (const callback of this.#participantEntrypoints) {
156
+ if (
157
+ p.identity in this.#participantTasks &&
158
+ this.#participantTasks[p.identity].callback == callback
159
+ ) {
160
+ this.#logger.warn(
161
+ 'a participant has joined before a prior prticipant task matching the same identity has finished:',
162
+ p.identity,
163
+ );
164
+ }
165
+ const result = callback(this, p);
166
+ result.finally(() => delete this.#participantTasks[p.identity]);
167
+ this.#participantTasks[p.identity] = { callback, result };
168
+ }
169
+ }
170
+
171
+ /**
172
+ * Adds a promise to be awaited whenever a new participant joins the room.
173
+ *
174
+ * @throws {@link FunctionExistsError} if an entrypoint already exists
175
+ */
176
+ addParticipantEntrypoint(callback: (job: JobContext, p: RemoteParticipant) => Promise<void>) {
177
+ if (this.#participantEntrypoints.includes(callback)) {
178
+ throw new FunctionExistsError('entrypoints cannot be added more than once');
179
+ }
180
+
181
+ this.#participantEntrypoints.push(callback);
182
+ }
183
+ }
184
+
185
+ export class JobProcess {
186
+ #pid = process.pid;
187
+ #userData: { [id: string]: unknown } = {};
188
+
189
+ get pid(): number {
190
+ return this.#pid;
191
+ }
192
+
193
+ get userData(): { [id: string]: unknown } {
194
+ return this.#userData;
195
+ }
196
+ }
197
+
198
+ /**
199
+ * A request sent by the server to spawn a new agent job.
200
+ *
201
+ * @remarks
202
+ * For most applications, this is best left to the default, which simply accepts the job and
203
+ * handles the logic inside the entrypoint function. This class is useful for vetting which
204
+ * requests should fill idle processes and which should be outright rejected.
205
+ */
206
+ export class JobRequest {
207
+ #job: proto.Job;
208
+ #onReject: () => Promise<void>;
209
+ #onAccept: (args: JobAcceptArguments) => Promise<void>;
210
+
211
+ /** @internal */
212
+ constructor(
213
+ job: proto.Job,
214
+ onReject: () => Promise<void>,
215
+ onAccept: (args: JobAcceptArguments) => Promise<void>,
216
+ ) {
217
+ this.#job = job;
218
+ this.#onReject = onReject;
219
+ this.#onAccept = onAccept;
220
+ }
221
+
222
+ /** @returns The ID of the job, set by the LiveKit server */
223
+ get id(): string {
224
+ return this.#job.id;
225
+ }
226
+
227
+ /** @see {@link https://www.npmjs.com/package/@livekit/protocol | @livekit/protocol} */
228
+ get job(): proto.Job {
229
+ return this.#job;
230
+ }
231
+
232
+ /** @see {@link https://www.npmjs.com/package/@livekit/protocol | @livekit/protocol} */
233
+ get room(): proto.Room | undefined {
234
+ return this.#job.room;
235
+ }
236
+
237
+ /** @see {@link https://www.npmjs.com/package/@livekit/protocol | @livekit/protocol} */
238
+ get publisher(): proto.ParticipantInfo | undefined {
239
+ return this.#job.participant;
240
+ }
241
+
242
+ /** @returns The agent's name, as set in {@link WorkerOptions} */
243
+ get agentName(): string {
244
+ return this.#job.agentName;
245
+ }
246
+
247
+ /** Rejects the job. */
248
+ async reject() {
249
+ await this.#onReject();
250
+ }
251
+
252
+ /** Accepts the job, launching it on an idle child process. */
253
+ async accept(name = '', identity = '', metadata = '') {
254
+ if (identity === '') identity = 'agent-' + this.id;
255
+
256
+ this.#onAccept({ name, identity, metadata });
257
+ }
258
+ }
@@ -0,0 +1,61 @@
1
+ // SPDX-FileCopyrightText: 2024 LiveKit, Inc.
2
+ //
3
+ // SPDX-License-Identifier: Apache-2.0
4
+ import { z } from 'zod';
5
+
6
+ // heavily inspired by Vercel AI's `tool()`:
7
+ // https://github.com/vercel/ai/blob/3b0983b/packages/ai/core/tool/tool.ts
8
+
9
+ /* eslint-disable @typescript-eslint/no-explicit-any */
10
+
11
+ /** Type reinforcement for the callable function's execute parameters. */
12
+ export type inferParameters<P extends z.ZodTypeAny> = z.infer<P>;
13
+
14
+ /** A definition for a function callable by the LLM. */
15
+ export interface CallableFunction<P extends z.ZodTypeAny = any, R = any> {
16
+ description: string;
17
+ parameters: P;
18
+ execute: (args: inferParameters<P>) => PromiseLike<R>;
19
+ }
20
+
21
+ /** An object containing callable functions and their names */
22
+ export type FunctionContext = {
23
+ [name: string]: CallableFunction;
24
+ };
25
+
26
+ /** @internal */
27
+ export const oaiParams = (p: z.AnyZodObject) => {
28
+ const properties: Record<string, any> = {};
29
+ const required_properties: string[] = [];
30
+
31
+ for (const key in p.shape) {
32
+ const field = p.shape[key];
33
+ const description = field._def.description || undefined;
34
+ let type: string;
35
+ let enumValues: any[] | undefined;
36
+
37
+ if (field instanceof z.ZodEnum) {
38
+ enumValues = field._def.values;
39
+ type = typeof enumValues![0];
40
+ } else {
41
+ type = field._def.typeName.toLowerCase();
42
+ }
43
+
44
+ properties[key] = {
45
+ type: type.includes('zod') ? type.substring(3) : type,
46
+ description,
47
+ enum: enumValues,
48
+ };
49
+
50
+ if (!field._def.defaultValue) {
51
+ required_properties.push(key);
52
+ }
53
+ }
54
+
55
+ const type = 'object' as const;
56
+ return {
57
+ type,
58
+ properties,
59
+ required_properties,
60
+ };
61
+ };
@@ -0,0 +1,11 @@
1
+ // SPDX-FileCopyrightText: 2024 LiveKit, Inc.
2
+ //
3
+ // SPDX-License-Identifier: Apache-2.0
4
+ import {
5
+ type CallableFunction,
6
+ type FunctionContext,
7
+ type inferParameters,
8
+ oaiParams,
9
+ } from './function_context.js';
10
+
11
+ export { CallableFunction, FunctionContext, inferParameters, oaiParams };
package/src/log.ts CHANGED
@@ -1,13 +1,45 @@
1
1
  // SPDX-FileCopyrightText: 2024 LiveKit, Inc.
2
2
  //
3
3
  // SPDX-License-Identifier: Apache-2.0
4
+ import type { Logger } from 'pino';
4
5
  import { pino } from 'pino';
5
6
 
6
- export const log = pino({
7
- transport: {
8
- target: 'pino-pretty',
9
- options: {
10
- colorize: true,
11
- },
12
- },
13
- });
7
+ /** @internal */
8
+ export type LoggerOptions = {
9
+ pretty: boolean;
10
+ level?: string;
11
+ };
12
+
13
+ /** @internal */
14
+ export let loggerOptions: LoggerOptions;
15
+
16
+ /** @internal */
17
+ let logger: Logger | undefined = undefined;
18
+
19
+ /** @internal */
20
+ export const log = () => {
21
+ if (!logger) {
22
+ throw new TypeError('logger not initialized. did you forget to run initializeLogger()?');
23
+ }
24
+ return logger;
25
+ };
26
+
27
+ /** @internal */
28
+ export const initializeLogger = ({ pretty, level }: LoggerOptions) => {
29
+ loggerOptions = { pretty, level };
30
+ logger = pino(
31
+ pretty
32
+ ? {
33
+ transport: {
34
+ target: 'pino-pretty',
35
+ options: {
36
+ colorize: true,
37
+ },
38
+ },
39
+ }
40
+ : {},
41
+ );
42
+ if (level) {
43
+ logger.level = level;
44
+ }
45
+ };
package/src/stt/index.ts CHANGED
@@ -2,5 +2,5 @@
2
2
  //
3
3
  // SPDX-License-Identifier: Apache-2.0
4
4
 
5
- export { STT, SpeechEvent, SpeechEventType, SpeechStream } from './stt.js';
5
+ export { STT, SpeechEvent, SpeechEventType, SpeechStream, type SpeechData } from './stt.js';
6
6
  export { StreamAdapter, StreamAdapterWrapper } from './stream_adapter.js';