@connextar/house 0.25.4 → 0.27.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (102) hide show
  1. package/README.md +112 -0
  2. package/dist/inbox/inbox.d.ts +104 -0
  3. package/dist/inbox/inbox.d.ts.map +1 -0
  4. package/dist/inbox/inbox.js +178 -0
  5. package/dist/inbox/inbox.js.map +1 -0
  6. package/dist/inbox/index.d.ts +11 -0
  7. package/dist/inbox/index.d.ts.map +1 -0
  8. package/dist/inbox/index.js +11 -0
  9. package/dist/inbox/index.js.map +1 -0
  10. package/dist/inbox/use-selection.d.ts +23 -0
  11. package/dist/inbox/use-selection.d.ts.map +1 -0
  12. package/dist/inbox/use-selection.js +51 -0
  13. package/dist/inbox/use-selection.js.map +1 -0
  14. package/dist/voice/handoff.d.ts +20 -0
  15. package/dist/voice/handoff.d.ts.map +1 -0
  16. package/dist/voice/handoff.js +18 -0
  17. package/dist/voice/handoff.js.map +1 -0
  18. package/dist/voice/index.d.ts +16 -0
  19. package/dist/voice/index.d.ts.map +1 -0
  20. package/dist/voice/index.js +16 -0
  21. package/dist/voice/index.js.map +1 -0
  22. package/dist/voice/opening-hours.d.ts +23 -0
  23. package/dist/voice/opening-hours.d.ts.map +1 -0
  24. package/dist/voice/opening-hours.js +117 -0
  25. package/dist/voice/opening-hours.js.map +1 -0
  26. package/dist/voice/out-of-hours.d.ts +29 -0
  27. package/dist/voice/out-of-hours.d.ts.map +1 -0
  28. package/dist/voice/out-of-hours.js +20 -0
  29. package/dist/voice/out-of-hours.js.map +1 -0
  30. package/dist/voice/phone.d.ts +33 -0
  31. package/dist/voice/phone.d.ts.map +1 -0
  32. package/dist/voice/phone.js +62 -0
  33. package/dist/voice/phone.js.map +1 -0
  34. package/dist/voice/relay/agent-client.d.ts +24 -0
  35. package/dist/voice/relay/agent-client.d.ts.map +1 -0
  36. package/dist/voice/relay/agent-client.js +45 -0
  37. package/dist/voice/relay/agent-client.js.map +1 -0
  38. package/dist/voice/relay/model.d.ts +124 -0
  39. package/dist/voice/relay/model.d.ts.map +1 -0
  40. package/dist/voice/relay/model.js +304 -0
  41. package/dist/voice/relay/model.js.map +1 -0
  42. package/dist/voice/relay/protocol.d.ts +44 -0
  43. package/dist/voice/relay/protocol.d.ts.map +1 -0
  44. package/dist/voice/relay/protocol.js +16 -0
  45. package/dist/voice/relay/protocol.js.map +1 -0
  46. package/dist/voice/relay/sentence-gate.d.ts +24 -0
  47. package/dist/voice/relay/sentence-gate.d.ts.map +1 -0
  48. package/dist/voice/relay/sentence-gate.js +65 -0
  49. package/dist/voice/relay/sentence-gate.js.map +1 -0
  50. package/dist/voice/relay/server.d.ts +71 -0
  51. package/dist/voice/relay/server.d.ts.map +1 -0
  52. package/dist/voice/relay/server.js +192 -0
  53. package/dist/voice/relay/server.js.map +1 -0
  54. package/dist/voice/relay/transfer-line.d.ts +33 -0
  55. package/dist/voice/relay/transfer-line.d.ts.map +1 -0
  56. package/dist/voice/relay/transfer-line.js +116 -0
  57. package/dist/voice/relay/transfer-line.js.map +1 -0
  58. package/dist/voice/relay-index.d.ts +13 -0
  59. package/dist/voice/relay-index.d.ts.map +1 -0
  60. package/dist/voice/relay-index.js +13 -0
  61. package/dist/voice/relay-index.js.map +1 -0
  62. package/dist/voice/session-token.d.ts +58 -0
  63. package/dist/voice/session-token.d.ts.map +1 -0
  64. package/dist/voice/session-token.js +152 -0
  65. package/dist/voice/session-token.js.map +1 -0
  66. package/dist/voice/transfer.d.ts +123 -0
  67. package/dist/voice/transfer.d.ts.map +1 -0
  68. package/dist/voice/transfer.js +95 -0
  69. package/dist/voice/transfer.js.map +1 -0
  70. package/dist/voice/twilio-request.d.ts +30 -0
  71. package/dist/voice/twilio-request.d.ts.map +1 -0
  72. package/dist/voice/twilio-request.js +46 -0
  73. package/dist/voice/twilio-request.js.map +1 -0
  74. package/dist/voice/twilio-signature.d.ts +8 -0
  75. package/dist/voice/twilio-signature.d.ts.map +1 -0
  76. package/dist/voice/twilio-signature.js +22 -0
  77. package/dist/voice/twilio-signature.js.map +1 -0
  78. package/dist/voice/twiml.d.ts +93 -0
  79. package/dist/voice/twiml.d.ts.map +1 -0
  80. package/dist/voice/twiml.js +107 -0
  81. package/dist/voice/twiml.js.map +1 -0
  82. package/package.json +19 -1
  83. package/src/inbox/inbox.ts +200 -0
  84. package/src/inbox/index.ts +33 -0
  85. package/src/inbox/use-selection.ts +60 -0
  86. package/src/voice/handoff.ts +34 -0
  87. package/src/voice/index.ts +78 -0
  88. package/src/voice/opening-hours.ts +125 -0
  89. package/src/voice/out-of-hours.ts +48 -0
  90. package/src/voice/phone.ts +68 -0
  91. package/src/voice/relay/agent-client.ts +64 -0
  92. package/src/voice/relay/model.ts +412 -0
  93. package/src/voice/relay/protocol.ts +52 -0
  94. package/src/voice/relay/sentence-gate.ts +64 -0
  95. package/src/voice/relay/server.ts +242 -0
  96. package/src/voice/relay/transfer-line.ts +114 -0
  97. package/src/voice/relay-index.ts +46 -0
  98. package/src/voice/session-token.ts +205 -0
  99. package/src/voice/transfer.ts +171 -0
  100. package/src/voice/twilio-request.ts +60 -0
  101. package/src/voice/twilio-signature.ts +27 -0
  102. package/src/voice/twiml.ts +184 -0
