@jambonz/sdk 0.11.0 → 0.12.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 (45) hide show
  1. package/dist/client/index.cjs +4 -0
  2. package/dist/client/index.cjs.map +1 -1
  3. package/dist/client/index.d.cts +4 -2
  4. package/dist/client/index.d.ts +4 -2
  5. package/dist/client/index.js +4 -0
  6. package/dist/client/index.js.map +1 -1
  7. package/dist/harness/index.cjs +843 -0
  8. package/dist/harness/index.cjs.map +1 -0
  9. package/dist/harness/index.d.cts +501 -0
  10. package/dist/harness/index.d.ts +501 -0
  11. package/dist/harness/index.js +832 -0
  12. package/dist/harness/index.js.map +1 -0
  13. package/dist/index.cjs +24 -0
  14. package/dist/index.cjs.map +1 -1
  15. package/dist/index.d.cts +4 -4
  16. package/dist/index.d.ts +4 -4
  17. package/dist/index.js +24 -0
  18. package/dist/index.js.map +1 -1
  19. package/dist/{rest-jYM4NgyN.d.cts → rest-qwPYz71v.d.ts} +29 -2
  20. package/dist/{rest-nkM1OQLd.d.ts → rest-rSaRlKBZ.d.cts} +29 -2
  21. package/dist/types/index.d.cts +163 -3
  22. package/dist/types/index.d.ts +163 -3
  23. package/dist/{verb-builder-D1rpCZ6y.d.ts → verb-builder-58TZ7DKD.d.cts} +2 -1
  24. package/dist/{verb-builder-Cbw6aUdF.d.cts → verb-builder-D20D5_vU.d.ts} +2 -1
  25. package/dist/{verbs-D0TgdJYZ.d.cts → verbs-YtIbYtiR.d.cts} +22 -1
  26. package/dist/{verbs-D0TgdJYZ.d.ts → verbs-YtIbYtiR.d.ts} +22 -1
  27. package/dist/webhook/index.cjs +3 -0
  28. package/dist/webhook/index.cjs.map +1 -1
  29. package/dist/webhook/index.d.cts +2 -2
  30. package/dist/webhook/index.d.ts +2 -2
  31. package/dist/webhook/index.js +3 -0
  32. package/dist/webhook/index.js.map +1 -1
  33. package/dist/websocket/index.cjs +20 -0
  34. package/dist/websocket/index.cjs.map +1 -1
  35. package/dist/websocket/index.d.cts +12 -3
  36. package/dist/websocket/index.d.ts +12 -3
  37. package/dist/websocket/index.js +20 -0
  38. package/dist/websocket/index.js.map +1 -1
  39. package/examples/harness/README.md +70 -0
  40. package/examples/harness/harness.ts +99 -0
  41. package/examples/harness/package.json +21 -0
  42. package/examples/harness/tsconfig.json +12 -0
  43. package/package.json +13 -2
  44. package/dist/session-DKaSRkIo.d.cts +0 -160
  45. package/dist/session-DKaSRkIo.d.ts +0 -160
