@koreaaitel/sdk 0.0.0-stage → 0.62.2

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 (49) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +943 -2
  3. package/dist/agent/index.cjs +5512 -0
  4. package/dist/agent/index.cjs.map +1 -0
  5. package/dist/agent/index.d.cts +1574 -0
  6. package/dist/agent/index.d.ts +1574 -0
  7. package/dist/agent/index.js +5402 -0
  8. package/dist/agent/index.js.map +1 -0
  9. package/dist/agent/livekit/index.cjs +675 -0
  10. package/dist/agent/livekit/index.cjs.map +1 -0
  11. package/dist/agent/livekit/index.d.cts +165 -0
  12. package/dist/agent/livekit/index.d.ts +165 -0
  13. package/dist/agent/livekit/index.js +669 -0
  14. package/dist/agent/livekit/index.js.map +1 -0
  15. package/dist/chunk-35XJNMFU.js +10 -0
  16. package/dist/chunk-35XJNMFU.js.map +1 -0
  17. package/dist/chunk-B3QB5WPI.cjs +202 -0
  18. package/dist/chunk-B3QB5WPI.cjs.map +1 -0
  19. package/dist/chunk-I7N2GTBL.js +6 -0
  20. package/dist/chunk-I7N2GTBL.js.map +1 -0
  21. package/dist/chunk-LLPMUDNE.cjs +16 -0
  22. package/dist/chunk-LLPMUDNE.cjs.map +1 -0
  23. package/dist/chunk-PDE4I4MV.cjs +1134 -0
  24. package/dist/chunk-PDE4I4MV.cjs.map +1 -0
  25. package/dist/chunk-T4ZQXFTN.js +181 -0
  26. package/dist/chunk-T4ZQXFTN.js.map +1 -0
  27. package/dist/chunk-TCIIGMEU.cjs +8 -0
  28. package/dist/chunk-TCIIGMEU.cjs.map +1 -0
  29. package/dist/chunk-ZFBHUDJB.js +1103 -0
  30. package/dist/chunk-ZFBHUDJB.js.map +1 -0
  31. package/dist/client-CrTIZPmY.d.cts +3074 -0
  32. package/dist/client-DJApW4Uf.d.ts +3074 -0
  33. package/dist/error-D1uHhe6r.d.cts +205 -0
  34. package/dist/error-D1uHhe6r.d.ts +205 -0
  35. package/dist/index.cjs +1741 -0
  36. package/dist/index.cjs.map +1 -0
  37. package/dist/index.d.cts +22 -0
  38. package/dist/index.d.ts +22 -0
  39. package/dist/index.js +1638 -0
  40. package/dist/index.js.map +1 -0
  41. package/dist/media-profile-DZCqLJKa.d.cts +492 -0
  42. package/dist/media-profile-DZCqLJKa.d.ts +492 -0
  43. package/dist/solapi/index.cjs +684 -0
  44. package/dist/solapi/index.cjs.map +1 -0
  45. package/dist/solapi/index.d.cts +282 -0
  46. package/dist/solapi/index.d.ts +282 -0
  47. package/dist/solapi/index.js +673 -0
  48. package/dist/solapi/index.js.map +1 -0
  49. package/package.json +121 -4
