@connextar/house 0.26.0 → 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.
- package/README.md +74 -0
- package/dist/voice/handoff.d.ts +20 -0
- package/dist/voice/handoff.d.ts.map +1 -0
- package/dist/voice/handoff.js +18 -0
- package/dist/voice/handoff.js.map +1 -0
- package/dist/voice/index.d.ts +16 -0
- package/dist/voice/index.d.ts.map +1 -0
- package/dist/voice/index.js +16 -0
- package/dist/voice/index.js.map +1 -0
- package/dist/voice/opening-hours.d.ts +23 -0
- package/dist/voice/opening-hours.d.ts.map +1 -0
- package/dist/voice/opening-hours.js +117 -0
- package/dist/voice/opening-hours.js.map +1 -0
- package/dist/voice/out-of-hours.d.ts +29 -0
- package/dist/voice/out-of-hours.d.ts.map +1 -0
- package/dist/voice/out-of-hours.js +20 -0
- package/dist/voice/out-of-hours.js.map +1 -0
- package/dist/voice/phone.d.ts +33 -0
- package/dist/voice/phone.d.ts.map +1 -0
- package/dist/voice/phone.js +62 -0
- package/dist/voice/phone.js.map +1 -0
- package/dist/voice/relay/agent-client.d.ts +24 -0
- package/dist/voice/relay/agent-client.d.ts.map +1 -0
- package/dist/voice/relay/agent-client.js +45 -0
- package/dist/voice/relay/agent-client.js.map +1 -0
- package/dist/voice/relay/model.d.ts +124 -0
- package/dist/voice/relay/model.d.ts.map +1 -0
- package/dist/voice/relay/model.js +304 -0
- package/dist/voice/relay/model.js.map +1 -0
- package/dist/voice/relay/protocol.d.ts +44 -0
- package/dist/voice/relay/protocol.d.ts.map +1 -0
- package/dist/voice/relay/protocol.js +16 -0
- package/dist/voice/relay/protocol.js.map +1 -0
- package/dist/voice/relay/sentence-gate.d.ts +24 -0
- package/dist/voice/relay/sentence-gate.d.ts.map +1 -0
- package/dist/voice/relay/sentence-gate.js +65 -0
- package/dist/voice/relay/sentence-gate.js.map +1 -0
- package/dist/voice/relay/server.d.ts +71 -0
- package/dist/voice/relay/server.d.ts.map +1 -0
- package/dist/voice/relay/server.js +192 -0
- package/dist/voice/relay/server.js.map +1 -0
- package/dist/voice/relay/transfer-line.d.ts +33 -0
- package/dist/voice/relay/transfer-line.d.ts.map +1 -0
- package/dist/voice/relay/transfer-line.js +116 -0
- package/dist/voice/relay/transfer-line.js.map +1 -0
- package/dist/voice/relay-index.d.ts +13 -0
- package/dist/voice/relay-index.d.ts.map +1 -0
- package/dist/voice/relay-index.js +13 -0
- package/dist/voice/relay-index.js.map +1 -0
- package/dist/voice/session-token.d.ts +58 -0
- package/dist/voice/session-token.d.ts.map +1 -0
- package/dist/voice/session-token.js +152 -0
- package/dist/voice/session-token.js.map +1 -0
- package/dist/voice/transfer.d.ts +123 -0
- package/dist/voice/transfer.d.ts.map +1 -0
- package/dist/voice/transfer.js +95 -0
- package/dist/voice/transfer.js.map +1 -0
- package/dist/voice/twilio-request.d.ts +30 -0
- package/dist/voice/twilio-request.d.ts.map +1 -0
- package/dist/voice/twilio-request.js +46 -0
- package/dist/voice/twilio-request.js.map +1 -0
- package/dist/voice/twilio-signature.d.ts +8 -0
- package/dist/voice/twilio-signature.d.ts.map +1 -0
- package/dist/voice/twilio-signature.js +22 -0
- package/dist/voice/twilio-signature.js.map +1 -0
- package/dist/voice/twiml.d.ts +93 -0
- package/dist/voice/twiml.d.ts.map +1 -0
- package/dist/voice/twiml.js +107 -0
- package/dist/voice/twiml.js.map +1 -0
- package/package.json +15 -1
- package/src/voice/handoff.ts +34 -0
- package/src/voice/index.ts +78 -0
- package/src/voice/opening-hours.ts +125 -0
- package/src/voice/out-of-hours.ts +48 -0
- package/src/voice/phone.ts +68 -0
- package/src/voice/relay/agent-client.ts +64 -0
- package/src/voice/relay/model.ts +412 -0
- package/src/voice/relay/protocol.ts +52 -0
- package/src/voice/relay/sentence-gate.ts +64 -0
- package/src/voice/relay/server.ts +242 -0
- package/src/voice/relay/transfer-line.ts +114 -0
- package/src/voice/relay-index.ts +46 -0
- package/src/voice/session-token.ts +205 -0
- package/src/voice/transfer.ts +171 -0
- package/src/voice/twilio-request.ts +60 -0
- package/src/voice/twilio-signature.ts +27 -0
- package/src/voice/twiml.ts +184 -0
|
@@ -0,0 +1,124 @@
|
|
|
1
|
+
import Anthropic from "@anthropic-ai/sdk";
|
|
2
|
+
import OpenAI from "openai";
|
|
3
|
+
import { type ResolvedAi } from "../../ai/config.js";
|
|
4
|
+
import { type AiCallResult } from "../../ai/provider.js";
|
|
5
|
+
/**
|
|
6
|
+
* The one place a voice relay calls either provider's SDK. Lifted from
|
|
7
|
+
* PharmaLineAI (0.27.7); its tools are now the app's, passed in.
|
|
8
|
+
*
|
|
9
|
+
* Everything above this file asks the same thing ("here is the call so far, what
|
|
10
|
+
* do you say and which tool do you want?") and gets back spoken text and tool
|
|
11
|
+
* calls. Which company answered is a deployment decision, not something the call
|
|
12
|
+
* session knows about. The harness in `@connextar/house/ai` answers one message
|
|
13
|
+
* with prose or a parsed object; a phone call is a streamed, multi-turn
|
|
14
|
+
* conversation with tools, which is why this is its own file.
|
|
15
|
+
*
|
|
16
|
+
* It hides three real differences, and deliberately nothing else:
|
|
17
|
+
*
|
|
18
|
+
* 1. **The history has two shapes.** Anthropic takes tool results as blocks in
|
|
19
|
+
* the next user message; OpenAI's Responses API takes them as their own items.
|
|
20
|
+
* 2. **Output budgets mean different things.** An OpenAI reasoning model spends
|
|
21
|
+
* `max_output_tokens` on reasoning before it says a word, hence the floor.
|
|
22
|
+
* 3. **OpenAI stores responses by default.** A call's words are personal data,
|
|
23
|
+
* so `store: false` is sent on every request.
|
|
24
|
+
*/
|
|
25
|
+
/** The slice of the Messages API the dialog needs, so tests can script the model. */
|
|
26
|
+
export type ContentBlock = {
|
|
27
|
+
type: "text";
|
|
28
|
+
text: string;
|
|
29
|
+
} | {
|
|
30
|
+
type: "tool_use";
|
|
31
|
+
id: string;
|
|
32
|
+
name: string;
|
|
33
|
+
input: Record<string, unknown>;
|
|
34
|
+
};
|
|
35
|
+
export type ToolResultBlock = {
|
|
36
|
+
type: "tool_result";
|
|
37
|
+
tool_use_id: string;
|
|
38
|
+
content: string;
|
|
39
|
+
};
|
|
40
|
+
export interface DialogMessage {
|
|
41
|
+
role: "user" | "assistant";
|
|
42
|
+
content: string | (ContentBlock | ToolResultBlock | {
|
|
43
|
+
type: "text";
|
|
44
|
+
text: string;
|
|
45
|
+
})[];
|
|
46
|
+
}
|
|
47
|
+
export interface ModelTurn {
|
|
48
|
+
content: ContentBlock[];
|
|
49
|
+
/** The reply stopped at the token limit, so its words and any tool call may be incomplete. */
|
|
50
|
+
cutOff?: boolean;
|
|
51
|
+
}
|
|
52
|
+
/** What one model request used, as the provider counted it: the harness's usage shape. */
|
|
53
|
+
export type TurnUsage = AiCallResult;
|
|
54
|
+
/** A tool, described the way the Messages API takes it. */
|
|
55
|
+
export interface DialogTool {
|
|
56
|
+
name: string;
|
|
57
|
+
description: string;
|
|
58
|
+
input_schema: {
|
|
59
|
+
type: "object";
|
|
60
|
+
properties: Record<string, unknown>;
|
|
61
|
+
required?: string[];
|
|
62
|
+
};
|
|
63
|
+
}
|
|
64
|
+
export interface DialogModel {
|
|
65
|
+
respond(args: {
|
|
66
|
+
/** The instructions as blocks, most stable first. Each boundary is a cache boundary. */
|
|
67
|
+
system: string[];
|
|
68
|
+
messages: DialogMessage[];
|
|
69
|
+
signal: AbortSignal;
|
|
70
|
+
/** Streamed text, forwarded to Twilio as it arrives so speech starts early. */
|
|
71
|
+
onText: (delta: string) => void;
|
|
72
|
+
/** The request's token usage, reported once when it is known. */
|
|
73
|
+
onUsage?: (usage: TurnUsage) => void;
|
|
74
|
+
/** Which tool list to offer (`tools(team)`), such as whether anyone can be put through. */
|
|
75
|
+
team?: string;
|
|
76
|
+
}): Promise<ModelTurn>;
|
|
77
|
+
}
|
|
78
|
+
/** The resolved provider, key and model, how long a reply may run, and the app's tools. */
|
|
79
|
+
export interface DialogModelOptions extends ResolvedAi {
|
|
80
|
+
maxTokens?: number;
|
|
81
|
+
/** How hard an OpenAI reasoning model thinks before it speaks. Sent only when set. */
|
|
82
|
+
reasoningEffort?: OpenAI.ReasoningEffort;
|
|
83
|
+
/** How hard a current Claude model thinks before it speaks. Sent only when set. */
|
|
84
|
+
anthropicEffort?: Anthropic.OutputConfig["effort"];
|
|
85
|
+
/** Claude only: `disabled` turns its adaptive thinking off, for measuring; not a default. */
|
|
86
|
+
anthropicThinking?: "adaptive" | "disabled";
|
|
87
|
+
/** The tools offered for each `team` value (default `"open"`). Called once per value and kept. */
|
|
88
|
+
tools: (team: string) => DialogTool[];
|
|
89
|
+
/** The tool whose `say` argument is spoken while it streams, such as `transfer_to_team`. */
|
|
90
|
+
transferTool?: string;
|
|
91
|
+
/** Flags on the transfer tool that silence its streamed line (see `TransferLineStream`). */
|
|
92
|
+
transferSilentKeys?: readonly string[];
|
|
93
|
+
/** Names the shared prompt cache on OpenAI (`cacheKey`). */
|
|
94
|
+
cacheKeyPrefix?: string;
|
|
95
|
+
}
|
|
96
|
+
/** Claude's tools. The transfer streams its arguments as they are written, so its line can be spoken early. */
|
|
97
|
+
export declare function anthropicTools(tools: DialogTool[], transferTool?: string): Anthropic.Tool[];
|
|
98
|
+
/** The same tools, described the way the Responses API asks for them. */
|
|
99
|
+
export declare function openAiTools(tools: DialogTool[]): OpenAI.Responses.FunctionTool[];
|
|
100
|
+
/** The dialog policy for the configured provider, streaming text and calling the app's tools. */
|
|
101
|
+
export declare function createDialogModel(opts: DialogModelOptions): DialogModel;
|
|
102
|
+
/** Anthropic's usage block, in the relay's terms. Its `input_tokens` already excludes the cache. */
|
|
103
|
+
export declare function anthropicUsage(model: string, usage: Anthropic.Usage): TurnUsage;
|
|
104
|
+
/**
|
|
105
|
+
* OpenAI's usage block, in the relay's terms. OpenAI counts cache reads and
|
|
106
|
+
* writes inside `input_tokens`, so both are taken out and priced at their own
|
|
107
|
+
* rates; reasoning tokens are already inside `output_tokens`.
|
|
108
|
+
*/
|
|
109
|
+
export declare function openAiUsage(model: string, usage: OpenAI.Responses.ResponseUsage): TurnUsage;
|
|
110
|
+
/** Names the shared prefix: the first block of instructions, the same for every tenant. */
|
|
111
|
+
export declare function cacheKey(system: string[], prefix?: string): string;
|
|
112
|
+
/**
|
|
113
|
+
* The conversation with a cache boundary on its last block, so the next request
|
|
114
|
+
* reads everything said so far from the cache. A copy: the history is left alone.
|
|
115
|
+
*/
|
|
116
|
+
export declare function withConversationCached(messages: DialogMessage[]): Anthropic.MessageParam[];
|
|
117
|
+
/**
|
|
118
|
+
* The call so far, as Responses API input items. Text becomes a message, a tool
|
|
119
|
+
* call a `function_call` and its result a `function_call_output`, in order.
|
|
120
|
+
* Items carry no `id`, so they are read as fresh input, which is what lets
|
|
121
|
+
* `store: false` work across turns.
|
|
122
|
+
*/
|
|
123
|
+
export declare function toResponsesInput(messages: DialogMessage[]): OpenAI.Responses.ResponseInputItem[];
|
|
124
|
+
//# sourceMappingURL=model.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"model.d.ts","sourceRoot":"","sources":["../../../src/voice/relay/model.ts"],"names":[],"mappings":"AAEA,OAAO,SAAS,MAAM,mBAAmB,CAAC;AAE1C,OAAO,MAAM,MAAM,QAAQ,CAAC;AAE5B,OAAO,EAAwC,KAAK,UAAU,EAAE,MAAM,oBAAoB,CAAC;AAC3F,OAAO,EAA4C,KAAK,YAAY,EAAE,MAAM,sBAAsB,CAAC;AAGnG;;;;;;;;;;;;;;;;;;;GAmBG;AAEH,qFAAqF;AACrF,MAAM,MAAM,YAAY,GACtB;IAAE,IAAI,EAAE,MAAM,CAAC;IAAC,IAAI,EAAE,MAAM,CAAA;CAAE,GAAG;IAAE,IAAI,EAAE,UAAU,CAAC;IAAC,EAAE,EAAE,MAAM,CAAC;IAAC,IAAI,EAAE,MAAM,CAAC;IAAC,KAAK,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAA;CAAE,CAAC;AAElH,MAAM,MAAM,eAAe,GAAG;IAAE,IAAI,EAAE,aAAa,CAAC;IAAC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SAAS,CAAC,YAAY,EAAE,CAU1F;AAYD;;;;;GAKG;AACH,wBAAgB,gBAAgB,CAAC,QAAQ,EAAE,aAAa,EAAE,GAAG,MAAM,CAAC,SAAS,CAAC,iBAAiB,EAAE,CAoChG"}
|
|
@@ -0,0 +1,304 @@
|
|
|
1
|
+
import { createHash } from "node:crypto";
|
|
2
|
+
import Anthropic from "@anthropic-ai/sdk";
|
|
3
|
+
import OpenAI from "openai";
|
|
4
|
+
import { PROVIDER_LABELS } from "../../ai/config.js";
|
|
5
|
+
import { AiServiceError, OPENAI_MIN_OUTPUT_TOKENS } from "../../ai/provider.js";
|
|
6
|
+
import { TransferLineStream } from "./transfer-line.js";
|
|
7
|
+
/** A spoken sentence or two needs very little room. */
|
|
8
|
+
const DEFAULT_MAX_TOKENS = 400;
|
|
9
|
+
/**
|
|
10
|
+
* Current Claude models think before they answer unless told not to, and the
|
|
11
|
+
* thinking counts against `max_tokens`: at 400, Claude Sonnet 5 was cut off
|
|
12
|
+
* mid-thought on an urgent call and said nothing. The cap is a safety net.
|
|
13
|
+
*/
|
|
14
|
+
const ANTHROPIC_MAX_TOKENS = 2000;
|
|
15
|
+
/**
|
|
16
|
+
* What one response says out loud: the model's words as they stream, then a
|
|
17
|
+
* transfer's line as it is written, with a space between the two.
|
|
18
|
+
*/
|
|
19
|
+
function speaker(onText, silentKeys) {
|
|
20
|
+
let spoke = false;
|
|
21
|
+
let words = "";
|
|
22
|
+
return {
|
|
23
|
+
words(delta) {
|
|
24
|
+
if (!delta)
|
|
25
|
+
return;
|
|
26
|
+
spoke = true;
|
|
27
|
+
words += delta;
|
|
28
|
+
onText(delta);
|
|
29
|
+
},
|
|
30
|
+
transferLine() {
|
|
31
|
+
let first = true;
|
|
32
|
+
return new TransferLineStream((piece) => {
|
|
33
|
+
onText(first && spoke ? ` ${piece}` : piece);
|
|
34
|
+
first = false;
|
|
35
|
+
spoke = true;
|
|
36
|
+
}, words, silentKeys);
|
|
37
|
+
},
|
|
38
|
+
};
|
|
39
|
+
}
|
|
40
|
+
function memo(make) {
|
|
41
|
+
const cache = new Map();
|
|
42
|
+
return (team) => {
|
|
43
|
+
let value = cache.get(team);
|
|
44
|
+
if (!value) {
|
|
45
|
+
value = make(team);
|
|
46
|
+
cache.set(team, value);
|
|
47
|
+
}
|
|
48
|
+
return value;
|
|
49
|
+
};
|
|
50
|
+
}
|
|
51
|
+
/** Claude's tools. The transfer streams its arguments as they are written, so its line can be spoken early. */
|
|
52
|
+
export function anthropicTools(tools, transferTool) {
|
|
53
|
+
return tools.map((tool) => tool.name === transferTool ? { ...tool, eager_input_streaming: true } : tool);
|
|
54
|
+
}
|
|
55
|
+
/** The same tools, described the way the Responses API asks for them. */
|
|
56
|
+
export function openAiTools(tools) {
|
|
57
|
+
return tools.map((tool) => ({
|
|
58
|
+
type: "function",
|
|
59
|
+
name: tool.name,
|
|
60
|
+
description: tool.description,
|
|
61
|
+
parameters: { ...tool.input_schema, additionalProperties: false },
|
|
62
|
+
// Not strict: a tool that takes no arguments, or optional ones, would otherwise be refused.
|
|
63
|
+
strict: false,
|
|
64
|
+
}));
|
|
65
|
+
}
|
|
66
|
+
/** The dialog policy for the configured provider, streaming text and calling the app's tools. */
|
|
67
|
+
export function createDialogModel(opts) {
|
|
68
|
+
return opts.provider === "OPENAI" ? createOpenAiModel(opts) : createAnthropicModel(opts);
|
|
69
|
+
}
|
|
70
|
+
/** Turn either SDK's error into the harness's, which the relay log names the provider in. */
|
|
71
|
+
function asDialogError(error, provider) {
|
|
72
|
+
if (error instanceof Anthropic.APIError || error instanceof OpenAI.APIError) {
|
|
73
|
+
const status = typeof error.status === "number" ? error.status : undefined;
|
|
74
|
+
throw new AiServiceError(`${PROVIDER_LABELS[provider]} refused the request (${status ?? "no status"}): ${error.message}`, status);
|
|
75
|
+
}
|
|
76
|
+
throw error;
|
|
77
|
+
}
|
|
78
|
+
/** Anthropic's usage block, in the relay's terms. Its `input_tokens` already excludes the cache. */
|
|
79
|
+
export function anthropicUsage(model, usage) {
|
|
80
|
+
return {
|
|
81
|
+
provider: "ANTHROPIC",
|
|
82
|
+
model,
|
|
83
|
+
inputTokens: usage.input_tokens,
|
|
84
|
+
outputTokens: usage.output_tokens,
|
|
85
|
+
cacheReadTokens: usage.cache_read_input_tokens ?? 0,
|
|
86
|
+
cacheWriteTokens: usage.cache_creation_input_tokens ?? 0,
|
|
87
|
+
};
|
|
88
|
+
}
|
|
89
|
+
/**
|
|
90
|
+
* OpenAI's usage block, in the relay's terms. OpenAI counts cache reads and
|
|
91
|
+
* writes inside `input_tokens`, so both are taken out and priced at their own
|
|
92
|
+
* rates; reasoning tokens are already inside `output_tokens`.
|
|
93
|
+
*/
|
|
94
|
+
export function openAiUsage(model, usage) {
|
|
95
|
+
const cacheRead = usage.input_tokens_details?.cached_tokens ?? 0;
|
|
96
|
+
const cacheWrite = usage.input_tokens_details?.cache_write_tokens ?? 0;
|
|
97
|
+
return {
|
|
98
|
+
provider: "OPENAI",
|
|
99
|
+
model,
|
|
100
|
+
inputTokens: Math.max(0, usage.input_tokens - cacheRead - cacheWrite),
|
|
101
|
+
outputTokens: usage.output_tokens,
|
|
102
|
+
cacheReadTokens: cacheRead,
|
|
103
|
+
cacheWriteTokens: cacheWrite,
|
|
104
|
+
};
|
|
105
|
+
}
|
|
106
|
+
function createAnthropicModel(opts) {
|
|
107
|
+
const client = new Anthropic({ apiKey: opts.apiKey });
|
|
108
|
+
const toolsFor = memo((team) => anthropicTools(opts.tools(team), opts.transferTool));
|
|
109
|
+
const silent = opts.transferSilentKeys ?? [];
|
|
110
|
+
return {
|
|
111
|
+
async respond({ system, messages, signal, onText, onUsage, team }) {
|
|
112
|
+
let stream;
|
|
113
|
+
try {
|
|
114
|
+
stream = client.messages.stream({
|
|
115
|
+
model: opts.model,
|
|
116
|
+
max_tokens: opts.maxTokens ?? ANTHROPIC_MAX_TOKENS,
|
|
117
|
+
...(opts.anthropicEffort ? { output_config: { effort: opts.anthropicEffort } } : {}),
|
|
118
|
+
...(opts.anthropicThinking ? { thinking: { type: opts.anthropicThinking } } : {}),
|
|
119
|
+
// A cache boundary after each block of instructions and one on the conversation so
|
|
120
|
+
// far, so each request pays full price only for what is new. Four: the most allowed.
|
|
121
|
+
system: system.map((text) => ({
|
|
122
|
+
type: "text",
|
|
123
|
+
text,
|
|
124
|
+
cache_control: { type: "ephemeral" },
|
|
125
|
+
})),
|
|
126
|
+
tools: toolsFor(team ?? "open"),
|
|
127
|
+
messages: withConversationCached(messages),
|
|
128
|
+
}, { signal });
|
|
129
|
+
const speak = speaker(onText, silent);
|
|
130
|
+
const lines = new Map();
|
|
131
|
+
stream.on("text", (delta) => speak.words(delta));
|
|
132
|
+
stream.on("streamEvent", (event) => {
|
|
133
|
+
if (event.type === "content_block_start" && event.content_block.type === "tool_use") {
|
|
134
|
+
if (opts.transferTool && event.content_block.name === opts.transferTool) {
|
|
135
|
+
lines.set(event.index, speak.transferLine());
|
|
136
|
+
}
|
|
137
|
+
}
|
|
138
|
+
else if (event.type === "content_block_delta" && event.delta.type === "input_json_delta") {
|
|
139
|
+
lines.get(event.index)?.push(event.delta.partial_json);
|
|
140
|
+
}
|
|
141
|
+
});
|
|
142
|
+
const message = await stream.finalMessage();
|
|
143
|
+
const content = [];
|
|
144
|
+
for (const block of message.content) {
|
|
145
|
+
if (block.type === "text")
|
|
146
|
+
content.push({ type: "text", text: block.text });
|
|
147
|
+
if (block.type === "tool_use") {
|
|
148
|
+
content.push({
|
|
149
|
+
type: "tool_use",
|
|
150
|
+
id: block.id,
|
|
151
|
+
name: block.name,
|
|
152
|
+
input: block.input,
|
|
153
|
+
});
|
|
154
|
+
}
|
|
155
|
+
}
|
|
156
|
+
// Last, so nothing after it can throw into the catch and count the request twice.
|
|
157
|
+
onUsage?.(anthropicUsage(message.model, message.usage));
|
|
158
|
+
return { content, cutOff: message.stop_reason === "max_tokens" };
|
|
159
|
+
}
|
|
160
|
+
catch (error) {
|
|
161
|
+
// A caller who talks over the agent aborts the request, but the prompt was already
|
|
162
|
+
// read, and billed. What the stream had counted by then is still the cost.
|
|
163
|
+
const partial = stream?.currentMessage;
|
|
164
|
+
if (partial)
|
|
165
|
+
onUsage?.(anthropicUsage(partial.model, partial.usage));
|
|
166
|
+
asDialogError(error, "ANTHROPIC");
|
|
167
|
+
}
|
|
168
|
+
},
|
|
169
|
+
};
|
|
170
|
+
}
|
|
171
|
+
function createOpenAiModel(opts) {
|
|
172
|
+
const client = new OpenAI({ apiKey: opts.apiKey });
|
|
173
|
+
const toolsFor = memo((team) => openAiTools(opts.tools(team)));
|
|
174
|
+
const silent = opts.transferSilentKeys ?? [];
|
|
175
|
+
return {
|
|
176
|
+
async respond({ system, messages, signal, onText, onUsage, team }) {
|
|
177
|
+
try {
|
|
178
|
+
const stream = client.responses.stream({
|
|
179
|
+
model: opts.model,
|
|
180
|
+
instructions: system.join("\n\n"),
|
|
181
|
+
// OpenAI caches prefixes by itself; the key sends requests that share the first
|
|
182
|
+
// block to the same cache, whichever tenant they are for.
|
|
183
|
+
prompt_cache_key: cacheKey(system, opts.cacheKeyPrefix),
|
|
184
|
+
input: toResponsesInput(messages),
|
|
185
|
+
tools: toolsFor(team ?? "open"),
|
|
186
|
+
max_output_tokens: Math.max(opts.maxTokens ?? DEFAULT_MAX_TOKENS, OPENAI_MIN_OUTPUT_TOKENS),
|
|
187
|
+
...(opts.reasoningEffort ? { reasoning: { effort: opts.reasoningEffort } } : {}),
|
|
188
|
+
// A call's words are personal data: OpenAI keeps none of it for us.
|
|
189
|
+
store: false,
|
|
190
|
+
}, { signal });
|
|
191
|
+
const speak = speaker(onText, silent);
|
|
192
|
+
const lines = new Map();
|
|
193
|
+
stream.on("response.output_text.delta", (event) => speak.words(event.delta));
|
|
194
|
+
stream.on("response.output_item.added", (event) => {
|
|
195
|
+
if (event.item.type === "function_call" && opts.transferTool && event.item.name === opts.transferTool) {
|
|
196
|
+
lines.set(event.output_index, speak.transferLine());
|
|
197
|
+
}
|
|
198
|
+
});
|
|
199
|
+
stream.on("response.function_call_arguments.delta", (event) => lines.get(event.output_index)?.push(event.delta));
|
|
200
|
+
const response = await stream.finalResponse();
|
|
201
|
+
// OpenAI reports usage only on a completed response, so an interrupted request
|
|
202
|
+
// goes unmetered here: the report undercounts OpenAI slightly.
|
|
203
|
+
if (response.usage)
|
|
204
|
+
onUsage?.(openAiUsage(response.model, response.usage));
|
|
205
|
+
const content = [];
|
|
206
|
+
for (const item of response.output) {
|
|
207
|
+
if (item.type === "message") {
|
|
208
|
+
for (const part of item.content) {
|
|
209
|
+
if (part.type === "output_text")
|
|
210
|
+
content.push({ type: "text", text: part.text });
|
|
211
|
+
}
|
|
212
|
+
}
|
|
213
|
+
if (item.type === "function_call") {
|
|
214
|
+
content.push({
|
|
215
|
+
type: "tool_use",
|
|
216
|
+
id: item.call_id,
|
|
217
|
+
name: item.name,
|
|
218
|
+
input: parseArguments(item.arguments),
|
|
219
|
+
});
|
|
220
|
+
}
|
|
221
|
+
}
|
|
222
|
+
return { content, cutOff: response.status === "incomplete" };
|
|
223
|
+
}
|
|
224
|
+
catch (error) {
|
|
225
|
+
asDialogError(error, "OPENAI");
|
|
226
|
+
}
|
|
227
|
+
},
|
|
228
|
+
};
|
|
229
|
+
}
|
|
230
|
+
/** Names the shared prefix: the first block of instructions, the same for every tenant. */
|
|
231
|
+
export function cacheKey(system, prefix = "voice-dialog") {
|
|
232
|
+
return `${prefix}-${createHash("sha256")
|
|
233
|
+
.update(system[0] ?? "")
|
|
234
|
+
.digest("hex")
|
|
235
|
+
.slice(0, 16)}`;
|
|
236
|
+
}
|
|
237
|
+
/**
|
|
238
|
+
* The conversation with a cache boundary on its last block, so the next request
|
|
239
|
+
* reads everything said so far from the cache. A copy: the history is left alone.
|
|
240
|
+
*/
|
|
241
|
+
export function withConversationCached(messages) {
|
|
242
|
+
const params = messages;
|
|
243
|
+
const last = params[params.length - 1];
|
|
244
|
+
if (!last)
|
|
245
|
+
return params;
|
|
246
|
+
const blocks = typeof last.content === "string" ? [{ type: "text", text: last.content }] : [...last.content];
|
|
247
|
+
const final = blocks[blocks.length - 1];
|
|
248
|
+
if (!final || (final.type === "text" && !final.text))
|
|
249
|
+
return params;
|
|
250
|
+
blocks[blocks.length - 1] = { ...final, cache_control: { type: "ephemeral" } };
|
|
251
|
+
return [...params.slice(0, -1), { ...last, content: blocks }];
|
|
252
|
+
}
|
|
253
|
+
/** A model that writes malformed arguments gets an empty object, and the app's tool decides. */
|
|
254
|
+
function parseArguments(args) {
|
|
255
|
+
try {
|
|
256
|
+
const parsed = JSON.parse(args);
|
|
257
|
+
return parsed && typeof parsed === "object" ? parsed : {};
|
|
258
|
+
}
|
|
259
|
+
catch {
|
|
260
|
+
return {};
|
|
261
|
+
}
|
|
262
|
+
}
|
|
263
|
+
/**
|
|
264
|
+
* The call so far, as Responses API input items. Text becomes a message, a tool
|
|
265
|
+
* call a `function_call` and its result a `function_call_output`, in order.
|
|
266
|
+
* Items carry no `id`, so they are read as fresh input, which is what lets
|
|
267
|
+
* `store: false` work across turns.
|
|
268
|
+
*/
|
|
269
|
+
export function toResponsesInput(messages) {
|
|
270
|
+
const items = [];
|
|
271
|
+
for (const message of messages) {
|
|
272
|
+
if (typeof message.content === "string") {
|
|
273
|
+
items.push({ role: message.role, content: message.content });
|
|
274
|
+
continue;
|
|
275
|
+
}
|
|
276
|
+
let text = "";
|
|
277
|
+
const flush = () => {
|
|
278
|
+
if (text.trim())
|
|
279
|
+
items.push({ role: message.role, content: text });
|
|
280
|
+
text = "";
|
|
281
|
+
};
|
|
282
|
+
for (const block of message.content) {
|
|
283
|
+
if (block.type === "text") {
|
|
284
|
+
text += text ? `\n${block.text}` : block.text;
|
|
285
|
+
continue;
|
|
286
|
+
}
|
|
287
|
+
flush();
|
|
288
|
+
if (block.type === "tool_use") {
|
|
289
|
+
items.push({
|
|
290
|
+
type: "function_call",
|
|
291
|
+
call_id: block.id,
|
|
292
|
+
name: block.name,
|
|
293
|
+
arguments: JSON.stringify(block.input),
|
|
294
|
+
});
|
|
295
|
+
}
|
|
296
|
+
else {
|
|
297
|
+
items.push({ type: "function_call_output", call_id: block.tool_use_id, output: block.content });
|
|
298
|
+
}
|
|
299
|
+
}
|
|
300
|
+
flush();
|
|
301
|
+
}
|
|
302
|
+
return items;
|
|
303
|
+
}
|
|
304
|
+
//# sourceMappingURL=model.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"model.js","sourceRoot":"","sources":["../../../src/voice/relay/model.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AAEzC,OAAO,SAAS,MAAM,mBAAmB,CAAC;AAE1C,OAAO,MAAM,MAAM,QAAQ,CAAC;AAE5B,OAAO,EAAE,eAAe,EAAwC,MAAM,oBAAoB,CAAC;AAC3F,OAAO,EAAE,cAAc,EAAE,wBAAwB,EAAqB,MAAM,sBAAsB,CAAC;AACnG,OAAO,EAAE,kBAAkB,EAAE,MAAM,oBAAoB,CAAC;AAoFxD,uDAAuD;AACvD,MAAM,kBAAkB,GAAG,GAAG,CAAC;AAC/B;;;;GAIG;AACH,MAAM,oBAAoB,GAAG,IAAI,CAAC;AAElC;;;GAGG;AACH,SAAS,OAAO,CAAC,MAA+B,EAAE,UAA6B;IAC7E,IAAI,KAAK,GAAG,KAAK,CAAC;IAClB,IAAI,KAAK,GAAG,EAAE,CAAC;IACf,OAAO;QACL,KAAK,CAAC,KAAa;YACjB,IAAI,CAAC,KAAK;gBAAE,OAAO;YACnB,KAAK,GAAG,IAAI,CAAC;YACb,KAAK,IAAI,KAAK,CAAC;YACf,MAAM,CAAC,KAAK,CAAC,CAAC;QAChB,CAAC;QACD,YAAY;YACV,IAAI,KAAK,GAAG,IAAI,CAAC;YACjB,OAAO,IAAI,kBAAkB,CAC3B,CAAC,KAAK,EAAE,EAAE;gBACR,MAAM,CAAC,KAAK,IAAI,KAAK,CAAC,CAAC,CAAC,IAAI,KAAK,EAAE,CAAC,CAAC,CAAC,KAAK,CAAC,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C,EAAE,IAAI,EAAE,OAAO,CAAC,IAAI,EAAE,OAAO,EAAE,IAAI,EAAE,CAAC,CAAC;YACnE,IAAI,GAAG,EAAE,CAAC;QACZ,CAAC,CAAC;QAEF,KAAK,MAAM,KAAK,IAAI,OAAO,CAAC,OAAO,EAAE,CAAC;YACpC,IAAI,KAAK,CAAC,IAAI,KAAK,MAAM,EAAE,CAAC;gBAC1B,IAAI,IAAI,IAAI,CAAC,CAAC,CAAC,KAAK,KAAK,CAAC,IAAI,EAAE,CAAC,CAAC,CAAC,KAAK,CAAC,IAAI,CAAC;gBAC9C,SAAS;YACX,CAAC;YACD,KAAK,EAAE,CAAC;YACR,IAAI,KAAK,CAAC,IAAI,KAAK,UAAU,EAAE,CAAC;gBAC9B,KAAK,CAAC,IAAI,CAAC;oBACT,IAAI,EAAE,eAAe;oBACrB,OAAO,EAAE,KAAK,CAAC,EAAE;oBACjB,IAAI,EAAE,KAAK,CAAC,IAAI;oBAChB,SAAS,EAAE,IAAI,CAAC,SAAS,CAAC,KAAK,CAAC,KAAK,CAAC;iBACvC,CAAC,CAAC;YACL,CAAC;iBAAM,CAAC;gBACN,KAAK,CAAC,IAAI,CAAC,EAAE,IAAI,EAAE,sBAAsB,EAAE,OAAO,EAAE,KAAK,CAAC,WAAW,EAAE,MAAM,EAAE,KAAK,CAAC,OAAO,EAAE,CAAC,CAAC;YAClG,CAAC;QACH,CAAC;QACD,KAAK,EAAE,CAAC;IACV,CAAC;IAED,OAAO,KAAK,CAAC;AACf,CAAC"}
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Twilio ConversationRelay WebSocket messages (the subset the relay uses).
|
|
3
|
+
* https://www.twilio.com/docs/voice/conversationrelay/websocket-messages
|
|
4
|
+
*/
|
|
5
|
+
export interface SetupMessage {
|
|
6
|
+
type: "setup";
|
|
7
|
+
sessionId: string;
|
|
8
|
+
callSid: string;
|
|
9
|
+
from?: string;
|
|
10
|
+
to?: string;
|
|
11
|
+
forwardedFrom?: string;
|
|
12
|
+
customParameters?: Record<string, string>;
|
|
13
|
+
}
|
|
14
|
+
export interface PromptMessage {
|
|
15
|
+
type: "prompt";
|
|
16
|
+
voicePrompt: string;
|
|
17
|
+
lang?: string;
|
|
18
|
+
last?: boolean;
|
|
19
|
+
}
|
|
20
|
+
export interface InterruptMessage {
|
|
21
|
+
type: "interrupt";
|
|
22
|
+
utteranceUntilInterrupt?: string;
|
|
23
|
+
durationUntilInterruptMs?: number;
|
|
24
|
+
}
|
|
25
|
+
export interface DtmfMessage {
|
|
26
|
+
type: "dtmf";
|
|
27
|
+
digit: string;
|
|
28
|
+
}
|
|
29
|
+
export interface ErrorMessage {
|
|
30
|
+
type: "error";
|
|
31
|
+
description?: string;
|
|
32
|
+
}
|
|
33
|
+
export type InboundMessage = SetupMessage | PromptMessage | InterruptMessage | DtmfMessage | ErrorMessage;
|
|
34
|
+
export type OutboundMessage = {
|
|
35
|
+
type: "text";
|
|
36
|
+
token: string;
|
|
37
|
+
last: boolean;
|
|
38
|
+
interruptible?: boolean;
|
|
39
|
+
} | {
|
|
40
|
+
type: "end";
|
|
41
|
+
handoffData?: string;
|
|
42
|
+
};
|
|
43
|
+
export declare function parseInbound(raw: string): InboundMessage | null;
|
|
44
|
+
//# sourceMappingURL=protocol.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"protocol.d.ts","sourceRoot":"","sources":["../../../src/voice/relay/protocol.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAEH,MAAM,WAAW,YAAY;IAC3B,IAAI,EAAE,OAAO,CAAC;IACd,SAAS,EAAE,MAAM,CAAC;IAClB,OAAO,EAAE,MAAM,CAAC;IAChB,IAAI,CAAC,EAAE,MAAM,CAAC;IACd,EAAE,CAAC,EAAE,MAAM,CAAC;IACZ,aAAa,CAAC,EAAE,MAAM,CAAC;IACvB,gBAAgB,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;CAC3C;AAED,MAAM,WAAW,aAAa;IAC5B,IAAI,EAAE,QAAQ,CAAC;IACf,WAAW,EAAE,MAAM,CAAC;IACpB,IAAI,CAAC,EAAE,MAAM,CAAC;IACd,IAAI,CAAC,EAAE,OAAO,CAAC;CAChB;AAED,MAAM,WAAW,gBAAgB;IAC/B,IAAI,EAAE,WAAW,CAAC;IAClB,uBAAuB,CAAC,EAAE,MAAM,CAAC;IACjC,wBAAwB,CAAC,EAAE,MAAM,CAAC;CACnC;AAED,MAAM,WAAW,WAAW;IAC1B,IAAI,EAAE,MAAM,CAAC;IACb,KAAK,EAAE,MAAM,CAAC;CACf;AAED,MAAM,WAAW,YAAY;IAC3B,IAAI,EAAE,OAAO,CAAC;IACd,WAAW,CAAC,EAAE,MAAM,CAAC;CACtB;AAED,MAAM,MAAM,cAAc,GAAG,YAAY,GAAG,aAAa,GAAG,gBAAgB,GAAG,WAAW,GAAG,YAAY,CAAC;AAE1G,MAAM,MAAM,eAAe,GACzB;IAAE,IAAI,EAAE,MAAM,CAAC;IAAC,KAAK,EAAE,MAAM,CAAC;IAAC,IAAI,EAAE,OAAO,CAAC;IAAC,aAAa,CAAC,EAAE,OAAO,CAAA;CAAE,GAAG;IAAE,IAAI,EAAE,KAAK,CAAC;IAAC,WAAW,CAAC,EAAE,MAAM,CAAA;CAAE,CAAC;AAElH,wBAAgB,YAAY,CAAC,GAAG,EAAE,MAAM,GAAG,cAAc,GAAG,IAAI,CAQ/D"}
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Twilio ConversationRelay WebSocket messages (the subset the relay uses).
|
|
3
|
+
* https://www.twilio.com/docs/voice/conversationrelay/websocket-messages
|
|
4
|
+
*/
|
|
5
|
+
export function parseInbound(raw) {
|
|
6
|
+
try {
|
|
7
|
+
const data = JSON.parse(raw);
|
|
8
|
+
if (typeof data?.type !== "string")
|
|
9
|
+
return null;
|
|
10
|
+
return data;
|
|
11
|
+
}
|
|
12
|
+
catch {
|
|
13
|
+
return null;
|
|
14
|
+
}
|
|
15
|
+
}
|
|
16
|
+
//# sourceMappingURL=protocol.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"protocol.js","sourceRoot":"","sources":["../../../src/voice/relay/protocol.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAwCH,MAAM,UAAU,YAAY,CAAC,GAAW;IACtC,IAAI,CAAC;QACH,MAAM,IAAI,GAAG,IAAI,CAAC,KAAK,CAAC,GAAG,CAAuB,CAAC;QACnD,IAAI,OAAO,IAAI,EAAE,IAAI,KAAK,QAAQ;YAAE,OAAO,IAAI,CAAC;QAChD,OAAO,IAAsB,CAAC;IAChC,CAAC;IAAC,MAAM,CAAC;QACP,OAAO,IAAI,CAAC;IACd,CAAC;AACH,CAAC"}
|
|
@@ -0,0 +1,24 @@
|
|
|
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 declare class SentenceGate {
|
|
12
|
+
private readonly emit;
|
|
13
|
+
private readonly drop;
|
|
14
|
+
private pending;
|
|
15
|
+
constructor(emit: (text: string) => void, drop: (sentence: string) => boolean);
|
|
16
|
+
push(delta: string): void;
|
|
17
|
+
/** The stream ended: what's left is the last sentence. */
|
|
18
|
+
flush(): void;
|
|
19
|
+
private release;
|
|
20
|
+
private pass;
|
|
21
|
+
}
|
|
22
|
+
/** A finished text with the sentences that fail removed — for a line that wasn't streamed. */
|
|
23
|
+
export declare function keepSentences(text: string, drop: (sentence: string) => boolean): string;
|
|
24
|
+
//# sourceMappingURL=sentence-gate.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"sentence-gate.d.ts","sourceRoot":"","sources":["../../../src/voice/relay/sentence-gate.ts"],"names":[],"mappings":"AAAA;;;;;;;;;GASG;AACH,qBAAa,YAAY;IAIrB,OAAO,CAAC,QAAQ,CAAC,IAAI;IACrB,OAAO,CAAC,QAAQ,CAAC,IAAI;IAJvB,OAAO,CAAC,OAAO,CAAM;gBAGF,IAAI,EAAE,CAAC,IAAI,EAAE,MAAM,KAAK,IAAI,EAC5B,IAAI,EAAE,CAAC,QAAQ,EAAE,MAAM,KAAK,OAAO;IAGtD,IAAI,CAAC,KAAK,EAAE,MAAM,GAAG,IAAI;IASzB,0DAA0D;IAC1D,KAAK,IAAI,IAAI;IAMb,OAAO,CAAC,OAAO;IAUf,OAAO,CAAC,IAAI;CAGb;AASD,8FAA8F;AAC9F,wBAAgB,aAAa,CAAC,IAAI,EAAE,MAAM,EAAE,IAAI,EAAE,CAAC,QAAQ,EAAE,MAAM,KAAK,OAAO,GAAG,MAAM,CAMvF"}
|
|
@@ -0,0 +1,65 @@
|
|
|
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
|
+
emit;
|
|
13
|
+
drop;
|
|
14
|
+
pending = "";
|
|
15
|
+
constructor(emit, drop) {
|
|
16
|
+
this.emit = emit;
|
|
17
|
+
this.drop = drop;
|
|
18
|
+
}
|
|
19
|
+
push(delta) {
|
|
20
|
+
this.pending += delta;
|
|
21
|
+
const end = lastSentenceEnd(this.pending);
|
|
22
|
+
if (end === -1)
|
|
23
|
+
return;
|
|
24
|
+
const complete = this.pending.slice(0, end);
|
|
25
|
+
this.pending = this.pending.slice(end);
|
|
26
|
+
this.release(complete);
|
|
27
|
+
}
|
|
28
|
+
/** The stream ended: what's left is the last sentence. */
|
|
29
|
+
flush() {
|
|
30
|
+
const rest = this.pending;
|
|
31
|
+
this.pending = "";
|
|
32
|
+
if (rest.trim())
|
|
33
|
+
this.release(rest);
|
|
34
|
+
}
|
|
35
|
+
release(text) {
|
|
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)
|
|
43
|
+
this.pass(text.slice(start));
|
|
44
|
+
}
|
|
45
|
+
pass(sentence) {
|
|
46
|
+
if (sentence.trim() && !this.drop(sentence))
|
|
47
|
+
this.emit(sentence);
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
/** Where the last complete sentence (and the space after it) ends, or -1. */
|
|
51
|
+
function lastSentenceEnd(text) {
|
|
52
|
+
let end = -1;
|
|
53
|
+
for (const match of text.matchAll(/[.!?]+\s+/g))
|
|
54
|
+
end = match.index + match[0].length;
|
|
55
|
+
return end;
|
|
56
|
+
}
|
|
57
|
+
/** A finished text with the sentences that fail removed — for a line that wasn't streamed. */
|
|
58
|
+
export function keepSentences(text, drop) {
|
|
59
|
+
let out = "";
|
|
60
|
+
const gate = new SentenceGate((s) => (out += s), drop);
|
|
61
|
+
gate.push(text);
|
|
62
|
+
gate.flush();
|
|
63
|
+
return out.trim();
|
|
64
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