@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,1134 @@
1
+ 'use strict';
2
+
3
+ var chunkTCIIGMEU_cjs = require('./chunk-TCIIGMEU.cjs');
4
+ var pino = require('pino');
5
+ var os = require('os');
6
+
7
+ function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }
8
+
9
+ var pino__default = /*#__PURE__*/_interopDefault(pino);
10
+ var os__default = /*#__PURE__*/_interopDefault(os);
11
+
12
+ // src/agent/audio.ts
13
+ var _BIAS = 132;
14
+ var _CLIP = 32635;
15
+ var DECODE_TABLE = [
16
+ -32124,
17
+ -31100,
18
+ -30076,
19
+ -29052,
20
+ -28028,
21
+ -27004,
22
+ -25980,
23
+ -24956,
24
+ -23932,
25
+ -22908,
26
+ -21884,
27
+ -20860,
28
+ -19836,
29
+ -18812,
30
+ -17788,
31
+ -16764,
32
+ -15996,
33
+ -15484,
34
+ -14972,
35
+ -14460,
36
+ -13948,
37
+ -13436,
38
+ -12924,
39
+ -12412,
40
+ -11900,
41
+ -11388,
42
+ -10876,
43
+ -10364,
44
+ -9852,
45
+ -9340,
46
+ -8828,
47
+ -8316,
48
+ -7932,
49
+ -7676,
50
+ -7420,
51
+ -7164,
52
+ -6908,
53
+ -6652,
54
+ -6396,
55
+ -6140,
56
+ -5884,
57
+ -5628,
58
+ -5372,
59
+ -5116,
60
+ -4860,
61
+ -4604,
62
+ -4348,
63
+ -4092,
64
+ -3900,
65
+ -3772,
66
+ -3644,
67
+ -3516,
68
+ -3388,
69
+ -3260,
70
+ -3132,
71
+ -3004,
72
+ -2876,
73
+ -2748,
74
+ -2620,
75
+ -2492,
76
+ -2364,
77
+ -2236,
78
+ -2108,
79
+ -1980,
80
+ -1884,
81
+ -1820,
82
+ -1756,
83
+ -1692,
84
+ -1628,
85
+ -1564,
86
+ -1500,
87
+ -1436,
88
+ -1372,
89
+ -1308,
90
+ -1244,
91
+ -1180,
92
+ -1116,
93
+ -1052,
94
+ -988,
95
+ -924,
96
+ -876,
97
+ -844,
98
+ -812,
99
+ -780,
100
+ -748,
101
+ -716,
102
+ -684,
103
+ -652,
104
+ -620,
105
+ -588,
106
+ -556,
107
+ -524,
108
+ -492,
109
+ -460,
110
+ -428,
111
+ -396,
112
+ -372,
113
+ -356,
114
+ -340,
115
+ -324,
116
+ -308,
117
+ -292,
118
+ -276,
119
+ -260,
120
+ -244,
121
+ -228,
122
+ -212,
123
+ -196,
124
+ -180,
125
+ -164,
126
+ -148,
127
+ -132,
128
+ -120,
129
+ -112,
130
+ -104,
131
+ -96,
132
+ -88,
133
+ -80,
134
+ -72,
135
+ -64,
136
+ -56,
137
+ -48,
138
+ -40,
139
+ -32,
140
+ -24,
141
+ -16,
142
+ -8,
143
+ 0,
144
+ 32124,
145
+ 31100,
146
+ 30076,
147
+ 29052,
148
+ 28028,
149
+ 27004,
150
+ 25980,
151
+ 24956,
152
+ 23932,
153
+ 22908,
154
+ 21884,
155
+ 20860,
156
+ 19836,
157
+ 18812,
158
+ 17788,
159
+ 16764,
160
+ 15996,
161
+ 15484,
162
+ 14972,
163
+ 14460,
164
+ 13948,
165
+ 13436,
166
+ 12924,
167
+ 12412,
168
+ 11900,
169
+ 11388,
170
+ 10876,
171
+ 10364,
172
+ 9852,
173
+ 9340,
174
+ 8828,
175
+ 8316,
176
+ 7932,
177
+ 7676,
178
+ 7420,
179
+ 7164,
180
+ 6908,
181
+ 6652,
182
+ 6396,
183
+ 6140,
184
+ 5884,
185
+ 5628,
186
+ 5372,
187
+ 5116,
188
+ 4860,
189
+ 4604,
190
+ 4348,
191
+ 4092,
192
+ 3900,
193
+ 3772,
194
+ 3644,
195
+ 3516,
196
+ 3388,
197
+ 3260,
198
+ 3132,
199
+ 3004,
200
+ 2876,
201
+ 2748,
202
+ 2620,
203
+ 2492,
204
+ 2364,
205
+ 2236,
206
+ 2108,
207
+ 1980,
208
+ 1884,
209
+ 1820,
210
+ 1756,
211
+ 1692,
212
+ 1628,
213
+ 1564,
214
+ 1500,
215
+ 1436,
216
+ 1372,
217
+ 1308,
218
+ 1244,
219
+ 1180,
220
+ 1116,
221
+ 1052,
222
+ 988,
223
+ 924,
224
+ 876,
225
+ 844,
226
+ 812,
227
+ 780,
228
+ 748,
229
+ 716,
230
+ 684,
231
+ 652,
232
+ 620,
233
+ 588,
234
+ 556,
235
+ 524,
236
+ 492,
237
+ 460,
238
+ 428,
239
+ 396,
240
+ 372,
241
+ 356,
242
+ 340,
243
+ 324,
244
+ 308,
245
+ 292,
246
+ 276,
247
+ 260,
248
+ 244,
249
+ 228,
250
+ 212,
251
+ 196,
252
+ 180,
253
+ 164,
254
+ 148,
255
+ 132,
256
+ 120,
257
+ 112,
258
+ 104,
259
+ 96,
260
+ 88,
261
+ 80,
262
+ 72,
263
+ 64,
264
+ 56,
265
+ 48,
266
+ 40,
267
+ 32,
268
+ 24,
269
+ 16,
270
+ 8,
271
+ 0
272
+ ];
273
+ function encodeUlawSample(sample) {
274
+ let sign = 0;
275
+ if (sample < 0) {
276
+ sign = 128;
277
+ sample = -sample;
278
+ }
279
+ if (sample > _CLIP) {
280
+ sample = _CLIP;
281
+ }
282
+ sample += _BIAS;
283
+ let exponent = 7;
284
+ const expValues = [16384, 8192, 4096, 2048, 1024, 512, 256];
285
+ for (const expVal of expValues) {
286
+ if (sample >= expVal) {
287
+ break;
288
+ }
289
+ exponent -= 1;
290
+ }
291
+ const mantissa = sample >> exponent + 3 & 15;
292
+ return ~(sign | exponent << 4 | mantissa) & 255;
293
+ }
294
+ function pcm16ToUlaw(pcm) {
295
+ if (!pcm.length) return Buffer.alloc(0);
296
+ const nSamples = pcm.length >> 1;
297
+ const out = Buffer.alloc(nSamples);
298
+ for (let i = 0; i < nSamples; i++) {
299
+ const sample = pcm.readInt16LE(i * 2);
300
+ out[i] = encodeUlawSample(sample);
301
+ }
302
+ return out;
303
+ }
304
+ function ulawToPcm16(ulaw) {
305
+ if (!ulaw.length) return Buffer.alloc(0);
306
+ const out = Buffer.alloc(ulaw.length * 2);
307
+ for (let i = 0; i < ulaw.length; i++) {
308
+ out.writeInt16LE(DECODE_TABLE[ulaw[i]], i * 2);
309
+ }
310
+ return out;
311
+ }
312
+ function applyPcm16Gain(pcm, gain) {
313
+ if (!pcm.length) return Buffer.alloc(0);
314
+ if (gain === 1) return pcm;
315
+ if (!Number.isFinite(gain) || gain < 0) {
316
+ throw new Error("gain must be a finite number >= 0");
317
+ }
318
+ const nSamples = pcm.length >> 1;
319
+ const out = Buffer.alloc(nSamples * 2);
320
+ for (let i = 0; i < nSamples; i++) {
321
+ let value = Math.round(pcm.readInt16LE(i * 2) * gain);
322
+ if (value > 32767) value = 32767;
323
+ else if (value < -32768) value = -32768;
324
+ out.writeInt16LE(value, i * 2);
325
+ }
326
+ return out;
327
+ }
328
+ function applyUlawGain(ulaw, gain) {
329
+ if (!ulaw.length) return Buffer.alloc(0);
330
+ if (gain === 1) return ulaw;
331
+ return pcm16ToUlaw(applyPcm16Gain(ulawToPcm16(ulaw), gain));
332
+ }
333
+ function resamplePcm16(pcm, fromRate, toRate) {
334
+ if (fromRate === toRate || !pcm.length) return pcm;
335
+ const nSamples = pcm.length >> 1;
336
+ const ratio = fromRate / toRate;
337
+ const outLen = Math.floor(nSamples / ratio);
338
+ const out = Buffer.alloc(outLen * 2);
339
+ for (let i = 0; i < outLen; i++) {
340
+ const srcPos = i * ratio;
341
+ const idx = Math.floor(srcPos);
342
+ const frac = srcPos - idx;
343
+ let val;
344
+ if (idx + 1 < nSamples) {
345
+ val = pcm.readInt16LE(idx * 2) * (1 - frac) + pcm.readInt16LE((idx + 1) * 2) * frac;
346
+ } else {
347
+ val = pcm.readInt16LE(idx * 2);
348
+ }
349
+ out.writeInt16LE(Math.round(val), i * 2);
350
+ }
351
+ return out;
352
+ }
353
+ var DEFAULT_LOGGER = pino__default.default({ name: "clawops.agent" });
354
+ var NOOP_LOGGER = pino__default.default({ level: "silent" });
355
+ function createAgentLogger(userLogger) {
356
+ return userLogger ?? DEFAULT_LOGGER;
357
+ }
358
+ function createPipelineLogger(parent) {
359
+ return parent.child({ module: "pipeline" });
360
+ }
361
+
362
+ // src/agent/media-profile.ts
363
+ var MediaProfile = /* @__PURE__ */ ((MediaProfile2) => {
364
+ MediaProfile2["MULAW_8000"] = "mulaw_8000";
365
+ MediaProfile2["PCM_S16LE_16000"] = "pcm_s16le_16000";
366
+ return MediaProfile2;
367
+ })(MediaProfile || {});
368
+ var PROFILES = Object.freeze({
369
+ ["mulaw_8000" /* MULAW_8000 */]: Object.freeze({ sampleRate: 8e3, frameBytes: 160, silenceByte: 255, encoding: "audio/x-mulaw" }),
370
+ ["pcm_s16le_16000" /* PCM_S16LE_16000 */]: Object.freeze({ sampleRate: 16e3, frameBytes: 640, silenceByte: 0, encoding: "audio/pcm;encoding=signed-integer;bits=16;endianness=little" })
371
+ });
372
+ function mediaContract(profile) {
373
+ const contract = PROFILES[profile];
374
+ if (!Object.prototype.hasOwnProperty.call(PROFILES, profile)) throw new Error("Unsupported media profile");
375
+ return contract;
376
+ }
377
+ function validateMediaFormat(profile, format) {
378
+ const expected = mediaContract(profile);
379
+ if ((format["encoding"] ?? "audio/x-mulaw") !== expected.encoding || (format["sampleRate"] ?? 8e3) !== expected.sampleRate || (format["channels"] ?? 1) !== 1) {
380
+ throw new Error("Media format does not match selected profile");
381
+ }
382
+ }
383
+ var MAX_ERRORS = 20;
384
+ var MAX_ERROR_MESSAGE_LENGTH = 200;
385
+ var SDK_CAPABILITIES = ["retire"];
386
+ function getSdkInfo() {
387
+ return {
388
+ name: "clawops-node",
389
+ version: chunkTCIIGMEU_cjs.VERSION,
390
+ runtime: `node/${process.versions.node}`,
391
+ os: `${process.platform}/${os__default.default.arch()}`,
392
+ capabilities: [...SDK_CAPABILITIES]
393
+ };
394
+ }
395
+ function createCallMetrics() {
396
+ return {
397
+ firstResponseMs: null,
398
+ turnCount: 0,
399
+ toolCallCount: 0,
400
+ toolErrorCount: 0,
401
+ bargeInCount: 0,
402
+ endReason: null,
403
+ errors: []
404
+ };
405
+ }
406
+ function addMetricError(metrics, err) {
407
+ metrics.toolErrorCount++;
408
+ if (metrics.errors.length < MAX_ERRORS) {
409
+ metrics.errors.push({
410
+ type: err.name || "Error",
411
+ message: (err.message || "").slice(0, MAX_ERROR_MESSAGE_LENGTH)
412
+ });
413
+ }
414
+ }
415
+
416
+ // src/agent/session.ts
417
+ var DtmfCollectorBusyError = class extends Error {
418
+ constructor(message = "\uC774\uBBF8 DTMF \uC218\uC9D1 \uC911\uC785\uB2C8\uB2E4") {
419
+ super(message);
420
+ this.name = "DtmfCollectorBusyError";
421
+ }
422
+ };
423
+ function buildTransferPayload(to, options) {
424
+ const callerIdMode = options?.callerIdMode;
425
+ if (callerIdMode !== void 0 && callerIdMode !== "account" && callerIdMode !== "original") {
426
+ throw new Error(`callerIdMode must be 'account' or 'original', got ${JSON.stringify(callerIdMode)}`);
427
+ }
428
+ return {
429
+ to,
430
+ destinationType: options?.destinationType ?? "pstn",
431
+ mode: options?.mode ?? "blind",
432
+ afterTransfer: options?.afterTransfer ?? "terminate",
433
+ holdMedia: options?.holdMedia ?? "ringback",
434
+ whisper: options?.whisper ?? null,
435
+ context: options?.context ?? null,
436
+ callerId: options?.callerId ?? null,
437
+ timeout: options?.timeout ?? 30,
438
+ // 안 주면 키를 붙이지 않는다 — 구 서버와 기존 동작을 그대로 둔다(additive).
439
+ ...callerIdMode !== void 0 ? { callerIdMode } : {},
440
+ // 같은 이유로 안 주면 키 자체를 안 붙인다. 빈 문자열도 보내지 않는다 — 서버가 빈 문장을
441
+ // 합성하러 가지 않게 하는 것은 서버 쪽에서도 막지만, 굳이 왕복시킬 이유가 없다.
442
+ ...options?.failureMessage ? { failureMessage: options.failureMessage } : {},
443
+ ...options?.failureVoice ? { failureVoice: options.failureVoice } : {}
444
+ };
445
+ }
446
+ var CallSession = class {
447
+ callId;
448
+ fromNumber;
449
+ toNumber;
450
+ accountId;
451
+ direction;
452
+ /**
453
+ * 수신 통화에서 발신자가 번호 표시제한(`*23#` 등)을 걸고 건 통화면 `true`.
454
+ * 번호는 `fromNumber` 에 그대로 전달되고, 표시제한 여부만 이 값으로 알 수 있다.
455
+ * 통신사가 표시제한 여부를 보내지 않은 통화와 발신 통화는 `false`.
456
+ */
457
+ callerIdRestricted;
458
+ /**
459
+ * 착신전환으로 들어온 수신 통화에서 발신자가 **원래 건 번호**. 착신전환을 실행한 통신사가
460
+ * 전환 정보를 함께 보내온 경우에만 값이 있고, 직접 걸려온 통화와 발신 통화는 `null`.
461
+ */
462
+ forwardedFrom;
463
+ startTime;
464
+ metadata;
465
+ _status;
466
+ _endedStatus = null;
467
+ _endedDuration = null;
468
+ _sendAudioFn = null;
469
+ _clearAudioFn = null;
470
+ _hangupFn = null;
471
+ /** @internal */
472
+ _sendDtmfFn = null;
473
+ /** @internal */
474
+ _transferFn = null;
475
+ /** @internal control 연결이 끊기면 풀리는 대기. 전환 결과를 기다리는 도구가 쓴다. */
476
+ _transferConnectionLost = null;
477
+ /** @internal */
478
+ _isTransportConnected = null;
479
+ /**
480
+ * @internal Media WS playout 마커 훅. LiveKit(`ClawOpsAudioOutput`)이 재생 완료
481
+ * 판정(mark echo)과 barge-in 절단 위치 계산에 쓴다. 다른 세션 타입은 읽지 않는다.
482
+ * prewarm 중(BufferingCall)에는 바인딩되지 않아 null 이다.
483
+ */
484
+ /** @internal */
485
+ _sendMark = null;
486
+ /** @internal */
487
+ _waitForMark = null;
488
+ /** @internal */
489
+ _flushTransport = null;
490
+ /**
491
+ * @internal 지금까지 보낸 오디오가 다 재생될 때까지 기다린다(`MediaWebSocket.waitPlayedOut`).
492
+ * `collectDtmf` 가 안내 재생이 끝난 뒤부터 대기를 세는 데 쓴다. 없으면 바로 센다(종전 동작).
493
+ */
494
+ /** @internal */
495
+ _waitPlayedOut = null;
496
+ /**
497
+ * @internal 키패드 자동 전달(=collectDtmf 가 안 걸린 입력)의 버퍼. 통화별로 들고 있어야
498
+ * 동시 통화의 키가 서로 섞이지 않는다. 확정·전달은 ClawOpsAgent 가 한다 — 규칙이 에이전트 설정이라서다.
499
+ */
500
+ /** @internal */
501
+ _passiveDtmfBuffer = [];
502
+ /** @internal */
503
+ _passiveDtmfTimer = null;
504
+ /** @internal 버퍼에 남은 키를 대기 없이 확정하는 함수. collectDtmf 가 열릴 때 부른다. */
505
+ /** @internal */
506
+ _passiveDtmfConfirmNow = null;
507
+ /** @internal 한 통화의 자동 전달은 차례로 보낸다. */
508
+ /** @internal */
509
+ _passiveDtmfFeedChain = Promise.resolve();
510
+ _dtmfCollectorActive = false;
511
+ _dtmfResolvers = [];
512
+ _dtmfBuffer = [];
513
+ _log = NOOP_LOGGER;
514
+ _handlers = /* @__PURE__ */ new Map();
515
+ _endedPromise;
516
+ _resolveEnded;
517
+ _metrics = createCallMetrics();
518
+ _firstResponseSent = false;
519
+ constructor(options) {
520
+ this.callId = options.callId;
521
+ this.fromNumber = options.fromNumber;
522
+ this.toNumber = options.toNumber;
523
+ this.accountId = options.accountId;
524
+ this.direction = options.direction;
525
+ this.callerIdRestricted = options.callerIdRestricted ?? false;
526
+ this.forwardedFrom = options.forwardedFrom ?? null;
527
+ this.metadata = options.metadata ?? {};
528
+ this._status = "ringing";
529
+ this.startTime = /* @__PURE__ */ new Date();
530
+ this._endedPromise = new Promise((resolve) => {
531
+ this._resolveEnded = resolve;
532
+ });
533
+ }
534
+ setLogger(logger) {
535
+ this._log = logger;
536
+ }
537
+ get status() {
538
+ return this._status;
539
+ }
540
+ /**
541
+ * 서버가 통보한 최종 종료 상태. 통화가 끝나기 전에는 null.
542
+ *
543
+ * `completed`(성사) / `no-answer`(벨은 울렸으나 무응답) / `busy`(통화중) /
544
+ * `rejected`(수신 거절) / `canceled`(응답 전 발신 측 취소) / `failed`(시스템·망 오류).
545
+ * `status` 는 SDK 내부 수명주기(ringing→active→ended)이므로 통화 성사 여부는
546
+ * 이 값이나 `call_failed` 이벤트로 판단한다.
547
+ */
548
+ get endedStatus() {
549
+ return this._endedStatus;
550
+ }
551
+ /**
552
+ * 서버가 확정한 통화 시간(초). 통화가 끝나기 전에는 `null`.
553
+ *
554
+ * ⚠️ `duration` 과 다르다 — 그쪽은 SDK 가 로컬 시계로 재는 **경과 시간**이라 통화 중에도
555
+ * 읽히고, 세션이 붙기 전후의 오차를 포함한다. 기록·정산에 쓸 값은 이쪽이다.
556
+ */
557
+ get endedDuration() {
558
+ return this._endedDuration;
559
+ }
560
+ get duration() {
561
+ return (Date.now() - this.startTime.getTime()) / 1e3;
562
+ }
563
+ /** @internal 서버가 통보한 통화 시간을 확정한다. */
564
+ _setEndedDuration(seconds) {
565
+ this._endedDuration = seconds;
566
+ }
567
+ get metrics() {
568
+ return this._metrics;
569
+ }
570
+ recordFirstResponse() {
571
+ if (!this._firstResponseSent) {
572
+ this._firstResponseSent = true;
573
+ this._metrics.firstResponseMs = Date.now() - this.startTime.getTime();
574
+ }
575
+ }
576
+ recordTurn() {
577
+ this._metrics.turnCount++;
578
+ }
579
+ recordToolCall() {
580
+ this._metrics.toolCallCount++;
581
+ }
582
+ recordToolError(err) {
583
+ addMetricError(this._metrics, err);
584
+ }
585
+ recordBargeIn() {
586
+ this._metrics.bargeInCount++;
587
+ }
588
+ recordEndReason(reason) {
589
+ this._metrics.endReason = reason;
590
+ }
591
+ /** Bind transport functions (called internally by the agent). */
592
+ _bindTransport(send, clear, hangup, sendDtmf, isConnected) {
593
+ this._sendAudioFn = send;
594
+ this._clearAudioFn = clear;
595
+ this._hangupFn = hangup;
596
+ if (sendDtmf) this._sendDtmfFn = sendDtmf;
597
+ if (isConnected) this._isTransportConnected = isConnected;
598
+ this._status = "active";
599
+ }
600
+ /**
601
+ * Send G.711 μ-law audio (8kHz, mono) to the caller.
602
+ *
603
+ * NOT PCM16. The transport applies μ-law gain and forwards the bytes as-is,
604
+ * so PCM16 input is reinterpreted as μ-law and plays as noise. Convert first.
605
+ */
606
+ sendAudio(audio) {
607
+ if (this._sendAudioFn) {
608
+ this._sendAudioFn(audio);
609
+ }
610
+ }
611
+ /** Clear any queued outbound audio. */
612
+ clearAudio() {
613
+ if (this._clearAudioFn) {
614
+ this._clearAudioFn();
615
+ }
616
+ }
617
+ /** Hang up the call, waiting for pending audio to finish. */
618
+ async hangup() {
619
+ if (this._hangupFn) {
620
+ await this._hangupFn();
621
+ }
622
+ }
623
+ /** @internal 수집 중인 collectDtmf 에 키를 넘긴다.
624
+ *
625
+ * ClawOpsAgent 는 수집이 열려 있을 때만 부른다. 구간 밖 키는 모델에 자동 전달되므로 여기까지
626
+ * 오면 같은 키가 두 경로로 간다 — 동의 때 누른 `1` 이 다음 수집의 첫 자리가 돼 「1534」 가 나왔다. */
627
+ _routeDtmf(digit) {
628
+ if (this._dtmfCollectorActive && this._dtmfResolvers.length > 0) {
629
+ const resolve = this._dtmfResolvers.shift();
630
+ resolve(digit);
631
+ } else {
632
+ this._dtmfBuffer.push(digit);
633
+ }
634
+ }
635
+ /**
636
+ * Collect DTMF digits from the caller.
637
+ *
638
+ * `timeout` 은 **자리 사이** 대기다(inter-digit). `<Gather>` 를 비롯한 IVR 관행과 같은
639
+ * 의미이고, 자리가 들어올 때마다 다시 시작한다.
640
+ *
641
+ * 대기는 **안내 음성이 다 재생된 뒤**부터 센다(Twilio `<Gather>` 와 같다). 모델은 안내 텍스트를
642
+ * 다 만든 순간 이 도구를 부르지만 발신자 쪽에선 음성이 아직 10초 넘게 남아 있을 수 있다 — 그때부터
643
+ * 세면 누를 틈도 없이 빈 값으로 끝난다. 재생 중에 누른 첫 키는 그대로 받고(안내는 ClawOpsAgent 가
644
+ * 끊는다), 그 순간부터 센다.
645
+ *
646
+ * 수집이 열린 **뒤에** 누른 키만 받는다. 그 전에 누른 키는 모델에 자동 전달된다.
647
+ *
648
+ * `maxWait` 는 그 관행이 만드는 최악을 막는 **전체 상한**이다(기본 30초). 자리마다
649
+ * 리셋되는 타이머만 있으면 수집 하나가 최대 `maxDigits × timeout` 동안 산다 —
650
+ * 11자리·5초면 **55초**이고, 그동안 모델은 이 도구에 붙들려 아무 말도 못 한다.
651
+ * 이것도 재생이 끝난 뒤부터 센다 — 「발신자가 누를 수 있게 된 뒤 최대 몇 초」라는 뜻이다. 재생 끝
652
+ * 대기 자체도 `maxWait`(null 이면 60초)로 묶이므로 최악은 그 둘의 합이다. `null` 을 주면 상한 없이
653
+ * 종전대로 돈다.
654
+ *
655
+ * ⚠️ **수집값을 로그에 쓰지 않는다.** 키패드로 받는 값은 카드번호·주민번호일 수 있고,
656
+ * 실제로 그런 구성이 있다. `secure` 와 무관하게 **자릿수만** 남긴다 — 이 옵션은 호환을
657
+ * 위해 남아 있을 뿐 로깅을 좌우하지 않는다.
658
+ */
659
+ async collectDtmf(options) {
660
+ if (this._dtmfCollectorActive) {
661
+ throw new DtmfCollectorBusyError();
662
+ }
663
+ const { maxDigits, finishOnKey = "#", timeout = 5, maxWait = 30 } = options;
664
+ this._dtmfCollectorActive = true;
665
+ if (this._passiveDtmfBuffer.length > 0 && this._passiveDtmfConfirmNow) {
666
+ this._passiveDtmfConfirmNow();
667
+ }
668
+ this._dtmfBuffer = [];
669
+ const collected = [];
670
+ let deadline = null;
671
+ try {
672
+ if (this._waitPlayedOut) {
673
+ const abort = new AbortController();
674
+ let onFirst;
675
+ const firstDigit = new Promise((resolve) => {
676
+ onFirst = resolve;
677
+ });
678
+ this._dtmfResolvers.push(onFirst);
679
+ const started = Date.now();
680
+ const outcome = await Promise.race([
681
+ firstDigit.then((digit) => ({ digit })),
682
+ this._waitPlayedOut((maxWait ?? 60) * 1e3, abort.signal).then(
683
+ (played) => ({ played }),
684
+ () => ({ played: false })
685
+ )
686
+ ]);
687
+ abort.abort();
688
+ if ("digit" in outcome) {
689
+ this._dtmfBuffer.unshift(outcome.digit);
690
+ } else {
691
+ this._dtmfResolvers = this._dtmfResolvers.filter((r) => r !== onFirst);
692
+ this._log.info(
693
+ "\uD0A4\uD328\uB4DC \uC218\uC9D1: \uC548\uB0B4 \uC7AC\uC0DD \uB05D %ss%s",
694
+ ((Date.now() - started) / 1e3).toFixed(2),
695
+ outcome.played ? "" : " (\uD655\uC778 \uBABB \uD568)"
696
+ );
697
+ }
698
+ }
699
+ deadline = maxWait === null ? null : Date.now() + maxWait * 1e3;
700
+ while (collected.length < maxDigits) {
701
+ if (this._dtmfBuffer.length > 0) {
702
+ const digit2 = this._dtmfBuffer.shift();
703
+ if (digit2 === finishOnKey) break;
704
+ collected.push(digit2);
705
+ continue;
706
+ }
707
+ let waitMs = timeout * 1e3;
708
+ if (deadline !== null) {
709
+ waitMs = Math.min(waitMs, deadline - Date.now());
710
+ if (waitMs <= 0) break;
711
+ }
712
+ let timer;
713
+ const digit = await Promise.race([
714
+ new Promise((resolve) => {
715
+ this._dtmfResolvers.push(resolve);
716
+ }),
717
+ new Promise((resolve) => {
718
+ timer = setTimeout(() => resolve(null), waitMs);
719
+ })
720
+ ]).finally(() => {
721
+ if (timer !== void 0) clearTimeout(timer);
722
+ });
723
+ if (digit === null) break;
724
+ if (digit === finishOnKey) break;
725
+ collected.push(digit);
726
+ }
727
+ } finally {
728
+ this._dtmfCollectorActive = false;
729
+ this._dtmfResolvers = [];
730
+ this._dtmfBuffer = [];
731
+ }
732
+ const result = collected.join("");
733
+ this._log.info("DTMF collected: %d digits", result.length);
734
+ return result;
735
+ }
736
+ /** Send a sequence of DTMF digits. */
737
+ async sendDtmfSequence(digits) {
738
+ if (!this._sendDtmfFn) {
739
+ throw new Error("DTMF \uC804\uC1A1 \uD568\uC218\uAC00 \uBC14\uC778\uB529\uB418\uC9C0 \uC54A\uC558\uC2B5\uB2C8\uB2E4");
740
+ }
741
+ for (const ch of digits) {
742
+ if (this._isTransportConnected && !this._isTransportConnected()) {
743
+ throw new Error("DTMF \uC804\uC1A1 \uC911 \uC5F0\uACB0\uC774 \uB04A\uC5B4\uC84C\uC2B5\uB2C8\uB2E4");
744
+ }
745
+ if (ch === "w") {
746
+ await new Promise((r) => setTimeout(r, 500));
747
+ } else if (ch === "W") {
748
+ await new Promise((r) => setTimeout(r, 1e3));
749
+ } else if ("0123456789*#".includes(ch)) {
750
+ if (this._sendDtmfFn) {
751
+ await this._sendDtmfFn(ch);
752
+ }
753
+ } else {
754
+ throw new Error(`\uC720\uD6A8\uD558\uC9C0 \uC54A\uC740 DTMF \uBB38\uC790: ${ch}`);
755
+ }
756
+ }
757
+ }
758
+ /**
759
+ * Transfer the call to a phone number or SIP endpoint.
760
+ *
761
+ * destinationType='pstn' (default): `to` is a phone number dialed via carrier.
762
+ * destinationType='sip': `to` is a SIP URI (e.g. `sip:user@host`) connected
763
+ * directly to a SIP endpoint without going through the PSTN carrier. Requires the
764
+ * account to have an active `sip_trunk` add-on; otherwise the transfer fails and
765
+ * the call continues with the AI (result `{ status: 'failed', ... }`).
766
+ *
767
+ * 전환받는 쪽에 표시되는 발신번호는 기본이 **계정 보유번호**(인바운드면 착신 070)다.
768
+ *
769
+ * `callerIdMode: 'original'` 은 인바운드 통화의 **발신자 번호를 표시하려는 선호**다.
770
+ * 표시할 수 없는 통화(KCT 직결 인입이 아니거나 국내 번호로 정규화되지 않는 발신번호)면
771
+ * 조용히 계정 보유번호로 내려앉고 **전환은 그대로 성사된다**. 바뀌는 것은 받는 쪽 표시뿐이라
772
+ * (통화 자체는 계정 번호에서 넘기는 전환이다) 받는 장비에 따라 계정 번호가 보일 수 있다.
773
+ *
774
+ * `callerId` 는 번호를 직접 주는 **지시**라 성격이 다르다. 허용 범위(계정 보유번호 또는
775
+ * KCT 직결 인입 통화의 발신자)를 벗어나면 전환 자체가 실패한다. 둘 다 주면 `callerId` 가
776
+ * 이기고 `callerIdMode` 는 무시된다 — 우선순위 판단은 서버가 한다.
777
+ */
778
+ async transfer(to, options) {
779
+ if (!this._transferFn) {
780
+ throw new Error("transfer not available");
781
+ }
782
+ return this._transferFn(buildTransferPayload(to, options));
783
+ }
784
+ /** Register an event handler. */
785
+ on(event, handler) {
786
+ let list = this._handlers.get(event);
787
+ if (!list) {
788
+ list = [];
789
+ this._handlers.set(event, list);
790
+ }
791
+ list.push(handler);
792
+ }
793
+ /** Wait for the call to end. */
794
+ async wait() {
795
+ return this._endedPromise;
796
+ }
797
+ /**
798
+ * Mark the session as ended (called internally).
799
+ *
800
+ * @param status 서버가 통보한 최종 상태(completed/no-answer/busy/rejected/canceled/
801
+ * failed). 주어지면 `endedStatus` 로 확정한다 — 상대가 받지 않은 통화를 성사된 통화와
802
+ * 구분하기 위함이다. 생략하면 미디어 세션 정리 경로에서의 호출이므로, 아직 종료 전일
803
+ * 때만 'completed' 로 채우고 이미 확정된 서버 상태는 덮어쓰지 않는다.
804
+ */
805
+ _markEnded(status) {
806
+ if (status !== void 0) {
807
+ this._endedStatus = status;
808
+ } else if (this._status !== "ended") {
809
+ this._endedStatus = "completed";
810
+ }
811
+ this._status = "ended";
812
+ if (this._passiveDtmfTimer) clearTimeout(this._passiveDtmfTimer);
813
+ this._passiveDtmfTimer = null;
814
+ this._passiveDtmfBuffer = [];
815
+ this._resolveEnded();
816
+ }
817
+ /** Emit an event to registered handlers. Matches Python SDK: _emit(event, ...args) */
818
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
819
+ _emit(event, ...args) {
820
+ const handlers = this._handlers.get(event);
821
+ if (handlers) {
822
+ for (const handler of handlers) {
823
+ try {
824
+ const result = handler(this, ...args);
825
+ if (result && typeof result.catch === "function") {
826
+ result.catch((err) => {
827
+ this._log.error({ err }, "CallSession handler error: %s", event);
828
+ });
829
+ }
830
+ } catch (err) {
831
+ this._log.error({ err }, "CallSession handler error: %s", event);
832
+ }
833
+ }
834
+ }
835
+ }
836
+ };
837
+
838
+ // src/agent/builtin-tool.ts
839
+ var BuiltinTool = /* @__PURE__ */ ((BuiltinTool2) => {
840
+ BuiltinTool2["HANG_UP"] = "hang_up";
841
+ BuiltinTool2["COLLECT_DTMF"] = "collect_dtmf";
842
+ BuiltinTool2["SEND_DTMF"] = "send_dtmf";
843
+ BuiltinTool2["TRANSFER_CALL"] = "transfer_call";
844
+ BuiltinTool2["ALL"] = "all";
845
+ BuiltinTool2["NONE"] = "none";
846
+ return BuiltinTool2;
847
+ })(BuiltinTool || {});
848
+ var INDIVIDUAL_TOOLS = /* @__PURE__ */ new Set([
849
+ "hang_up" /* HANG_UP */,
850
+ "collect_dtmf" /* COLLECT_DTMF */,
851
+ "send_dtmf" /* SEND_DTMF */,
852
+ "transfer_call" /* TRANSFER_CALL */
853
+ ]);
854
+ function resolveBuiltinTools(value) {
855
+ if (typeof value === "string") {
856
+ if (value === "all" /* ALL */) {
857
+ return new Set(INDIVIDUAL_TOOLS);
858
+ }
859
+ if (value === "none" /* NONE */) {
860
+ return /* @__PURE__ */ new Set();
861
+ }
862
+ return /* @__PURE__ */ new Set([value]);
863
+ }
864
+ return new Set(value.filter((t) => INDIVIDUAL_TOOLS.has(t)));
865
+ }
866
+
867
+ // src/agent/pipeline/builtin-tool-schemas.ts
868
+ var log = createAgentLogger();
869
+ var HANG_UP = {
870
+ name: "hang_up",
871
+ description: "End the phone call. Use when the conversation is finished or the caller says goodbye.",
872
+ parameters: { type: "object", properties: {} }
873
+ };
874
+ var COLLECT_DTMF = {
875
+ name: "collect_dtmf",
876
+ description: "\uC0AC\uC6A9\uC790\uB85C\uBD80\uD130 DTMF(\uC804\uD654 \uD0A4\uD328\uB4DC) \uC785\uB825\uC744 \uC218\uC9D1\uD569\uB2C8\uB2E4. \uBC18\uB4DC\uC2DC \uC0AC\uC6A9\uC790\uC5D0\uAC8C \uBB34\uC5C7\uC744 \uC785\uB825\uD574\uC57C \uD558\uB294\uC9C0 \uC548\uB0B4\uD55C \uD6C4 \uD638\uCD9C\uD558\uC138\uC694.",
877
+ parameters: {
878
+ type: "object",
879
+ properties: {
880
+ max_digits: { type: "integer", description: "\uC218\uC9D1\uD560 \uCD5C\uB300 \uC790\uB9BF\uC218" },
881
+ finish_on_key: { type: "string", description: "\uC785\uB825 \uC885\uB8CC \uD0A4 (\uAE30\uBCF8: #)" },
882
+ timeout: { type: "integer", description: "\uC785\uB825 \uB300\uAE30 \uC2DC\uAC04(\uCD08, \uAE30\uBCF8: 5)" }
883
+ },
884
+ required: ["max_digits"]
885
+ }
886
+ };
887
+ var SEND_DTMF = {
888
+ name: "send_dtmf",
889
+ description: "DTMF \uC2E0\uD638\uB97C \uC804\uC1A1\uD569\uB2C8\uB2E4. ARS \uBA54\uB274 \uD0D0\uC0C9\uC774\uB098 \uB0B4\uC120\uBC88\uD638 \uC785\uB825 \uC2DC \uC0AC\uC6A9\uD569\uB2C8\uB2E4.",
890
+ parameters: {
891
+ type: "object",
892
+ properties: {
893
+ digits: {
894
+ type: "string",
895
+ description: "\uC804\uC1A1\uD560 \uBC88\uD638 (0-9, *, #). 'w'\uB294 500ms \uB300\uAE30, 'W'\uB294 1000ms \uB300\uAE30. \uC608: '1', '1234#', '1w2'"
896
+ }
897
+ },
898
+ required: ["digits"]
899
+ }
900
+ };
901
+ var TRANSFER_CALL = {
902
+ name: "transfer_call",
903
+ description: "Transfer the current call to another phone number or SIP endpoint. Use for blind transfer (direct handoff) or warm transfer (with whisper message to the target).",
904
+ parameters: {
905
+ type: "object",
906
+ properties: {
907
+ to: { type: "string", description: "Transfer destination. A phone number when destination_type is 'pstn', or a SIP URI (e.g. 'sip:user@host') when destination_type is 'sip'." },
908
+ destination_type: { type: "string", enum: ["pstn", "sip"], description: "pstn: dial a phone number via carrier (default). sip: connect directly to a SIP endpoint (no carrier/PSTN)." },
909
+ mode: { type: "string", enum: ["blind", "warm"], description: "blind: direct transfer (default), warm: play whisper to target first" },
910
+ after_transfer: { type: "string", enum: ["terminate", "return"], description: "terminate: end AI session (default), return: AI resumes after transfer ends" },
911
+ whisper: { type: "string", description: "Message to speak to transfer target before connecting customer (warm mode only)" },
912
+ caller_id_mode: { type: "string", enum: ["account", "original"], description: "What the transfer target sees as the caller. account: the account's own number (default). original: prefer the inbound caller's number, falling back to the account number when it cannot be inherited. Prefer this over caller_id." },
913
+ caller_id: { type: "string", description: "Exact caller ID for the transfer leg. Must be a number the account owns, or the original inbound caller. Anything else fails the transfer outright \u2014 use caller_id_mode unless a specific number is required." },
914
+ timeout: { type: "integer", description: "Seconds to wait for transfer target to answer (default 30)" }
915
+ },
916
+ required: ["to"]
917
+ }
918
+ };
919
+ function transferOptionsFromArgs(args) {
920
+ return {
921
+ destinationType: args["destination_type"] ?? void 0,
922
+ mode: args["mode"] ?? void 0,
923
+ afterTransfer: args["after_transfer"] ?? void 0,
924
+ whisper: args["whisper"] ?? void 0,
925
+ callerId: args["caller_id"] ?? void 0,
926
+ callerIdMode: args["caller_id_mode"] ?? void 0,
927
+ timeout: args["timeout"] ?? void 0
928
+ };
929
+ }
930
+ var TOOL_MAP = /* @__PURE__ */ new Map([
931
+ ["hang_up" /* HANG_UP */, HANG_UP],
932
+ ["collect_dtmf" /* COLLECT_DTMF */, COLLECT_DTMF],
933
+ ["send_dtmf" /* SEND_DTMF */, SEND_DTMF],
934
+ ["transfer_call" /* TRANSFER_CALL */, TRANSFER_CALL]
935
+ ]);
936
+ var BUILTIN_TOOL_NAMES = new Set(
937
+ Array.from(TOOL_MAP.values()).map((s) => s.name)
938
+ );
939
+ var CALL_NOT_READY_RESULT = "\uD1B5\uD654\uAC00 \uC544\uC9C1 \uC5F0\uACB0\uB418\uC9C0 \uC54A\uC558\uC2B5\uB2C8\uB2E4(\uBC1C\uC2E0 \uD638\uCD9C\uC74C \uB2E8\uACC4). \uC0C1\uB300\uAC00 \uC804\uD654\uB97C \uBC1B\uC740 \uB4A4\uC5D0 \uB2E4\uC2DC \uC2DC\uB3C4\uD558\uC138\uC694.";
940
+ function toChatCompletions(schema) {
941
+ return {
942
+ type: "function",
943
+ function: {
944
+ name: schema.name,
945
+ description: schema.description,
946
+ parameters: schema.parameters
947
+ }
948
+ };
949
+ }
950
+ function toRealtime(schema) {
951
+ return {
952
+ type: "function",
953
+ name: schema.name,
954
+ description: schema.description,
955
+ parameters: schema.parameters
956
+ };
957
+ }
958
+ function toGemini(schema) {
959
+ return {
960
+ name: schema.name,
961
+ description: schema.description,
962
+ parameters: schema.parameters
963
+ };
964
+ }
965
+ var CONVERTERS = {
966
+ chat: toChatCompletions,
967
+ realtime: toRealtime,
968
+ gemini: toGemini
969
+ };
970
+ function getBuiltinToolSchemas(builtinTools, fmt) {
971
+ const converter = CONVERTERS[fmt];
972
+ const result = [];
973
+ for (const [toolEnum, schema] of TOOL_MAP) {
974
+ if (builtinTools === null || builtinTools.has(toolEnum)) {
975
+ result.push(converter(schema));
976
+ }
977
+ }
978
+ return result;
979
+ }
980
+ function isBuiltinTool(name) {
981
+ return BUILTIN_TOOL_NAMES.has(name);
982
+ }
983
+ async function executeBuiltinTool(funcName, args, call) {
984
+ if (funcName === "hang_up") {
985
+ await call.hangup();
986
+ return "";
987
+ }
988
+ if (funcName === "collect_dtmf") {
989
+ try {
990
+ const result = await call.collectDtmf({
991
+ maxDigits: args["max_digits"] ?? 4,
992
+ finishOnKey: args["finish_on_key"] ?? "#",
993
+ timeout: args["timeout"] ?? 5
994
+ });
995
+ return result || "(\uD0C0\uC784\uC544\uC6C3 - \uC785\uB825 \uC5C6\uC74C)";
996
+ } catch (e) {
997
+ if (e instanceof DtmfCollectorBusyError) {
998
+ return "(\uC774\uBBF8 \uC785\uB825\uC744 \uBC1B\uB294 \uC911\uC785\uB2C8\uB2E4. \uACB0\uACFC\uB97C \uAE30\uB2E4\uB9AC\uC138\uC694.)";
999
+ }
1000
+ return `Error: ${e}`;
1001
+ }
1002
+ }
1003
+ if (funcName === "send_dtmf") {
1004
+ try {
1005
+ await call.sendDtmfSequence(args["digits"] ?? "");
1006
+ return "sent";
1007
+ } catch (e) {
1008
+ return `Error: ${e}`;
1009
+ }
1010
+ }
1011
+ if (funcName === "transfer_call") {
1012
+ try {
1013
+ call.transfer(args["to"], {
1014
+ ...transferOptionsFromArgs(args)
1015
+ // 결과를 안 기다리므로 실패가 통째로 조용하다 — 모델은 "시작됨" 을 받고, 예외는
1016
+ // 프로미스 안에 갇힌다. 최소한 로그에는 남긴다.
1017
+ }).catch((e) => {
1018
+ log.error({ err: e }, "transfer_call \uB3C4\uAD6C\uAC00 \uAC74 \uC804\uD658\uC774 \uC2E4\uD328\uD588\uB2E4");
1019
+ });
1020
+ return JSON.stringify({ status: "transfer_initiated" });
1021
+ } catch (e) {
1022
+ return `Error: ${e}`;
1023
+ }
1024
+ }
1025
+ return null;
1026
+ }
1027
+
1028
+ // src/agent/pipeline/buffering-call.ts
1029
+ var MetricsStub = class {
1030
+ recordToolCall() {
1031
+ }
1032
+ recordInterrupt() {
1033
+ }
1034
+ recordToolError() {
1035
+ }
1036
+ };
1037
+ var BufferingCall = class {
1038
+ _buffer = [];
1039
+ _droppedEvents = {};
1040
+ metrics = new MetricsStub();
1041
+ async sendAudio(chunk) {
1042
+ this._buffer.push(chunk);
1043
+ }
1044
+ /** clearAudio 도 prewarm 동안엔 no-op (드물긴 하지만 안전하게). */
1045
+ clearAudio() {
1046
+ this._buffer = [];
1047
+ }
1048
+ /**
1049
+ * transcript 등 lifecycle 이벤트는 prewarm 동안 무시한다. silent drop 은 디버깅이
1050
+ * 어려우므로 event name 별 카운터로 누적하고 attachBuffered() 시 한 번에 로깅한다.
1051
+ */
1052
+ _emit(...args) {
1053
+ this._recordDropped(args);
1054
+ }
1055
+ async emit(...args) {
1056
+ this._recordDropped(args);
1057
+ }
1058
+ _recordDropped(args) {
1059
+ let eventName = "?";
1060
+ if (args.length > 0 && typeof args[0] === "string") {
1061
+ eventName = args[0];
1062
+ }
1063
+ this._droppedEvents[eventName] = (this._droppedEvents[eventName] ?? 0) + 1;
1064
+ }
1065
+ recordToolCall() {
1066
+ }
1067
+ recordToolError() {
1068
+ }
1069
+ recordFirstResponse() {
1070
+ }
1071
+ recordBargeIn() {
1072
+ }
1073
+ drainBuffer() {
1074
+ const out = this._buffer;
1075
+ this._buffer = [];
1076
+ return out;
1077
+ }
1078
+ drainDroppedEvents() {
1079
+ const out = this._droppedEvents;
1080
+ this._droppedEvents = {};
1081
+ return out;
1082
+ }
1083
+ };
1084
+ function attachBuffered(prev, next) {
1085
+ if (!(prev instanceof BufferingCall)) {
1086
+ return false;
1087
+ }
1088
+ const drained = prev.drainBuffer();
1089
+ const flushed = drained.length > 0;
1090
+ const callId = next.callId ?? "?";
1091
+ if (flushed) {
1092
+ console.info(
1093
+ `[PREWARM-T] first-audio call_id=${callId} t=${(process.hrtime.bigint() / 1000000n).toString()} buffered_chunks=${drained.length} source=prebuffer`
1094
+ );
1095
+ }
1096
+ for (const chunk of drained) {
1097
+ next.sendAudio(chunk);
1098
+ }
1099
+ const dropped = prev.drainDroppedEvents();
1100
+ if (Object.keys(dropped).length > 0) {
1101
+ console.info(
1102
+ `[PREWARM] dropped events during prewarm call_id=${callId} events=${JSON.stringify(dropped)}`
1103
+ );
1104
+ }
1105
+ return flushed;
1106
+ }
1107
+
1108
+ exports.BUILTIN_TOOL_NAMES = BUILTIN_TOOL_NAMES;
1109
+ exports.BufferingCall = BufferingCall;
1110
+ exports.BuiltinTool = BuiltinTool;
1111
+ exports.CALL_NOT_READY_RESULT = CALL_NOT_READY_RESULT;
1112
+ exports.CallSession = CallSession;
1113
+ exports.DECODE_TABLE = DECODE_TABLE;
1114
+ exports.DtmfCollectorBusyError = DtmfCollectorBusyError;
1115
+ exports.MediaProfile = MediaProfile;
1116
+ exports.NOOP_LOGGER = NOOP_LOGGER;
1117
+ exports.applyUlawGain = applyUlawGain;
1118
+ exports.attachBuffered = attachBuffered;
1119
+ exports.buildTransferPayload = buildTransferPayload;
1120
+ exports.createAgentLogger = createAgentLogger;
1121
+ exports.createPipelineLogger = createPipelineLogger;
1122
+ exports.executeBuiltinTool = executeBuiltinTool;
1123
+ exports.getBuiltinToolSchemas = getBuiltinToolSchemas;
1124
+ exports.getSdkInfo = getSdkInfo;
1125
+ exports.isBuiltinTool = isBuiltinTool;
1126
+ exports.mediaContract = mediaContract;
1127
+ exports.pcm16ToUlaw = pcm16ToUlaw;
1128
+ exports.resamplePcm16 = resamplePcm16;
1129
+ exports.resolveBuiltinTools = resolveBuiltinTools;
1130
+ exports.transferOptionsFromArgs = transferOptionsFromArgs;
1131
+ exports.ulawToPcm16 = ulawToPcm16;
1132
+ exports.validateMediaFormat = validateMediaFormat;
1133
+ //# sourceMappingURL=chunk-PDE4I4MV.cjs.map
1134
+ //# sourceMappingURL=chunk-PDE4I4MV.cjs.map