@voicethere/agent 0.10.1 → 0.12.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 +88 -0
- package/dist/agent.js +175 -5
- package/dist/build-bundle.d.ts.map +1 -1
- package/dist/build-bundle.js +1 -0
- package/dist/build-bundle.js.map +1 -1
- package/dist/host/index.d.ts +4 -0
- package/dist/host/index.d.ts.map +1 -0
- package/dist/host/index.js +3 -0
- package/dist/host/index.js.map +1 -0
- package/dist/host/session-speak-controller.d.ts +70 -0
- package/dist/host/session-speak-controller.d.ts.map +1 -0
- package/dist/host/session-speak-controller.js +296 -0
- package/dist/host/session-speak-controller.js.map +1 -0
- package/dist/host/speak-text.d.ts +11 -0
- package/dist/host/speak-text.d.ts.map +1 -0
- package/dist/host/speak-text.js +21 -0
- package/dist/host/speak-text.js.map +1 -0
- package/dist/index.d.ts +2 -2
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +1 -1
- package/dist/index.js.map +1 -1
- package/dist/llm/agent/config.d.ts +376 -0
- package/dist/llm/agent/config.d.ts.map +1 -0
- package/dist/llm/agent/config.js +678 -0
- package/dist/llm/agent/config.js.map +1 -0
- package/dist/llm/agent/create-llm-agent.d.ts +22 -0
- package/dist/llm/agent/create-llm-agent.d.ts.map +1 -0
- package/dist/llm/agent/create-llm-agent.js +720 -0
- package/dist/llm/agent/create-llm-agent.js.map +1 -0
- package/dist/llm/agent/define-tool.d.ts +8 -0
- package/dist/llm/agent/define-tool.d.ts.map +1 -0
- package/dist/llm/agent/define-tool.js +9 -0
- package/dist/llm/agent/define-tool.js.map +1 -0
- package/dist/llm/agent/history.d.ts +35 -0
- package/dist/llm/agent/history.d.ts.map +1 -0
- package/dist/llm/agent/history.js +79 -0
- package/dist/llm/agent/history.js.map +1 -0
- package/dist/llm/agent/hooks.d.ts +50 -0
- package/dist/llm/agent/hooks.d.ts.map +1 -0
- package/dist/llm/agent/hooks.js +2 -0
- package/dist/llm/agent/hooks.js.map +1 -0
- package/dist/llm/agent/sentence-splitter.d.ts +10 -0
- package/dist/llm/agent/sentence-splitter.d.ts.map +1 -0
- package/dist/llm/agent/sentence-splitter.js +92 -0
- package/dist/llm/agent/sentence-splitter.js.map +1 -0
- package/dist/llm/anthropic-provider.d.ts +7 -0
- package/dist/llm/anthropic-provider.d.ts.map +1 -0
- package/dist/llm/anthropic-provider.js +115 -0
- package/dist/llm/anthropic-provider.js.map +1 -0
- package/dist/llm/bounded-provider.d.ts +12 -0
- package/dist/llm/bounded-provider.d.ts.map +1 -0
- package/dist/llm/bounded-provider.js +132 -0
- package/dist/llm/bounded-provider.js.map +1 -0
- package/dist/llm/catalog.d.ts +9 -0
- package/dist/llm/catalog.d.ts.map +1 -0
- package/dist/llm/catalog.js +35 -0
- package/dist/llm/catalog.js.map +1 -0
- package/dist/llm/gemini-provider.d.ts +7 -0
- package/dist/llm/gemini-provider.d.ts.map +1 -0
- package/dist/llm/gemini-provider.js +120 -0
- package/dist/llm/gemini-provider.js.map +1 -0
- package/dist/llm/index.d.ts +18 -0
- package/dist/llm/index.d.ts.map +1 -0
- package/dist/llm/index.js +11 -0
- package/dist/llm/index.js.map +1 -0
- package/dist/llm/mcp/index.d.ts +5 -0
- package/dist/llm/mcp/index.d.ts.map +1 -0
- package/dist/llm/mcp/index.js +3 -0
- package/dist/llm/mcp/index.js.map +1 -0
- package/dist/llm/mcp/mcp-tool-source.d.ts +65 -0
- package/dist/llm/mcp/mcp-tool-source.d.ts.map +1 -0
- package/dist/llm/mcp/mcp-tool-source.js +328 -0
- package/dist/llm/mcp/mcp-tool-source.js.map +1 -0
- package/dist/llm/mcp/tool-registry.d.ts +44 -0
- package/dist/llm/mcp/tool-registry.d.ts.map +1 -0
- package/dist/llm/mcp/tool-registry.js +147 -0
- package/dist/llm/mcp/tool-registry.js.map +1 -0
- package/dist/llm/openai-provider.d.ts +8 -0
- package/dist/llm/openai-provider.d.ts.map +1 -0
- package/dist/llm/openai-provider.js +146 -0
- package/dist/llm/openai-provider.js.map +1 -0
- package/dist/llm/providers.d.ts +10 -0
- package/dist/llm/providers.d.ts.map +1 -0
- package/dist/llm/providers.js +32 -0
- package/dist/llm/providers.js.map +1 -0
- package/dist/llm/types.d.ts +70 -0
- package/dist/llm/types.d.ts.map +1 -0
- package/dist/llm/types.js +11 -0
- package/dist/llm/types.js.map +1 -0
- package/dist/protocol.d.ts +95 -2
- package/dist/protocol.d.ts.map +1 -1
- package/dist/protocol.js.map +1 -1
- package/dist/runtime.d.ts +69 -6
- package/dist/runtime.d.ts.map +1 -1
- package/dist/runtime.js +274 -7
- package/dist/runtime.js.map +1 -1
- package/dist/templates/echo/agent.js +178 -7
- package/dist/templates/echo-dc/agent.js +85 -2
- package/dist/templates/game-sync/agent.js +85 -2
- package/dist/templates/language-switch/agent.js +173 -5
- package/dist/templates/llm-agent/agent.js +121378 -0
- package/dist/templates/positional-tts/agent.js +173 -5
- package/dist/templates/recording-consent/agent.js +173 -5
- package/dist/templates/registry.d.ts +1 -1
- package/dist/templates/registry.d.ts.map +1 -1
- package/dist/templates/registry.js +24 -0
- package/dist/templates/registry.js.map +1 -1
- package/dist/templates/spatial-showcase/agent.js +173 -5
- package/dist/templates/voice-showcase/agent.js +178 -7
- package/dist/templates/voice-starter/agent.js +176 -5
- package/dist/templates/webhooks/agent.js +176 -5
- package/dist/templates/webhooks-redis/agent.js +85 -2
- package/dist/templates/world-sync/agent.js +85 -2
- package/dist/templates/world-sync-binary/agent.js +85 -2
- package/eject/llm/loop.ts +913 -0
- package/package.json +54 -4
- package/schema/voicethere.llm.schema.json +325 -0
- package/templates/llm-agent/README.md +24 -0
- package/templates/llm-agent/agent.ts +8 -0
- package/templates/llm-agent/hooks.ts +21 -0
- package/templates/llm-agent/md.d.ts +4 -0
- package/templates/llm-agent/prompt.md +11 -0
- package/templates/llm-agent/tools.ts +51 -0
- package/templates/llm-agent/voicethere.llm.json +21 -0
|
@@ -0,0 +1,913 @@
|
|
|
1
|
+
// Copied from @voicethere/agent 0.12.0. Package updates no longer change this file.
|
|
2
|
+
import { randomUUID } from "node:crypto";
|
|
3
|
+
import {
|
|
4
|
+
type AgentHandlers,
|
|
5
|
+
type AgentInterruptedContext,
|
|
6
|
+
agentLog,
|
|
7
|
+
announce,
|
|
8
|
+
cancelSpeech,
|
|
9
|
+
parseChatText,
|
|
10
|
+
sendToClient,
|
|
11
|
+
type SessionContext,
|
|
12
|
+
setAgentState,
|
|
13
|
+
setBargeIn,
|
|
14
|
+
speak,
|
|
15
|
+
} from "@voicethere/agent";
|
|
16
|
+
import {
|
|
17
|
+
ConversationHistory,
|
|
18
|
+
createLlmProvider,
|
|
19
|
+
type CustomTool,
|
|
20
|
+
LLM_AGENT_CONFIG_DEFAULTS,
|
|
21
|
+
type LlmAgentConfig,
|
|
22
|
+
type LlmAgentHooks,
|
|
23
|
+
type LlmMessage,
|
|
24
|
+
type LlmProvider,
|
|
25
|
+
LlmProviderError,
|
|
26
|
+
type LlmStreamEvent,
|
|
27
|
+
type LlmToolResult,
|
|
28
|
+
McpToolSource,
|
|
29
|
+
type McpToolSourceOptions,
|
|
30
|
+
resolveModel,
|
|
31
|
+
SentenceSplitter,
|
|
32
|
+
ToolRegistry,
|
|
33
|
+
type TurnContext,
|
|
34
|
+
type TurnSummary,
|
|
35
|
+
validateLlmAgentConfig,
|
|
36
|
+
} from "@voicethere/agent/llm";
|
|
37
|
+
|
|
38
|
+
const D = LLM_AGENT_CONFIG_DEFAULTS;
|
|
39
|
+
const CANCEL_SETTLE_MS = 2_000;
|
|
40
|
+
|
|
41
|
+
export interface CreateLlmAgentOptions {
|
|
42
|
+
/** Validated here; an invalid config throws `LLM_CONFIG_INVALID`. */
|
|
43
|
+
config: unknown;
|
|
44
|
+
systemPrompt: string;
|
|
45
|
+
tools?: CustomTool[];
|
|
46
|
+
hooks?: LlmAgentHooks;
|
|
47
|
+
/** Environment used to resolve secrets. Default `process.env`. */
|
|
48
|
+
env?: () => Record<string, string | undefined>;
|
|
49
|
+
/** Test injection. */
|
|
50
|
+
provider?: LlmProvider;
|
|
51
|
+
now?: () => number;
|
|
52
|
+
/** Test injection for MCP tool sources. */
|
|
53
|
+
sourceFactory?: (opts: McpToolSourceOptions) => McpToolSource;
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
type Source = "voice" | "chat";
|
|
57
|
+
|
|
58
|
+
interface TurnState {
|
|
59
|
+
turnId: string;
|
|
60
|
+
source: Source;
|
|
61
|
+
inputText: string;
|
|
62
|
+
controller: AbortController;
|
|
63
|
+
startedAt: number;
|
|
64
|
+
spoken: string[];
|
|
65
|
+
toolCalls: TurnSummary["toolCalls"];
|
|
66
|
+
llmCalls: number;
|
|
67
|
+
firstTokenMs?: number;
|
|
68
|
+
inputTokens?: number;
|
|
69
|
+
outputTokens?: number;
|
|
70
|
+
errorCode?: string;
|
|
71
|
+
abortStatus?: "interrupted" | "cancelled";
|
|
72
|
+
roundOpen: boolean;
|
|
73
|
+
roundText: string;
|
|
74
|
+
playedOverride?: string;
|
|
75
|
+
spokeFirst: boolean;
|
|
76
|
+
fillerSpoken: boolean;
|
|
77
|
+
fallbackSpoken: boolean;
|
|
78
|
+
status: TurnSummary["status"];
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
interface ActiveTurn {
|
|
82
|
+
turnId: string;
|
|
83
|
+
state: TurnState;
|
|
84
|
+
promise: Promise<void>;
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
interface SessionState {
|
|
88
|
+
sessionId: string;
|
|
89
|
+
history: ConversationHistory;
|
|
90
|
+
active?: ActiveTurn;
|
|
91
|
+
queued?: { text: string; source: Source };
|
|
92
|
+
announcing: number;
|
|
93
|
+
chain: Promise<void>;
|
|
94
|
+
lastInterruption?: {
|
|
95
|
+
turnId: string;
|
|
96
|
+
playedText: string;
|
|
97
|
+
unplayedText: string;
|
|
98
|
+
};
|
|
99
|
+
ended: boolean;
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
function configError(message: string, code: string): Error {
|
|
103
|
+
const err = new Error(message) as Error & { code: string };
|
|
104
|
+
err.code = code;
|
|
105
|
+
return err;
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
function truncateBytes(text: string, max: number): string {
|
|
109
|
+
const buf = Buffer.from(text, "utf8");
|
|
110
|
+
if (buf.length <= max) return text;
|
|
111
|
+
let end = max;
|
|
112
|
+
while (end > 0 && (buf[end] & 0xc0) === 0x80) end -= 1;
|
|
113
|
+
return `${buf.subarray(0, end).toString("utf8")}\n[truncated]`;
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
function interruptionNote(played: string, unplayed: string): string {
|
|
117
|
+
return `(The caller interrupted your previous reply after: "${played}". They did not hear: "${unplayed}".)`;
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
function nonEmpty(v: string | undefined): v is string {
|
|
121
|
+
return v !== undefined && v.length > 0;
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
export function createLlmAgent(opts: CreateLlmAgentOptions): AgentHandlers {
|
|
125
|
+
const validated = validateLlmAgentConfig(opts.config);
|
|
126
|
+
if (!validated.ok) {
|
|
127
|
+
throw configError(
|
|
128
|
+
`invalid LLM agent config:\n${validated.errors
|
|
129
|
+
.map((e) => `${e.path || "(root)"}: ${e.message}`)
|
|
130
|
+
.join("\n")}`,
|
|
131
|
+
"LLM_CONFIG_INVALID",
|
|
132
|
+
);
|
|
133
|
+
}
|
|
134
|
+
const config: LlmAgentConfig = validated.config;
|
|
135
|
+
const hooks = opts.hooks ?? {};
|
|
136
|
+
const now = opts.now ?? Date.now;
|
|
137
|
+
const getEnv = opts.env ?? (() => process.env);
|
|
138
|
+
const makeSource =
|
|
139
|
+
opts.sourceFactory ?? ((o: McpToolSourceOptions) => new McpToolSource(o));
|
|
140
|
+
|
|
141
|
+
const maxRounds = config.tools?.maxRounds ?? D.toolMaxRounds;
|
|
142
|
+
const toolTimeoutMs = config.tools?.timeoutMs ?? D.toolTimeoutMs;
|
|
143
|
+
const toolMaxBytes = config.tools?.maxResultBytes ?? D.toolMaxResultBytes;
|
|
144
|
+
const policy = config.interruptPolicy ?? D.interruptPolicy;
|
|
145
|
+
const fallbackText = config.fallbackText ?? D.fallbackText;
|
|
146
|
+
const speakChat = config.speakChatReplies ?? D.speakChatReplies;
|
|
147
|
+
const useNote = config.history?.interruptionNote ?? D.interruptionNote;
|
|
148
|
+
const historyTurns = config.history?.turns ?? D.historyTurns;
|
|
149
|
+
const serviceWaitMs = config.serviceWaitMs ?? D.serviceWaitMs;
|
|
150
|
+
|
|
151
|
+
let provider: LlmProvider | undefined = opts.provider;
|
|
152
|
+
let registry: ToolRegistry | undefined;
|
|
153
|
+
let serviceSource: McpToolSource | undefined;
|
|
154
|
+
let serviceWaited = false;
|
|
155
|
+
const sessions = new Map<string, SessionState>();
|
|
156
|
+
|
|
157
|
+
// ---- hooks -------------------------------------------------------------
|
|
158
|
+
|
|
159
|
+
async function callHook<T>(
|
|
160
|
+
name: string,
|
|
161
|
+
sessionId: string,
|
|
162
|
+
fn: () => T | Promise<T>,
|
|
163
|
+
): Promise<{ ok: true; value: T } | { ok: false }> {
|
|
164
|
+
try {
|
|
165
|
+
return { ok: true, value: await fn() };
|
|
166
|
+
} catch (err) {
|
|
167
|
+
const message = err instanceof Error ? err.message : String(err);
|
|
168
|
+
agentLog("error", `llm hook ${name} failed: ${message}`, sessionId);
|
|
169
|
+
return { ok: false };
|
|
170
|
+
}
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
// ---- delivery ----------------------------------------------------------
|
|
174
|
+
|
|
175
|
+
function trackAnnouncement(s: SessionState, done: Promise<unknown>): void {
|
|
176
|
+
s.announcing += 1;
|
|
177
|
+
void done.then(
|
|
178
|
+
() => {
|
|
179
|
+
s.announcing = Math.max(0, s.announcing - 1);
|
|
180
|
+
},
|
|
181
|
+
() => {
|
|
182
|
+
s.announcing = Math.max(0, s.announcing - 1);
|
|
183
|
+
},
|
|
184
|
+
);
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
/** The one place where a sentence of a reply leaves the agent. */
|
|
188
|
+
function deliver(
|
|
189
|
+
s: SessionState,
|
|
190
|
+
t: TurnState,
|
|
191
|
+
text: string,
|
|
192
|
+
interruptible = true,
|
|
193
|
+
): void {
|
|
194
|
+
t.spoken.push(text);
|
|
195
|
+
if (!t.spokeFirst) {
|
|
196
|
+
t.spokeFirst = true;
|
|
197
|
+
setAgentState(s.sessionId, "speaking");
|
|
198
|
+
}
|
|
199
|
+
if (t.source === "chat") {
|
|
200
|
+
sendToClient(s.sessionId, {
|
|
201
|
+
type: "assistant_delta",
|
|
202
|
+
turnId: t.turnId,
|
|
203
|
+
text,
|
|
204
|
+
});
|
|
205
|
+
}
|
|
206
|
+
if (t.source === "voice" || speakChat) {
|
|
207
|
+
if (interruptible) {
|
|
208
|
+
speak(s.sessionId, text, { turnId: t.turnId });
|
|
209
|
+
} else {
|
|
210
|
+
const h = announce(s.sessionId, text, { turnId: t.turnId });
|
|
211
|
+
trackAnnouncement(s, h.done);
|
|
212
|
+
}
|
|
213
|
+
}
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
function speakAnnouncement(
|
|
217
|
+
s: SessionState,
|
|
218
|
+
turnId: string,
|
|
219
|
+
text: string,
|
|
220
|
+
interruptible: boolean,
|
|
221
|
+
): void {
|
|
222
|
+
if (interruptible) {
|
|
223
|
+
speak(s.sessionId, text, { turnId });
|
|
224
|
+
} else {
|
|
225
|
+
trackAnnouncement(s, announce(s.sessionId, text, { turnId }).done);
|
|
226
|
+
}
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
// ---- tools -------------------------------------------------------------
|
|
230
|
+
|
|
231
|
+
function buildRegistry(env: Record<string, string | undefined>): void {
|
|
232
|
+
const reg = new ToolRegistry({
|
|
233
|
+
log: (level, message, fields) => agentLog(level, message, fields ?? {}),
|
|
234
|
+
});
|
|
235
|
+
for (const tool of opts.tools ?? []) reg.addCustomTool(tool);
|
|
236
|
+
const sources: McpToolSource[] = [];
|
|
237
|
+
for (const src of config.toolSources ?? []) {
|
|
238
|
+
if (src.kind === "service") {
|
|
239
|
+
const base = env.VOICETHERE_SERVICE_URL;
|
|
240
|
+
if (!nonEmpty(base)) {
|
|
241
|
+
agentLog(
|
|
242
|
+
"warn",
|
|
243
|
+
"toolSources: service configured but this project has no service",
|
|
244
|
+
);
|
|
245
|
+
continue;
|
|
246
|
+
}
|
|
247
|
+
const headers: Record<string, string> = {};
|
|
248
|
+
const token = env.VOICETHERE_SERVICE_TOKEN;
|
|
249
|
+
if (nonEmpty(token)) {
|
|
250
|
+
headers.Authorization = `Bearer ${token}`;
|
|
251
|
+
} else {
|
|
252
|
+
agentLog("warn", "toolSources: VOICETHERE_SERVICE_TOKEN is not set");
|
|
253
|
+
}
|
|
254
|
+
const source = makeSource({
|
|
255
|
+
name: "service",
|
|
256
|
+
url: `${base}${src.path ?? D.servicePath}`,
|
|
257
|
+
headers,
|
|
258
|
+
allow: src.allow,
|
|
259
|
+
deny: src.deny,
|
|
260
|
+
log: (level, message, fields) =>
|
|
261
|
+
agentLog(level, message, fields ?? {}),
|
|
262
|
+
});
|
|
263
|
+
serviceSource = source;
|
|
264
|
+
sources.push(source);
|
|
265
|
+
} else {
|
|
266
|
+
const headers: Record<string, string> = {};
|
|
267
|
+
let missing: string | undefined;
|
|
268
|
+
const auth = src.auth ?? { type: "none" as const };
|
|
269
|
+
if (auth.type === "bearer") {
|
|
270
|
+
const v = env[auth.secret];
|
|
271
|
+
if (nonEmpty(v)) headers.Authorization = `Bearer ${v}`;
|
|
272
|
+
else missing = auth.secret;
|
|
273
|
+
} else if (auth.type === "headers") {
|
|
274
|
+
for (const [header, envName] of Object.entries(auth.headers)) {
|
|
275
|
+
const v = env[envName];
|
|
276
|
+
if (nonEmpty(v)) headers[header] = v;
|
|
277
|
+
else missing = envName;
|
|
278
|
+
}
|
|
279
|
+
}
|
|
280
|
+
if (missing) {
|
|
281
|
+
agentLog(
|
|
282
|
+
"warn",
|
|
283
|
+
`toolSources: ${src.name} skipped, environment variable ${missing} is not set`,
|
|
284
|
+
);
|
|
285
|
+
continue;
|
|
286
|
+
}
|
|
287
|
+
sources.push(
|
|
288
|
+
makeSource({
|
|
289
|
+
name: src.name,
|
|
290
|
+
url: src.url,
|
|
291
|
+
headers,
|
|
292
|
+
allow: src.allow,
|
|
293
|
+
deny: src.deny,
|
|
294
|
+
log: (level, message, fields) =>
|
|
295
|
+
agentLog(level, message, fields ?? {}),
|
|
296
|
+
}),
|
|
297
|
+
);
|
|
298
|
+
}
|
|
299
|
+
}
|
|
300
|
+
for (const source of sources) {
|
|
301
|
+
reg.addSource(source);
|
|
302
|
+
source.start();
|
|
303
|
+
}
|
|
304
|
+
registry = reg;
|
|
305
|
+
}
|
|
306
|
+
|
|
307
|
+
async function runTools(
|
|
308
|
+
s: SessionState,
|
|
309
|
+
t: TurnState,
|
|
310
|
+
ctx: TurnContext,
|
|
311
|
+
calls: { id: string; name: string; input: unknown }[],
|
|
312
|
+
): Promise<LlmToolResult[]> {
|
|
313
|
+
const signal = t.controller.signal;
|
|
314
|
+
const aborted = new Promise<"aborted">((resolve) => {
|
|
315
|
+
if (signal.aborted) resolve("aborted");
|
|
316
|
+
else
|
|
317
|
+
signal.addEventListener("abort", () => resolve("aborted"), {
|
|
318
|
+
once: true,
|
|
319
|
+
});
|
|
320
|
+
});
|
|
321
|
+
const one = async (call: {
|
|
322
|
+
id: string;
|
|
323
|
+
name: string;
|
|
324
|
+
input: unknown;
|
|
325
|
+
}): Promise<LlmToolResult> => {
|
|
326
|
+
const started = now();
|
|
327
|
+
let content = "";
|
|
328
|
+
let isError = false;
|
|
329
|
+
const work = (async () => {
|
|
330
|
+
const hooked = hooks.onToolCall
|
|
331
|
+
? await callHook("onToolCall", s.sessionId, () =>
|
|
332
|
+
hooks.onToolCall!({ name: call.name, args: call.input }, ctx),
|
|
333
|
+
)
|
|
334
|
+
: undefined;
|
|
335
|
+
if (hooked?.ok && hooked.value) {
|
|
336
|
+
return {
|
|
337
|
+
content: String(hooked.value.result),
|
|
338
|
+
isError: hooked.value.isError === true,
|
|
339
|
+
};
|
|
340
|
+
}
|
|
341
|
+
if (!registry) return { content: "no tools available", isError: true };
|
|
342
|
+
return registry.call(call.name, call.input, {
|
|
343
|
+
signal,
|
|
344
|
+
timeoutMs: toolTimeoutMs,
|
|
345
|
+
sessionId: s.sessionId,
|
|
346
|
+
});
|
|
347
|
+
})();
|
|
348
|
+
const raced = await Promise.race([work, aborted]);
|
|
349
|
+
if (raced === "aborted") {
|
|
350
|
+
work.catch(() => {});
|
|
351
|
+
content = "cancelled";
|
|
352
|
+
isError = true;
|
|
353
|
+
} else {
|
|
354
|
+
content = raced.content;
|
|
355
|
+
isError = raced.isError;
|
|
356
|
+
if (hooks.onToolResult) {
|
|
357
|
+
const r = await callHook("onToolResult", s.sessionId, () =>
|
|
358
|
+
hooks.onToolResult!(
|
|
359
|
+
{ name: call.name, args: call.input, result: content, isError },
|
|
360
|
+
ctx,
|
|
361
|
+
),
|
|
362
|
+
);
|
|
363
|
+
if (r.ok && typeof r.value === "string") content = r.value;
|
|
364
|
+
}
|
|
365
|
+
}
|
|
366
|
+
content = truncateBytes(content, toolMaxBytes);
|
|
367
|
+
t.toolCalls.push({ name: call.name, isError, ms: now() - started });
|
|
368
|
+
return { callId: call.id, name: call.name, content, isError };
|
|
369
|
+
};
|
|
370
|
+
return Promise.all(calls.map(one));
|
|
371
|
+
}
|
|
372
|
+
|
|
373
|
+
// ---- one LLM round -----------------------------------------------------
|
|
374
|
+
|
|
375
|
+
async function emitSentence(
|
|
376
|
+
s: SessionState,
|
|
377
|
+
t: TurnState,
|
|
378
|
+
ctx: TurnContext,
|
|
379
|
+
sentence: string,
|
|
380
|
+
): Promise<void> {
|
|
381
|
+
let out: string = sentence;
|
|
382
|
+
if (hooks.onAssistantText) {
|
|
383
|
+
const r = await callHook("onAssistantText", s.sessionId, () =>
|
|
384
|
+
hooks.onAssistantText!(sentence, ctx),
|
|
385
|
+
);
|
|
386
|
+
if (r.ok && r.value !== undefined) {
|
|
387
|
+
if (r.value === null || r.value === "") return;
|
|
388
|
+
if (typeof r.value === "string") out = r.value;
|
|
389
|
+
}
|
|
390
|
+
}
|
|
391
|
+
if (t.controller.signal.aborted) return;
|
|
392
|
+
t.roundText += `${t.roundText ? " " : ""}${out}`;
|
|
393
|
+
deliver(s, t, out);
|
|
394
|
+
}
|
|
395
|
+
|
|
396
|
+
async function runRound(
|
|
397
|
+
s: SessionState,
|
|
398
|
+
t: TurnState,
|
|
399
|
+
ctx: TurnContext,
|
|
400
|
+
): Promise<Extract<LlmStreamEvent, { type: "done" }>> {
|
|
401
|
+
const signal = t.controller.signal;
|
|
402
|
+
let messages: LlmMessage[] = s.history.messages();
|
|
403
|
+
if (hooks.onBeforeLlmCall) {
|
|
404
|
+
const r = await callHook("onBeforeLlmCall", s.sessionId, () =>
|
|
405
|
+
hooks.onBeforeLlmCall!(messages, ctx),
|
|
406
|
+
);
|
|
407
|
+
if (r.ok && Array.isArray(r.value)) messages = r.value;
|
|
408
|
+
}
|
|
409
|
+
if (messages.length > 0 && messages[0].role === "assistant") {
|
|
410
|
+
// Providers want a conversation that starts with the caller.
|
|
411
|
+
messages = [
|
|
412
|
+
{ role: "user", text: "(The call has started.)" },
|
|
413
|
+
...messages,
|
|
414
|
+
];
|
|
415
|
+
}
|
|
416
|
+
t.llmCalls += 1;
|
|
417
|
+
t.roundOpen = true;
|
|
418
|
+
t.roundText = "";
|
|
419
|
+
const splitter = new SentenceSplitter();
|
|
420
|
+
let done: Extract<LlmStreamEvent, { type: "done" }> | undefined;
|
|
421
|
+
const stream = provider!.stream({
|
|
422
|
+
model: resolveModel(config.provider, config.model),
|
|
423
|
+
system: opts.systemPrompt,
|
|
424
|
+
messages,
|
|
425
|
+
tools: registry ? registry.list().map((e) => e.spec) : [],
|
|
426
|
+
temperature: config.temperature,
|
|
427
|
+
maxOutputTokens: config.maxOutputTokens ?? D.maxOutputTokens,
|
|
428
|
+
signal,
|
|
429
|
+
});
|
|
430
|
+
for await (const ev of stream) {
|
|
431
|
+
if (signal.aborted) break;
|
|
432
|
+
if (ev.type === "text_delta") {
|
|
433
|
+
if (t.firstTokenMs === undefined) t.firstTokenMs = now() - t.startedAt;
|
|
434
|
+
for (const sentence of splitter.push(ev.text)) {
|
|
435
|
+
await emitSentence(s, t, ctx, sentence);
|
|
436
|
+
}
|
|
437
|
+
} else {
|
|
438
|
+
done = ev;
|
|
439
|
+
}
|
|
440
|
+
}
|
|
441
|
+
if (signal.aborted) throw new LlmProviderError("LLM_ABORTED", "aborted");
|
|
442
|
+
if (!done) {
|
|
443
|
+
throw new LlmProviderError(
|
|
444
|
+
"LLM_PROVIDER_ERROR",
|
|
445
|
+
"stream ended without done",
|
|
446
|
+
);
|
|
447
|
+
}
|
|
448
|
+
for (const sentence of splitter.end()) {
|
|
449
|
+
await emitSentence(s, t, ctx, sentence);
|
|
450
|
+
}
|
|
451
|
+
if (done.usage) {
|
|
452
|
+
if (done.usage.inputTokens !== undefined) {
|
|
453
|
+
t.inputTokens = (t.inputTokens ?? 0) + done.usage.inputTokens;
|
|
454
|
+
}
|
|
455
|
+
if (done.usage.outputTokens !== undefined) {
|
|
456
|
+
t.outputTokens = (t.outputTokens ?? 0) + done.usage.outputTokens;
|
|
457
|
+
}
|
|
458
|
+
}
|
|
459
|
+
t.roundOpen = false;
|
|
460
|
+
return done;
|
|
461
|
+
}
|
|
462
|
+
|
|
463
|
+
// ---- one turn ----------------------------------------------------------
|
|
464
|
+
|
|
465
|
+
function summarize(t: TurnState): TurnSummary {
|
|
466
|
+
return {
|
|
467
|
+
turnId: t.turnId,
|
|
468
|
+
status: t.status,
|
|
469
|
+
assistantText: t.spoken.join(" "),
|
|
470
|
+
toolCalls: [...t.toolCalls],
|
|
471
|
+
llmCalls: t.llmCalls,
|
|
472
|
+
...(t.firstTokenMs !== undefined ? { firstTokenMs: t.firstTokenMs } : {}),
|
|
473
|
+
...(t.inputTokens !== undefined ? { inputTokens: t.inputTokens } : {}),
|
|
474
|
+
...(t.outputTokens !== undefined ? { outputTokens: t.outputTokens } : {}),
|
|
475
|
+
...(t.errorCode ? { errorCode: t.errorCode } : {}),
|
|
476
|
+
};
|
|
477
|
+
}
|
|
478
|
+
|
|
479
|
+
function speakFallback(s: SessionState, t: TurnState): void {
|
|
480
|
+
if (t.fallbackSpoken) return;
|
|
481
|
+
t.fallbackSpoken = true;
|
|
482
|
+
deliver(s, t, fallbackText);
|
|
483
|
+
}
|
|
484
|
+
|
|
485
|
+
async function ensureService(t: TurnState): Promise<void> {
|
|
486
|
+
if (serviceWaited || !serviceSource || serviceWaitMs <= 0) return;
|
|
487
|
+
serviceWaited = true;
|
|
488
|
+
if (serviceSource.status === "ready") return;
|
|
489
|
+
const signal = t.controller.signal;
|
|
490
|
+
await Promise.race([
|
|
491
|
+
serviceSource.ready(serviceWaitMs),
|
|
492
|
+
new Promise<void>((resolve) => {
|
|
493
|
+
if (signal.aborted) resolve();
|
|
494
|
+
else signal.addEventListener("abort", () => resolve(), { once: true });
|
|
495
|
+
}),
|
|
496
|
+
]);
|
|
497
|
+
}
|
|
498
|
+
|
|
499
|
+
async function body(
|
|
500
|
+
s: SessionState,
|
|
501
|
+
t: TurnState,
|
|
502
|
+
ctx: TurnContext,
|
|
503
|
+
): Promise<TurnSummary> {
|
|
504
|
+
const signal = t.controller.signal;
|
|
505
|
+
let filler: ReturnType<typeof setTimeout> | undefined;
|
|
506
|
+
try {
|
|
507
|
+
if (!provider) {
|
|
508
|
+
throw new LlmProviderError("LLM_BAD_REQUEST", "provider not started");
|
|
509
|
+
}
|
|
510
|
+
await ensureService(t);
|
|
511
|
+
for (let round = 0; round < maxRounds; round += 1) {
|
|
512
|
+
const done = await runRound(s, t, ctx);
|
|
513
|
+
const calls = done.toolCalls;
|
|
514
|
+
if (calls.length === 0) {
|
|
515
|
+
s.history.addAssistant(
|
|
516
|
+
{
|
|
517
|
+
role: "assistant",
|
|
518
|
+
text: done.text,
|
|
519
|
+
...(done.providerState !== undefined
|
|
520
|
+
? { providerState: done.providerState }
|
|
521
|
+
: {}),
|
|
522
|
+
},
|
|
523
|
+
{ turnId: t.turnId },
|
|
524
|
+
);
|
|
525
|
+
t.status = "completed";
|
|
526
|
+
return summarize(t);
|
|
527
|
+
}
|
|
528
|
+
if (round === maxRounds - 1) {
|
|
529
|
+
// Tools requested again after the last allowed round: keep the text
|
|
530
|
+
// only, so history never holds tool calls without results.
|
|
531
|
+
s.history.addAssistant(
|
|
532
|
+
{ role: "assistant", text: done.text },
|
|
533
|
+
{ turnId: t.turnId },
|
|
534
|
+
);
|
|
535
|
+
t.errorCode = "LLM_TOOL_ROUNDS_EXCEEDED";
|
|
536
|
+
agentLog(
|
|
537
|
+
"error",
|
|
538
|
+
"llm turn failed: LLM_TOOL_ROUNDS_EXCEEDED",
|
|
539
|
+
s.sessionId,
|
|
540
|
+
);
|
|
541
|
+
speakFallback(s, t);
|
|
542
|
+
t.status = "failed";
|
|
543
|
+
return summarize(t);
|
|
544
|
+
}
|
|
545
|
+
s.history.addAssistant(
|
|
546
|
+
{
|
|
547
|
+
role: "assistant",
|
|
548
|
+
text: done.text,
|
|
549
|
+
toolCalls: calls,
|
|
550
|
+
...(done.providerState !== undefined
|
|
551
|
+
? { providerState: done.providerState }
|
|
552
|
+
: {}),
|
|
553
|
+
},
|
|
554
|
+
{ turnId: t.turnId },
|
|
555
|
+
);
|
|
556
|
+
setAgentState(s.sessionId, "tool_call", {
|
|
557
|
+
detail: calls
|
|
558
|
+
.map((c) => c.name)
|
|
559
|
+
.join(",")
|
|
560
|
+
.slice(0, 64),
|
|
561
|
+
});
|
|
562
|
+
const fillerCfg = config.tools?.filler;
|
|
563
|
+
if (fillerCfg && !t.fillerSpoken) {
|
|
564
|
+
filler = setTimeout(() => {
|
|
565
|
+
if (t.fillerSpoken || signal.aborted) return;
|
|
566
|
+
t.fillerSpoken = true;
|
|
567
|
+
speakAnnouncement(
|
|
568
|
+
s,
|
|
569
|
+
t.turnId,
|
|
570
|
+
fillerCfg.text,
|
|
571
|
+
fillerCfg.interruptible ?? D.fillerInterruptible,
|
|
572
|
+
);
|
|
573
|
+
}, fillerCfg.afterMs ?? D.fillerAfterMs);
|
|
574
|
+
}
|
|
575
|
+
let results: LlmToolResult[];
|
|
576
|
+
try {
|
|
577
|
+
results = await runTools(s, t, ctx, calls);
|
|
578
|
+
} finally {
|
|
579
|
+
if (filler) clearTimeout(filler);
|
|
580
|
+
filler = undefined;
|
|
581
|
+
}
|
|
582
|
+
s.history.addToolResults(results, { turnId: t.turnId });
|
|
583
|
+
if (signal.aborted)
|
|
584
|
+
throw new LlmProviderError("LLM_ABORTED", "aborted");
|
|
585
|
+
}
|
|
586
|
+
t.status = "completed";
|
|
587
|
+
return summarize(t);
|
|
588
|
+
} catch (err) {
|
|
589
|
+
if (signal.aborted) {
|
|
590
|
+
if (t.roundOpen) {
|
|
591
|
+
const text = (t.playedOverride ?? t.roundText).trim();
|
|
592
|
+
if (text) {
|
|
593
|
+
s.history.addAssistant(
|
|
594
|
+
{ role: "assistant", text },
|
|
595
|
+
{ turnId: t.turnId },
|
|
596
|
+
);
|
|
597
|
+
}
|
|
598
|
+
t.roundOpen = false;
|
|
599
|
+
}
|
|
600
|
+
t.status = t.abortStatus ?? "cancelled";
|
|
601
|
+
return summarize(t);
|
|
602
|
+
}
|
|
603
|
+
const code =
|
|
604
|
+
err instanceof LlmProviderError ? err.code : "LLM_TURN_ERROR";
|
|
605
|
+
t.errorCode = code;
|
|
606
|
+
agentLog("error", `llm turn failed: ${code}`, s.sessionId);
|
|
607
|
+
speakFallback(s, t);
|
|
608
|
+
t.status = "failed";
|
|
609
|
+
return summarize(t);
|
|
610
|
+
} finally {
|
|
611
|
+
if (filler) clearTimeout(filler);
|
|
612
|
+
}
|
|
613
|
+
}
|
|
614
|
+
|
|
615
|
+
async function execute(
|
|
616
|
+
s: SessionState,
|
|
617
|
+
t: TurnState,
|
|
618
|
+
ctx: TurnContext,
|
|
619
|
+
): Promise<void> {
|
|
620
|
+
const note = useNote ? s.history.takePendingNote() : undefined;
|
|
621
|
+
s.history.addUser(note ? `${note}\n${t.inputText}` : t.inputText, {
|
|
622
|
+
turnId: t.turnId,
|
|
623
|
+
});
|
|
624
|
+
setAgentState(s.sessionId, "thinking");
|
|
625
|
+
|
|
626
|
+
let summary: TurnSummary;
|
|
627
|
+
let nextCalled = false;
|
|
628
|
+
let nextSummary: TurnSummary | undefined;
|
|
629
|
+
const next = async (): Promise<TurnSummary> => {
|
|
630
|
+
nextCalled = true;
|
|
631
|
+
nextSummary = await body(s, t, ctx);
|
|
632
|
+
return nextSummary;
|
|
633
|
+
};
|
|
634
|
+
if (hooks.respond) {
|
|
635
|
+
const r = await callHook("respond", s.sessionId, () =>
|
|
636
|
+
hooks.respond!(ctx, next),
|
|
637
|
+
);
|
|
638
|
+
if (r.ok && r.value) {
|
|
639
|
+
summary = r.value;
|
|
640
|
+
} else if (nextSummary) {
|
|
641
|
+
summary = nextSummary;
|
|
642
|
+
} else if (!r.ok && !nextCalled) {
|
|
643
|
+
summary = await next();
|
|
644
|
+
} else {
|
|
645
|
+
t.status =
|
|
646
|
+
t.abortStatus ??
|
|
647
|
+
(t.controller.signal.aborted ? "cancelled" : "completed");
|
|
648
|
+
summary = summarize(t);
|
|
649
|
+
}
|
|
650
|
+
} else {
|
|
651
|
+
summary = await next();
|
|
652
|
+
}
|
|
653
|
+
|
|
654
|
+
if (
|
|
655
|
+
t.source === "chat" &&
|
|
656
|
+
(summary.status === "completed" || summary.status === "failed")
|
|
657
|
+
) {
|
|
658
|
+
const text = t.spoken.join(" ");
|
|
659
|
+
sendToClient(s.sessionId, {
|
|
660
|
+
type: "assistant_done",
|
|
661
|
+
turnId: t.turnId,
|
|
662
|
+
text,
|
|
663
|
+
});
|
|
664
|
+
sendToClient(s.sessionId, { type: "chat_reply", text });
|
|
665
|
+
}
|
|
666
|
+
setAgentState(s.sessionId, "listening");
|
|
667
|
+
if (hooks.onTurnEnd) {
|
|
668
|
+
await callHook("onTurnEnd", s.sessionId, () =>
|
|
669
|
+
hooks.onTurnEnd!(summary, ctx),
|
|
670
|
+
);
|
|
671
|
+
}
|
|
672
|
+
agentLog(
|
|
673
|
+
"info",
|
|
674
|
+
"llm turn",
|
|
675
|
+
{
|
|
676
|
+
turnId: summary.turnId,
|
|
677
|
+
status: summary.status,
|
|
678
|
+
llmCalls: summary.llmCalls,
|
|
679
|
+
toolCalls: summary.toolCalls.map((c) => c.name),
|
|
680
|
+
firstTokenMs: summary.firstTokenMs,
|
|
681
|
+
inputTokens: summary.inputTokens,
|
|
682
|
+
outputTokens: summary.outputTokens,
|
|
683
|
+
},
|
|
684
|
+
s.sessionId,
|
|
685
|
+
);
|
|
686
|
+
}
|
|
687
|
+
|
|
688
|
+
function startTurn(s: SessionState, text: string, source: Source): void {
|
|
689
|
+
const turnId = randomUUID();
|
|
690
|
+
const controller = new AbortController();
|
|
691
|
+
const t: TurnState = {
|
|
692
|
+
turnId,
|
|
693
|
+
source,
|
|
694
|
+
inputText: text,
|
|
695
|
+
controller,
|
|
696
|
+
startedAt: now(),
|
|
697
|
+
spoken: [],
|
|
698
|
+
toolCalls: [],
|
|
699
|
+
llmCalls: 0,
|
|
700
|
+
roundOpen: false,
|
|
701
|
+
roundText: "",
|
|
702
|
+
spokeFirst: false,
|
|
703
|
+
fillerSpoken: false,
|
|
704
|
+
fallbackSpoken: false,
|
|
705
|
+
status: "completed",
|
|
706
|
+
};
|
|
707
|
+
const ctx: TurnContext = {
|
|
708
|
+
sessionId: s.sessionId,
|
|
709
|
+
turnId,
|
|
710
|
+
inputText: text,
|
|
711
|
+
source,
|
|
712
|
+
signal: controller.signal,
|
|
713
|
+
speak: (speech, o) => {
|
|
714
|
+
const splitter = new SentenceSplitter();
|
|
715
|
+
const parts = [...splitter.push(`${speech}\n`), ...splitter.end()];
|
|
716
|
+
for (const part of parts) deliver(s, t, part, o?.interruptible);
|
|
717
|
+
},
|
|
718
|
+
};
|
|
719
|
+
const active: ActiveTurn = {
|
|
720
|
+
turnId,
|
|
721
|
+
state: t,
|
|
722
|
+
promise: Promise.resolve(),
|
|
723
|
+
};
|
|
724
|
+
s.active = active;
|
|
725
|
+
active.promise = (async () => {
|
|
726
|
+
try {
|
|
727
|
+
await execute(s, t, ctx);
|
|
728
|
+
} catch (err) {
|
|
729
|
+
const message = err instanceof Error ? err.message : String(err);
|
|
730
|
+
agentLog("error", `llm turn crashed: ${message}`, s.sessionId);
|
|
731
|
+
} finally {
|
|
732
|
+
if (s.active === active) s.active = undefined;
|
|
733
|
+
const q = s.queued;
|
|
734
|
+
if (q && !s.ended && !s.active) {
|
|
735
|
+
s.queued = undefined;
|
|
736
|
+
startTurn(s, q.text, q.source);
|
|
737
|
+
}
|
|
738
|
+
}
|
|
739
|
+
})();
|
|
740
|
+
}
|
|
741
|
+
|
|
742
|
+
async function handleInput(
|
|
743
|
+
s: SessionState,
|
|
744
|
+
text: string,
|
|
745
|
+
source: Source,
|
|
746
|
+
): Promise<void> {
|
|
747
|
+
if (s.ended) return;
|
|
748
|
+
if (
|
|
749
|
+
source === "voice" &&
|
|
750
|
+
config.speechDuringNonInterruptible === "discard" &&
|
|
751
|
+
s.announcing > 0
|
|
752
|
+
) {
|
|
753
|
+
agentLog("info", "final discarded during announcement", s.sessionId);
|
|
754
|
+
if (hooks.onTurnEnd) {
|
|
755
|
+
const turnId = randomUUID();
|
|
756
|
+
const summary: TurnSummary = {
|
|
757
|
+
turnId,
|
|
758
|
+
status: "discarded",
|
|
759
|
+
assistantText: "",
|
|
760
|
+
toolCalls: [],
|
|
761
|
+
llmCalls: 0,
|
|
762
|
+
};
|
|
763
|
+
const ctx: TurnContext = {
|
|
764
|
+
sessionId: s.sessionId,
|
|
765
|
+
turnId,
|
|
766
|
+
inputText: text,
|
|
767
|
+
source,
|
|
768
|
+
signal: new AbortController().signal,
|
|
769
|
+
speak: () => {},
|
|
770
|
+
};
|
|
771
|
+
await callHook("onTurnEnd", s.sessionId, () =>
|
|
772
|
+
hooks.onTurnEnd!(summary, ctx),
|
|
773
|
+
);
|
|
774
|
+
}
|
|
775
|
+
return;
|
|
776
|
+
}
|
|
777
|
+
const active = s.active;
|
|
778
|
+
if (active) {
|
|
779
|
+
if (policy === "finish") {
|
|
780
|
+
s.queued = { text, source };
|
|
781
|
+
return;
|
|
782
|
+
}
|
|
783
|
+
cancelSpeech(s.sessionId, { turnId: active.turnId });
|
|
784
|
+
active.state.abortStatus = "cancelled";
|
|
785
|
+
active.state.controller.abort();
|
|
786
|
+
let timer: ReturnType<typeof setTimeout> | undefined;
|
|
787
|
+
await Promise.race([
|
|
788
|
+
active.promise,
|
|
789
|
+
new Promise<void>((resolve) => {
|
|
790
|
+
timer = setTimeout(resolve, CANCEL_SETTLE_MS);
|
|
791
|
+
}),
|
|
792
|
+
]);
|
|
793
|
+
if (timer) clearTimeout(timer);
|
|
794
|
+
if (s.ended) return;
|
|
795
|
+
}
|
|
796
|
+
startTurn(s, text, source);
|
|
797
|
+
}
|
|
798
|
+
|
|
799
|
+
/** Never awaits the LLM: the session's serial queue must stay free. */
|
|
800
|
+
function submit(sessionId: string, text: string, source: Source): void {
|
|
801
|
+
const s = sessions.get(sessionId);
|
|
802
|
+
const trimmed = text.trim();
|
|
803
|
+
if (!s || !trimmed) return;
|
|
804
|
+
s.chain = s.chain
|
|
805
|
+
.then(() => handleInput(s, trimmed, source))
|
|
806
|
+
.catch((err) => {
|
|
807
|
+
const message = err instanceof Error ? err.message : String(err);
|
|
808
|
+
agentLog("error", `llm input failed: ${message}`, sessionId);
|
|
809
|
+
});
|
|
810
|
+
}
|
|
811
|
+
|
|
812
|
+
// ---- handlers ----------------------------------------------------------
|
|
813
|
+
|
|
814
|
+
return {
|
|
815
|
+
async onAgentStart() {
|
|
816
|
+
const env = getEnv();
|
|
817
|
+
const apiKey = env[config.apiKeySecret];
|
|
818
|
+
if (!nonEmpty(apiKey)) {
|
|
819
|
+
throw configError(
|
|
820
|
+
`environment variable ${config.apiKeySecret} is not set`,
|
|
821
|
+
"LLM_API_KEY_MISSING",
|
|
822
|
+
);
|
|
823
|
+
}
|
|
824
|
+
if (!provider) {
|
|
825
|
+
provider = createLlmProvider({
|
|
826
|
+
provider: config.provider,
|
|
827
|
+
apiKey,
|
|
828
|
+
baseUrl: config.baseUrl,
|
|
829
|
+
});
|
|
830
|
+
}
|
|
831
|
+
buildRegistry(env);
|
|
832
|
+
},
|
|
833
|
+
|
|
834
|
+
async onSessionStart(ctx: SessionContext) {
|
|
835
|
+
const s: SessionState = {
|
|
836
|
+
sessionId: ctx.sessionId,
|
|
837
|
+
history: new ConversationHistory(historyTurns),
|
|
838
|
+
announcing: 0,
|
|
839
|
+
chain: Promise.resolve(),
|
|
840
|
+
ended: false,
|
|
841
|
+
};
|
|
842
|
+
sessions.set(ctx.sessionId, s);
|
|
843
|
+
const mode = config.bargeIn?.mode ?? D.bargeInMode;
|
|
844
|
+
if (ctx.speakControlAvailable && (mode === "on" || mode === "off")) {
|
|
845
|
+
await setBargeIn(ctx.sessionId, mode === "on");
|
|
846
|
+
}
|
|
847
|
+
const greeting = config.greeting;
|
|
848
|
+
if (greeting) {
|
|
849
|
+
const turnId = `greet-${randomUUID()}`;
|
|
850
|
+
s.history.addAssistant(
|
|
851
|
+
{ role: "assistant", text: greeting.text },
|
|
852
|
+
{ turnId },
|
|
853
|
+
);
|
|
854
|
+
speakAnnouncement(
|
|
855
|
+
s,
|
|
856
|
+
turnId,
|
|
857
|
+
greeting.text,
|
|
858
|
+
greeting.interruptible ?? D.greetingInterruptible,
|
|
859
|
+
);
|
|
860
|
+
}
|
|
861
|
+
},
|
|
862
|
+
|
|
863
|
+
onUserSpeechFinal(ctx) {
|
|
864
|
+
submit(ctx.sessionId, ctx.text, "voice");
|
|
865
|
+
},
|
|
866
|
+
|
|
867
|
+
onDataChannelMessage(ctx) {
|
|
868
|
+
const text = parseChatText(ctx.message);
|
|
869
|
+
if (text) submit(ctx.sessionId, text, "chat");
|
|
870
|
+
},
|
|
871
|
+
|
|
872
|
+
onAgentInterrupted(ctx: AgentInterruptedContext) {
|
|
873
|
+
const s = sessions.get(ctx.sessionId);
|
|
874
|
+
if (!s || !ctx.turnId) return;
|
|
875
|
+
const note = useNote
|
|
876
|
+
? interruptionNote(ctx.playedText, ctx.unplayedText)
|
|
877
|
+
: undefined;
|
|
878
|
+
s.lastInterruption = {
|
|
879
|
+
turnId: ctx.turnId,
|
|
880
|
+
playedText: ctx.playedText,
|
|
881
|
+
unplayedText: ctx.unplayedText,
|
|
882
|
+
};
|
|
883
|
+
const active = s.active;
|
|
884
|
+
if (active && active.turnId === ctx.turnId) {
|
|
885
|
+
const t = active.state;
|
|
886
|
+
if (t.roundOpen) {
|
|
887
|
+
t.playedOverride = ctx.playedText;
|
|
888
|
+
if (note) s.history.setPendingNote(note);
|
|
889
|
+
} else {
|
|
890
|
+
s.history.replaceAssistantText(ctx.turnId, ctx.playedText, note);
|
|
891
|
+
}
|
|
892
|
+
if (policy === "cancel") {
|
|
893
|
+
t.abortStatus = "interrupted";
|
|
894
|
+
t.controller.abort();
|
|
895
|
+
}
|
|
896
|
+
} else {
|
|
897
|
+
s.history.replaceAssistantText(ctx.turnId, ctx.playedText, note);
|
|
898
|
+
}
|
|
899
|
+
},
|
|
900
|
+
|
|
901
|
+
onSessionEnd(ctx) {
|
|
902
|
+
const s = sessions.get(ctx.sessionId);
|
|
903
|
+
if (!s) return;
|
|
904
|
+
s.ended = true;
|
|
905
|
+
s.queued = undefined;
|
|
906
|
+
if (s.active) {
|
|
907
|
+
s.active.state.abortStatus = "cancelled";
|
|
908
|
+
s.active.state.controller.abort();
|
|
909
|
+
}
|
|
910
|
+
sessions.delete(ctx.sessionId);
|
|
911
|
+
},
|
|
912
|
+
};
|
|
913
|
+
}
|