@@ -0,0 +1,64 @@
1
+ /**
2
+ * The relay's side of an app's agent API: JSON over HTTPS with the call's
3
+ * session token as a Bearer token, and every answer in the `{ success, data }`
4
+ * shape the house apps use. The routes and their bodies are the app's own.
5
+ */
6
+
7
+ export class AgentApiError extends Error {
8
+ constructor(
9
+ message: string,
10
+ readonly status?: number,
11
+ ) {
12
+ super(message);
13
+ this.name = "AgentApiError";
14
+ }
15
+ }
16
+
17
+ export interface AgentFetch {
18
+ get<T>(path: string): Promise<T>;
19
+ post<T>(path: string, body: unknown): Promise<T>;
20
+ }
21
+
22
+ export interface AgentFetchOptions {
23
+ /** The app's base URL, such as `https://support.example.com`. */
24
+ baseUrl: string;
25
+ /** The call's session token. */
26
+ sessionToken: string;
27
+ /** Per-request timeout. Default 8 s: a caller is waiting. */
28
+ timeoutMs?: number;
29
+ fetch?: typeof fetch;
30
+ }
31
+
32
+ export function createAgentFetch(o: AgentFetchOptions): AgentFetch {
33
+ const timeoutMs = o.timeoutMs ?? 8_000;
34
+ const doFetch = o.fetch ?? fetch;
35
+
36
+ async function call<T>(method: "GET" | "POST", path: string, body?: unknown): Promise<T> {
37
+ const response = await doFetch(new URL(path, o.baseUrl), {
38
+ method,
39
+ headers: {
40
+ authorization: `Bearer ${o.sessionToken}`,
41
+ ...(body === undefined ? {} : { "content-type": "application/json" }),
42
+ },
43
+ body: body === undefined ? undefined : JSON.stringify(body),
44
+ signal: AbortSignal.timeout(timeoutMs),
45
+ });
46
+ type Answer = { success?: boolean; data?: T; error?: { message?: string } | string };
47
+ let json: Answer | null;
48
+ try {
49
+ json = (await response.json()) as Answer;
50
+ } catch {
51
+ json = null;
52
+ }
53
+ if (!response.ok || !json || json.success === false) {
54
+ const message = typeof json?.error === "string" ? json.error : json?.error?.message;
55
+ throw new AgentApiError(message ?? `Agent API ${method} ${path} failed (${response.status})`, response.status);
56
+ }
57
+ return json.data as T;
58
+ }
59
+
60
+ return {
61
+ get: (path) => call("GET", path),
62
+ post: (path, body) => call("POST", path, body),
63
+ };
64
+ }
@@ -0,0 +1,412 @@
1
+ import { createHash } from "node:crypto";
2
+
3
+ import Anthropic from "@anthropic-ai/sdk";
4
+ import type { MessageStream } from "@anthropic-ai/sdk/lib/MessageStream";
5
+ import OpenAI from "openai";
6
+
7
+ import { PROVIDER_LABELS, type AiProviderName, type ResolvedAi } from "../../ai/config.js";
8
+ import { AiServiceError, OPENAI_MIN_OUTPUT_TOKENS, type AiCallResult } from "../../ai/provider.js";
9
+ import { TransferLineStream } from "./transfer-line.js";
10
+
11
+ /**
12
+ * The one place a voice relay calls either provider's SDK. Lifted from
13
+ * PharmaLineAI (0.27.7); its tools are now the app's, passed in.
14
+ *
15
+ * Everything above this file asks the same thing ("here is the call so far, what
16
+ * do you say and which tool do you want?") and gets back spoken text and tool
17
+ * calls. Which company answered is a deployment decision, not something the call
18
+ * session knows about. The harness in `@connextar/house/ai` answers one message
19
+ * with prose or a parsed object; a phone call is a streamed, multi-turn
20
+ * conversation with tools, which is why this is its own file.
21
+ *
22
+ * It hides three real differences, and deliberately nothing else:
23
+ *
24
+ * 1. **The history has two shapes.** Anthropic takes tool results as blocks in
25
+ * the next user message; OpenAI's Responses API takes them as their own items.
26
+ * 2. **Output budgets mean different things.** An OpenAI reasoning model spends
27
+ * `max_output_tokens` on reasoning before it says a word, hence the floor.
28
+ * 3. **OpenAI stores responses by default.** A call's words are personal data,
29
+ * so `store: false` is sent on every request.
30
+ */
31
+
32
+ /** The slice of the Messages API the dialog needs, so tests can script the model. */
33
+ export type ContentBlock =
34
+ { type: "text"; text: string } | { type: "tool_use"; id: string; name: string; input: Record<string, unknown> };
35
+
36
+ export type ToolResultBlock = { type: "tool_result"; tool_use_id: string; content: string };
37
+
38
+ export interface DialogMessage {
39
+ role: "user" | "assistant";
40
+ content: string | (ContentBlock | ToolResultBlock | { type: "text"; text: string })[];
41
+ }
42
+
43
+ export interface ModelTurn {
44
+ content: ContentBlock[];
45
+ /** The reply stopped at the token limit, so its words and any tool call may be incomplete. */
46
+ cutOff?: boolean;
47
+ }
48
+
49
+ /** What one model request used, as the provider counted it: the harness's usage shape. */
50
+ export type TurnUsage = AiCallResult;
51
+
52
+ /** A tool, described the way the Messages API takes it. */
53
+ export interface DialogTool {
54
+ name: string;
55
+ description: string;
56
+ input_schema: { type: "object"; properties: Record<string, unknown>; required?: string[] };
57
+ }
58
+
59
+ export interface DialogModel {
60
+ respond(args: {
61
+ /** The instructions as blocks, most stable first. Each boundary is a cache boundary. */
62
+ system: string[];
63
+ messages: DialogMessage[];
64
+ signal: AbortSignal;
65
+ /** Streamed text, forwarded to Twilio as it arrives so speech starts early. */
66
+ onText: (delta: string) => void;
67
+ /** The request's token usage, reported once when it is known. */
68
+ onUsage?: (usage: TurnUsage) => void;
69
+ /** Which tool list to offer (`tools(team)`), such as whether anyone can be put through. */
70
+ team?: string;
71
+ }): Promise<ModelTurn>;
72
+ }
73
+
74
+ /** The resolved provider, key and model, how long a reply may run, and the app's tools. */
75
+ export interface DialogModelOptions extends ResolvedAi {
76
+ maxTokens?: number;
77
+ /** How hard an OpenAI reasoning model thinks before it speaks. Sent only when set. */
78
+ reasoningEffort?: OpenAI.ReasoningEffort;
79
+ /** How hard a current Claude model thinks before it speaks. Sent only when set. */
80
+ anthropicEffort?: Anthropic.OutputConfig["effort"];
81
+ /** Claude only: `disabled` turns its adaptive thinking off, for measuring; not a default. */
82
+ anthropicThinking?: "adaptive" | "disabled";
83
+ /** The tools offered for each `team` value (default `"open"`). Called once per value and kept. */
84
+ tools: (team: string) => DialogTool[];
85
+ /** The tool whose `say` argument is spoken while it streams, such as `transfer_to_team`. */
86
+ transferTool?: string;
87
+ /** Flags on the transfer tool that silence its streamed line (see `TransferLineStream`). */
88
+ transferSilentKeys?: readonly string[];
89
+ /** Names the shared prompt cache on OpenAI (`cacheKey`). */
90
+ cacheKeyPrefix?: string;
91
+ }
92
+
93
+ /** A spoken sentence or two needs very little room. */
94
+ const DEFAULT_MAX_TOKENS = 400;
95
+ /**
96
+ * Current Claude models think before they answer unless told not to, and the
97
+ * thinking counts against `max_tokens`: at 400, Claude Sonnet 5 was cut off
98
+ * mid-thought on an urgent call and said nothing. The cap is a safety net.
99
+ */
100
+ const ANTHROPIC_MAX_TOKENS = 2000;
101
+
102
+ /**
103
+ * What one response says out loud: the model's words as they stream, then a
104
+ * transfer's line as it is written, with a space between the two.
105
+ */
106
+ function speaker(onText: (delta: string) => void, silentKeys: readonly string[]) {
107
+ let spoke = false;
108
+ let words = "";
109
+ return {
110
+ words(delta: string) {
111
+ if (!delta) return;
112
+ spoke = true;
113
+ words += delta;
114
+ onText(delta);
115
+ },
116
+ transferLine(): TransferLineStream {
117
+ let first = true;
118
+ return new TransferLineStream(
119
+ (piece) => {
120
+ onText(first && spoke ? ` ${piece}` : piece);
121
+ first = false;
122
+ spoke = true;
123
+ },
124
+ words,
125
+ silentKeys,
126
+ );
127
+ },
128
+ };
129
+ }
130
+
131
+ function memo<T>(make: (team: string) => T): (team: string) => T {
132
+ const cache = new Map<string, T>();
133
+ return (team) => {
134
+ let value = cache.get(team);
135
+ if (!value) {
136
+ value = make(team);
137
+ cache.set(team, value);
138
+ }
139
+ return value;
140
+ };
141
+ }
142
+
143
+ /** Claude's tools. The transfer streams its arguments as they are written, so its line can be spoken early. */
144
+ export function anthropicTools(tools: DialogTool[], transferTool?: string): Anthropic.Tool[] {
145
+ return tools.map((tool) =>
146
+ tool.name === transferTool ? { ...tool, eager_input_streaming: true } : tool,
147
+ ) as unknown as Anthropic.Tool[];
148
+ }
149
+
150
+ /** The same tools, described the way the Responses API asks for them. */
151
+ export function openAiTools(tools: DialogTool[]): OpenAI.Responses.FunctionTool[] {
152
+ return tools.map((tool) => ({
153
+ type: "function",
154
+ name: tool.name,
155
+ description: tool.description,
156
+ parameters: { ...tool.input_schema, additionalProperties: false },
157
+ // Not strict: a tool that takes no arguments, or optional ones, would otherwise be refused.
158
+ strict: false,
159
+ }));
160
+ }
161
+
162
+ /** The dialog policy for the configured provider, streaming text and calling the app's tools. */
163
+ export function createDialogModel(opts: DialogModelOptions): DialogModel {
164
+ return opts.provider === "OPENAI" ? createOpenAiModel(opts) : createAnthropicModel(opts);
165
+ }
166
+
167
+ /** Turn either SDK's error into the harness's, which the relay log names the provider in. */
168
+ function asDialogError(error: unknown, provider: AiProviderName): never {
169
+ if (error instanceof Anthropic.APIError || error instanceof OpenAI.APIError) {
170
+ const status = typeof error.status === "number" ? error.status : undefined;
171
+ throw new AiServiceError(
172
+ `${PROVIDER_LABELS[provider]} refused the request (${status ?? "no status"}): ${error.message}`,
173
+ status,
174
+ );
175
+ }
176
+ throw error;
177
+ }
178
+
179
+ /** Anthropic's usage block, in the relay's terms. Its `input_tokens` already excludes the cache. */
180
+ export function anthropicUsage(model: string, usage: Anthropic.Usage): TurnUsage {
181
+ return {
182
+ provider: "ANTHROPIC",
183
+ model,
184
+ inputTokens: usage.input_tokens,
185
+ outputTokens: usage.output_tokens,
186
+ cacheReadTokens: usage.cache_read_input_tokens ?? 0,
187
+ cacheWriteTokens: usage.cache_creation_input_tokens ?? 0,
188
+ };
189
+ }
190
+
191
+ /**
192
+ * OpenAI's usage block, in the relay's terms. OpenAI counts cache reads and
193
+ * writes inside `input_tokens`, so both are taken out and priced at their own
194
+ * rates; reasoning tokens are already inside `output_tokens`.
195
+ */
196
+ export function openAiUsage(model: string, usage: OpenAI.Responses.ResponseUsage): TurnUsage {
197
+ const cacheRead = usage.input_tokens_details?.cached_tokens ?? 0;
198
+ const cacheWrite = usage.input_tokens_details?.cache_write_tokens ?? 0;
199
+ return {
200
+ provider: "OPENAI",
201
+ model,
202
+ inputTokens: Math.max(0, usage.input_tokens - cacheRead - cacheWrite),
203
+ outputTokens: usage.output_tokens,
204
+ cacheReadTokens: cacheRead,
205
+ cacheWriteTokens: cacheWrite,
206
+ };
207
+ }
208
+
209
+ function createAnthropicModel(opts: DialogModelOptions): DialogModel {
210
+ const client = new Anthropic({ apiKey: opts.apiKey });
211
+ const toolsFor = memo((team) => anthropicTools(opts.tools(team), opts.transferTool));
212
+ const silent = opts.transferSilentKeys ?? [];
213
+ return {
214
+ async respond({ system, messages, signal, onText, onUsage, team }) {
215
+ let stream: MessageStream | undefined;
216
+ try {
217
+ stream = client.messages.stream(
218
+ {
219
+ model: opts.model,
220
+ max_tokens: opts.maxTokens ?? ANTHROPIC_MAX_TOKENS,
221
+ ...(opts.anthropicEffort ? { output_config: { effort: opts.anthropicEffort } } : {}),
222
+ ...(opts.anthropicThinking ? { thinking: { type: opts.anthropicThinking } } : {}),
223
+ // A cache boundary after each block of instructions and one on the conversation so
224
+ // far, so each request pays full price only for what is new. Four: the most allowed.
225
+ system: system.map((text) => ({
226
+ type: "text" as const,
227
+ text,
228
+ cache_control: { type: "ephemeral" as const },
229
+ })),
230
+ tools: toolsFor(team ?? "open"),
231
+ messages: withConversationCached(messages),
232
+ },
233
+ { signal },
234
+ );
235
+ const speak = speaker(onText, silent);
236
+ const lines = new Map<number, TransferLineStream>();
237
+ stream.on("text", (delta) => speak.words(delta));
238
+ stream.on("streamEvent", (event) => {
239
+ if (event.type === "content_block_start" && event.content_block.type === "tool_use") {
240
+ if (opts.transferTool && event.content_block.name === opts.transferTool) {
241
+ lines.set(event.index, speak.transferLine());
242
+ }
243
+ } else if (event.type === "content_block_delta" && event.delta.type === "input_json_delta") {
244
+ lines.get(event.index)?.push(event.delta.partial_json);
245
+ }
246
+ });
247
+ const message = await stream.finalMessage();
248
+ const content: ContentBlock[] = [];
249
+ for (const block of message.content) {
250
+ if (block.type === "text") content.push({ type: "text", text: block.text });
251
+ if (block.type === "tool_use") {
252
+ content.push({
253
+ type: "tool_use",
254
+ id: block.id,
255
+ name: block.name,
256
+ input: block.input as Record<string, unknown>,
257
+ });
258
+ }
259
+ }
260
+ // Last, so nothing after it can throw into the catch and count the request twice.
261
+ onUsage?.(anthropicUsage(message.model, message.usage));
262
+ return { content, cutOff: message.stop_reason === "max_tokens" };
263
+ } catch (error) {
264
+ // A caller who talks over the agent aborts the request, but the prompt was already
265
+ // read, and billed. What the stream had counted by then is still the cost.
266
+ const partial = stream?.currentMessage;
267
+ if (partial) onUsage?.(anthropicUsage(partial.model, partial.usage));
268
+ asDialogError(error, "ANTHROPIC");
269
+ }
270
+ },
271
+ };
272
+ }
273
+
274
+ function createOpenAiModel(opts: DialogModelOptions): DialogModel {
275
+ const client = new OpenAI({ apiKey: opts.apiKey });
276
+ const toolsFor = memo((team) => openAiTools(opts.tools(team)));
277
+ const silent = opts.transferSilentKeys ?? [];
278
+ return {
279
+ async respond({ system, messages, signal, onText, onUsage, team }) {
280
+ try {
281
+ const stream = client.responses.stream(
282
+ {
283
+ model: opts.model,
284
+ instructions: system.join("\n\n"),
285
+ // OpenAI caches prefixes by itself; the key sends requests that share the first
286
+ // block to the same cache, whichever tenant they are for.
287
+ prompt_cache_key: cacheKey(system, opts.cacheKeyPrefix),
288
+ input: toResponsesInput(messages),
289
+ tools: toolsFor(team ?? "open"),
290
+ max_output_tokens: Math.max(opts.maxTokens ?? DEFAULT_MAX_TOKENS, OPENAI_MIN_OUTPUT_TOKENS),
291
+ ...(opts.reasoningEffort ? { reasoning: { effort: opts.reasoningEffort } } : {}),
292
+ // A call's words are personal data: OpenAI keeps none of it for us.
293
+ store: false,
294
+ },
295
+ { signal },
296
+ );
297
+ const speak = speaker(onText, silent);
298
+ const lines = new Map<number, TransferLineStream>();
299
+ stream.on("response.output_text.delta", (event) => speak.words(event.delta));
300
+ stream.on("response.output_item.added", (event) => {
301
+ if (event.item.type === "function_call" && opts.transferTool && event.item.name === opts.transferTool) {
302
+ lines.set(event.output_index, speak.transferLine());
303
+ }
304
+ });
305
+ stream.on("response.function_call_arguments.delta", (event) =>
306
+ lines.get(event.output_index)?.push(event.delta),
307
+ );
308
+ const response = await stream.finalResponse();
309
+ // OpenAI reports usage only on a completed response, so an interrupted request
310
+ // goes unmetered here: the report undercounts OpenAI slightly.
311
+ if (response.usage) onUsage?.(openAiUsage(response.model, response.usage));
312
+ const content: ContentBlock[] = [];
313
+ for (const item of response.output) {
314
+ if (item.type === "message") {
315
+ for (const part of item.content) {
316
+ if (part.type === "output_text") content.push({ type: "text", text: part.text });
317
+ }
318
+ }
319
+ if (item.type === "function_call") {
320
+ content.push({
321
+ type: "tool_use",
322
+ id: item.call_id,
323
+ name: item.name,
324
+ input: parseArguments(item.arguments),
325
+ });
326
+ }
327
+ }
328
+ return { content, cutOff: response.status === "incomplete" };
329
+ } catch (error) {
330
+ asDialogError(error, "OPENAI");
331
+ }
332
+ },
333
+ };
334
+ }
335
+
336
+ /** Names the shared prefix: the first block of instructions, the same for every tenant. */
337
+ export function cacheKey(system: string[], prefix = "voice-dialog"): string {
338
+ return `${prefix}-${createHash("sha256")
339
+ .update(system[0] ?? "")
340
+ .digest("hex")
341
+ .slice(0, 16)}`;
342
+ }
343
+
344
+ /**
345
+ * The conversation with a cache boundary on its last block, so the next request
346
+ * reads everything said so far from the cache. A copy: the history is left alone.
347
+ */
348
+ export function withConversationCached(messages: DialogMessage[]): Anthropic.MessageParam[] {
349
+ const params = messages as unknown as Anthropic.MessageParam[];
350
+ const last = params[params.length - 1];
351
+ if (!last) return params;
352
+ const blocks: Anthropic.ContentBlockParam[] =
353
+ typeof last.content === "string" ? [{ type: "text", text: last.content }] : [...last.content];
354
+ const final = blocks[blocks.length - 1];
355
+ if (!final || (final.type === "text" && !final.text)) return params;
356
+ blocks[blocks.length - 1] = { ...final, cache_control: { type: "ephemeral" } } as Anthropic.ContentBlockParam;
357
+ return [...params.slice(0, -1), { ...last, content: blocks }];
358
+ }
359
+
360
+ /** A model that writes malformed arguments gets an empty object, and the app's tool decides. */
361
+ function parseArguments(args: string): Record<string, unknown> {
362
+ try {
363
+ const parsed: unknown = JSON.parse(args);
364
+ return parsed && typeof parsed === "object" ? (parsed as Record<string, unknown>) : {};
365
+ } catch {
366
+ return {};
367
+ }
368
+ }
369
+
370
+ /**
371
+ * The call so far, as Responses API input items. Text becomes a message, a tool
372
+ * call a `function_call` and its result a `function_call_output`, in order.
373
+ * Items carry no `id`, so they are read as fresh input, which is what lets
374
+ * `store: false` work across turns.
375
+ */
376
+ export function toResponsesInput(messages: DialogMessage[]): OpenAI.Responses.ResponseInputItem[] {
377
+ const items: OpenAI.Responses.ResponseInputItem[] = [];
378
+
379
+ for (const message of messages) {
380
+ if (typeof message.content === "string") {
381
+ items.push({ role: message.role, content: message.content });
382
+ continue;
383
+ }
384
+
385
+ let text = "";
386
+ const flush = () => {
387
+ if (text.trim()) items.push({ role: message.role, content: text });
388
+ text = "";
389
+ };
390
+
391
+ for (const block of message.content) {
392
+ if (block.type === "text") {
393
+ text += text ? `\n${block.text}` : block.text;
394
+ continue;
395
+ }
396
+ flush();
397
+ if (block.type === "tool_use") {
398
+ items.push({
399
+ type: "function_call",
400
+ call_id: block.id,
401
+ name: block.name,
402
+ arguments: JSON.stringify(block.input),
403
+ });
404
+ } else {
405
+ items.push({ type: "function_call_output", call_id: block.tool_use_id, output: block.content });
406
+ }
407
+ }
408
+ flush();
409
+ }
410
+
411
+ return items;
412
+ }
@@ -0,0 +1,52 @@
1
+ /**
2
+ * Twilio ConversationRelay WebSocket messages (the subset the relay uses).
3
+ * https://www.twilio.com/docs/voice/conversationrelay/websocket-messages
4
+ */
5
+
6
+ export interface SetupMessage {
7
+ type: "setup";
8
+ sessionId: string;
9
+ callSid: string;
10
+ from?: string;
11
+ to?: string;
12
+ forwardedFrom?: string;
13
+ customParameters?: Record<string, string>;
14
+ }
15
+
16
+ export interface PromptMessage {
17
+ type: "prompt";
18
+ voicePrompt: string;
19
+ lang?: string;
20
+ last?: boolean;
21
+ }
22
+
23
+ export interface InterruptMessage {
24
+ type: "interrupt";
25
+ utteranceUntilInterrupt?: string;
26
+ durationUntilInterruptMs?: number;
27
+ }
28
+
29
+ export interface DtmfMessage {
30
+ type: "dtmf";
31
+ digit: string;
32
+ }
33
+
34
+ export interface ErrorMessage {
35
+ type: "error";
36
+ description?: string;
37
+ }
38
+
39
+ export type InboundMessage = SetupMessage | PromptMessage | InterruptMessage | DtmfMessage | ErrorMessage;
40
+
41
+ export type OutboundMessage =
42
+ { type: "text"; token: string; last: boolean; interruptible?: boolean } | { type: "end"; handoffData?: string };
43
+
44
+ export function parseInbound(raw: string): InboundMessage | null {
45
+ try {
46
+ const data = JSON.parse(raw) as { type?: unknown };
47
+ if (typeof data?.type !== "string") return null;
48
+ return data as InboundMessage;
49
+ } catch {
50
+ return null;
51
+ }
52
+ }
@@ -0,0 +1,64 @@
1
+ /**
2
+ * Holds streamed words back a sentence at a time, and lets through only the sentences that pass.
3
+ *
4
+ * Out of hours nobody can be put through, but models were found saying "I'm putting you through
5
+ * now" anyway — 26 of 62 starter scenarios on gpt-5-mini, told plainly not to. Words are spoken as
6
+ * they stream, so a promise can't be taken back once said; held until its sentence ends, it can be
7
+ * dropped. That costs the first sentence's worth of time to the first word, and only out of hours.
8
+ *
9
+ * A sentence ends at `.`, `!` or `?` followed by a space, so "6.30pm" and "£16.50" stay whole.
10
+ */
11
+ export class SentenceGate {
12
+ private pending = "";
13
+
14
+ constructor(
15
+ private readonly emit: (text: string) => void,
16
+ private readonly drop: (sentence: string) => boolean,
17
+ ) {}
18
+
19
+ push(delta: string): void {
20
+ this.pending += delta;
21
+ const end = lastSentenceEnd(this.pending);
22
+ if (end === -1) return;
23
+ const complete = this.pending.slice(0, end);
24
+ this.pending = this.pending.slice(end);
25
+ this.release(complete);
26
+ }
27
+
28
+ /** The stream ended: what's left is the last sentence. */
29
+ flush(): void {
30
+ const rest = this.pending;
31
+ this.pending = "";
32
+ if (rest.trim()) this.release(rest);
33
+ }
34
+
35
+ private release(text: string) {
36
+ let start = 0;
37
+ for (const match of text.matchAll(/[.!?]+(?:\s+|$)/g)) {
38
+ const end = match.index + match[0].length;
39
+ this.pass(text.slice(start, end));
40
+ start = end;
41
+ }
42
+ if (start < text.length) this.pass(text.slice(start));
43
+ }
44
+
45
+ private pass(sentence: string) {
46
+ if (sentence.trim() && !this.drop(sentence)) this.emit(sentence);
47
+ }
48
+ }
49
+
50
+ /** Where the last complete sentence (and the space after it) ends, or -1. */
51
+ function lastSentenceEnd(text: string): number {
52
+ let end = -1;
53
+ for (const match of text.matchAll(/[.!?]+\s+/g)) end = match.index + match[0].length;
54
+ return end;
55
+ }
56
+
57
+ /** A finished text with the sentences that fail removed — for a line that wasn't streamed. */
58
+ export function keepSentences(text: string, drop: (sentence: string) => boolean): string {
59
+ let out = "";
60
+ const gate = new SentenceGate((s) => (out += s), drop);
61
+ gate.push(text);
62
+ gate.flush();
63
+ return out.trim();
64
+ }