@@ -0,0 +1,501 @@
1
+ import { Logger } from 'pino';
2
+
3
+ /**
4
+ * The jambonz harness protocol (subprotocol `harness.jambonz.org`), protocol version 1.
5
+ *
6
+ * jambonz (feature-server) opens one WebSocket per call to the harness. Every frame is a
7
+ * JSON text message with a `type`. Unknown types and fields must be ignored: new ones are
8
+ * added without changing the protocol version.
9
+ */
10
+ declare const HARNESS_SUBPROTOCOL = "harness.jambonz.org";
11
+ declare const HARNESS_PROTOCOL_VERSION = 1;
12
+ /** A function tool definition, as passed to an OpenAI-compatible model. */
13
+ interface ChatTool {
14
+ type: 'function';
15
+ function: {
16
+ name: string;
17
+ description?: string;
18
+ parameters?: Record<string, unknown>;
19
+ };
20
+ }
21
+ interface ChatToolCall {
22
+ id: string;
23
+ type: 'function';
24
+ function: {
25
+ name: string;
26
+ arguments: string;
27
+ };
28
+ }
29
+ type ChatMessage = {
30
+ role: 'system';
31
+ content: string;
32
+ } | {
33
+ role: 'user';
34
+ content: string;
35
+ } | {
36
+ role: 'assistant';
37
+ content: string | null;
38
+ tool_calls?: ChatToolCall[];
39
+ } | {
40
+ role: 'tool';
41
+ tool_call_id: string;
42
+ content: string;
43
+ };
44
+ interface ChatCompletionChunkDelta {
45
+ role?: string;
46
+ content?: string | null;
47
+ tool_calls?: Array<{
48
+ index: number;
49
+ id?: string;
50
+ type?: 'function';
51
+ function?: {
52
+ name?: string;
53
+ arguments?: string;
54
+ };
55
+ }>;
56
+ }
57
+ /** An OpenAI `ChatCompletionChunk`. Only `choices[0].delta.content` is spoken by jambonz. */
58
+ interface ChatCompletionChunk {
59
+ id?: string;
60
+ object?: string;
61
+ created?: number;
62
+ model?: string;
63
+ choices: Array<{
64
+ index: number;
65
+ delta: ChatCompletionChunkDelta;
66
+ finish_reason?: string | null;
67
+ }>;
68
+ usage?: {
69
+ prompt_tokens?: number;
70
+ completion_tokens?: number;
71
+ total_tokens?: number;
72
+ } | null;
73
+ [key: string]: unknown;
74
+ }
75
+ interface FromJambonz {
76
+ call_sid: string;
77
+ }
78
+ interface SessionStartMessage extends FromJambonz {
79
+ type: 'session:start';
80
+ protocol: number;
81
+ account_sid?: string;
82
+ application_sid?: string;
83
+ direction?: 'inbound' | 'outbound';
84
+ from?: string;
85
+ to?: string;
86
+ language?: string;
87
+ sip_headers?: Record<string, string>;
88
+ /** Free-form JSON from the verb (Studio puts agent id, version and per-call variables here). */
89
+ metadata?: Record<string, unknown>;
90
+ /** The agent's tools as OpenAI function definitions; run them with `tool:call`. */
91
+ tools?: ChatTool[];
92
+ /** True when jambonz reconnected after the socket dropped mid-call. */
93
+ resumed?: boolean;
94
+ /** On a resumed session, the last turn id jambonz knows of. */
95
+ turn_id?: number;
96
+ }
97
+ interface SpeechStartMessage extends FromJambonz {
98
+ type: 'speech:start';
99
+ turn_id: number;
100
+ }
101
+ interface TranscriptMessage extends FromJambonz {
102
+ type: 'transcript';
103
+ turn_id: number;
104
+ /** The whole utterance so far, not a delta. */
105
+ text: string;
106
+ /** The STT will not revise this text. It does not mean the caller has finished. */
107
+ final: boolean;
108
+ confidence?: number;
109
+ }
110
+ type TurnInput = {
111
+ type: 'speech';
112
+ text: string;
113
+ confidence?: number;
114
+ language?: string;
115
+ } | {
116
+ type: 'greeting';
117
+ } | {
118
+ type: 'no_input';
119
+ };
120
+ interface TurnStartMessage extends FromJambonz {
121
+ type: 'turn:start';
122
+ turn_id: number;
123
+ input: TurnInput;
124
+ }
125
+ interface TurnCancelMessage extends FromJambonz {
126
+ type: 'turn:cancel';
127
+ turn_id: number;
128
+ reason: 'barge_in' | 'call_ended' | string;
129
+ }
130
+ interface CommandResultMessage extends FromJambonz {
131
+ type: 'command:result';
132
+ command_id: string;
133
+ ok: boolean;
134
+ error?: string;
135
+ [key: string]: unknown;
136
+ }
137
+ interface ToolResultMessage extends FromJambonz {
138
+ type: 'tool:result';
139
+ call_id: string;
140
+ result?: unknown;
141
+ error?: string;
142
+ }
143
+ interface SessionEndMessage extends FromJambonz {
144
+ type: 'session:end';
145
+ reason: 'caller_hangup' | 'harness_hangup' | 'application_hangup' | 'application_redirect' | 'error' | string;
146
+ duration_ms?: number;
147
+ }
148
+ interface UserInterruptionEvent {
149
+ name: 'user_interruption';
150
+ turn_id?: number;
151
+ reply_id: string;
152
+ spoken: string;
153
+ unspoken?: string;
154
+ }
155
+ interface ReplySpokenEvent {
156
+ name: 'reply_spoken';
157
+ reply_id: string;
158
+ }
159
+ interface ReplyDroppedEvent {
160
+ name: 'reply_dropped';
161
+ reply_id: string;
162
+ reason: 'replaced' | 'call_ended' | string;
163
+ }
164
+ interface SilenceEvent {
165
+ name: 'silence';
166
+ seconds?: number;
167
+ streak: number;
168
+ turn_id?: number;
169
+ }
170
+ interface DtmfEvent {
171
+ name: 'dtmf';
172
+ digits: string;
173
+ duration_ms?: number;
174
+ }
175
+ interface ExternalEvent {
176
+ name: 'external';
177
+ event: string;
178
+ variables?: Record<string, unknown>;
179
+ }
180
+ interface TransferEvent {
181
+ name: 'transfer';
182
+ command_id: string;
183
+ outcome: 'bridged' | 'failed' | 'returned';
184
+ sip_status?: number;
185
+ reason?: string;
186
+ }
187
+ interface PlaybackEvent {
188
+ name: 'playback';
189
+ command_id: string;
190
+ outcome: string;
191
+ }
192
+ interface RecordingEvent {
193
+ name: 'recording';
194
+ command_id?: string;
195
+ state: string;
196
+ by: 'harness' | 'application';
197
+ }
198
+ interface ListenEvent {
199
+ name: 'listen';
200
+ language?: string;
201
+ hints?: string[];
202
+ by: string;
203
+ }
204
+ interface ApplicationUpdateEvent {
205
+ name: 'application_update';
206
+ type: string;
207
+ data?: unknown;
208
+ }
209
+ interface ErrorEvent {
210
+ name: 'error';
211
+ code: string;
212
+ message: string;
213
+ ref?: unknown;
214
+ }
215
+ type HarnessEvent = UserInterruptionEvent | ReplySpokenEvent | ReplyDroppedEvent | SilenceEvent | DtmfEvent | ExternalEvent | TransferEvent | PlaybackEvent | RecordingEvent | ListenEvent | ApplicationUpdateEvent | ErrorEvent;
216
+ /** Maps an event name to its payload, for typed `onEvent` handlers. */
217
+ type HarnessEventMap = {
218
+ [E in HarnessEvent as E['name']]: E;
219
+ };
220
+ type EventMessage = FromJambonz & {
221
+ type: 'event';
222
+ } & (HarnessEvent | {
223
+ name: string;
224
+ [key: string]: unknown;
225
+ });
226
+ type JambonzToHarnessMessage = SessionStartMessage | SpeechStartMessage | TranscriptMessage | TurnStartMessage | TurnCancelMessage | EventMessage | CommandResultMessage | ToolResultMessage | SessionEndMessage;
227
+ interface ReplyChunkMessage {
228
+ type: 'reply:chunk';
229
+ reply_id: string;
230
+ /** Present when the reply answers a turn; absent for an unprompted reply. */
231
+ turn_id?: number;
232
+ /** `false` on the first chunk holds barge-in until the whole reply has played. */
233
+ interruptible?: boolean;
234
+ /** `true` on the first chunk of an unprompted reply cuts off whatever is playing. */
235
+ interrupt?: boolean;
236
+ chunk: ChatCompletionChunk;
237
+ }
238
+ /** The harness's account of a turn (A.13). Every field is optional; ≤ 16 KB as JSON. */
239
+ interface TurnRecord {
240
+ route?: string;
241
+ procedures?: string[];
242
+ steps?: Array<{
243
+ name: string;
244
+ ms: number;
245
+ result?: string;
246
+ detail?: Record<string, unknown>;
247
+ }>;
248
+ model_calls?: Array<{
249
+ model: string;
250
+ purpose?: string;
251
+ input_tokens?: number;
252
+ output_tokens?: number;
253
+ first_token_ms?: number;
254
+ ms: number;
255
+ }>;
256
+ own_tools?: Array<{
257
+ name: string;
258
+ ok: boolean;
259
+ ms: number;
260
+ }>;
261
+ flags?: string[];
262
+ note?: string;
263
+ [key: string]: unknown;
264
+ }
265
+ interface ReplyDoneMessage {
266
+ type: 'reply:done';
267
+ reply_id: string;
268
+ turn_id?: number;
269
+ turn_record?: TurnRecord;
270
+ }
271
+ interface ToolCallMessage {
272
+ type: 'tool:call';
273
+ call_id: string;
274
+ turn_id?: number;
275
+ name: string;
276
+ args: Record<string, unknown>;
277
+ }
278
+ /** Call-control commands (A.8). */
279
+ interface HarnessCommandArgs {
280
+ hangup: {
281
+ reason?: string;
282
+ };
283
+ transfer: {
284
+ to: string;
285
+ trunk?: string;
286
+ headers?: Record<string, string>;
287
+ announce?: string;
288
+ transcribe?: boolean;
289
+ };
290
+ play: {
291
+ url: string;
292
+ interruptible?: boolean;
293
+ };
294
+ record: {
295
+ action: 'start' | 'stop' | 'pause' | 'resume';
296
+ };
297
+ barge_in: {
298
+ enabled: boolean;
299
+ };
300
+ listen: {
301
+ language?: string;
302
+ hints?: string[];
303
+ };
304
+ }
305
+ type HarnessCommandName = keyof HarnessCommandArgs;
306
+ interface CommandMessage {
307
+ type: 'command';
308
+ command_id: string;
309
+ name: HarnessCommandName | string;
310
+ args: Record<string, unknown>;
311
+ }
312
+ type HarnessToJambonzMessage = ReplyChunkMessage | ReplyDoneMessage | ToolCallMessage | CommandMessage;
313
+
314
+ /**
315
+ * A minimal streaming client for OpenAI-compatible chat completions (`POST {baseURL}/chat/completions`
316
+ * with `stream: true`, server-sent events). Uses the global fetch, so there is no dependency on the
317
+ * OpenAI SDK, and works with any endpoint that speaks the same wire format.
318
+ */
319
+
320
+ interface ModelClientOptions {
321
+ /** API key, sent as `Authorization: Bearer`. Default: `process.env.OPENAI_API_KEY`. */
322
+ apiKey?: string;
323
+ /** Base URL of the API, up to and including the version. Default: `process.env.OPENAI_BASE_URL` or `https://api.openai.com/v1`. */
324
+ baseURL?: string;
325
+ /** Extra headers for every request. */
326
+ headers?: Record<string, string>;
327
+ }
328
+ interface StreamRequest {
329
+ model: string;
330
+ messages: ChatMessage[];
331
+ tools?: ChatTool[];
332
+ /** Extra request body fields (temperature, max_tokens, ...). */
333
+ params?: Record<string, unknown>;
334
+ signal: AbortSignal;
335
+ }
336
+ declare class ModelError extends Error {
337
+ readonly status?: number | undefined;
338
+ constructor(message: string, status?: number | undefined);
339
+ }
340
+ declare function createModelClient(opts?: ModelClientOptions): {
341
+ baseURL: string;
342
+ stream(req: StreamRequest): AsyncGenerator<ChatCompletionChunk>;
343
+ };
344
+ type ModelClient = ReturnType<typeof createModelClient>;
345
+
346
+ /** A turn as the hooks see it. */
347
+ interface HarnessTurn {
348
+ turnId: number;
349
+ input: TurnInput;
350
+ /** The caller's words (`''` for a greeting or no-input turn). */
351
+ text: string;
352
+ }
353
+ /** A turn whose reply has finished, as `afterTurn` sees it. */
354
+ interface CompletedTurn extends HarnessTurn {
355
+ /** The text sent to text-to-speech for this turn. */
356
+ reply: string;
357
+ /** The turn record built so far; add to it with `ctx.record()`. */
358
+ record: TurnRecord;
359
+ }
360
+ interface CommandResult {
361
+ ok: boolean;
362
+ error?: string;
363
+ [key: string]: unknown;
364
+ }
365
+ interface SayOptions {
366
+ /** Cut off whatever reply is playing (the caller is still never talked over). */
367
+ interrupt?: boolean;
368
+ /** `false` holds barge-in until the whole reply has played. */
369
+ interruptible?: boolean;
370
+ }
371
+ /** Per-call context passed to every hook. */
372
+ interface HarnessContext {
373
+ readonly callSid: string;
374
+ /** The `session:start` message for this call (from, to, metadata, the agent's tools, ...). */
375
+ readonly session: SessionStartMessage;
376
+ /** Per-call state, yours to use. */
377
+ readonly state: Map<string, unknown>;
378
+ /**
379
+ * The conversation so far: user, assistant and tool messages, oldest first. The system prompt is not
380
+ * in it; it is built for each model call from `instructions`. You may edit it.
381
+ */
382
+ readonly history: ChatMessage[];
383
+ /** A pino logger bound to this call's `call_sid`. */
384
+ readonly log: Logger;
385
+ /** Speak on the harness's own initiative (an unprompted reply). Returns the reply id. */
386
+ say(text: string, opts?: SayOptions): string;
387
+ /** Send a call-control command (A.8) and wait for its `command:result`. */
388
+ command<N extends keyof HarnessCommandArgs>(name: N, args?: HarnessCommandArgs[N]): Promise<CommandResult>;
389
+ command(name: string, args?: Record<string, unknown>): Promise<CommandResult>;
390
+ /** Run one of the agent's Studio tools (a name from `session.tools`) via `tool:call`; resolves with its result. */
391
+ callTool(name: string, args?: Record<string, unknown>): Promise<unknown>;
392
+ /** Add a field to the current turn's record (or the next one, when called between turns). */
393
+ record(field: string, value: unknown): void;
394
+ }
395
+ /** What `beforeModel` may return to shape the turn. Every field is optional. */
396
+ interface BeforeModelResult {
397
+ /** The system prompt for this turn's model calls (default: `options.instructions`). */
398
+ instructions?: string;
399
+ /**
400
+ * The full message list to send instead of `[system, ...ctx.history]`. Include your own system message.
401
+ * Tool round-trips during the turn are appended to it.
402
+ */
403
+ messages?: ChatMessage[];
404
+ /** Names of the tools to offer the model this turn (your `tools` and the agent's Studio tools). Default: all. */
405
+ tools?: string[];
406
+ /** The model for this turn (default: `options.model`). */
407
+ model?: string;
408
+ /** Speak this and skip the model entirely. */
409
+ reply?: string;
410
+ /** Recorded as `turn_record.route`. */
411
+ route?: string;
412
+ /** `false` holds barge-in until this turn's reply has played. */
413
+ interruptible?: boolean;
414
+ }
415
+ interface HarnessTool {
416
+ description: string;
417
+ /** JSON schema for the arguments. */
418
+ parameters?: Record<string, unknown>;
419
+ run(args: Record<string, unknown>, ctx: HarnessContext): unknown | Promise<unknown>;
420
+ }
421
+ type EventHandler<E> = (event: E, ctx: HarnessContext) => void | Promise<void>;
422
+ /** Handlers by event name (A.7). Events without a handler get the built-in behaviour, if any. */
423
+ type EventHandlers = {
424
+ [K in keyof HarnessEventMap]?: EventHandler<HarnessEventMap[K]>;
425
+ };
426
+ interface HarnessOptions {
427
+ /** The model used for every turn unless `beforeModel` says otherwise. Default `gpt-4.1-mini`. */
428
+ model?: string;
429
+ /** The system prompt. */
430
+ instructions?: string;
431
+ /** Speak this on the greeting turn instead of asking the model to greet. */
432
+ greeting?: string;
433
+ /** The OpenAI-compatible endpoint. Defaults from `OPENAI_API_KEY` / `OPENAI_BASE_URL`. */
434
+ client?: ModelClientOptions;
435
+ /** Extra chat-completion request fields (temperature, max_tokens, ...). */
436
+ modelParams?: Record<string, unknown>;
437
+ /** Most model calls in one turn when the model keeps calling tools. Default 5. */
438
+ maxToolRounds?: number;
439
+ /** Spoken when a turn fails (model or hook error) before anything was said. */
440
+ errorReply?: string;
441
+ /** When set, jambonz must send `Authorization: Bearer <apiKey>` (the Harness credential's key). */
442
+ apiKey?: string;
443
+ /** A pino logger. Default: pino at `LOG_LEVEL` (default `info`). */
444
+ logger?: Logger;
445
+ /** Once, when the call connects. Set up `ctx.state`. */
446
+ onSessionStart?(session: SessionStartMessage, ctx: HarnessContext): void | Promise<void>;
447
+ /** Each turn, before the model is called: routing, retrieval, gating, prompt assembly. */
448
+ beforeModel?(turn: HarnessTurn, ctx: HarnessContext): BeforeModelResult | void | Promise<BeforeModelResult | void>;
449
+ /** The harness's own tools. The agent's Studio tools are offered to the model too and run via `tool:call`. */
450
+ tools?: Record<string, HarnessTool>;
451
+ /** Before each sentence goes to TTS: `true` speaks it, `false` stops the reply, a string is spoken instead. */
452
+ checkSentence?(sentence: string, ctx: HarnessContext): boolean | string | Promise<boolean | string>;
453
+ /** When a turn's reply is done, before `reply:done` is sent. Add to the record with `ctx.record()`. */
454
+ afterTurn?(turn: CompletedTurn, ctx: HarnessContext): void | Promise<void>;
455
+ /** Per event name (`dtmf`, `silence`, `external`, `application_update`, ...). */
456
+ onEvent?: EventHandlers;
457
+ /** When the call ends. */
458
+ onSessionEnd?(end: SessionEndMessage, ctx: HarnessContext): void | Promise<void>;
459
+ }
460
+ interface HarnessServer {
461
+ /** Start listening. Resolves with the bound address (use port 0 for an ephemeral port). */
462
+ listen(opts: number | {
463
+ port: number;
464
+ host?: string;
465
+ }): Promise<{
466
+ port: number;
467
+ host: string;
468
+ }>;
469
+ /** Close every call's socket and stop listening. */
470
+ close(): Promise<void>;
471
+ }
472
+
473
+ /**
474
+ * createHarness — a complete jambonz harness server (Appendix A protocol) that works unchanged as a
475
+ * pass-through to an OpenAI-compatible model, with hooks for the parts a developer cares about.
476
+ */
477
+
478
+ /**
479
+ * Create a harness server.
480
+ *
481
+ * @example
482
+ * ```ts
483
+ * import { createHarness } from '@jambonz/sdk/harness';
484
+ * createHarness({ model: 'gpt-4.1-mini', instructions: 'You answer calls for Acme.' }).listen(8080);
485
+ * ```
486
+ */
487
+ declare function createHarness(options?: HarnessOptions): HarnessServer;
488
+
489
+ /**
490
+ * Splits streamed text into sentences, so each can be checked before it is spoken.
491
+ */
492
+ /** Accumulates text and returns complete sentences as they form. */
493
+ declare class SentenceSplitter {
494
+ private buffer;
495
+ /** Add streamed text; returns any sentences it completed (each with its trailing whitespace). */
496
+ push(text: string): string[];
497
+ /** Returns whatever is left (the final, possibly unterminated, sentence) and clears it. */
498
+ flush(): string;
499
+ }
500
+
501
+ export { type ApplicationUpdateEvent, type BeforeModelResult, type ChatCompletionChunk, type ChatCompletionChunkDelta, type ChatMessage, type ChatTool, type ChatToolCall, type CommandMessage, type CommandResult, type CommandResultMessage, type CompletedTurn, type DtmfEvent, type ErrorEvent, type EventHandler, type EventHandlers, type EventMessage, type ExternalEvent, HARNESS_PROTOCOL_VERSION, HARNESS_SUBPROTOCOL, type HarnessCommandArgs, type HarnessCommandName, type HarnessContext, type HarnessEvent, type HarnessEventMap, type HarnessOptions, type HarnessServer, type HarnessToJambonzMessage, type HarnessTool, type HarnessTurn, type JambonzToHarnessMessage, type ListenEvent, type ModelClient, type ModelClientOptions, ModelError, type PlaybackEvent, type RecordingEvent, type ReplyChunkMessage, type ReplyDoneMessage, type ReplyDroppedEvent, type ReplySpokenEvent, type SayOptions, SentenceSplitter, type SessionEndMessage, type SessionStartMessage, type SilenceEvent, type SpeechStartMessage, type ToolCallMessage, type ToolResultMessage, type TranscriptMessage, type TransferEvent, type TurnCancelMessage, type TurnInput, type TurnRecord, type TurnStartMessage, type UserInterruptionEvent, createHarness, createModelClient };