@koreaaitel/sdk 0.0.0-stage → 0.62.1

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-3QH5DUA2.js +6 -0
  18. package/dist/chunk-3QH5DUA2.js.map +1 -0
  19. package/dist/chunk-5ZH3XGLJ.cjs +1134 -0
  20. package/dist/chunk-5ZH3XGLJ.cjs.map +1 -0
  21. package/dist/chunk-B3QB5WPI.cjs +202 -0
  22. package/dist/chunk-B3QB5WPI.cjs.map +1 -0
  23. package/dist/chunk-DO6A7FLM.js +1103 -0
  24. package/dist/chunk-DO6A7FLM.js.map +1 -0
  25. package/dist/chunk-LLPMUDNE.cjs +16 -0
  26. package/dist/chunk-LLPMUDNE.cjs.map +1 -0
  27. package/dist/chunk-LPQFS6AS.cjs +8 -0
  28. package/dist/chunk-LPQFS6AS.cjs.map +1 -0
  29. package/dist/chunk-T4ZQXFTN.js +181 -0
  30. package/dist/chunk-T4ZQXFTN.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,1574 @@
1
+ import { F as FunctionTool, T as TransferOptions, S as Session, B as BuiltinTool, a as ToolOptions, C as CallSession, M as MediaProfile, b as STT, L as LLM, c as TTS, d as ToolRegistry, e as SessionTelemetry, f as ToolBehavior, g as ToolScheduling, h as SpeechEvent, i as ConversationMessage, j as LLMChunk } from '../media-profile-DZCqLJKa.cjs';
2
+ export { k as CallDirection, l as CallStatus, D as DtmfCollectorBusyError, O as OpenAIToolDefinition, m as ToolCallRequest, n as functionTool, z as zodToToolParams } from '../media-profile-DZCqLJKa.cjs';
3
+ import { Logger } from 'pino';
4
+ export { Logger } from 'pino';
5
+ import { e as AgentAuthRejectedError } from '../error-D1uHhe6r.cjs';
6
+ import 'zod';
7
+
8
+ /**
9
+ * MCP (Model Context Protocol) client for discovering and calling tools.
10
+ */
11
+
12
+ interface MCPServerConfig {
13
+ /** Server type discriminator. */
14
+ type: 'stdio' | 'http';
15
+ [key: string]: unknown;
16
+ }
17
+ declare class MCPClient {
18
+ private _servers;
19
+ private _clients;
20
+ private _log;
21
+ setLogger(logger: Logger): void;
22
+ /** Add an MCP server configuration. */
23
+ addServer(name: string, config: MCPServerConfig & Record<string, unknown>): void;
24
+ /** Connect to all configured MCP servers and discover tools. */
25
+ connect(): Promise<FunctionTool[]>;
26
+ /** Disconnect from all MCP servers. */
27
+ disconnect(): Promise<void>;
28
+ private _connectServer;
29
+ }
30
+
31
+ /**
32
+ * MCP server configuration for stdio-based servers.
33
+ */
34
+ interface MCPServerStdio {
35
+ type: 'stdio';
36
+ /** Command to execute. */
37
+ command: string;
38
+ /** Command arguments. */
39
+ args?: string[];
40
+ /** Environment variables. */
41
+ env?: Record<string, string>;
42
+ [key: string]: unknown;
43
+ }
44
+ /**
45
+ * Create a stdio MCP server configuration.
46
+ */
47
+ declare function mcpServerStdio(options: {
48
+ command: string;
49
+ args?: string[];
50
+ env?: Record<string, string>;
51
+ }): MCPServerStdio;
52
+
53
+ /**
54
+ * MCP server configuration for HTTP-based servers.
55
+ */
56
+ interface MCPServerHTTP {
57
+ type: 'http';
58
+ /** Server URL. */
59
+ url: string;
60
+ /** Additional headers to send with requests. */
61
+ headers?: Record<string, string>;
62
+ [key: string]: unknown;
63
+ }
64
+ /**
65
+ * Create an HTTP MCP server configuration.
66
+ */
67
+ declare function mcpServerHTTP(options: {
68
+ url: string;
69
+ headers?: Record<string, string>;
70
+ }): MCPServerHTTP;
71
+
72
+ /**
73
+ * 수신 통화 선별 — `agent.onIncoming(hook)` 이 받는 객체 (clawops#1251).
74
+ *
75
+ * 받기 **전에** 서버가 보낸 `call.incoming` 을 보고 거절할지 정한다. 이 객체는 `CallSession` 이
76
+ * 아니다 — 아직 받지 않은 통화라 미디어도, 세션도 없다. 거절하면 세션이 아예 만들어지지 않는다.
77
+ *
78
+ * 와이어:
79
+ * 서버 → `{ event: 'call.incoming', callId, from, to, mediaUrl, callerIdRestricted?, forwardedFrom? }`
80
+ * SDK → `{ event: 'call.accept', callId }` 또는 `{ event: 'call.reject', callId, reason }`
81
+ *
82
+ * `call.reject` 에는 **반드시 reason 을 싣는다.** reason 없는 거절은 서버가 「에이전트 응답 실패」로
83
+ * 보고 대체 경로로 넘긴다 — 고객이 원한 「끊기」가 아니다.
84
+ *
85
+ * `transfer(to)` 를 부르면 AI 없이 받아서 곧바로 `to` 로 넘긴다. AI 세션은 만들지 않는다(첫 인사도,
86
+ * 모델 연결도 없다). 서버는 미디어가 붙은 뒤에야 통화를 받으므로 SDK 가 미디어만 붙이고, 발신자
87
+ * 음성이 흐르기 시작하면(=서버가 받았다) 전환을 요청한다.
88
+ */
89
+
90
+ /** 거절 사유. `'rejected'` = SIP 403(기본), `'busy'` = SIP 486(통화중). */
91
+ type IncomingRejectReason = 'rejected' | 'busy';
92
+ /**
93
+ * `IncomingCall.transfer()` 옵션. `CallSession.transfer` 와 같되, AI 가 이어받을 수 없으므로
94
+ * `mode`·`afterTransfer` 는 받지 않는다(`blind`·`terminate` 고정).
95
+ */
96
+ type IncomingTransferOptions = Omit<TransferOptions, 'mode' | 'afterTransfer'>;
97
+ interface IncomingRejectOptions {
98
+ /** 기본 `'rejected'`. */
99
+ reason?: IncomingRejectReason;
100
+ }
101
+ /** `agent.onIncoming()` 에 넘기는 선별 함수. reject 하지 않고 돌아오면 받는다. */
102
+ type IncomingHandler = (call: IncomingCall) => void | Promise<void>;
103
+ /** @internal */
104
+ interface IncomingCallInit {
105
+ callId: string;
106
+ fromNumber: string;
107
+ toNumber: string;
108
+ callerIdRestricted: boolean;
109
+ forwardedFrom?: string | null;
110
+ /** 거절이 확정되는 순간 한 번 불린다 — `call.reject` 를 보내는 자리. */
111
+ onReject: (reason: IncomingRejectReason) => void;
112
+ /** `transfer()` 로 결정이 나는 순간 한 번 불린다 — 선별 함수가 끝나기를 기다리지 않고 받게 한다. */
113
+ onDecide?: () => void;
114
+ logger?: Logger;
115
+ }
116
+ declare class IncomingCall {
117
+ /** 통화 ID */
118
+ readonly callId: string;
119
+ /** 발신 번호 (`CallSession.fromNumber` 와 같은 값) */
120
+ readonly fromNumber: string;
121
+ /** 수신 번호 (`CallSession.toNumber` 와 같은 값) */
122
+ readonly toNumber: string;
123
+ /** 발신자가 번호 표시제한을 걸고 건 통화면 `true`. 통신사가 표시제한 여부를 안 보낸 통화는 `false`. */
124
+ readonly callerIdRestricted: boolean;
125
+ /**
126
+ * 착신전환으로 들어온 통화에서 발신자가 **원래 건 번호**. 착신전환을 실행한 통신사가 전환 정보를
127
+ * 함께 보내온 경우에만 값이 있고, 직접 걸려온 통화는 `null`.
128
+ */
129
+ readonly forwardedFrom: string | null;
130
+ private _state;
131
+ private _transfer;
132
+ private _reason;
133
+ private readonly _onReject;
134
+ private readonly _onDecide;
135
+ private readonly _log;
136
+ /** @internal — SDK 가 만든다. */
137
+ constructor(init: IncomingCallInit);
138
+ /** 거절했으면 `true`. */
139
+ get rejected(): boolean;
140
+ /** 거절 사유. 거절하지 않았으면 `null`. */
141
+ get rejectReason(): IncomingRejectReason | null;
142
+ /** `transfer()` 로 정한 전환 요청 본문. 부르지 않았으면 `null`. */
143
+ get transferRequest(): Record<string, unknown> | null;
144
+ /**
145
+ * AI 없이 받아서 곧바로 `to` 로 넘긴다.
146
+ *
147
+ * - AI 세션을 만들지 않는다. 발신자는 AI 인사 없이 연결음을 듣는다.
148
+ * - 이 통화에는 `call_start` 등 통화 이벤트가 없다(AI 세션이 없으므로).
149
+ * - 옵션은 `CallSession.transfer` 와 같다. `blind`·`terminate` 로 고정한다 — 대상이 받지 않으면
150
+ * `failureMessage` 를 들려주고 끊는다(없으면 그냥 끊는다).
151
+ * - `reject()` 와 둘 중 먼저 부른 것만 효과가 있다. 선별 시간(5초)이 지나면 무시된다.
152
+ * - 부르는 즉시 결정된다 — 선별 함수가 뒤에 더 일해도 기다리지 않는다.
153
+ */
154
+ transfer(to: string, opts?: IncomingTransferOptions): Promise<void>;
155
+ /**
156
+ * 이 통화를 받지 않고 끝낸다. 과금되지 않고, 대체 경로로도 넘어가지 않는다.
157
+ *
158
+ * - 두 번 불러도 처음 한 번만 보낸다.
159
+ * - 선별 시간(5초)이 지난 뒤에는 이미 받은 통화라 아무것도 하지 않는다(경고만 남긴다).
160
+ * - `reason` 이 `'rejected'`·`'busy'` 가 아니면 예외를 던진다.
161
+ */
162
+ reject(opts?: IncomingRejectOptions): Promise<void>;
163
+ /** @internal — 선별이 끝나 받기로 확정됐다. 이후 reject() 는 no-op. */
164
+ _close(): void;
165
+ }
166
+
167
+ /**
168
+ * Tracing configuration for OpenTelemetry integration.
169
+ */
170
+ interface TracingConfig {
171
+ /** Whether tracing is enabled. Default: false */
172
+ enabled: boolean;
173
+ /** Service name for traces. Default: 'clawops-agent' */
174
+ serviceName?: string;
175
+ /**
176
+ * Optional TracerProvider instance from @opentelemetry/api.
177
+ * If not provided, the global tracer provider will be used.
178
+ */
179
+ tracerProvider?: unknown;
180
+ }
181
+ /** Get the current tracing configuration. */
182
+ declare function getTracingConfig(): TracingConfig;
183
+ /** Set the tracing configuration. */
184
+ declare function setTracingConfig(config: Partial<TracingConfig>): void;
185
+ /** Reset tracing configuration to defaults. */
186
+ declare function resetTracingConfig(): void;
187
+
188
+ /**
189
+ * ClawOpsAgent - main agent class for handling voice calls.
190
+ */
191
+
192
+ type AgentEventType = 'call_start' | 'call_end' | 'call_failed' | 'transcript' | 'dtmf';
193
+ type AgentEventHandler = (...args: any[]) => void | Promise<void>;
194
+ /** Tool 실행 관련 설정. */
195
+ interface ToolConfig {
196
+ /** Tool 실행 중 재생할 hold audio. true=기본 차임, string=wav 파일 경로, Buffer=raw ulaw. */
197
+ holdAudio?: boolean | string | Buffer;
198
+ }
199
+ interface ClawOpsAgentOptions {
200
+ /** ClawOps API key. Falls back to CLAWOPS_API_KEY env var. */
201
+ apiKey?: string;
202
+ /** Account ID. Falls back to CLAWOPS_ACCOUNT_ID env var. */
203
+ accountId?: string;
204
+ /** API base URL. */
205
+ baseUrl?: string;
206
+ /** Phone number to send/receive calls from. Required. */
207
+ from: string;
208
+ /** Session implementation (OpenAIRealtime, GeminiRealtime, PipelineSession, etc.). */
209
+ session: Session;
210
+ /** Enable call recording. */
211
+ recording?: boolean;
212
+ /** Recording output directory. Default: './recordings' */
213
+ recordingPath?: string;
214
+ /** MCP server configurations. */
215
+ mcpServers?: Array<MCPServerStdio | MCPServerHTTP>;
216
+ /** Tracing configuration. */
217
+ tracing?: TracingConfig;
218
+ /** 활성화할 내장 도구. Default: BuiltinTool.ALL */
219
+ builtinTools?: BuiltinTool | BuiltinTool[];
220
+ /**
221
+ * 키패드 자동 전달: 마지막 키 뒤 이만큼(ms) 더 안 눌리면 모은 키를 모델에 전달한다. Default: 2000
222
+ *
223
+ * 확정 규칙은 셋 중 먼저 오는 것이다 — 종료키 / 자리 수 / 이 대기. 2초는 Pipecat
224
+ * `DTMFAggregator` 와 같다. 0.5초였을 땐 사람 손 간격(실측 0.33~0.94초)보다 짧아 534 가
225
+ * 5·3·4 로 쪼개져 들어갔다.
226
+ */
227
+ passiveDtmfDebounceMs?: number;
228
+ /**
229
+ * 키패드 자동 전달의 종료키. 누르는 즉시 그때까지를 전달하고, 키 자신은 값에서 뺀다.
230
+ * 모인 키 없이 누르면 그 키를 그대로 전달한다(「#번을 누르세요」 메뉴). `null` 이면 끈다. Default: '#'
231
+ */
232
+ passiveDtmfFinishKey?: string | null;
233
+ /**
234
+ * 키패드 자동 전달: 이 자리 수가 모이면 바로 전달한다. 받을 자리 수가 항상 같을 때만 쓴다 —
235
+ * 넘치게 누른 키는 다음 입력으로 넘어간다. Default: 없음
236
+ */
237
+ passiveDtmfMaxDigits?: number | null;
238
+ /** Custom pino logger instance. If omitted, a default logger is created. */
239
+ logger?: Logger;
240
+ /** Tool 실행 관련 설정. */
241
+ toolConfig?: ToolConfig;
242
+ /**
243
+ * Called when another process takes over this number's control connection — the normal
244
+ * middle of a rolling deploy, seen from the instance being replaced. New calls already go
245
+ * elsewhere; finish the calls still in flight and exit. `serve()` handles this for you;
246
+ * wire this only if you drive `connect()` yourself, and call `drain()` from it.
247
+ */
248
+ onTakenOver?: (info: {
249
+ code: number;
250
+ reason: string;
251
+ }) => void;
252
+ /**
253
+ * Gain applied to inbound audio (caller → AI). 1.0 = pass-through (default), 0 = mute, 2.0 = 2x amplify.
254
+ * AI/STT receive the gained audio, and recording captures it post-gain.
255
+ */
256
+ rxGain?: number;
257
+ /**
258
+ * Gain applied to outbound audio (AI → caller). 1.0 = pass-through (default), 0 = mute, 2.0 = 2x amplify.
259
+ * The caller hears the gained audio, and recording captures it post-gain.
260
+ */
261
+ txGain?: number;
262
+ /**
263
+ * outbound_ready 시점에 session.prewarm() 을 백그라운드로 시작할지 여부.
264
+ * false 면 기존 start() 단일 경로로 동작 (prewarm 비활성). Default: true.
265
+ * Python SDK 의 `prewarm_enabled` 과 mirror.
266
+ */
267
+ prewarmEnabled?: boolean;
268
+ /**
269
+ * 이 에이전트의 모든 발신에 적용되는 AMD(machineDetection) default.
270
+ * `'Enable'`=감지 후 `AnsweredBy` 통보(통화 계속), `'Hangup'`=음성사서함 감지 시 자동 종료.
271
+ * `call(to, { machineDetection })` 로 호출별 override 가능.
272
+ * 우선순위: 호출 인자 > 인스턴스 default > 비활성. Python SDK 의 `machine_detection` 과 mirror.
273
+ */
274
+ machineDetection?: 'Enable' | 'Hangup';
275
+ }
276
+ declare class ClawOpsAgent {
277
+ private _apiKey;
278
+ private _accountId;
279
+ private _baseUrl;
280
+ private _fromNumber;
281
+ private _session;
282
+ private _tools;
283
+ private _handlers;
284
+ private _controlWs;
285
+ private _mcpServers;
286
+ private _recording;
287
+ private _recordingPath;
288
+ private _activeSessions;
289
+ /** `onIncoming()` 선별 함수. 없으면 수신 통화는 예전처럼 곧바로 받는다. */
290
+ private _incomingHook;
291
+ /** 선별 함수 상한(ms). 넘기면 받는다(fail-open). 게이트웨이는 11초 기다린다. 테스트에서 줄인다. */
292
+ private _incomingDeadlineMs;
293
+ /** 선별 중인 수신 통화. callId → 그 사이 서버가 call.ended 를 보냈나. */
294
+ private _screening;
295
+ /** Set once the server hands this number to another process (rolling deploy takeover). */
296
+ private _takenOver;
297
+ /**
298
+ * Set once the server refuses the control connection for good (revoked key, number reclaimed).
299
+ * Reconnecting gives the same answer, so this agent is finished.
300
+ */
301
+ private _authRejected;
302
+ /**
303
+ * Set once we deliberately give up the control connection (`drain()`/`disconnect()`).
304
+ * Distinct from `_controlWs === null`, which also covers "never connected": only after a
305
+ * hand-back is it certain that no server terminal frame can still arrive.
306
+ */
307
+ private _controlGivenUp;
308
+ /** serve()'s stop hook, so takeover can end the block the same way a signal does. */
309
+ private _stopServe;
310
+ private _onRetired;
311
+ private _ready;
312
+ private _onTakenOver?;
313
+ /** 미디어 정리를 마친 통화가 서버 종료 프레임을 기다리는 자리. callId → resolve. */
314
+ private _terminalWaiters;
315
+ private _builtinTools;
316
+ private _passiveDtmfDebounceMs;
317
+ private _passiveDtmfFinishKey;
318
+ private _passiveDtmfMaxDigits;
319
+ private _callSessions;
320
+ private _log;
321
+ private _pipelineLog;
322
+ private _isPipelineSession;
323
+ private _holdAudioChunks;
324
+ private _rxGain;
325
+ private _txGain;
326
+ private _prewarmTasks;
327
+ private _prewarmFailed;
328
+ /** prewarm 세션이 실제 CallSession 에 attach 완료된 callId. attached 이후의 stop() 은 정상 종료 경로가 책임진다. */
329
+ private _prewarmAttached;
330
+ private _prewarmEnabled;
331
+ /** 모든 발신에 적용되는 AMD default. call() 인자로 호출별 override 가능. */
332
+ private _machineDetection?;
333
+ constructor(options: ClawOpsAgentOptions);
334
+ private static _validateGain;
335
+ /**
336
+ * Register a function tool.
337
+ *
338
+ * Supports two signatures (matching Python SDK):
339
+ * agent.tool(name, description, parameters, handler)
340
+ * agent.tool(functionToolObject)
341
+ */
342
+ tool(nameOrTool: string | FunctionTool, description?: string, parameters?: Record<string, unknown>, handler?: (args: Record<string, unknown>) => unknown | Promise<unknown>, options?: ToolOptions): this;
343
+ /**
344
+ * Register an event handler.
345
+ *
346
+ * Matches Python SDK decorator style:
347
+ * agent.on("call_start", (call) => { ... })
348
+ * agent.on("transcript", (call, role, text) => { ... })
349
+ */
350
+ on(event: AgentEventType, handler: AgentEventHandler): this;
351
+ /**
352
+ * 수신 통화를 받기 전에 거절할지 정하는 함수를 등록한다 (clawops#1251).
353
+ *
354
+ * ```ts
355
+ * agent.onIncoming(async (call) => {
356
+ * if (call.callerIdRestricted) await call.reject({ reason: 'busy' });
357
+ * });
358
+ * ```
359
+ *
360
+ * - `call.reject()` 를 부르지 않고 돌아오면 받는다.
361
+ * - 5초 안에 끝나지 않거나 예외를 던지면 경고를 남기고 **받는다** — 선별 함수의 실수로 통화를
362
+ * 잃지 않게 한다.
363
+ * - 거절한 통화는 세션이 만들어지지 않으므로 `call_start`·`call_end` 등이 발화되지 않는다.
364
+ * - 다시 부르면 이전 함수를 바꾼다. 등록하지 않으면 동작은 예전과 같다.
365
+ */
366
+ onIncoming(handler: IncomingHandler): this;
367
+ /**
368
+ * Connect to the ClawOps platform and start listening for calls.
369
+ *
370
+ * Throws `AgentAuthRejectedError` right away when the server refuses the connection (the API
371
+ * key is revoked or expired, or the number is not this account's). Retrying gives the same
372
+ * answer — fix the key or number and start a new agent.
373
+ */
374
+ connect(): Promise<void>;
375
+ /**
376
+ * Connect and block until it is time to stop.
377
+ *
378
+ * Returns on SIGINT/SIGTERM, or when another process takes over this number — in every case
379
+ * after `drain()` has let in-flight calls finish. A second signal skips the wait and cuts them.
380
+ *
381
+ * ⚠️ **The takeover notice does not always arrive.** It is sent when a connection is replaced
382
+ * within the same gateway; if the new instance lands on a different one, the old instance is
383
+ * never told (measured in production, 2026-09-09). It then stays up — taking no new calls —
384
+ * until a stop signal, and drains there instead.
385
+ *
386
+ * Either way **calls always go to the newest instance**, because delivery is decided by the
387
+ * shared registry rather than any one gateway's. So zero-downtime holds regardless. What does
388
+ * not hold is "start the new one and the old one disappears" — a rolling deploy still has to
389
+ * take the old instance down.
390
+ *
391
+ * **There is no deadline by default.** In-flight calls are waited out and the only thing that
392
+ * ends them is the platform SIGKILL. The old default (110s) came from the ECS `stopTimeout`
393
+ * ceiling and was applied to k8s too, which is why **29.8% of in-flight calls were being cut
394
+ * by us** rather than finishing.
395
+ *
396
+ * Set the platform grace period (k8s `terminationGracePeriodSeconds`, ECS `stopTimeout`) to
397
+ * cover your calls. Where that grace is capped — ECS tops out at 120s — pass an explicit
398
+ * `shutdownDeadlineMs` slightly under it so the process cleans up on its own terms instead.
399
+ * A finite deadline is **shared** between the handover wait and the drain, never added.
400
+ *
401
+ * ⚠️ Without a deadline there is still a way out: a second stop signal skips the handover and
402
+ * a third cuts in-flight calls. SIGINT counts its first as the second, so two Ctrl-C's cut.
403
+ *
404
+ * @param options.drainTimeoutMs Passed through to `drain()`. Unbounded by default.
405
+ */
406
+ serve(options?: {
407
+ drainTimeoutMs?: number;
408
+ handoverWaitMs?: number;
409
+ shutdownDeadlineMs?: number;
410
+ /** Open `/healthz` on this port — the only probe a distroless image can answer. */
411
+ healthPort?: number;
412
+ }): Promise<void>;
413
+ private _serveInner;
414
+ private _handleTakenOver;
415
+ /**
416
+ * The server handed the slot to another process (`agent.retired`) — **the connection is
417
+ * still open.** It was left open so terminal events of calls already in progress come back
418
+ * here, so this must not close it. The server closes it once we are idle.
419
+ *
420
+ * Arriving with no stop signal means this is not a deploy we know about — almost always two
421
+ * instances running on the same number. Say so in the log.
422
+ */
423
+ private _handleRetired;
424
+ /**
425
+ * The server refused a reconnect for good — the key was revoked or the number reclaimed while
426
+ * running. No more calls can come here: drop readiness and wake serve() so it finishes the calls
427
+ * in progress and ends with `AgentAuthRejectedError`.
428
+ */
429
+ private _handleRejected;
430
+ /** No longer able to take calls — drop both readiness signals. Idempotent. */
431
+ private _notReady;
432
+ /** Whether another process has taken over this number's control connection. */
433
+ get takenOver(): boolean;
434
+ /**
435
+ * Stop accepting new calls, let the ones already in progress finish, then disconnect.
436
+ *
437
+ * This is what a rolling deploy needs. `disconnect()` cuts live calls mid-sentence, which is
438
+ * correct when you mean "stop now" and wrong when you mean "hand over". The two are separated
439
+ * because only the caller knows which one a SIGTERM meant.
440
+ *
441
+ * It works because control and media are different connections. Closing the control WebSocket
442
+ * only gives up this number's delivery slot — the server stops sending us `call.incoming` and
443
+ * routes new calls to whichever process holds the slot next. Calls already up keep streaming
444
+ * over their own per-call media connections, which nothing here touches, and each one tears
445
+ * itself down normally when the caller hangs up.
446
+ *
447
+ * Deploy shape this is built for: start the new instance, let it take the slot (the server
448
+ * hands it over and tells us not to reconnect), then drain the old one. New calls go to the
449
+ * new instance from the moment it connects; in-flight calls end on the old one. No gap.
450
+ *
451
+ * One thing is given up: `endedDuration` on `call_end`. That figure rides the control
452
+ * connection we just closed, so calls finishing during a drain report a null duration.
453
+ *
454
+ * @param options.timeoutMs How long to wait for in-flight calls. **Unbounded by default** —
455
+ * calls are waited out and only the platform SIGKILL ends them. Pass a value and calls still
456
+ * running when it expires are ended the way `disconnect()` ends them; that only makes sense
457
+ * where the platform grace period is capped (ECS `stopTimeout` tops out at 120s) and you would
458
+ * rather clean up on your own terms than be killed mid-drain.
459
+ * @returns How many calls ended on their own, and how many had to be cut short.
460
+ */
461
+ drain(options?: {
462
+ timeoutMs?: number;
463
+ /**
464
+ * Whether to give up the delivery slot ourselves.
465
+ *
466
+ * When the server has already sent the handover notice (`agent.retired`) the slot is gone
467
+ * anyway, so pass **false** and keep the connection: that is how the terminal events of
468
+ * in-flight calls — and their durations — still reach us. Only a shutdown without a
469
+ * handover has to release the slot itself.
470
+ */
471
+ releaseSlot?: boolean;
472
+ }): Promise<{
473
+ completed: number;
474
+ forced: number;
475
+ }>;
476
+ /** Disconnect from the platform. */
477
+ disconnect(): Promise<void>;
478
+ /**
479
+ * Initiate an outbound call.
480
+ * Matches Python SDK: agent.call(to, { timeout, machineDetection })
481
+ *
482
+ * @param options.machineDetection 자동응답기/음성사서함 감지(AMD).
483
+ * `'Enable'`=감지 후 `AnsweredBy` 통보(통화 계속), `'Hangup'`=음성사서함 감지 시 자동 종료.
484
+ * 미지정 시 인스턴스 default(생성자의 `machineDetection`)를 따른다.
485
+ * 우선순위: 호출 인자 > 인스턴스 default > 비활성.
486
+ */
487
+ call(to: string, options?: {
488
+ timeout?: number;
489
+ machineDetection?: 'Enable' | 'Hangup';
490
+ }): Promise<CallSession>;
491
+ /**
492
+ * 선별 함수가 없으면 예전 그대로 동기로 받는다(세션 생성 → call.accept → 미디어). 있으면
493
+ * 선별을 거친 뒤 같은 경로로 받거나, call.reject 를 보내고 끝낸다.
494
+ */
495
+ private _handleIncoming;
496
+ private _screenIncoming;
497
+ /**
498
+ * `IncomingCall.transfer()` — AI 세션 없이 받아서 곧바로 넘긴다.
499
+ *
500
+ * Session 은 만들지 않고 통화 이벤트(`call_start` 등)도 없다. 서버의 `call.ended` 가 상태를
501
+ * 채울 수 있게 `_activeSessions` 에만 올린다.
502
+ */
503
+ private _acceptForTransfer;
504
+ /**
505
+ * 미디어만 붙이고, 서버가 통화를 받으면(발신자 음성이 흐르면) 전환을 요청한다.
506
+ *
507
+ * 서버는 미디어 WS 가 붙은 **뒤에** 통화를 받고 전환 가능한 상태(mediaSession)를 만든다. 그 전의
508
+ * 전환은 `No active media session` 으로 거절되므로 첫 음성 프레임을 기다리고, 그래도 거절되면
509
+ * 짧게 다시 시도한다.
510
+ *
511
+ * 요청이 나간 뒤에는 SDK 가 통화를 끊지 않는다 — 전환·실패 안내·종료는 서버 몫이고, 끝나면 서버가
512
+ * 미디어를 닫는다. SDK 가 끊는 경우는 둘뿐이다: 요청을 아예 보내지 못했을 때, 그리고 시작 전
513
+ * 거절(사유가 있는 failed: 번호 오류 등)이라 서버가 통화를 그대로 두었을 때. 그동안
514
+ * `_activeSessions` 에 남아 있으므로 drain 은 이 통화가 끝나기를 기다린다.
515
+ */
516
+ private _runTransferOnly;
517
+ private _acceptIncoming;
518
+ /**
519
+ * 서버 종료 프레임을 짧게 기다린다. 미디어 정리 직후에만 부른다.
520
+ *
521
+ * 왜 기다리나: `call_end` 는 인바운드 사용자가 통화 결과를 받는 **유일한 통로**인데, 서버는
522
+ * 미디어 WS 를 먼저 닫고 자원 정리를 마친 뒤에야 control 종료 프레임을 보낸다. 안 기다리면
523
+ * 그 핸들러 안에서 `endedDuration` 은 영영 null 이다.
524
+ *
525
+ * 상한을 다 쓰는 경우는 제어 연결이 죽어 프레임이 아예 안 오는 때뿐이다 — 그 프레임은
526
+ * 예전부터 늘 오던 것이고(이번에 바뀐 건 내용뿐), 정상 경로에서는 밀리초 안에 풀린다.
527
+ */
528
+ private _awaitServerTerminal;
529
+ private _handleEnded;
530
+ /**
531
+ * Drop prewarm bookkeeping for a callId. Used on hangup/failure paths.
532
+ *
533
+ * prewarm 이 진행 중이거나 완료됐지만 attach 전에 호출되면 LLM WS 가 leak 되므로
534
+ * race 후 session.stop() 으로 정리한다. (TS 에는 Promise.cancel 이 없어 Python
535
+ * 의 task.cancel() 등가물은 _session.stop() 호출이다.)
536
+ *
537
+ * 이미 attach 된 callId 면 stop() 을 호출하지 않는다 — 정상 종료 경로 (call-session
538
+ * finally) 가 책임지기 때문이다.
539
+ */
540
+ private _cleanupPrewarm;
541
+ private _handleOutboundReady;
542
+ /**
543
+ * Start the LLM session prewarm task for the given callId. Safe to call
544
+ * multiple times — only the first invocation starts the task. Failures are
545
+ * recorded in _prewarmFailed so the call-session path can fall back to start().
546
+ */
547
+ /**
548
+ * 세션에 콜별 의존성(도구·내장도구·hold audio·recorder·logger)을 주입한다.
549
+ *
550
+ * prewarm 과 _startCallSession 양쪽에서 부른다. prewarm 은 세션이 LLM 에 보낼
551
+ * tool 스키마를 그 시점에 확정하므로(OpenAI session.update / Gemini live connect
552
+ * config), prewarm **전에** 최소 한 번은 도구가 들어가 있어야 한다.
553
+ */
554
+ private _injectSessionDeps;
555
+ private _startPrewarm;
556
+ private _handleRinging;
557
+ private _handleFailed;
558
+ /**
559
+ * 키 하나를 수집 중인 collectDtmf 로, 아니면 모델 자동 전달로 보낸다. 한 키는 둘 중 한 곳으로만 간다.
560
+ *
561
+ * 자동 전달 버퍼는 **통화별**(`CallSession`)이다. 예전엔 에이전트에 하나뿐이라 동시 통화 두 건이
562
+ * 대기 창 안에서 누르면 키가 합쳐져 마지막 통화 하나로만 갔다.
563
+ */
564
+ private _onDtmfEvent;
565
+ /** 대기 없이 지금까지 모인 키를 확정해 전달한다. */
566
+ private _confirmPassiveDtmf;
567
+ /**
568
+ * _startCallSession 의 예외를 잡아 control WS 로 call.session_failed 전송한다.
569
+ *
570
+ * OpenAI/Gemini API 키 누락 등 session.start() 단계 실패는 media WS connect 에
571
+ * 도달하지 못해 call-engine 이 30 초간 무음 통화를 유지하게 만든다. 서버에 즉시
572
+ * 알려서 fail-fast 시키고 _activeSessions 에서 정리한다.
573
+ */
574
+ private _safeStartCallSession;
575
+ private _startCallSession;
576
+ }
577
+
578
+ /**
579
+ * Control WebSocket for agent signaling (call.incoming, call.ended, etc.).
580
+ */
581
+
582
+ interface ControlWsOptions {
583
+ baseUrl: string;
584
+ apiKey: string;
585
+ accountId: string;
586
+ /** Phone number to register on. */
587
+ number?: string;
588
+ /**
589
+ * Called when the server closes the connection with a code that means "do not reconnect"
590
+ * (the number was handed to another process, or is no longer owned by this account).
591
+ * Reconnection has already been abandoned by the time this fires.
592
+ */
593
+ onTerminalClose?: (info: {
594
+ code: number;
595
+ reason: string;
596
+ }) => void;
597
+ /**
598
+ * Called when the server refuses the handshake for good (revoked key, number not owned …).
599
+ * Reconnection has already been abandoned by the time this fires.
600
+ */
601
+ onRejected?: (err: AgentAuthRejectedError) => void;
602
+ }
603
+ /**
604
+ * Control event is a flat JSON object with an 'event' field.
605
+ * Example: { "event": "call.incoming", "callId": "xxx", "from": "010...", "to": "070...",
606
+ * "mediaUrl": "wss://...", "callerIdRestricted": false }
607
+ * Replies to call.incoming (SDK → server):
608
+ * { "event": "call.accept", "callId": "xxx" }
609
+ * { "event": "call.reject", "callId": "xxx", "reason": "rejected" | "busy" } // agent.onIncoming()
610
+ * reason is mandatory — a reject without it is treated as an agent failure and falls back.
611
+ */
612
+ interface ControlEvent {
613
+ event: string;
614
+ [key: string]: unknown;
615
+ }
616
+ type ControlEventHandler = (event: ControlEvent) => void | Promise<void>;
617
+ /**
618
+ * Build the full control WebSocket URL from options.
619
+ * Matches Python SDK: /v1/accounts/{account_id}/agent/listen?number={number}
620
+ */
621
+ declare function buildControlWsUrl(options: ControlWsOptions, role?: string): string;
622
+ declare class ControlWebSocket {
623
+ private readonly _options;
624
+ private _url;
625
+ private _ws;
626
+ private _handlers;
627
+ /**
628
+ * Keyed by `requestId`, not `callId`: `afterTransfer: 'return'` comes back to the agent and can
629
+ * transfer again on the same call, and a second wait must not overwrite the first.
630
+ */
631
+ private _transferResolvers;
632
+ private _transferCleanupTimers;
633
+ private _connectionLostWaiters;
634
+ private _reconnectDelay;
635
+ private _closed;
636
+ private _connectedResolve;
637
+ private _connectedReject;
638
+ private _connectedPromise;
639
+ private _rejected;
640
+ private _log;
641
+ private _pingTimer;
642
+ private _lameDuck;
643
+ setLogger(logger: Logger): void;
644
+ constructor(_options: ControlWsOptions);
645
+ /** Stop reconnecting for good — this process is stepping down. Not reversible. */
646
+ enterLameDuck(): void;
647
+ get lameDuck(): boolean;
648
+ /** Register an event handler for a specific event type. */
649
+ on(event: string, handler: ControlEventHandler): void;
650
+ /** Connect to the control WebSocket. */
651
+ connect(): Promise<void>;
652
+ /**
653
+ * Wait until the WebSocket is connected.
654
+ *
655
+ * Rejects with `AgentAuthRejectedError` as soon as the server refuses the handshake for good —
656
+ * before, it never settled and the reconnect loop ran on in the background.
657
+ */
658
+ waitConnected(): Promise<void>;
659
+ /** The refusal that stopped this connection, if any. */
660
+ get rejected(): AgentAuthRejectedError | null;
661
+ /**
662
+ * Request a call transfer and wait for the result.
663
+ *
664
+ * Rejects with `AgentConnectionError` before anything starts waiting when there is no open
665
+ * connection. After a drop this object stays alive and reconnecting for a second or more, so the
666
+ * agent's own `_controlWs` check does not cover that window. It does not wait for the reconnect:
667
+ * a transfer moves a customer who is on the line now, and nobody knows when the connection returns.
668
+ */
669
+ requestTransfer(callId: string, params: Record<string, unknown>): Promise<Record<string, unknown>>;
670
+ /**
671
+ * Resolves when the current connection drops — at once if there is none. Result events are not
672
+ * resent, so after this a pending transfer result may never come. `cancel` drops the wait.
673
+ */
674
+ connectionLost(): {
675
+ promise: Promise<void>;
676
+ cancel: () => void;
677
+ };
678
+ private _fireConnectionLost;
679
+ /**
680
+ * Which request a result event answers. The server echoes `requestId`; without it (an older
681
+ * server) fall back to `callId`, only when that call has exactly one wait.
682
+ */
683
+ private _resolveTransferRequest;
684
+ /** After `call.ended` no result is coming: release the wait so the caller does not hang. */
685
+ private _scheduleTransferCleanup;
686
+ /** Send a JSON message over the control WebSocket. */
687
+ send(message: Record<string, unknown>): void;
688
+ /** Close the WebSocket and stop reconnecting. */
689
+ close(): void;
690
+ private _doConnect;
691
+ private _dispatchEvent;
692
+ private _resetPingTimer;
693
+ private _clearPingTimer;
694
+ private _scheduleReconnect;
695
+ }
696
+
697
+ interface MediaStartEvent {
698
+ streamId: string;
699
+ callId: string;
700
+ accountId: string;
701
+ sampleRate: number;
702
+ }
703
+ interface MediaEvent {
704
+ audio: Buffer;
705
+ timestamp: number;
706
+ }
707
+ interface DtmfEvent {
708
+ digit: string;
709
+ track: string;
710
+ }
711
+ declare class MediaWebSocket {
712
+ private readonly options;
713
+ private _ws;
714
+ private _audioQueue;
715
+ private _sendLoopRunning;
716
+ private _closed;
717
+ private _onAudio;
718
+ private _onStart;
719
+ private _onClose;
720
+ private _onDtmf;
721
+ private _markWaiters;
722
+ /** 마지막으로 오디오를 큐에 넣은 시각(ms). 재생 끝 판정의 「조용한 구간」 기준. */
723
+ private _lastAudioAt;
724
+ private _log;
725
+ private _formatValidated;
726
+ constructor(options?: {
727
+ expectedMediaProfile?: MediaProfile;
728
+ });
729
+ setLogger(logger: Logger): void;
730
+ /** Set the handler for inbound audio data. */
731
+ onAudio(handler: (audio: Buffer, timestamp: number) => void): void;
732
+ /** Set the handler for the start event. */
733
+ onStart(handler: (event: MediaStartEvent) => void): void;
734
+ /** Set the handler for connection close. */
735
+ onClose(handler: () => void): void;
736
+ /** Set the handler for inbound DTMF events. */
737
+ onDtmf(handler: (digit: string) => void): void;
738
+ /** Send a single DTMF digit to the platform. */
739
+ sendDtmf(digit: string): void;
740
+ /** Whether the WebSocket is connected. */
741
+ get isConnected(): boolean;
742
+ /**
743
+ * Connect to a media WebSocket URL.
744
+ *
745
+ * 인증은 서버가 준 URL 의 1회용 `token` 하나다. 두 번째 인자(API 키)는 호환을 위해 받기만 하고
746
+ * 쓰지 않는다 — 예전엔 `Authorization: Bearer` 로 실었지만 서버는 그 헤더를 읽은 적이 없고,
747
+ * 서버가 `ws://` 를 주던 동안엔 계정 API 키가 평문 첫 요청에 실려 나갔다(clawops#1250).
748
+ */
749
+ connect(url: string, _apiKey?: string): Promise<void>;
750
+ /** Queue base64-encoded audio for sending. */
751
+ sendAudio(audioBase64: string): void;
752
+ /** Clear all queued outbound audio. */
753
+ sendClear(): void;
754
+ /** Send a mark event. */
755
+ sendMark(name: string): void;
756
+ /** Wait for all queued audio to be sent. */
757
+ flush(): Promise<void>;
758
+ /** Wait for a named mark to be echoed back by the server. */
759
+ waitForMark(name: string, timeoutMs?: number): Promise<void>;
760
+ /**
761
+ * 지금까지 보낸 오디오가 발신자에게 다 재생될 때까지 기다린다. 재생 끝 echo 를 받았으면 `true`.
762
+ *
763
+ * 서버는 mark 앞의 오디오를 RTP 로 다 내보낸 뒤 mark 를 돌려주고, `clear` 때는 남은 mark 를
764
+ * 즉시 돌려준다(Twilio Media Streams 와 같은 의미). 그래서 순서가 중요하다.
765
+ * - 오디오는 송신 큐를 거치고 mark 는 바로 나가므로, 큐를 먼저 비워야 mark 가 오디오를 앞지르지 않는다.
766
+ * - 오디오가 조각조각 이어서 들어오는 중이면(TTS 를 만들면서 흘려 보내는 경로) 큐가 잠깐 빈 틈을
767
+ * 재생 끝으로 보게 된다. 새 오디오가 {@link PLAYOUT_QUIET_MS} 동안 안 들어온 뒤에 보낸다.
768
+ * - 재생할 게 없으면 echo 가 곧장 오므로 waiter 를 **보내기 전에** 건다.
769
+ *
770
+ * `signal` 이 abort 되면(먼저 키가 눌렸을 때) 기다림을 접고 `false` 를 돌려준다 — 타이머가
771
+ * 남아 이벤트 루프를 붙잡지 않게.
772
+ */
773
+ waitPlayedOut(timeoutMs: number, signal?: AbortSignal): Promise<boolean>;
774
+ /** Close the media WebSocket. */
775
+ close(): void;
776
+ private _handleMessage;
777
+ private _startSendLoop;
778
+ }
779
+
780
+ /**
781
+ * Audio codec utilities: PCM16 <-> ulaw conversion and resampling.
782
+ */
783
+ declare const DECODE_TABLE: readonly number[];
784
+ /**
785
+ * Convert PCM16 little-endian audio to ulaw.
786
+ */
787
+ declare function pcm16ToUlaw(pcm: Buffer): Buffer;
788
+ /**
789
+ * Convert ulaw audio to PCM16 little-endian.
790
+ */
791
+ declare function ulawToPcm16(ulaw: Buffer): Buffer;
792
+ /**
793
+ * Resample PCM16 audio using linear interpolation.
794
+ */
795
+ declare function resamplePcm16(pcm: Buffer, fromRate: number, toRate: number): Buffer;
796
+
797
+ declare class AudioRecorder {
798
+ private readonly _dir;
799
+ private _fdIn;
800
+ private _fdOut;
801
+ private _fdMix;
802
+ private _inWritten;
803
+ private _outWritten;
804
+ private _mixWritten;
805
+ private _started;
806
+ private _baseTs;
807
+ private _outCursor;
808
+ private _log;
809
+ setLogger(logger: Logger): void;
810
+ constructor(recordingPath: string, callId: string);
811
+ start(): void;
812
+ private _timestampToBytes;
813
+ private _padSilence;
814
+ private _writeToMix;
815
+ writeInbound(pcm16_8k: Buffer, mediaTsMs?: number): void;
816
+ writeOutbound(pcm16_8k: Buffer, mediaTsMs?: number): void;
817
+ stop(): void;
818
+ }
819
+
820
+ /**
821
+ * PipelineSession orchestrates STT -> LLM -> TTS for a voice call.
822
+ */
823
+
824
+ interface PipelineSessionOptions {
825
+ stt: STT;
826
+ llm: LLM;
827
+ tts: TTS;
828
+ /** System prompt for the LLM. */
829
+ systemPrompt?: string;
830
+ /** Send initial greeting. Default: true */
831
+ greeting?: boolean;
832
+ /** Language code. Default: 'ko' */
833
+ language?: string;
834
+ /** Tool registry for function calling. */
835
+ toolRegistry?: ToolRegistry;
836
+ /** Audio recorder for the session. */
837
+ recorder?: AudioRecorder;
838
+ /** LLM temperature. */
839
+ temperature?: number;
840
+ /** Max tokens for LLM generation. */
841
+ maxTokens?: number;
842
+ /** Sample rate for audio. Default: 8000 */
843
+ sampleRate?: number;
844
+ /** Whether to interrupt TTS when user starts speaking. Default: true */
845
+ interruptOnSpeech?: boolean;
846
+ }
847
+ declare class PipelineSession implements Session {
848
+ private _stt;
849
+ private _llm;
850
+ private _tts;
851
+ private _systemPrompt;
852
+ private _greeting;
853
+ private _language;
854
+ private _temperature;
855
+ private _maxTokens;
856
+ private _sampleRate;
857
+ private _interruptOnSpeech;
858
+ private _callSession;
859
+ private _tools;
860
+ private _recorder;
861
+ private _conversation;
862
+ private _audioBuffer;
863
+ private _running;
864
+ private _speaking;
865
+ private _builtinTools;
866
+ private _holdAudioChunks;
867
+ private _log;
868
+ constructor(options: PipelineSessionOptions);
869
+ setToolRegistry(registry: ToolRegistry): void;
870
+ setRecorder(recorder: AudioRecorder): void;
871
+ setBuiltinTools(tools: Set<BuiltinTool>): void;
872
+ /** Tool 실행 중 재생할 hold audio 청크를 설정한다. */
873
+ setHoldAudio(chunks: Buffer[]): void;
874
+ getTelemetry(): SessionTelemetry;
875
+ setLogger(logger: Logger): void;
876
+ /**
877
+ * Pre-bootstrap conversation state and (optionally) trigger greeting synthesis
878
+ * before a real CallSession is attached. Audio chunks are buffered into a
879
+ * BufferingCall until attach() flushes them.
880
+ */
881
+ prewarm(tools?: ToolRegistry): Promise<void>;
882
+ /** Attach a real CallSession to the prewarmed session and flush buffered audio. */
883
+ attach(callSession: CallSession): Promise<void>;
884
+ start(callSession: CallSession, tools?: ToolRegistry): Promise<void>;
885
+ feedAudio(audio: Buffer): void;
886
+ feedDtmf(digits: string): Promise<void>;
887
+ stop(): Promise<void>;
888
+ private _runSttLoop;
889
+ private _createAudioStream;
890
+ private _generateGreeting;
891
+ private _handleUserSpeech;
892
+ private _buildEffectiveTools;
893
+ private _respond;
894
+ private _handleToolCall;
895
+ private _synthesizeAndSend;
896
+ }
897
+
898
+ /**
899
+ * OpenAI Realtime API session (speech-to-speech).
900
+ *
901
+ * Matches Python SDK's OpenAIRealtime implementation.
902
+ */
903
+
904
+ interface OpenAIRealtimeOptions {
905
+ /** OpenAI API key. Falls back to OPENAI_API_KEY env var. */
906
+ apiKey?: string;
907
+ /** System prompt / instructions for the AI. */
908
+ systemPrompt?: string;
909
+ /** Model to use. Default: 'gpt-realtime-2' */
910
+ model?: string;
911
+ /** Voice ID. Default: 'marin' */
912
+ voice?: string;
913
+ /** Language code (BCP 47). Default: 'ko' */
914
+ language?: string;
915
+ /**
916
+ * Turn detection configuration. Default: semantic_vad with eagerness 'low'.
917
+ * - `{ type: 'semantic_vad', eagerness?: 'low'|'medium'|'high'|'auto', create_response?: boolean, interrupt_response?: boolean }`
918
+ * - `{ type: 'server_vad', threshold?: number, silence_duration_ms?: number, prefix_padding_ms?: number }`
919
+ * - `null` to disable turn detection
920
+ */
921
+ turnDetection?: Record<string, unknown> | null;
922
+ /** Send initial greeting. Default: true */
923
+ greeting?: boolean;
924
+ /**
925
+ * 발신자 음성 **전사**에 넘기는 어휘 힌트(자유 문장). 예: `'재진, 초진, 예약 변경, 직원 연결'`.
926
+ * 전사 텍스트(`transcript` 이벤트)의 정확도에만 영향을 주며, 모델이 오디오를 알아듣는
927
+ * 방식은 바뀌지 않는다 — 모델 쪽 어휘는 `systemPrompt` 에 적는다. 빈 문자열은 보내지 않는다.
928
+ */
929
+ transcriptionPrompt?: string;
930
+ }
931
+ declare class OpenAIRealtime implements Session {
932
+ private _apiKey;
933
+ private _transcriptionPrompt;
934
+ private _systemPrompt;
935
+ private _model;
936
+ private _voice;
937
+ private _language;
938
+ private _turnDetection;
939
+ private _greeting;
940
+ private _log;
941
+ private _builtinTools;
942
+ /**
943
+ * 마지막 session.update 로 LLM 에 알린 tool 이름들. attach() 가 이 값과 현재
944
+ * registry 를 비교해 달라졌을 때만(=MCP 도구 등 뒤늦게 붙은 경우) 재전송한다.
945
+ */
946
+ private _sentToolNames;
947
+ setLogger(logger: Logger): void;
948
+ setBuiltinTools(tools: Set<BuiltinTool>): void;
949
+ getTelemetry(): SessionTelemetry;
950
+ private _ws;
951
+ private _call;
952
+ private _tools;
953
+ private _recorder;
954
+ private _closed;
955
+ private _playback;
956
+ private _latestMediaTs;
957
+ private _pendingToolCalls;
958
+ private _responseInProgress;
959
+ private _onResponseDone;
960
+ private _holdAudioChunks;
961
+ constructor(options?: OpenAIRealtimeOptions);
962
+ /** Inject per-call ToolRegistry. */
963
+ setToolRegistry(registry: ToolRegistry): void;
964
+ /** Inject per-call AudioRecorder. */
965
+ setRecorder(recorder: AudioRecorder): void;
966
+ /** Tool 실행 중 재생할 hold audio 청크를 설정한다. */
967
+ setHoldAudio(chunks: Buffer[]): void;
968
+ /** Open WS + session.update + (optional) response.create without a CallSession. */
969
+ prewarm(tools?: ToolRegistry): Promise<void>;
970
+ /** Attach a real CallSession to the prewarmed session and flush buffered audio. */
971
+ attach(callSession: CallSession): Promise<void>;
972
+ start(callSession: CallSession, tools?: ToolRegistry): Promise<void>;
973
+ feedDtmf(digits: string): Promise<void>;
974
+ feedAudio(audio: Buffer, timestamp?: number): void;
975
+ stop(): Promise<void>;
976
+ /** Current tool schemas: user tools + builtin tools (flat realtime format). */
977
+ private _currentToolSchemas;
978
+ /**
979
+ * prewarm 이후 도구가 바뀌었으면 session.update 로 재전송한다.
980
+ *
981
+ * MCP 도구는 통화 시작 시점에 registry 에 붙으므로 prewarm 시점의 스키마에는
982
+ * 없다. 여기서 맞춰주지 않으면 발신 통화에서 MCP 도구를 영영 못 쓴다.
983
+ */
984
+ private _resyncTools;
985
+ private _sendSessionUpdate;
986
+ private _handleMessage;
987
+ private _handleAudioDelta;
988
+ private _handleTruncation;
989
+ private _handleToolCall;
990
+ private _waitForResponseDone;
991
+ private _send;
992
+ }
993
+
994
+ /**
995
+ * Google Gemini Realtime API session (speech-to-speech).
996
+ *
997
+ * Uses @google/genai SDK's live.connect() method.
998
+ * Matches Python SDK's GeminiRealtime implementation (v0.14.0).
999
+ */
1000
+
1001
+ /** Gemini Live 함수 선언의 `behavior` 허용값(= `ToolBehavior`). */
1002
+ type GeminiToolBehavior = ToolBehavior;
1003
+ declare const GEMINI_TOOL_BEHAVIORS: readonly GeminiToolBehavior[];
1004
+ declare function isExtendedThinkingModel(model: string): boolean;
1005
+ /**
1006
+ * 모델별 함수 호출 `behavior` 기본값.
1007
+ *
1008
+ * - `gemini-3.8-live-extended-thinking` 은 NON_BLOCKING 만 받고 BLOCKING 은 하드 에러다.
1009
+ * - `gemini-3.8-live` 는 서버 기본값이 NON_BLOCKING 으로 바뀌었다(모델 페이지 「Migrating from
1010
+ * Gemini 3.1 Flash Live」). behavior 를 안 보내면 서버는 도구를 비동기로 돌려, 도구 결과를
1011
+ * 기다리는 동안 모델이 계속 말한다. 전화 SDK 는 결과를 기다리는 동안 모델이 말하지 않아야
1012
+ * 하므로 BLOCKING 을 명시해 3.1 과 같은 동작을 복원한다.
1013
+ * - 그 외(3.1 등)는 보내지 않는다(서버 기본값 = 동기).
1014
+ *
1015
+ * LiveKit `livekit-plugins-google` 의 `_default_tool_behavior` 와 같은 자리이되, 기본값 방향은
1016
+ * 반대다(LiveKit 은 3.8 에 NON_BLOCKING 을 명시한다).
1017
+ */
1018
+ declare function defaultToolBehavior(model: string): GeminiToolBehavior | null;
1019
+ interface GeminiRealtimeOptions {
1020
+ /** Google API key. Falls back to GOOGLE_API_KEY env var. */
1021
+ apiKey?: string;
1022
+ /** System prompt / instructions for the AI. */
1023
+ systemPrompt?: string;
1024
+ /** Model to use. Default: 'gemini-3.1-flash-live-preview' */
1025
+ model?: string;
1026
+ /** Voice name. Default: 'Kore' */
1027
+ voice?: string;
1028
+ /** Language code. Default: 'ko' */
1029
+ language?: string;
1030
+ /** Send initial greeting. Default: true */
1031
+ greeting?: boolean;
1032
+ /** Gemini VAD config. @google/genai RealtimeInputConfig 구조 그대로 전달. */
1033
+ realtimeInputConfig?: Record<string, unknown>;
1034
+ /**
1035
+ * 입력 음성 전사 설정. @google/genai AudioTranscriptionConfig 구조 그대로 `inputAudioTranscription` 에 실린다.
1036
+ * `languageCodes`(BCP-47 목록)·`customVocabulary`(최대 1,000개)를 받는다. 지정하지 않으면 `{}`.
1037
+ */
1038
+ inputAudioTranscription?: Record<string, unknown>;
1039
+ /**
1040
+ * Gemini thinking 설정. @google/genai ThinkingConfig 구조 그대로 전달.
1041
+ * `gemini-3.8-live-extended-thinking` 은 `{ thinkingLevel: 'LOW' | 'MEDIUM' | 'HIGH' }` 이 필수다.
1042
+ */
1043
+ thinkingConfig?: Record<string, unknown>;
1044
+ /**
1045
+ * Gemini proactive audio. `proactivity.proactiveAudio` 에 그대로 실린다.
1046
+ * 3.8 두 모델은 영구 ON 이라 `false` 를 보내면 거절되고, 3.1 은 미지원이다. 지정하지 않으면 보내지 않는다.
1047
+ */
1048
+ proactiveAudio?: boolean;
1049
+ /**
1050
+ * 함수 선언의 `behavior`. 지정하지 않으면 모델별 기본값({@link defaultToolBehavior}):
1051
+ * `gemini-3.8-live` 는 BLOCKING, `gemini-3.8-live-extended-thinking` 은 NON_BLOCKING, 그 외는 보내지 않음.
1052
+ */
1053
+ toolBehavior?: GeminiToolBehavior;
1054
+ /**
1055
+ * NON_BLOCKING 도구 결과의 기본 `scheduling`(`SILENT`·`WHEN_IDLE`·`INTERRUPT`). 도구별 값이 이를 덮는다.
1056
+ * BLOCKING 결과에는 서버가 무시하고, extended-thinking 은 거절하므로 보내지 않는다.
1057
+ */
1058
+ toolResponseScheduling?: ToolScheduling;
1059
+ /** Gemini API 버전(`v1beta` 기본). `GoogleGenAI({ httpOptions: { apiVersion } })` 로 넘긴다. */
1060
+ apiVersion?: string;
1061
+ /**
1062
+ * Gemini `contextWindowCompression` 그대로 전달. 압축을 켜지 않은 오디오 세션은 15분에서 끝나므로
1063
+ * 긴 통화에는 `{ slidingWindow: {} }` 를 권장. 지정하지 않으면 보내지 않는다.
1064
+ */
1065
+ contextWindowCompression?: Record<string, unknown>;
1066
+ /**
1067
+ * 세션 재접속(기본 true). 접속 때마다 `sessionResumption` 핸들을 보내 서버가 주는 새 핸들을 보관하고,
1068
+ * `goAway`(연결 약 10분 한도)·예기치 않은 끊김에서 그 핸들로 다시 접속해 대화를 이어 간다.
1069
+ */
1070
+ sessionResumption?: boolean;
1071
+ /** 재접속 시도 상한(기본 3). 다 실패하면 통화에 `session_lost` 를 알리고 끊는다. */
1072
+ reconnectMaxAttempts?: number;
1073
+ }
1074
+ declare class GeminiRealtime implements Session {
1075
+ /**
1076
+ * Gemini Live 는 connect 시점의 config 로 도구가 고정되어 세션 도중 변경할 수 없다.
1077
+ *
1078
+ * 통화 시작 시점에야 붙는 MCP 도구는 prewarm 된 세션에 넣을 방법이 없으므로,
1079
+ * `ClawOpsAgent` 가 MCP 서버 설정과 이 플래그를 보고 prewarm 을 건너뛴다.
1080
+ */
1081
+ readonly toolsFrozenAfterPrewarm = true;
1082
+ private _apiKey;
1083
+ private _systemPrompt;
1084
+ private _model;
1085
+ private _voice;
1086
+ private _language;
1087
+ private _greeting;
1088
+ private _realtimeInputConfig;
1089
+ private _inputAudioTranscription;
1090
+ private _thinkingConfig;
1091
+ private _proactiveAudio;
1092
+ private _toolBehavior;
1093
+ private _toolResponseScheduling;
1094
+ private _apiVersion;
1095
+ private _traceT0;
1096
+ private _declaredBehavior;
1097
+ private _declaredScheduling;
1098
+ private _inflight;
1099
+ private _schedulingDroppedWarned;
1100
+ private _contextWindowCompression;
1101
+ private _sessionResumption;
1102
+ private _reconnectMaxAttempts;
1103
+ private _resumptionHandle;
1104
+ private _reconnecting;
1105
+ private _stopping;
1106
+ private _client;
1107
+ private _session;
1108
+ private _call;
1109
+ private _tools;
1110
+ private _recorder;
1111
+ private _closed;
1112
+ private _sentAudioChunks;
1113
+ private _audioRemainder;
1114
+ private _builtinTools;
1115
+ private _pendingToolCall;
1116
+ private _toolDrainTimer;
1117
+ private _lastAudioTime;
1118
+ private _holdAudioChunks;
1119
+ private _log;
1120
+ constructor(options?: GeminiRealtimeOptions);
1121
+ /**
1122
+ * 선언 하나에 실을 behavior 를 정한다.
1123
+ * - extended-thinking 은 NON_BLOCKING 만 받으므로 무엇을 요청해도 NON_BLOCKING(요청이 BLOCKING 이면 경고).
1124
+ * - 내장 도구(hang_up·collect_dtmf·send_dtmf·transfer_call)는 통화 제어라 항상 BLOCKING —
1125
+ * NON_BLOCKING 이면 모델이 끊기·전환 중에도 말을 이어 가 음성이 잘린다.
1126
+ * - 그 외는 도구별 요청 → 세션 기본값 순.
1127
+ */
1128
+ private _behaviorFor;
1129
+ /**
1130
+ * 응답에 실을 `scheduling`. NON_BLOCKING 선언에만 의미가 있고 BLOCKING 엔 서버가 무시한다.
1131
+ * extended-thinking 은 scheduling 을 거절(1007 "Function response scheduling is not supported")하므로
1132
+ * 절대 보내지 않는다. 결과가 없고(=모델에 전할 말이 없음) 따로 정한 값이 없으면 SILENT.
1133
+ */
1134
+ private _schedulingFor;
1135
+ /** 이 세션의 함수 선언에 실리는 `behavior`. 지정이 없으면 모델별 기본값. */
1136
+ effectiveToolBehavior(): GeminiToolBehavior | null;
1137
+ /** `CLAWOPS_GEMINI_DEBUG=1` 일 때만 서버·클라이언트 이벤트를 한 줄로 남긴다. */
1138
+ private _trace;
1139
+ private _traceMessage;
1140
+ /** Inject per-call ToolRegistry. */
1141
+ setToolRegistry(registry: ToolRegistry): void;
1142
+ /** Inject per-call AudioRecorder. */
1143
+ setRecorder(recorder: AudioRecorder): void;
1144
+ setBuiltinTools(tools: Set<BuiltinTool>): void;
1145
+ /** Tool 실행 중 재생할 hold audio 청크를 설정한다. */
1146
+ setHoldAudio(chunks: Buffer[]): void;
1147
+ setLogger(logger: Logger): void;
1148
+ getTelemetry(): SessionTelemetry;
1149
+ /** Open Live session (no CallSession). Audio deltas accumulate into BufferingCall until attach(). */
1150
+ prewarm(tools?: ToolRegistry): Promise<void>;
1151
+ /** Live 연결 하나를 연다(setupComplete 까지 기다림). prewarm 과 재접속이 함께 쓴다. */
1152
+ private _connect;
1153
+ /** 연결 하나를 조용히 닫는다. 서버가 세션을 놓아야 같은 핸들로 다시 붙을 수 있다. */
1154
+ private _closeQuietly;
1155
+ /**
1156
+ * 같은 대화를 새 연결로 이어 간다(sessionResumption 핸들).
1157
+ * 순서: 옛 연결을 먼저 닫는다(서버가 세션을 놓게) → 핸들로 재접속(상한만큼, 백오프 1/2/4초) → 그래도 안 되면
1158
+ * 핸들 없이 새 세션으로 이어 간다(대화 기억은 잃지만 통화는 산다) → 그것마저 실패하면 통화에 `session_lost` 를
1159
+ * 알리고 끊는다. 모델만 사라진 채 통화가 무음으로 이어지는 것이 가장 나쁜 실패다.
1160
+ *
1161
+ * 2026-10-10 실측(Python): setup 이 안 끝나 버린 연결이 서버엔 살아 있어 다음 시도가 1008 "session is already
1162
+ * connected to an existing client" 로 거절됐다. 그래서 실패한 시도의 연결도 반드시 닫는다.
1163
+ */
1164
+ private _reconnect;
1165
+ /** 재접속을 포기했다. 통화 쪽에 알리고 끊는다(무음 방치 금지). */
1166
+ private _onSessionLost;
1167
+ /** Attach a real CallSession to the prewarmed session and flush buffered audio. */
1168
+ attach(callSession: CallSession): Promise<void>;
1169
+ start(callSession: CallSession, tools?: ToolRegistry): Promise<void>;
1170
+ feedAudio(audio: Buffer): void;
1171
+ feedDtmf(digits: string): Promise<void>;
1172
+ stop(): Promise<void>;
1173
+ private _buildToolSchemas;
1174
+ /**
1175
+ * 서버 메시지 하나를 처리한다. `stale` 은 재접속으로 교체된 옛 연결에서 온 메시지다 — 남은 오디오·전사는
1176
+ * 그대로 흘리되 goAway·sessionResumptionUpdate·toolCall 같은 제어 메시지는 무시한다(옛 연결의 늦은
1177
+ * goAway 가 재접속을 또 일으키거나 옛 핸들이 새 핸들을 덮으면 안 된다).
1178
+ */
1179
+ private _handleMessage;
1180
+ /**
1181
+ * NON_BLOCKING 호출은 즉시 실행하고, BLOCKING 호출만 묶어 돌려준다(drain 뒤 실행).
1182
+ * NON_BLOCKING 은 서버가 결과를 기다리지 않고 모델이 계속 말하므로 drain 을 기다릴 이유가 없고,
1183
+ * hold audio 도 틀지 않는다(모델 음성과 겹친다).
1184
+ */
1185
+ private _dispatchToolCall;
1186
+ private _runAsyncTool;
1187
+ /**
1188
+ * 함수 호출 하나를 실행해 FunctionResponse 객체로 만든다. hang_up 이면 'hang_up', 실행할 게 없으면 null.
1189
+ * 서버가 id 를 주지 않은 호출에는 id 를 돌려보내지 않는다(우리가 지어낸 id 는 서버가 모른다).
1190
+ */
1191
+ private _executeFunctionCall;
1192
+ private _handleAudioData;
1193
+ private _flushAudioRemainder;
1194
+ private static readonly TOOL_DRAIN_TIMEOUT;
1195
+ private _scheduleToolExecution;
1196
+ /** BLOCKING 호출 묶음을 실행한다. 모델이 결과를 기다리므로 그동안 hold audio 를 튼다. */
1197
+ private _handleToolCall;
1198
+ }
1199
+
1200
+ /**
1201
+ * Deepgram STT (Speech-to-Text) provider.
1202
+ */
1203
+
1204
+ interface DeepgramSTTOptions {
1205
+ /** Deepgram API key. Falls back to DEEPGRAM_API_KEY env var. */
1206
+ apiKey?: string;
1207
+ /** Model to use. Default: 'nova-3' */
1208
+ model?: string;
1209
+ /** Language code. Default: 'ko' */
1210
+ language?: string;
1211
+ /** Sample rate. Default: 16000 */
1212
+ sampleRate?: number;
1213
+ /** Encoding. Default: 'linear16' */
1214
+ encoding?: string;
1215
+ /** Enable punctuation. Default: true */
1216
+ punctuate?: boolean;
1217
+ /** Enable interim results. Default: true */
1218
+ interimResults?: boolean;
1219
+ /** Endpointing timeout in ms. Default: 300 */
1220
+ endpointing?: number;
1221
+ /** Utterance end silence timeout in ms. Default: 1000 */
1222
+ utteranceEndMs?: number;
1223
+ }
1224
+ declare class DeepgramSTT implements STT {
1225
+ private _options;
1226
+ private _log;
1227
+ get provider(): string;
1228
+ get model(): string;
1229
+ setLogger(logger: Logger): void;
1230
+ constructor(options?: DeepgramSTTOptions);
1231
+ transcribe(audioStream: AsyncIterable<Buffer>, options?: {
1232
+ language?: string;
1233
+ sampleRate?: number;
1234
+ }): AsyncGenerator<SpeechEvent>;
1235
+ }
1236
+
1237
+ /**
1238
+ * ElevenLabs TTS (Text-to-Speech) provider.
1239
+ */
1240
+
1241
+ interface ElevenLabsTTSOptions {
1242
+ /** ElevenLabs API key. Falls back to ELEVENLABS_API_KEY env var. */
1243
+ apiKey?: string;
1244
+ /** Voice ID. Default: 'EXAVITQu4vr4xnSDxMaL' (Rachel) */
1245
+ voiceId?: string;
1246
+ /** Model ID. Default: 'eleven_flash_v2_5' */
1247
+ model?: string;
1248
+ /** Output format. Default: 'pcm_24000' */
1249
+ outputFormat?: string;
1250
+ /** Stability. Default: 0.5 */
1251
+ stability?: number;
1252
+ /** Similarity boost. Default: 0.75 */
1253
+ similarityBoost?: number;
1254
+ /** Language code. Default: 'ko' */
1255
+ languageCode?: string;
1256
+ }
1257
+ declare class ElevenLabsTTS implements TTS {
1258
+ private _options;
1259
+ private _log;
1260
+ get provider(): string;
1261
+ get model(): string;
1262
+ get voiceId(): string;
1263
+ setLogger(logger: Logger): void;
1264
+ constructor(options?: ElevenLabsTTSOptions);
1265
+ synthesize(text: string | AsyncIterable<string>, options?: {
1266
+ voice?: string;
1267
+ sampleRate?: number;
1268
+ }): AsyncGenerator<Buffer>;
1269
+ private _synthesizeSingle;
1270
+ private _synthesizeStreaming;
1271
+ }
1272
+
1273
+ /**
1274
+ * OpenAI LLM provider for pipeline-based voice agents.
1275
+ */
1276
+
1277
+ interface OpenAILLMOptions {
1278
+ /** OpenAI API key. Falls back to OPENAI_API_KEY env var. */
1279
+ apiKey?: string;
1280
+ /** Model to use. Default: 'gpt-4o-mini' */
1281
+ model?: string;
1282
+ /** Default temperature. Default: 0.8 */
1283
+ temperature?: number;
1284
+ /** Default max tokens. Default: 4096 */
1285
+ maxTokens?: number;
1286
+ }
1287
+ declare class OpenAILLM implements LLM {
1288
+ private _options;
1289
+ get provider(): string;
1290
+ get model(): string;
1291
+ constructor(options?: OpenAILLMOptions);
1292
+ generate(messages: ConversationMessage[], options?: {
1293
+ tools?: ToolRegistry;
1294
+ temperature?: number;
1295
+ maxTokens?: number;
1296
+ }): AsyncGenerator<LLMChunk>;
1297
+ }
1298
+
1299
+ /**
1300
+ * Anthropic LLM provider for pipeline-based voice agents.
1301
+ */
1302
+
1303
+ interface AnthropicLLMOptions {
1304
+ /** Anthropic API key. Falls back to ANTHROPIC_API_KEY env var. */
1305
+ apiKey?: string;
1306
+ /** Model to use. Default: 'claude-sonnet-4-6' */
1307
+ model?: string;
1308
+ /** Default temperature. Default: 0.8 */
1309
+ temperature?: number;
1310
+ /** Default max tokens. Default: 4096 */
1311
+ maxTokens?: number;
1312
+ }
1313
+ declare class AnthropicLLM implements LLM {
1314
+ private _options;
1315
+ get provider(): string;
1316
+ get model(): string;
1317
+ constructor(options?: AnthropicLLMOptions);
1318
+ generate(messages: ConversationMessage[], options?: {
1319
+ tools?: ToolRegistry;
1320
+ temperature?: number;
1321
+ maxTokens?: number;
1322
+ }): AsyncGenerator<LLMChunk>;
1323
+ }
1324
+
1325
+ /**
1326
+ * Google Gemini LLM provider for pipeline-based voice agents.
1327
+ */
1328
+
1329
+ interface GeminiLLMOptions {
1330
+ /** Google API key. Falls back to GOOGLE_API_KEY env var. */
1331
+ apiKey?: string;
1332
+ /** Model to use. Default: 'gemini-2.5-flash' */
1333
+ model?: string;
1334
+ /** Default temperature. Default: 0.8 */
1335
+ temperature?: number;
1336
+ /** Default max tokens. Default: 4096 */
1337
+ maxTokens?: number;
1338
+ }
1339
+ declare class GeminiLLM implements LLM {
1340
+ private _options;
1341
+ get provider(): string;
1342
+ get model(): string;
1343
+ constructor(options?: GeminiLLMOptions);
1344
+ generate(messages: ConversationMessage[], options?: {
1345
+ tools?: ToolRegistry;
1346
+ temperature?: number;
1347
+ maxTokens?: number;
1348
+ }): AsyncGenerator<LLMChunk>;
1349
+ }
1350
+
1351
+ /**
1352
+ * OpenAI-compatible LLM provider (works with any OpenAI-compatible API).
1353
+ */
1354
+
1355
+ interface OpenAICompatLLMOptions {
1356
+ /** API key. */
1357
+ apiKey?: string;
1358
+ /** Base URL for the OpenAI-compatible API. */
1359
+ baseUrl: string;
1360
+ /** Model to use. */
1361
+ model: string;
1362
+ /** Default temperature. */
1363
+ temperature?: number;
1364
+ /** Default max tokens. */
1365
+ maxTokens?: number;
1366
+ /** Additional default headers. */
1367
+ defaultHeaders?: Record<string, string>;
1368
+ }
1369
+ declare class OpenAICompatLLM implements LLM {
1370
+ private _options;
1371
+ get provider(): string;
1372
+ get model(): string;
1373
+ constructor(options: OpenAICompatLLMOptions);
1374
+ generate(messages: ConversationMessage[], options?: {
1375
+ tools?: ToolRegistry;
1376
+ temperature?: number;
1377
+ maxTokens?: number;
1378
+ }): AsyncGenerator<LLMChunk>;
1379
+ }
1380
+
1381
+ /**
1382
+ * Ollama LLM provider for pipeline-based voice agents.
1383
+ * Uses the OpenAI-compatible API that Ollama exposes.
1384
+ */
1385
+
1386
+ interface OllamaLLMOptions {
1387
+ /** Ollama server URL. Falls back to OLLAMA_BASE_URL env var. Default: 'http://localhost:11434/v1' */
1388
+ baseUrl?: string;
1389
+ /** Model to use. Default: 'llama3.2' */
1390
+ model?: string;
1391
+ /** Default temperature. Default: 0.8 */
1392
+ temperature?: number;
1393
+ /** Default max tokens. Default: 4096 */
1394
+ maxTokens?: number;
1395
+ }
1396
+ declare class OllamaLLM implements LLM {
1397
+ private _inner;
1398
+ get provider(): string;
1399
+ get model(): string;
1400
+ constructor(options?: OllamaLLMOptions);
1401
+ generate(messages: ConversationMessage[], options?: {
1402
+ tools?: ToolRegistry;
1403
+ temperature?: number;
1404
+ maxTokens?: number;
1405
+ }): AsyncGenerator<LLMChunk>;
1406
+ }
1407
+
1408
+ interface MistralLLMOptions {
1409
+ apiKey?: string;
1410
+ model?: string;
1411
+ temperature?: number;
1412
+ maxTokens?: number;
1413
+ }
1414
+ declare class MistralLLM implements LLM {
1415
+ private _inner;
1416
+ get provider(): string;
1417
+ get model(): string;
1418
+ constructor(options?: MistralLLMOptions);
1419
+ generate(messages: ConversationMessage[], options?: {
1420
+ tools?: ToolRegistry;
1421
+ temperature?: number;
1422
+ maxTokens?: number;
1423
+ }): AsyncGenerator<LLMChunk>;
1424
+ }
1425
+
1426
+ interface GroqLLMOptions {
1427
+ apiKey?: string;
1428
+ model?: string;
1429
+ temperature?: number;
1430
+ maxTokens?: number;
1431
+ }
1432
+ declare class GroqLLM implements LLM {
1433
+ private _inner;
1434
+ get provider(): string;
1435
+ get model(): string;
1436
+ constructor(options?: GroqLLMOptions);
1437
+ generate(messages: ConversationMessage[], options?: {
1438
+ tools?: ToolRegistry;
1439
+ temperature?: number;
1440
+ maxTokens?: number;
1441
+ }): AsyncGenerator<LLMChunk>;
1442
+ }
1443
+
1444
+ interface PerplexityLLMOptions {
1445
+ apiKey?: string;
1446
+ model?: string;
1447
+ temperature?: number;
1448
+ maxTokens?: number;
1449
+ }
1450
+ declare class PerplexityLLM implements LLM {
1451
+ private _inner;
1452
+ get provider(): string;
1453
+ get model(): string;
1454
+ constructor(options?: PerplexityLLMOptions);
1455
+ generate(messages: ConversationMessage[], options?: {
1456
+ tools?: ToolRegistry;
1457
+ temperature?: number;
1458
+ maxTokens?: number;
1459
+ }): AsyncGenerator<LLMChunk>;
1460
+ }
1461
+
1462
+ interface TogetherLLMOptions {
1463
+ apiKey?: string;
1464
+ model?: string;
1465
+ temperature?: number;
1466
+ maxTokens?: number;
1467
+ }
1468
+ declare class TogetherLLM implements LLM {
1469
+ private _inner;
1470
+ get provider(): string;
1471
+ get model(): string;
1472
+ constructor(options?: TogetherLLMOptions);
1473
+ generate(messages: ConversationMessage[], options?: {
1474
+ tools?: ToolRegistry;
1475
+ temperature?: number;
1476
+ maxTokens?: number;
1477
+ }): AsyncGenerator<LLMChunk>;
1478
+ }
1479
+
1480
+ interface FireworksLLMOptions {
1481
+ apiKey?: string;
1482
+ model?: string;
1483
+ temperature?: number;
1484
+ maxTokens?: number;
1485
+ }
1486
+ declare class FireworksLLM implements LLM {
1487
+ private _inner;
1488
+ get provider(): string;
1489
+ get model(): string;
1490
+ constructor(options?: FireworksLLMOptions);
1491
+ generate(messages: ConversationMessage[], options?: {
1492
+ tools?: ToolRegistry;
1493
+ temperature?: number;
1494
+ maxTokens?: number;
1495
+ }): AsyncGenerator<LLMChunk>;
1496
+ }
1497
+
1498
+ interface DeepSeekLLMOptions {
1499
+ apiKey?: string;
1500
+ model?: string;
1501
+ temperature?: number;
1502
+ maxTokens?: number;
1503
+ }
1504
+ declare class DeepSeekLLM implements LLM {
1505
+ private _inner;
1506
+ get provider(): string;
1507
+ get model(): string;
1508
+ constructor(options?: DeepSeekLLMOptions);
1509
+ generate(messages: ConversationMessage[], options?: {
1510
+ tools?: ToolRegistry;
1511
+ temperature?: number;
1512
+ maxTokens?: number;
1513
+ }): AsyncGenerator<LLMChunk>;
1514
+ }
1515
+
1516
+ interface XaiLLMOptions {
1517
+ apiKey?: string;
1518
+ model?: string;
1519
+ temperature?: number;
1520
+ maxTokens?: number;
1521
+ }
1522
+ declare class XaiLLM implements LLM {
1523
+ private _inner;
1524
+ get provider(): string;
1525
+ get model(): string;
1526
+ constructor(options?: XaiLLMOptions);
1527
+ generate(messages: ConversationMessage[], options?: {
1528
+ tools?: ToolRegistry;
1529
+ temperature?: number;
1530
+ maxTokens?: number;
1531
+ }): AsyncGenerator<LLMChunk>;
1532
+ }
1533
+
1534
+ /**
1535
+ * Built-in tool 스키마 정의, 포맷 변환, 실행 헬퍼.
1536
+ *
1537
+ * 모든 세션(PipelineSession, OpenAIRealtime, GeminiRealtime)이 공통으로 사용하는
1538
+ * 내장 도구 스키마를 한 곳에서 관리한다.
1539
+ */
1540
+
1541
+ declare const BUILTIN_TOOL_NAMES: Set<string>;
1542
+ /**
1543
+ * 활성화된 builtin tool 스키마를 요청한 포맷으로 반환.
1544
+ */
1545
+ declare function getBuiltinToolSchemas(builtinTools: Set<BuiltinTool> | null, fmt: 'chat' | 'realtime' | 'gemini'): Array<Record<string, unknown>>;
1546
+ /**
1547
+ * Builtin tool을 실행하고 결과 문자열을 반환한다.
1548
+ *
1549
+ * `funcName`이 builtin tool이 아니면 `null`을 반환한다.
1550
+ * `hang_up`의 경우 빈 문자열 `""`을 반환한다 (호출자가 종료 처리).
1551
+ */
1552
+ declare function isBuiltinTool(name: string): boolean;
1553
+ declare function executeBuiltinTool(funcName: string, args: Record<string, unknown>, call: CallSession): Promise<string | null>;
1554
+
1555
+ /**
1556
+ * Logger factory for the ClawOps agent module.
1557
+ *
1558
+ * Provides a 2-level hierarchy matching the Python SDK:
1559
+ * - clawops.agent (core: agent, session, control-ws, media-ws, recorder, mcp, realtime)
1560
+ * - clawops.agent.pipeline (pipeline: pipeline-session, stt, tts)
1561
+ */
1562
+
1563
+ /**
1564
+ * Create or return an agent-level logger.
1565
+ * If no user logger is provided, returns the default pino instance.
1566
+ */
1567
+ declare function createAgentLogger(userLogger?: Logger): Logger;
1568
+ /**
1569
+ * Create a pipeline child logger from a parent agent logger.
1570
+ * Adds `{ module: 'pipeline' }` to all log entries.
1571
+ */
1572
+ declare function createPipelineLogger(parent: Logger): Logger;
1573
+
1574
+ export { type AgentEventType, AnthropicLLM, type AnthropicLLMOptions, AudioRecorder, BUILTIN_TOOL_NAMES, BuiltinTool, CallSession, ClawOpsAgent, type ClawOpsAgentOptions, type ControlEvent, ControlWebSocket, type ControlWsOptions, ConversationMessage, DECODE_TABLE, DeepSeekLLM, type DeepSeekLLMOptions, DeepgramSTT, type DeepgramSTTOptions, type DtmfEvent, ElevenLabsTTS, type ElevenLabsTTSOptions, FireworksLLM, type FireworksLLMOptions, FunctionTool, GEMINI_TOOL_BEHAVIORS, GeminiLLM, type GeminiLLMOptions, GeminiRealtime, type GeminiRealtimeOptions, type GeminiToolBehavior, GroqLLM, type GroqLLMOptions, IncomingCall, type IncomingHandler, type IncomingRejectOptions, type IncomingRejectReason, type IncomingTransferOptions, LLM, LLMChunk, MCPClient, type MCPServerConfig, type MCPServerHTTP, type MCPServerStdio, type MediaEvent, MediaProfile, type MediaStartEvent, MediaWebSocket, MistralLLM, type MistralLLMOptions, OllamaLLM, type OllamaLLMOptions, OpenAICompatLLM, type OpenAICompatLLMOptions, OpenAILLM, type OpenAILLMOptions, OpenAIRealtime, type OpenAIRealtimeOptions, PerplexityLLM, type PerplexityLLMOptions, PipelineSession, type PipelineSessionOptions, STT, Session, SpeechEvent, TTS, TogetherLLM, type TogetherLLMOptions, ToolBehavior, type ToolConfig, ToolOptions, ToolRegistry, ToolScheduling, type TracingConfig, XaiLLM, type XaiLLMOptions, buildControlWsUrl, createAgentLogger, createPipelineLogger, defaultToolBehavior, executeBuiltinTool, getBuiltinToolSchemas, getTracingConfig, isBuiltinTool, isExtendedThinkingModel, mcpServerHTTP, mcpServerStdio, pcm16ToUlaw, resamplePcm16, resetTracingConfig, setTracingConfig, ulawToPcm16 };