@voicethere/agent 0.34.0 → 0.35.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (35) hide show
  1. package/dist/llm/agent/config.d.ts +47 -0
  2. package/dist/llm/agent/config.d.ts.map +1 -1
  3. package/dist/llm/agent/config.js +128 -0
  4. package/dist/llm/agent/config.js.map +1 -1
  5. package/dist/llm/agent/create-llm-agent.d.ts +4 -0
  6. package/dist/llm/agent/create-llm-agent.d.ts.map +1 -1
  7. package/dist/llm/agent/create-llm-agent.js +63 -9
  8. package/dist/llm/agent/create-llm-agent.js.map +1 -1
  9. package/dist/llm/anthropic-provider.d.ts.map +1 -1
  10. package/dist/llm/anthropic-provider.js +1 -0
  11. package/dist/llm/anthropic-provider.js.map +1 -1
  12. package/dist/llm/gemini-provider.d.ts.map +1 -1
  13. package/dist/llm/gemini-provider.js +1 -0
  14. package/dist/llm/gemini-provider.js.map +1 -1
  15. package/dist/llm/openai-provider.d.ts.map +1 -1
  16. package/dist/llm/openai-provider.js +1 -0
  17. package/dist/llm/openai-provider.js.map +1 -1
  18. package/dist/llm/types.d.ts +6 -0
  19. package/dist/llm/types.d.ts.map +1 -1
  20. package/dist/llm/types.js.map +1 -1
  21. package/dist/templates/flow-agent/agent.js +23 -0
  22. package/dist/templates/llm-agent/agent.js +189 -8
  23. package/dist/templates/llm-board/agent.js +189 -8
  24. package/dist/templates/llm-docs-rag/agent.js +189 -8
  25. package/dist/templates/llm-language-switch/agent.js +205 -11
  26. package/dist/templates/llm-language-tutor/agent.js +189 -8
  27. package/dist/templates/llm-mcp-service/agent.js +189 -8
  28. package/dist/templates/llm-store-support/agent.js +189 -8
  29. package/dist/templates/llm-support-sticky-user/agent.js +189 -8
  30. package/eject/llm/loop.ts +79 -9
  31. package/package.json +1 -1
  32. package/schema/voicethere.llm.schema.json +24 -0
  33. package/templates/llm-agent/README.md +25 -0
  34. package/templates/llm-language-switch/README.md +2 -2
  35. package/templates/llm-language-switch/language.ts +30 -3
package/eject/llm/loop.ts CHANGED
@@ -1,4 +1,4 @@
1
- // Copied from @voicethere/agent 0.34.0. Package updates no longer change this file.
1
+ // Copied from @voicethere/agent 0.35.1. Package updates no longer change this file.
2
2
  import { randomUUID } from "node:crypto";