@@ -0,0 +1,675 @@
1
+ 'use strict';
2
+
3
+ var chunkPDE4I4MV_cjs = require('../../chunk-PDE4I4MV.cjs');
4
+ require('../../chunk-TCIIGMEU.cjs');
5
+
6
+ // src/agent/livekit/io.ts
7
+ var SAMPLE_RATE = 8e3;
8
+ var FRAME_BYTES = 160;
9
+ var MARK_TIMEOUT_MARGIN_MS = 1e4;
10
+ var Deferred = class {
11
+ promise;
12
+ _resolve;
13
+ _done = false;
14
+ constructor() {
15
+ this.promise = new Promise((resolve) => {
16
+ this._resolve = resolve;
17
+ });
18
+ }
19
+ get done() {
20
+ return this._done;
21
+ }
22
+ resolve(value) {
23
+ if (this._done) return;
24
+ this._done = true;
25
+ this._resolve(value);
26
+ }
27
+ };
28
+ var _cached = null;
29
+ async function loadClawOpsIO() {
30
+ if (_cached) return _cached;
31
+ const [agents, rtc] = await Promise.all([
32
+ import('@livekit/agents'),
33
+ import('@livekit/rtc-node')
34
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
35
+ ]);
36
+ if (typeof agents.initializeLogger === "function" && (typeof agents.loggerOptions !== "function" || !agents.loggerOptions())) {
37
+ agents.initializeLogger({ pretty: false, level: process.env["LIVEKIT_LOG_LEVEL"] ?? "info" });
38
+ }
39
+ const AudioOutputBase = agents.voice.AudioOutput;
40
+ const AudioFrame = rtc.AudioFrame;
41
+ class ClawOpsAudioInput {
42
+ constructor(profile = "mulaw_8000" /* MULAW_8000 */) {
43
+ this.profile = profile;
44
+ this._profile = chunkPDE4I4MV_cjs.mediaContract(profile);
45
+ this._stream = new ReadableStream({
46
+ start: (c) => {
47
+ this._controller = c;
48
+ },
49
+ cancel: () => {
50
+ this._closed = true;
51
+ }
52
+ });
53
+ }
54
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
55
+ _controller = null;
56
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
57
+ _stream;
58
+ _closed = false;
59
+ _profile;
60
+ get stream() {
61
+ return this._stream;
62
+ }
63
+ /** G.711 μ-law 청크를 PCM16 프레임으로 바꿔 스트림에 밀어넣는다. */
64
+ pushUlaw(ulaw) {
65
+ if (this.profile !== "mulaw_8000" /* MULAW_8000 */) throw new Error("pushUlaw requires mulaw_8000");
66
+ this.pushAudio(ulaw);
67
+ }
68
+ pushAudio(audio) {
69
+ if (this._closed || !this._controller || audio.length === 0) return;
70
+ if (this.profile === "pcm_s16le_16000" /* PCM_S16LE_16000 */ && audio.length % 2) throw new Error("Incomplete PCM16 sample");
71
+ const ulaw = audio;
72
+ const samples = new Int16Array(this.profile === "mulaw_8000" /* MULAW_8000 */ ? ulaw.length : ulaw.length / 2);
73
+ for (let i = 0; i < samples.length; i++) {
74
+ samples[i] = this.profile === "mulaw_8000" /* MULAW_8000 */ ? chunkPDE4I4MV_cjs.DECODE_TABLE[ulaw[i]] : ulaw.readInt16LE(i * 2);
75
+ }
76
+ const frame = new AudioFrame(samples, this._profile.sampleRate, 1, samples.length);
77
+ try {
78
+ this._controller.enqueue(frame);
79
+ } catch {
80
+ }
81
+ }
82
+ /** 스트림 종료 — 리더가 완료를 본다. */
83
+ endInput() {
84
+ this._closeStream();
85
+ }
86
+ async close() {
87
+ this._closeStream();
88
+ }
89
+ onAttached() {
90
+ }
91
+ onDetached() {
92
+ }
93
+ _closeStream() {
94
+ if (this._closed) return;
95
+ this._closed = true;
96
+ try {
97
+ this._controller?.close();
98
+ } catch {
99
+ }
100
+ }
101
+ }
102
+ class ClawOpsAudioOutput extends AudioOutputBase {
103
+ constructor(call, profile = "mulaw_8000" /* MULAW_8000 */) {
104
+ super(chunkPDE4I4MV_cjs.mediaContract(profile).sampleRate, void 0, { pause: false });
105
+ this.profile = profile;
106
+ this._profile = chunkPDE4I4MV_cjs.mediaContract(profile);
107
+ this._call = call;
108
+ }
109
+ _call;
110
+ _pushedDurationMs = 0;
111
+ _captureStartedAt = 0;
112
+ _tail = Buffer.alloc(0);
113
+ _flushPromise = null;
114
+ _flushInProgress = false;
115
+ _interrupted = new Deferred();
116
+ _attached = new Deferred();
117
+ _markSeq = 0;
118
+ _closed = false;
119
+ _profile;
120
+ /**
121
+ * attach() 시 실제 CallSession 으로 교체한다 (prewarm -> 실제 통화).
122
+ *
123
+ * prewarm 중 버퍼링된 오디오는 지금부터 실제 재생되므로 경과 기준점을 여기로 옮긴다 —
124
+ * 안 그러면 링 구간까지 "재생됐다"고 계산돼 barge-in 절단 위치가 뒤로 밀린다.
125
+ */
126
+ setCall(call) {
127
+ this._call = call;
128
+ if (this._pushedDurationMs > 0) {
129
+ this._captureStartedAt = Date.now();
130
+ }
131
+ this._attached.resolve();
132
+ }
133
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
134
+ async captureFrame(frame) {
135
+ if (this._closed) return;
136
+ if (this.profile === "pcm_s16le_16000" /* PCM_S16LE_16000 */ && (frame.sampleRate !== 16e3 || frame.channels !== 1 || frame.data.length !== frame.samplesPerChannel)) {
137
+ throw new Error("Audio frame does not match selected PCM16 profile");
138
+ }
139
+ await super.captureFrame(frame);
140
+ if (this._flushInProgress && this._flushPromise) {
141
+ await this._flushPromise;
142
+ }
143
+ if (this._pushedDurationMs === 0) {
144
+ this._captureStartedAt = Date.now();
145
+ this.onPlaybackStarted(Date.now());
146
+ }
147
+ this._pushedDurationMs += frame.samplesPerChannel / frame.sampleRate * 1e3;
148
+ const pcm = Buffer.from(frame.data.buffer, frame.data.byteOffset, frame.data.byteLength);
149
+ const encoded = this.profile === "mulaw_8000" /* MULAW_8000 */ ? chunkPDE4I4MV_cjs.pcm16ToUlaw(pcm) : Buffer.alloc(frame.data.length * 2);
150
+ if (this.profile === "pcm_s16le_16000" /* PCM_S16LE_16000 */) {
151
+ for (let i = 0; i < frame.data.length; i++) encoded.writeInt16LE(frame.data[i], i * 2);
152
+ }
153
+ const ulaw = this._tail.length === 0 ? encoded : Buffer.concat([this._tail, encoded]);
154
+ let off = 0;
155
+ while (off + this._profile.frameBytes <= ulaw.length) {
156
+ await this._call.sendAudio(ulaw.subarray(off, off + this._profile.frameBytes));
157
+ off += this._profile.frameBytes;
158
+ }
159
+ this._tail = Buffer.from(ulaw.subarray(off));
160
+ }
161
+ flush() {
162
+ super.flush();
163
+ if (this._pushedDurationMs > 0) {
164
+ this._interrupted = new Deferred();
165
+ this._flushInProgress = true;
166
+ this._flushPromise = this._runPlayoutHandshake().finally(() => {
167
+ this._flushInProgress = false;
168
+ });
169
+ } else {
170
+ this._tail = Buffer.alloc(0);
171
+ }
172
+ }
173
+ clearBuffer() {
174
+ this._tail = Buffer.alloc(0);
175
+ if (this._pushedDurationMs > 0) {
176
+ this._interrupted.resolve();
177
+ }
178
+ this._call.clearAudio();
179
+ }
180
+ /** 세션 종료 시 남은 대기를 깨워 정리한다. */
181
+ close() {
182
+ this._closed = true;
183
+ this._interrupted.resolve();
184
+ this._attached.resolve();
185
+ }
186
+ // ── 내부 ───────────────────────────────────────────────────
187
+ /** 실 통화이고 transport 가 살아 있으면 mark 훅을 가진 CallSession 을 돌려준다. */
188
+ _mediaCall() {
189
+ const c = this._call;
190
+ if (typeof c._sendMark !== "function" || typeof c._waitForMark !== "function" || typeof c._flushTransport !== "function") {
191
+ return null;
192
+ }
193
+ if (typeof c._isTransportConnected === "function" && !c._isTransportConnected()) {
194
+ return null;
195
+ }
196
+ return this._call;
197
+ }
198
+ /** `p` 와 barge-in 중 먼저 오는 걸 기다린다. 반환: p 가 이겼는가(=중단 아님). */
199
+ async _race(p) {
200
+ const winner = await Promise.race([
201
+ p.then(() => "main"),
202
+ this._interrupted.promise.then(() => "interrupt")
203
+ ]);
204
+ return winner === "main";
205
+ }
206
+ async _runPlayoutHandshake() {
207
+ let interrupted = true;
208
+ try {
209
+ const tail = this._tail;
210
+ this._tail = Buffer.alloc(0);
211
+ if (tail.length > 0) {
212
+ const padded = Buffer.concat([
213
+ tail,
214
+ Buffer.alloc(this._profile.frameBytes - tail.length, this._profile.silenceByte)
215
+ ]);
216
+ await this._call.sendAudio(padded);
217
+ }
218
+ interrupted = await this._awaitPlayout();
219
+ } catch {
220
+ interrupted = true;
221
+ } finally {
222
+ const played = interrupted ? Math.min(Math.max(0, Date.now() - this._captureStartedAt), this._pushedDurationMs) : this._pushedDurationMs;
223
+ this.onPlaybackFinished({ playbackPosition: played / 1e3, interrupted });
224
+ this._pushedDurationMs = 0;
225
+ this._interrupted = new Deferred();
226
+ }
227
+ }
228
+ /** 재생이 끝나거나 barge-in 될 때까지 대기. 반환: interrupted 여부. */
229
+ async _awaitPlayout() {
230
+ let media = this._mediaCall();
231
+ if (!media) {
232
+ if (!await this._race(this._attached.promise)) {
233
+ return true;
234
+ }
235
+ media = this._mediaCall();
236
+ if (!media) {
237
+ return this._interrupted.done;
238
+ }
239
+ }
240
+ await media._flushTransport();
241
+ const markName = `lk-${this._markSeq++}`;
242
+ media._sendMark(markName);
243
+ const timeout = Math.round(this._pushedDurationMs) + MARK_TIMEOUT_MARGIN_MS;
244
+ return !await this._race(media._waitForMark(markName, timeout));
245
+ }
246
+ }
247
+ _cached = { ClawOpsAudioInput, ClawOpsAudioOutput };
248
+ return _cached;
249
+ }
250
+
251
+ // src/agent/transfer-tool.ts
252
+ var RESUME = " The caller is on the line with you again. Tell them and continue the conversation.";
253
+ var FAILED_MESSAGES = {
254
+ "no-answer": `The transfer target did not answer.${RESUME}`,
255
+ busy: `The transfer target was busy.${RESUME}`
256
+ };
257
+ var RESULT_UNKNOWN = JSON.stringify({
258
+ status: "unknown",
259
+ message: "The transfer result is unavailable. If the caller speaks, continue the conversation."
260
+ });
261
+ function transferResultForModel(result) {
262
+ const status = result["status"] || "failed";
263
+ let message;
264
+ if (status === "completed") {
265
+ message = "The transfer target finished the call and the caller is on the line with you again. Ask whether they need anything else.";
266
+ } else if (status === "canceled") {
267
+ message = "The caller hung up. The call is over.";
268
+ } else {
269
+ message = FAILED_MESSAGES[status] ?? `The transfer could not be connected.${RESUME}`;
270
+ }
271
+ return JSON.stringify({ status, message });
272
+ }
273
+ var CALL_OVER = transferResultForModel({ status: "canceled" });
274
+ async function waitForTransferResult(transfer, connectionLost) {
275
+ if (!connectionLost) return transferResultForModel(await transfer);
276
+ const lost = connectionLost.then(() => new Promise((resolve) => setTimeout(resolve, 0))).then(() => null);
277
+ const result = await Promise.race([transfer, lost]);
278
+ return result === null ? RESULT_UNKNOWN : transferResultForModel(result);
279
+ }
280
+
281
+ // src/agent/livekit/toolset.ts
282
+ var IGNORE_ON_ENTER_TOOLS = /* @__PURE__ */ new Set(["hang_up", "transfer_call"]);
283
+ var HANG_UP_PLAYOUT_CAP_MS = 15e3;
284
+ var HANG_UP_FAREWELL_PROMPT = "The call is ending. The caller hears only what you say next, so never describe ending, closing or hanging up the call. If you already said goodbye to the caller, reply with an empty message. Otherwise say one short goodbye sentence in the same language as this conversation. Do not ask anything and do not call any tools.";
285
+ var HANG_UP_REPLY_CREATED_TIMEOUT_MS = 5e3;
286
+ async function waitUntil(promise, deadline) {
287
+ let timer;
288
+ try {
289
+ await Promise.race([
290
+ promise.catch(() => void 0),
291
+ new Promise((resolve) => {
292
+ timer = setTimeout(resolve, Math.max(0, deadline - Date.now()));
293
+ })
294
+ ]);
295
+ } finally {
296
+ if (timer) clearTimeout(timer);
297
+ }
298
+ }
299
+ function spokeSince(speech, start) {
300
+ for (const item of (speech?.chatItems ?? []).slice(start)) {
301
+ if (item?.type === "message" && item?.role === "assistant" && (item.textContent ?? "").trim()) {
302
+ return true;
303
+ }
304
+ }
305
+ return false;
306
+ }
307
+ function turnDone(speech) {
308
+ return new Promise((resolve) => speech.addDoneCallback(() => resolve()));
309
+ }
310
+ function repliesInNewSpeech(llm, ctx) {
311
+ let model;
312
+ try {
313
+ model = ctx?.session?.currentAgent?.getActivityOrThrow?.()?.llm;
314
+ } catch {
315
+ model = void 0;
316
+ }
317
+ model ??= ctx?.session?.llm;
318
+ return typeof llm.RealtimeModel === "function" && model instanceof llm.RealtimeModel && // eslint-disable-next-line @typescript-eslint/no-explicit-any
319
+ model.capabilities?.autoToolReplyGeneration === true;
320
+ }
321
+ function nextSpeechDone(session, limit, deadline) {
322
+ let onCreated;
323
+ const created = new Promise((resolve) => {
324
+ onCreated = (ev) => resolve(ev?.speechHandle);
325
+ session.on?.("speech_created", onCreated);
326
+ });
327
+ let timer;
328
+ const timeout = new Promise((resolve) => {
329
+ timer = setTimeout(() => resolve(void 0), Math.max(0, limit - Date.now()));
330
+ });
331
+ return Promise.race([created, timeout]).then((handle) => handle ? waitUntil(turnDone(handle), deadline) : void 0).finally(() => {
332
+ if (timer) clearTimeout(timer);
333
+ session.off?.("speech_created", onCreated);
334
+ });
335
+ }
336
+ async function transferAndWait(args, call, ctx) {
337
+ const speech = ctx?.speechHandle;
338
+ const allowedBefore = speech?.allowInterruptions;
339
+ if (speech) ctx.disallowInterruptions?.();
340
+ try {
341
+ const transfer = call.transfer(args["to"], chunkPDE4I4MV_cjs.transferOptionsFromArgs(args));
342
+ const lost = call._transferConnectionLost?.();
343
+ try {
344
+ return await waitForTransferResult(transfer, lost?.promise);
345
+ } finally {
346
+ lost?.cancel();
347
+ }
348
+ } catch (e) {
349
+ return `Error: ${e instanceof Error ? e.message : String(e)}`;
350
+ } finally {
351
+ if (allowedBefore) speech.allowInterruptions = true;
352
+ }
353
+ }
354
+ function createClawOpsPhoneTools(llm, options) {
355
+ const state = {
356
+ call: null,
357
+ hungUp: false,
358
+ deferred: null
359
+ };
360
+ const requireCall = () => {
361
+ if (!state.call) {
362
+ throw new Error("\uD1B5\uD654\uAC00 \uC544\uC9C1 \uC5F0\uACB0\uB418\uC9C0 \uC54A\uC558\uC2B5\uB2C8\uB2E4");
363
+ }
364
+ return state.call;
365
+ };
366
+ const hangUpOnce = async (call) => {
367
+ if (state.hungUp) return;
368
+ state.hungUp = true;
369
+ await call.hangup();
370
+ };
371
+ const hangUp = async (call, ctx) => {
372
+ if (ctx) {
373
+ const deadline = Date.now() + HANG_UP_PLAYOUT_CAP_MS;
374
+ const speech = ctx.speechHandle;
375
+ const itemsBefore = (speech?.chatItems ?? []).length;
376
+ try {
377
+ ctx.disallowInterruptions?.();
378
+ } catch {
379
+ return "\uD1B5\uD654\uB97C \uB04A\uC9C0 \uC54A\uC558\uC2B5\uB2C8\uB2E4. \uBC1C\uC2E0\uC790\uAC00 \uB9D0\uC744 \uC774\uC5C8\uC2B5\uB2C8\uB2E4.";
380
+ }
381
+ if (typeof ctx.waitForPlayout === "function") {
382
+ await waitUntil(Promise.resolve().then(() => ctx.waitForPlayout()), deadline);
383
+ }
384
+ if (state.deferred === null && typeof speech?.addDoneCallback === "function" && Date.now() < deadline && !spokeSince(speech, itemsBefore)) {
385
+ const farewell = repliesInNewSpeech(llm, ctx) ? nextSpeechDone(
386
+ ctx.session,
387
+ Math.min(deadline, Date.now() + HANG_UP_REPLY_CREATED_TIMEOUT_MS),
388
+ deadline
389
+ ) : waitUntil(turnDone(speech), deadline);
390
+ state.deferred = farewell.then(() => hangUpOnce(call)).catch(() => void 0);
391
+ return HANG_UP_FAREWELL_PROMPT;
392
+ }
393
+ }
394
+ await hangUpOnce(call);
395
+ return void 0;
396
+ };
397
+ const exclude = options.excludeNames ?? /* @__PURE__ */ new Set();
398
+ const ignoreFlag = llm.ToolFlag?.IGNORE_ON_ENTER;
399
+ const schemas = chunkPDE4I4MV_cjs.getBuiltinToolSchemas(options.enabled, "chat");
400
+ const tools = [];
401
+ for (const schema of schemas) {
402
+ const { name, description, parameters } = schema.function;
403
+ if (exclude.has(name)) continue;
404
+ tools.push(
405
+ llm.tool({
406
+ name,
407
+ description,
408
+ parameters,
409
+ // raw JSON schema (agents-js 가 JSONSchema7 을 그대로 받는다).
410
+ flags: IGNORE_ON_ENTER_TOOLS.has(name) ? ignoreFlag : void 0,
411
+ // raw schema tool 의 execute 는 파싱된 args 를 그대로 받는다.
412
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
413
+ execute: async (args, opts) => {
414
+ if (name === "transfer_call" && args?.["after_transfer"] === "return") {
415
+ const result = await transferAndWait(args, requireCall(), opts?.ctx);
416
+ if (result === CALL_OVER && typeof options.StopResponse === "function") {
417
+ throw new options.StopResponse();
418
+ }
419
+ return result;
420
+ }
421
+ if (name === "hang_up") {
422
+ return hangUp(requireCall(), opts?.ctx);
423
+ }
424
+ return await chunkPDE4I4MV_cjs.executeBuiltinTool(name, args ?? {}, requireCall()) ?? "";
425
+ }
426
+ })
427
+ );
428
+ }
429
+ const toolset = llm.Toolset.create({ id: "clawops_phone", tools });
430
+ return {
431
+ toolset,
432
+ setCall: (call) => {
433
+ if (state.call !== call) {
434
+ state.hungUp = false;
435
+ state.deferred = null;
436
+ }
437
+ state.call = call;
438
+ }
439
+ };
440
+ }
441
+
442
+ // src/agent/livekit/session.ts
443
+ var LiveKitSession = class {
444
+ constructor(create, options = {}) {
445
+ this.options = options;
446
+ chunkPDE4I4MV_cjs.mediaContract(options.mediaProfile ?? "mulaw_8000" /* MULAW_8000 */);
447
+ this._create = create;
448
+ }
449
+ _create;
450
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
451
+ _session = null;
452
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
453
+ _agent = null;
454
+ _input = null;
455
+ _output = null;
456
+ _phone = null;
457
+ _target = null;
458
+ /** 유저 원본 도구 스냅샷 (우리 도구 추가 전). attach 재적용 시 누적 방지. */
459
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
460
+ _userToolCtx = null;
461
+ _toolRegistry = null;
462
+ _builtinTools = null;
463
+ _log = chunkPDE4I4MV_cjs.NOOP_LOGGER;
464
+ // 동적 로드한 agents-js 네임스페이스 (boot 시 캐시).
465
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
466
+ _llm = null;
467
+ _StopResponse = void 0;
468
+ // ── ClawOpsAgent 가 duck-typing 으로 주입하는 setter ──────────
469
+ setToolRegistry(registry) {
470
+ this._toolRegistry = registry;
471
+ }
472
+ setBuiltinTools(tools) {
473
+ this._builtinTools = tools;
474
+ }
475
+ setLogger(logger) {
476
+ this._log = logger;
477
+ }
478
+ getTelemetry() {
479
+ return null;
480
+ }
481
+ // ── Session 계약 ────────────────────────────────────────────
482
+ async start(callSession, tools) {
483
+ if (tools) this._toolRegistry = tools;
484
+ await this._boot(callSession);
485
+ }
486
+ async prewarm(tools) {
487
+ if (tools) this._toolRegistry = tools;
488
+ await this._boot(null);
489
+ }
490
+ async attach(callSession) {
491
+ if (!this._session || !this._output || !this._agent) {
492
+ await this._boot(callSession);
493
+ return;
494
+ }
495
+ const prev = this._target;
496
+ this._output.setCall(callSession);
497
+ this._target = callSession;
498
+ await this._applyTools(callSession);
499
+ chunkPDE4I4MV_cjs.attachBuffered(prev, callSession);
500
+ }
501
+ feedAudio(audio, _timestamp) {
502
+ this._input?.pushAudio(audio);
503
+ }
504
+ async feedDtmf(digits) {
505
+ if (!this._session) return;
506
+ try {
507
+ this._session.generateReply({ userInput: `[\uC804\uD654 \uD0A4\uD328\uB4DC \uC785\uB825] ${digits}` });
508
+ } catch (err) {
509
+ this._log.debug({ err }, "feedDtmf skipped (session not running)");
510
+ }
511
+ }
512
+ async stop() {
513
+ this._input?.endInput();
514
+ await this._closeAgentSession();
515
+ }
516
+ // ── 내부 ────────────────────────────────────────────────────
517
+ async _boot(call) {
518
+ await this._closeAgentSession();
519
+ const [agents, io] = await Promise.all([
520
+ import('@livekit/agents'),
521
+ loadClawOpsIO()
522
+ ]);
523
+ this._llm = agents.llm;
524
+ this._StopResponse = agents.voice?.StopResponse;
525
+ const { ClawOpsAudioInput, ClawOpsAudioOutput } = io;
526
+ const target = call ?? new chunkPDE4I4MV_cjs.BufferingCall();
527
+ const [session, agent] = await this._create(call);
528
+ this._validate(session, agent);
529
+ const input = new ClawOpsAudioInput(this.options.mediaProfile);
530
+ const output = new ClawOpsAudioOutput(target, this.options.mediaProfile);
531
+ this._input = input;
532
+ this._output = output;
533
+ session.input.audio = input;
534
+ session.output.audio = output;
535
+ session.output.transcription = null;
536
+ this._wireTranscripts(session);
537
+ this._agent = agent;
538
+ this._userToolCtx = agent.toolCtx;
539
+ await this._applyTools(call);
540
+ await session.start({ agent });
541
+ this._session = session;
542
+ this._target = target;
543
+ }
544
+ /**
545
+ * 유저 도구 + 브리지된 registry 도구 + 내장 전화 도구를 이름 충돌 없이 붙인다.
546
+ *
547
+ * 아웃바운드 prewarm(_boot(null))은 setter 실행 전에 돌아 registry/builtin 이 비어
548
+ * 있고, 그 사이엔 통화가 연결되지 않아 도구를 쓸 일도 없다. 그래서 이때는 유저 도구만
549
+ * 올리고, attach() 가 setter 실행 후 실제 도구를 붙이는 유일한 조립 지점이 된다.
550
+ */
551
+ async _applyTools(call) {
552
+ if (!this._agent) return;
553
+ const agent = this._agent;
554
+ const llm = this._llm;
555
+ if (call === null) {
556
+ await agent.updateTools(this._userToolCtx);
557
+ return;
558
+ }
559
+ const taken = new Set(llm.sortedToolNames(this._userToolCtx));
560
+ const bridged = this._bridgeRegistry(this._toolRegistry, taken);
561
+ const enabled = this._builtinTools ?? /* @__PURE__ */ new Set();
562
+ this._phone = createClawOpsPhoneTools(llm, {
563
+ enabled,
564
+ excludeNames: taken,
565
+ StopResponse: this._StopResponse
566
+ });
567
+ this._phone.setCall(call);
568
+ const userTools = llm.sortedToolEntries(this._userToolCtx).map(
569
+ (entry) => entry[1]
570
+ );
571
+ await agent.updateTools([...userTools, ...bridged, this._phone.toolset]);
572
+ }
573
+ /** `@tool` / MCP 도구(ToolRegistry)를 LiveKit function tool 로 노출한다. */
574
+ _bridgeRegistry(registry, taken) {
575
+ if (!registry) return [];
576
+ const llm = this._llm;
577
+ const out = [];
578
+ for (const def of registry.toOpenAITools()) {
579
+ const name = def.function.name;
580
+ if (taken.has(name)) continue;
581
+ taken.add(name);
582
+ out.push(
583
+ llm.tool({
584
+ name,
585
+ description: def.function.description,
586
+ parameters: def.function.parameters,
587
+ execute: async (args) => {
588
+ const result = await registry.call(name, args ?? {});
589
+ return typeof result === "string" ? result : JSON.stringify(result);
590
+ }
591
+ })
592
+ );
593
+ }
594
+ return out;
595
+ }
596
+ /**
597
+ * LiveKit 의 최종 대화 항목을 ClawOps `transcript` 훅으로 흘려보낸다.
598
+ *
599
+ * 네이티브 세션(OpenAI/Gemini/Pipeline)은 `call._emit('transcript', role, text)` 를
600
+ * 부른다. `@on('transcript')` 로 트랜스크립트를 모으는 기존 앱이 세션만 바꿔도 그대로
601
+ * 돌게 하려면 여기서 같은 계약을 재현한다.
602
+ *
603
+ * `conversation_item_added` 는 user·assistant 최종 메시지가 히스토리에 커밋될 때 한
604
+ * 번씩 뜬다 — 부분(interim) 중복 없이 최종만 얻는다. item 이 handoff 등 ChatMessage 가
605
+ * 아니면 role/textContent 가 없어 자연히 걸러진다.
606
+ */
607
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
608
+ _wireTranscripts(session) {
609
+ session.on("conversation_item_added", (ev) => {
610
+ const item = ev?.item;
611
+ const role = item?.role;
612
+ if (role !== "user" && role !== "assistant") return;
613
+ const text = item?.textContent;
614
+ if (!text) return;
615
+ const target = this._target;
616
+ target?._emit?.("transcript", role, text);
617
+ });
618
+ }
619
+ async _closeAgentSession() {
620
+ if (this._output) {
621
+ this._output.close();
622
+ this._output = null;
623
+ }
624
+ if (this._session) {
625
+ const s = this._session;
626
+ this._session = null;
627
+ try {
628
+ if (typeof s.aclose === "function") {
629
+ await s.aclose();
630
+ } else if (typeof s.close === "function") {
631
+ await s.close();
632
+ }
633
+ } catch (err) {
634
+ this._log.warn({ err }, "AgentSession close failed");
635
+ }
636
+ }
637
+ }
638
+ /**
639
+ * LiveKit 이 조용히 넘어가는 두 조합을 우리가 막는다 — 실수하면 "말을 못 하는
640
+ * 에이전트"가 아무 예외 없이 배포된다.
641
+ */
642
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
643
+ _validate(session, agent) {
644
+ let audioOutput;
645
+ let tts;
646
+ try {
647
+ const llm = agent?.llm ?? session?.llm;
648
+ tts = agent?.tts ?? session?.tts;
649
+ audioOutput = llm?.capabilities?.audioOutput;
650
+ } catch {
651
+ return;
652
+ }
653
+ if (audioOutput === void 0 || audioOutput === null) {
654
+ return;
655
+ }
656
+ if (audioOutput === false && (tts === void 0 || tts === null)) {
657
+ throw new Error(
658
+ "RealtimeModel \uC774 modalities=['text'] \uC778\uB370 tts \uAC00 \uC5C6\uC2B5\uB2C8\uB2E4 \u2014 \uC5D0\uC774\uC804\uD2B8\uAC00 \uC18C\uB9AC\uB97C \uB0B4\uC9C0 \uBABB\uD569\uB2C8\uB2E4. AgentSession(tts=...) \uB97C \uC8FC\uAC70\uB098 modalities \uC5D0 'audio' \uB97C \uB123\uC73C\uC138\uC694."
659
+ );
660
+ }
661
+ if (audioOutput === true && tts !== void 0 && tts !== null) {
662
+ this._log.warn(
663
+ "RealtimeModel \uC774 \uC624\uB514\uC624\uB97C \uC9C1\uC811 \uCD9C\uB825\uD558\uBBC0\uB85C tts \uAC00 \uBB34\uC2DC\uB429\uB2C8\uB2E4. TTS \uB97C \uC4F0\uB824\uBA74 RealtimeModel(modalities=['text']) \uB85C \uC124\uC815\uD558\uC138\uC694."
664
+ );
665
+ }
666
+ }
667
+ };
668
+
669
+ exports.FRAME_BYTES = FRAME_BYTES;
670
+ exports.LiveKitSession = LiveKitSession;
671
+ exports.SAMPLE_RATE = SAMPLE_RATE;
672
+ exports.createClawOpsPhoneTools = createClawOpsPhoneTools;
673
+ exports.loadClawOpsIO = loadClawOpsIO;
674
+ //# sourceMappingURL=index.cjs.map
675
+ //# sourceMappingURL=index.cjs.map