3
3
  import {
4
4
  type AgentHandlers,
@@ -6,6 +6,7 @@ import {
6
6
  agentLog,
7
7
  announce,
8
8
  cancelSpeech,
9
+ disconnectClient,
9
10
  getSessionUser,
10
11
  parseChatText,
11
12
  recordReply,
@@ -61,6 +62,10 @@ import {
61
62
 
62
63
  const D = LLM_AGENT_CONFIG_DEFAULTS;
63
64
  const CANCEL_SETTLE_MS = 2_000;
65
+ /** Longest wait for the closing message to finish before the call is closed (`failedReplies`). */
66
+ export const FAIL_CLOSE_SPEAK_WAIT_MS = 15_000;
67
+ /** Disconnect reason sent to the runner when `failedReplies` closes the call. */
68
+ export const FAIL_CLOSE_REASON = "llm_failed_replies";
64
69
 
65
70
  export interface CreateLlmAgentOptions {
66
71
  /** Validated here; an invalid config throws `LLM_CONFIG_INVALID`. */
@@ -144,6 +149,8 @@ interface TurnState {
144
149
  pendingChars: number;
145
150
  coalesceTimer?: ReturnType<typeof setTimeout>;
146
151
  fallbackSpoken: boolean;
152
+ /** The closing message of `failedReplies` was spoken this turn; completes when it finished. */
153
+ closeSpeech?: Promise<unknown>;
147
154
  /** Characters of `<thinking>` blocks removed from the reply this turn. */
148
155
  thinkingCharsStripped: number;
149
156
  /** URLs sent as `assistant_content` in this turn. */
@@ -191,6 +198,10 @@ interface SessionState {
191
198
  unplayedText: string;
192
199
  };
193
200
  ended: boolean;
201
+ /** Consecutive failed turns (`failedReplies`). Per session, never module state. */
202
+ failedStreak: number;
203
+ /** The call is being closed by `failedReplies`: no further turn starts. */
204
+ closing: boolean;
194
205
  }
195
206
 
196
207
  function configError(message: string, code: string): Error {
@@ -304,6 +315,8 @@ export function createLlmAgent(opts: CreateLlmAgentOptions): AgentHandlers {
304
315
  const toolMaxBytes = config.tools?.maxResultBytes ?? D.toolMaxResultBytes;
305
316
  const policy = config.interruptPolicy ?? D.interruptPolicy;
306
317
  const fallbackText = config.fallbackText ?? D.fallbackText;
318
+ const closeAfter = config.failedReplies?.closeAfter;
319
+ const closeMessage = config.failedReplies?.message ?? D.failedRepliesMessage;
307
320
  const speakChat = config.speakChatReplies ?? D.speakChatReplies;
308
321
  const useNote = config.history?.interruptionNote ?? D.interruptionNote;
309
322
  const historyTurns = config.history?.turns ?? D.historyTurns;
@@ -530,24 +543,25 @@ export function createLlmAgent(opts: CreateLlmAgentOptions): AgentHandlers {
530
543
  t: TurnState,
531
544
  text: string,
532
545
  interruptible = true,
533
- ): void {
546
+ ): Promise<unknown> {
534
547
  flushSpeech(s, t);
535
548
  t.spoken.push(text);
536
549
  markReplyStarted(s, t);
537
550
  sendReplyDelta(s, t, text);
538
551
  if (t.source === "voice" || speakChat) {
539
552
  if (interruptible) {
540
- trackSpeech(s, speak(s.sessionId, text, replyOpts(t)), {
553
+ return trackSpeech(s, speak(s.sessionId, text, replyOpts(t)), {
541
554
  turnId: t.turnId,
542
555
  text,
543
556
  sentences: t.spoken,
544
557
  indexes: [t.spoken.length - 1],
545
- });
546
- } else {
547
- const h = announce(s.sessionId, text, replyOpts(t));
548
- trackAnnouncement(s, h.done);
558
+ }).done;
549
559
  }
560
+ const h = announce(s.sessionId, text, replyOpts(t));
561
+ trackAnnouncement(s, h.done);
562
+ return h.done;
550
563
  }
564
+ return Promise.resolve();
551
565
  }
552
566
 
553
567
  /**
@@ -1051,6 +1065,7 @@ export function createLlmAgent(opts: CreateLlmAgentOptions): AgentHandlers {
1051
1065
  ...(config.toolChoice === "required-first-round" && t.llmCalls === 1
1052
1066
  ? { toolChoice: "required" as const }
1053
1067
  : {}),
1068
+ ...(config.vendorConfig ? { vendorConfig: config.vendorConfig } : {}),
1054
1069
  temperature: config.temperature,
1055
1070
  maxOutputTokens: config.maxOutputTokens ?? D.maxOutputTokens,
1056
1071
  signal,
@@ -1137,9 +1152,60 @@ export function createLlmAgent(opts: CreateLlmAgentOptions): AgentHandlers {
1137
1152
  function speakFallback(s: SessionState, t: TurnState): void {
1138
1153
  if (t.fallbackSpoken) return;
1139
1154
  t.fallbackSpoken = true;
1155
+ if (closeAfter !== undefined && s.failedStreak + 1 >= closeAfter) {
1156
+ t.closeSpeech = deliver(s, t, closeMessage);
1157
+ return;
1158
+ }
1140
1159
  deliver(s, t, fallbackText);
1141
1160
  }
1142
1161
 
1162
+ /**
1163
+ * `failedReplies`: counts consecutive failed turns. At the limit the closing
1164
+ * message is on its way (or is spoken here when a `respond` hook failed the
1165
+ * turn), the wait for it is bounded, then the runner is asked to disconnect.
1166
+ * The runner registers `customer_disconnect` before teardown.
1167
+ */
1168
+ function trackFailedReplies(
1169
+ s: SessionState,
1170
+ t: TurnState,
1171
+ summary: TurnSummary,
1172
+ ): boolean {
1173
+ if (closeAfter === undefined || s.closing || s.ended) return false;
1174
+ if (summary.status === "completed") {
1175
+ s.failedStreak = 0;
1176
+ return false;
1177
+ }
1178
+ if (summary.status !== "failed") return false;
1179
+ s.failedStreak += 1;
1180
+ if (s.failedStreak < closeAfter) return false;
1181
+ s.closing = true;
1182
+ t.closeSpeech ??= deliver(s, t, closeMessage);
1183
+ return true;
1184
+ }
1185
+
1186
+ async function closeAfterFailedReplies(
1187
+ s: SessionState,
1188
+ t: TurnState,
1189
+ ): Promise<void> {
1190
+ const started = now();
1191
+ let timer: ReturnType<typeof setTimeout> | undefined;
1192
+ await Promise.race([
1193
+ t.closeSpeech,
1194
+ new Promise<void>((resolve) => {
1195
+ timer = setTimeout(resolve, FAIL_CLOSE_SPEAK_WAIT_MS);
1196
+ }),
1197
+ ]);
1198
+ if (timer) clearTimeout(timer);
1199
+ if (s.ended) return;
1200
+ agentLog(
1201
+ "info",
1202
+ "closing call after failed replies",
1203
+ { closeAfter, waitedMs: now() - started },
1204
+ s.sessionId,
1205
+ );
1206
+ disconnectClient(s.sessionId, { reason: FAIL_CLOSE_REASON });
1207
+ }
1208
+
1143
1209
  async function ensureService(t: TurnState): Promise<void> {
1144
1210
  if (serviceWaited || !serviceSource || serviceWaitMs <= 0) return;
1145
1211
  serviceWaited = true;
@@ -1382,6 +1448,7 @@ export function createLlmAgent(opts: CreateLlmAgentOptions): AgentHandlers {
1382
1448
  });
1383
1449
  }
1384
1450
  setAgentState(s.sessionId, "listening");
1451
+ const closeNow = trackFailedReplies(s, t, summary);
1385
1452
  if (hooks.onTurnEnd) {
1386
1453
  await callHook("onTurnEnd", s.sessionId, () =>
1387
1454
  hooks.onTurnEnd!(summary, ctx),
@@ -1406,6 +1473,7 @@ export function createLlmAgent(opts: CreateLlmAgentOptions): AgentHandlers {
1406
1473
  },
1407
1474
  s.sessionId,
1408
1475
  );
1476
+ if (closeNow) await closeAfterFailedReplies(s, t);
1409
1477
  }
1410
1478
 
1411
1479
  function startTurn(
@@ -1473,7 +1541,7 @@ export function createLlmAgent(opts: CreateLlmAgentOptions): AgentHandlers {
1473
1541
  } finally {
1474
1542
  if (s.active === active) s.active = undefined;
1475
1543
  const q = s.queued;
1476
- if (q && !s.ended && !s.active) {
1544
+ if (q && !s.ended && !s.closing && !s.active) {
1477
1545
  s.queued = undefined;
1478
1546
  startTurn(s, q.text, q.source, q.utteranceId);
1479
1547
  }
@@ -1487,7 +1555,7 @@ export function createLlmAgent(opts: CreateLlmAgentOptions): AgentHandlers {
1487
1555
  source: Source,
1488
1556
  utteranceId?: string,
1489
1557
  ): Promise<void> {
1490
- if (s.ended) return;
1558
+ if (s.ended || s.closing) return;
1491
1559
  if (
1492
1560
  source === "voice" &&
1493
1561
  config.speechDuringNonInterruptible === "discard" &&
@@ -1611,6 +1679,8 @@ export function createLlmAgent(opts: CreateLlmAgentOptions): AgentHandlers {
1611
1679
  announcing: 0,
1612
1680
  chain: Promise.resolve(),
1613
1681
  ended: false,
1682
+ failedStreak: 0,
1683
+ closing: false,
1614
1684
  };
1615
1685
  sessions.set(ctx.sessionId, s);
1616
1686
  const mode = config.bargeIn?.mode ?? D.bargeInMode;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@voicethere/agent",
3
- "version": "0.34.0",
3
+ "version": "0.35.1",
4
4
  "description": "VoiceThere customer agent SDK — IPC types and runtime helpers for sandboxed child bundles",
5
5
  "type": "module",
6
6
  "exports": {
@@ -382,6 +382,30 @@
382
382
  "maxLength": 500,
383
383
  "default": "Sorry, something went wrong. Please try again."
384
384
  },
385
+ "failedReplies": {
386
+ "type": "object",
387
+ "additionalProperties": false,
388
+ "required": ["closeAfter"],
389
+ "description": "Close the call after this many failed replies in a row. Off when absent. A completed reply resets the count.",
390
+ "properties": {
391
+ "closeAfter": {
392
+ "type": "integer",
393
+ "minimum": 1,
394
+ "maximum": 20
395
+ },
396
+ "message": {
397
+ "type": "string",
398
+ "minLength": 1,
399
+ "maxLength": 300,
400
+ "default": "Sorry, I can't answer right now. Please try again later.",
401
+ "description": "Spoken and sent to chat on the closing reply, instead of fallbackText."
402
+ }
403
+ }
404
+ },
405
+ "vendorConfig": {
406
+ "type": "object",
407
+ "description": "Extra request keys for the provider's own API, merged under the fields the agent sets itself (at most 8 KB serialized). Keys the agent sets itself (model, messages or contents, system, tools, tool choice, stream, max tokens, temperature) are rejected. See the provider's API reference for the keys it accepts."
408
+ },
385
409
  "speakChatReplies": {
386
410
  "type": "boolean",
387
411
  "default": true
@@ -91,6 +91,31 @@ createLlmAgent({
91
91
 
92
92
  It is never added automatically.
93
93
 
94
+ ## Close the call after failed replies
95
+
96
+ Off by default. Set `failedReplies` in `voicethere.llm.json` to hang up when the model keeps failing:
97
+
98
+ ```json
99
+ "failedReplies": { "closeAfter": 3, "message": "Sorry, I can't answer right now. Please try again later." }
100
+ ```
101
+
102
+ - `closeAfter` (integer 1 to 20): consecutive failed replies that end the call. A completed reply resets the count. Cancelled and interrupted replies leave it unchanged. The count is per session.
103
+ - `message` (1 to 300 characters, optional): spoken and sent to chat on the closing reply instead of `fallbackText`. Default: "Sorry, I can't answer right now. Please try again later."
104
+ - After the message the agent waits for the speech to finish, at most 15 seconds, then asks the runner to disconnect the caller with the reason `llm_failed_replies`. No further reply starts after that.
105
+
106
+ ## Provider request options (`vendorConfig`)
107
+
108
+ `vendorConfig` is a plain JSON object (at most 8 KB serialized) merged into the provider request next to the fields the agent sets. The agent never reads it. Use the keys your provider's API documents:
109
+
110
+ ```json
111
+ "vendorConfig": { "top_p": 0.8 }
112
+ ```
113
+
114
+ - OpenAI and OpenRouter: chat completion parameters, sent as given.
115
+ - Anthropic: `messages.create` parameters, sent as given.
116
+ - Gemini: keys of `GenerateContentConfig`. The Gemini SDK sends only the keys it knows and drops the rest.
117
+ - Keys the agent sets itself are rejected at load time with the key named: the model, the messages (`messages`, `contents`, `system`, `systemInstruction`), `tools`, the tool choice (`tool_choice`, `toolConfig`), `stream`, the max tokens (`max_tokens`, `max_completion_tokens`, `maxOutputTokens`) and `temperature`. Provider-specific extras the agent sends (`stream_options`, `output_config`, `abortSignal`) are rejected too.
118
+
94
119
  ## Output token cap
95
120
 
96
121
  `maxOutputTokens` is 1024 in `voicethere.llm.json`. Thinking models count hidden reasoning against `maxOutputTokens`, so keep spoken replies short in the prompt, not with a small cap. A reply cut off by the cap before anything was spoken ends the turn with `LLM_OUTPUT_TRUNCATED` and the fallback text.
@@ -14,8 +14,8 @@ A small travel-help assistant that follows the caller when they change language
14
14
 
15
15
  The runner owns the switch. The agent never calls `setVoiceLanguage`.
16
16
 
17
- - `onVoiceLanguageChanged` records the committed language and sends `{ "type": "language", "language": "de" }` to the client. Only a committed language changes what the LLM is told. The agent appends one line ("The caller now speaks German (de). Reply only in German.") to a copy of the last caller message on every LLM call, so it never piles up in the history.
18
- - `onUserLanguage` only reports what was heard: `{ "type": "language_detected", "language": "it", "supported": false }`. The runner may still reject a detection, so the LLM note does not change on it.
17
+ - `onVoiceLanguageChanged` records the committed language and sends `{ "type": "language", "language": "de" }` to the client. The runner sends it after it has replayed the switching utterance, so the replayed final (`replay: true`) is answered in the language detected for it; every other final is answered in the committed language. The agent appends one line ("The caller now speaks German (de). Reply only in German.") to a copy of the last caller message on every LLM call, so it never piles up in the history.
18
+ - `onUserLanguage` only reports what was heard: `{ "type": "language_detected", "language": "it", "supported": false }`. The runner may still reject a detection, so a detection alone does not change the LLM note: only the replay that follows a switch uses it.
19
19
  - When the detected language is not in `SUPPORTED_LANGUAGES`, the runner does not switch and the transcript comes from the wrong language's speech model. The agent skips the LLM for that utterance and says, in the current language, "I heard Italian. I can talk with you in English, German, Spanish or French." That notice is not added to the LLM history.
20
20
  - Typed chat messages are answered in the language they are written in (the prompt says so); chat does not change the voice.
21
21
 
@@ -119,6 +119,20 @@ interface SessionLanguage {
119
119
  current: string;
120
120
  /** Detected language outside the list, waiting for its final. */
121
121
  unsupported?: string;
122
+ /** Last detected language in the list, until it is committed. */
123
+ detected?: string;
124
+ /**
125
+ * Language of the turn the LLM is answering now. Set by a replayed final:
126
+ * the runner replays only after it has swapped to the detected language,
127
+ * and it sends `voice_language_changed` after the replay, so the commit can
128
+ * arrive after the LLM call starts.
129
+ */
130
+ turn?: string;
131
+ }
132
+
133
+ /** The language the LLM is told for the current turn. */
134
+ function replyLanguage(state: SessionLanguage | undefined): string {
135
+ return state?.turn ?? state?.current ?? DEFAULT_LANGUAGE;
122
136
  }
123
137
 
124
138
  /**
@@ -134,8 +148,10 @@ export function languageSwitchAgent(
134
148
  onBeforeLlmCall(messages, ctx) {
135
149
  // Typed chat is answered in the language it is written in.
136
150
  if (ctx.source === "chat") return;
137
- const code = sessions.get(ctx.sessionId)?.current ?? DEFAULT_LANGUAGE;
138
- return withLanguageNote(messages, code);
151
+ return withLanguageNote(
152
+ messages,
153
+ replyLanguage(sessions.get(ctx.sessionId)),
154
+ );
139
155
  },
140
156
  });
141
157
 
@@ -168,7 +184,10 @@ export function languageSwitchAgent(
168
184
  supported,
169
185
  });
170
186
  const state = sessions.get(ctx.sessionId);
171
- if (state) state.unsupported = supported ? undefined : language;
187
+ if (state) {
188
+ state.unsupported = supported ? undefined : language;
189
+ state.detected = supported ? language : undefined;
190
+ }
172
191
  },
173
192
 
174
193
  onVoiceLanguageChanged(ctx) {
@@ -178,12 +197,20 @@ export function languageSwitchAgent(
178
197
  if (state) {
179
198
  state.current = language;
180
199
  state.unsupported = undefined;
200
+ state.detected = undefined;
201
+ state.turn = undefined;
181
202
  }
182
203
  sendToClient(ctx.sessionId, { type: "language", language });
183
204
  },
184
205
 
185
206
  onUserSpeechFinal(ctx) {
186
207
  const state = sessions.get(ctx.sessionId);
208
+ if (state) {
209
+ // A replayed final is the switching utterance re-decoded by the new
210
+ // language's STT; the commit follows it. Any other final is answered
211
+ // in the committed language.
212
+ state.turn = ctx.replay ? (state.detected ?? state.current) : undefined;
213
+ }
187
214
  if (state?.unsupported && !ctx.replay) {
188
215
  // The transcript came from the wrong language's STT: do not ask the
189
216
  // LLM, say what was heard in the current language instead.