@todoforai/voiceloop 0.1.13 → 0.1.14
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 +6 -4
- package/package.json +1 -1
- package/src/index.d.ts +6 -5
- package/src/llm-openai.js +64 -13
- package/src/voice-agent.js +14 -65
package/README.md
CHANGED
|
@@ -17,7 +17,7 @@ A zero-dependency JavaScript library that runs the full voice loop — **VAD →
|
|
|
17
17
|
- **Real barge-in** — triggers on transcribed *novel words*, not mic energy, so the agent's own voice never cuts it off.
|
|
18
18
|
- **Self-echo filtering** — 0 self-interruptions with AEC off (Pipecat cut itself 20/30, OpenAI Realtime 17/30 [bench](bench/results/RESULTS.md#scenario-echo-smalltalk--speakermic-coupling-15db--30ms)).
|
|
19
19
|
- **First audio <1s** — TTS speaks sentence 1 while the LLM writes sentence 2, and the LLM call starts speculatively during your end-of-turn pause.
|
|
20
|
-
- **Serialized turns** — rapid-fire turns, tool results, holds and replays can never talk over each other. Locked in by
|
|
20
|
+
- **Serialized turns** — rapid-fire turns, tool results, holds and replays can never talk over each other. Locked in by 184 tests.
|
|
21
21
|
- **Local-first** — Silero VAD and Piper TTS run as WASM in the tab: free, no cloud round-trip (CDN, then cache).
|
|
22
22
|
|
|
23
23
|
Extra:
|
|
@@ -169,7 +169,8 @@ const agent = new VoiceAgent({
|
|
|
169
169
|
// toolGate: only for adapters that run tools themselves — see below; ignore it otherwise
|
|
170
170
|
for await (const delta of myProvider.stream({ history, system, signal })) {
|
|
171
171
|
yield { text: delta }; // speech text → streamed into TTS
|
|
172
|
-
// yield { tool: 'name', args: {...} }; // tool call →
|
|
172
|
+
// yield { tool: 'name', args: {...} }; // tool call → the agent runs it during playback;
|
|
173
|
+
// // the NEXT user turn sees its tool_result
|
|
173
174
|
}
|
|
174
175
|
},
|
|
175
176
|
});
|
|
@@ -190,13 +191,13 @@ const agent = new VoiceAgent({
|
|
|
190
191
|
});
|
|
191
192
|
```
|
|
192
193
|
|
|
193
|
-
Tool calls execute while the agent is still talking.
|
|
194
|
+
Tool calls execute while the agent is still talking. The default adapter is a loop: it feeds each result back to the model inside the same reply, so the model keeps talking with the answer in hand (bounded to 6 model messages per turn). Results are recorded natively (tool_use / tool_result) so the model never re-fires the same call, and `agent.notify('[TOOL RESULT get_weather] 22°C sunny')` relays an async outcome back for a spoken follow-up — bursts of results collapse into one reply instead of three interrupting monologues.
|
|
194
195
|
|
|
195
196
|
Tools are **dispatched, not awaited**: the turn completes when the agent stops speaking, whatever the tool is still doing. A slow or hung tool can never stall the conversation, and a tool is free to `await agent.notify(...)` with its own result. Long work belongs in a tool that returns promptly ("checking that now") and delivers the outcome later via `notify()`.
|
|
196
197
|
|
|
197
198
|
### Adapters that run tools themselves
|
|
198
199
|
|
|
199
|
-
|
|
200
|
+
The default `makeOpenAILLM` and any agent loop execute tools **inside** the generator, feeding results back to the model so it keeps talking with the answer in hand — all within one turn. A custom loop declares two flags so voiceloop adapts, and yields `{ newMessage: true }` where the model's next message starts:
|
|
200
201
|
|
|
201
202
|
```js
|
|
202
203
|
async function* myAgentLoop(history, system, signal, { toolGate } = {}) {
|
|
@@ -204,6 +205,7 @@ async function* myAgentLoop(history, system, signal, { toolGate } = {}) {
|
|
|
204
205
|
if (ev.type === 'text') yield { text: ev.delta };
|
|
205
206
|
if (ev.type === 'tool_start') yield { tool: ev.name, id: ev.id, args: ev.args, running: true };
|
|
206
207
|
if (ev.type === 'tool_end') yield { tool: ev.name, id: ev.id, args: ev.args, result: ev.result };
|
|
208
|
+
if (ev.type === 'message_start' && !first) yield { newMessage: true };
|
|
207
209
|
}
|
|
208
210
|
}
|
|
209
211
|
myAgentLoop.executesTools = true; // chunks carry the outcome — voiceloop reports, never re-runs
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@todoforai/voiceloop",
|
|
3
|
-
"version": "0.1.
|
|
3
|
+
"version": "0.1.14",
|
|
4
4
|
"description": "Fast, interruptible browser voice agent: VAD → STT → LLM → TTS with real barge-in, echo filtering, streaming first-sentence TTS and tap-to-seek. Zero runtime dependencies.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "src/index.js",
|
package/src/index.d.ts
CHANGED
|
@@ -59,9 +59,10 @@ export type HistoryBlock =
|
|
|
59
59
|
| { type: 'tool_result'; tool_use_id: string; content: string; is_error?: boolean };
|
|
60
60
|
export type HistoryMessage = { role: string; content: string | HistoryBlock[] };
|
|
61
61
|
// Pluggable LLM: lazy async generator over the chat history (fetch fires on first pull).
|
|
62
|
-
// The default (makeOpenAILLM)
|
|
63
|
-
//
|
|
64
|
-
//
|
|
62
|
+
// The default (makeOpenAILLM) is a tool LOOP: it runs each call inside the generator, feeds the
|
|
63
|
+
// result back to the model and marks the model's next message with { newMessage }. A plain adapter
|
|
64
|
+
// (no flags) yields bare tool chunks that the AGENT executes and records; the NEXT user turn sees
|
|
65
|
+
// the tool_result (no reaction turn is started).
|
|
65
66
|
export interface LLM {
|
|
66
67
|
(
|
|
67
68
|
history: HistoryMessage[],
|
|
@@ -71,12 +72,12 @@ export interface LLM {
|
|
|
71
72
|
): AsyncIterable<LLMChunk>;
|
|
72
73
|
/** This generator is a tool LOOP: it runs every call itself and feeds the result back inside the
|
|
73
74
|
* same reply (chunks carry `result`/`error`, optionally preceded by a `running` announcement).
|
|
74
|
-
* The agent never executes its calls
|
|
75
|
+
* The agent never executes its calls. */
|
|
75
76
|
executesTools?: boolean;
|
|
76
77
|
/** This generator awaits `options.toolGate` before ANY tool executes. Required to keep
|
|
77
78
|
* speculative prefetch on: prefetch starts from an uncommitted interim, and the gate is what
|
|
78
79
|
* stops a speculation from firing a real side effect. `executesTools` without this silently
|
|
79
|
-
* disables prefetch (see voice-agent.js
|
|
80
|
+
* disables prefetch (see _startPrefetch in voice-agent.js). */
|
|
80
81
|
acceptsToolGate?: boolean;
|
|
81
82
|
}
|
|
82
83
|
|
package/src/llm-openai.js
CHANGED
|
@@ -1,9 +1,10 @@
|
|
|
1
1
|
// ── Default LLM: any OpenAI-compatible /chat/completions endpoint ───────────────────────────────
|
|
2
|
-
//
|
|
3
|
-
//
|
|
4
|
-
//
|
|
5
|
-
//
|
|
6
|
-
//
|
|
2
|
+
// A LOOP adapter (executesTools + acceptsToolGate): one turn may span several model messages. Each
|
|
3
|
+
// completion streams { text } deltas straight to the TTS; a COMPLETED tool call (arguments accumulate
|
|
4
|
+
// across deltas; a call whose arguments never parse as JSON is DROPPED with a warning — firing a
|
|
5
|
+
// side-effecting tool with guessed args would be worse) is announced ({ running: true }), executed
|
|
6
|
+
// here, reported with its outcome, fed back to the model as a tool message, and the model's next
|
|
7
|
+
// message starts after a { newMessage } boundary — bounded by MAX_ROUNDS per turn.
|
|
7
8
|
//
|
|
8
9
|
// Works against OpenAI, Groq, Cerebras, Together, OpenRouter, Ollama, vLLM, LiteLLM… anything that
|
|
9
10
|
// speaks /chat/completions SSE. NEVER ship a provider secret key to a public page — in production
|
|
@@ -37,6 +38,19 @@ export const toOpenAIMessages = (history) => history.flatMap((m) => {
|
|
|
37
38
|
return text ? [...results, { role: m.role, content: text }] : results; // OpenAI has no is_error → text-marked
|
|
38
39
|
});
|
|
39
40
|
|
|
41
|
+
// Render a host tool's return value as model-facing text (the tool_result content in history, and
|
|
42
|
+
// what adapters feed back to the model). Never throws: the side effect already RAN, so an
|
|
43
|
+
// unserializable result must not retro-fail the call and invite a retry.
|
|
44
|
+
export const toolResultText = (result) => {
|
|
45
|
+
if (result === undefined) return 'ok';
|
|
46
|
+
if (typeof result === 'string') return result;
|
|
47
|
+
if (result && typeof result.text === 'string' && typeof result.ok === 'boolean')
|
|
48
|
+
return result.ok ? result.text : `[failed] ${result.text}`;
|
|
49
|
+
try { return JSON.stringify(result) ?? 'ok'; } catch { return String(result); }
|
|
50
|
+
};
|
|
51
|
+
|
|
52
|
+
const MAX_ROUNDS = 6; // model messages per user turn — a model that keeps calling tools then waits for the user
|
|
53
|
+
|
|
40
54
|
export function makeOpenAILLM({ llmUrl, apiKey = '', model = '', maxTokens = 1024, tools = {}, fetchFn, extraBody = {} } = {}) {
|
|
41
55
|
const toolSpecs = Object.entries(tools).map(([name, t]) => ({
|
|
42
56
|
type: 'function',
|
|
@@ -47,15 +61,15 @@ export function makeOpenAILLM({ llmUrl, apiKey = '', model = '', maxTokens = 102
|
|
|
47
61
|
},
|
|
48
62
|
}));
|
|
49
63
|
|
|
50
|
-
|
|
51
|
-
|
|
64
|
+
// One completion: streams { text } and COMPLETED { tool, args, id } chunks for a wire-shaped message list.
|
|
65
|
+
async function* streamOnce(messages, signal) {
|
|
52
66
|
const doFetch = fetchFn ?? fetch;
|
|
53
67
|
const r = await doFetch(llmUrl, {
|
|
54
68
|
method: 'POST', signal,
|
|
55
69
|
headers: { 'Content-Type': 'application/json', ...(apiKey ? { Authorization: `Bearer ${apiKey}` } : {}) },
|
|
56
70
|
body: JSON.stringify({
|
|
57
71
|
stream: true,
|
|
58
|
-
messages
|
|
72
|
+
messages,
|
|
59
73
|
max_tokens: maxTokens,
|
|
60
74
|
...(model ? { model } : {}),
|
|
61
75
|
...(toolSpecs.length ? { tools: toolSpecs } : {}),
|
|
@@ -76,9 +90,6 @@ export function makeOpenAILLM({ llmUrl, apiKey = '', model = '', maxTokens = 102
|
|
|
76
90
|
for (const c of pending.values()) {
|
|
77
91
|
if (!c.name) continue;
|
|
78
92
|
let args;
|
|
79
|
-
// Truncated/invalid argument JSON (aborted stream, provider bug) → DROP the call. The agent
|
|
80
|
-
// dispatches tools immediately, so guessing `{}` could fire a real side effect with the
|
|
81
|
-
// wrong arguments.
|
|
82
93
|
try { args = c.args ? JSON.parse(c.args) : {}; }
|
|
83
94
|
catch { console.warn(`makeOpenAILLM: dropping tool call "${c.name}" — arguments never parsed: ${c.args}`); continue; }
|
|
84
95
|
yield { tool: c.name, args, ...(c.id ? { id: c.id } : {}) };
|
|
@@ -86,9 +97,8 @@ export function makeOpenAILLM({ llmUrl, apiKey = '', model = '', maxTokens = 102
|
|
|
86
97
|
pending.clear();
|
|
87
98
|
};
|
|
88
99
|
|
|
89
|
-
// One SSE data payload → zero or more chunks.
|
|
100
|
+
// One SSE data payload → zero or more chunks.
|
|
90
101
|
const handle = function* (payload) {
|
|
91
|
-
if (payload === '[DONE]') return; // caller checks the sentinel itself
|
|
92
102
|
let m; try { m = JSON.parse(payload); } catch { return; } // tolerate keep-alive junk
|
|
93
103
|
if (m.error) throw new Error(m.error.message ?? String(m.error));
|
|
94
104
|
const choice = m.choices?.[0];
|
|
@@ -136,5 +146,46 @@ export function makeOpenAILLM({ llmUrl, apiKey = '', model = '', maxTokens = 102
|
|
|
136
146
|
} finally {
|
|
137
147
|
reader.cancel().catch(() => {});
|
|
138
148
|
}
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
const gen = async function* (history, system, signal, { toolGate } = {}) {
|
|
152
|
+
if (!llmUrl) throw new Error('VoiceAgent: no `llm` generator and no `llmUrl` configured — pass one of them');
|
|
153
|
+
// Anthropic-shaped working history (what VoiceAgent keeps); re-serialized to the wire every round
|
|
154
|
+
// so tool_use/tool_result pairing stays in ONE place (toOpenAIMessages).
|
|
155
|
+
const hist = [...history];
|
|
156
|
+
for (let round = 0; round < MAX_ROUNDS; round++) {
|
|
157
|
+
let text = '';
|
|
158
|
+
const calls = []; // { id, tool, args, outcome: Promise<{result}|{error}> }
|
|
159
|
+
const seen = new Set();
|
|
160
|
+
for await (const c of streamOnce([{ role: 'system', content: system }, ...toOpenAIMessages(hist)], signal)) {
|
|
161
|
+
if (c.text) { text += c.text; yield c; continue; }
|
|
162
|
+
const id = c.id || `call-${round}-${calls.length + 1}`; // announcements need an id to be replaced in place
|
|
163
|
+
if (seen.has(id)) continue;
|
|
164
|
+
seen.add(id);
|
|
165
|
+
yield { tool: c.tool, id, args: c.args, running: true };
|
|
166
|
+
// Execute NOW, in parallel with TTS. A speculative run waits at the gate: it rejects when the
|
|
167
|
+
// speculation is dropped, so the tool never fires for a turn the user was still amending.
|
|
168
|
+
const outcome = (async () => {
|
|
169
|
+
if (toolGate) await toolGate;
|
|
170
|
+
try { return { result: await tools[c.tool]?.run?.(c.args) }; }
|
|
171
|
+
catch (e) { return { error: e?.message || String(e ?? 'failed') }; }
|
|
172
|
+
})();
|
|
173
|
+
calls.push({ id, tool: c.tool, args: c.args, outcome });
|
|
174
|
+
}
|
|
175
|
+
if (!calls.length) return;
|
|
176
|
+
const results = [];
|
|
177
|
+
for (const c of calls) {
|
|
178
|
+
const o = await c.outcome;
|
|
179
|
+
yield { tool: c.tool, id: c.id, args: c.args, ...o };
|
|
180
|
+
const failed = 'error' in o || (o.result && typeof o.result === 'object' && o.result.ok === false);
|
|
181
|
+
results.push({ type: 'tool_result', tool_use_id: c.id, content: 'error' in o ? String(o.error) : toolResultText(o.result), ...(failed ? { is_error: true } : {}) });
|
|
182
|
+
}
|
|
183
|
+
hist.push({ role: 'assistant', content: [...(text ? [{ type: 'text', text }] : []), ...calls.map((c) => ({ type: 'tool_use', id: c.id, name: c.tool, input: c.args ?? {} }))] });
|
|
184
|
+
hist.push({ role: 'user', content: results });
|
|
185
|
+
yield { newMessage: true };
|
|
186
|
+
}
|
|
139
187
|
};
|
|
188
|
+
gen.executesTools = true;
|
|
189
|
+
gen.acceptsToolGate = true;
|
|
190
|
+
return gen;
|
|
140
191
|
}
|
package/src/voice-agent.js
CHANGED
|
@@ -19,7 +19,8 @@
|
|
|
19
19
|
|
|
20
20
|
import { STT_PROVIDERS, resolveSttProvider } from './stt.js';
|
|
21
21
|
import { TUNING } from './tuning.js';
|
|
22
|
-
import { makeOpenAILLM } from './llm-openai.js';
|
|
22
|
+
import { makeOpenAILLM, toolResultText } from './llm-openai.js';
|
|
23
|
+
export { toolResultText };
|
|
23
24
|
|
|
24
25
|
// Default persona: a minimal voice-first system prompt. Hosts replace it via `persona`
|
|
25
26
|
// (who the agent is) and append live context via `sysmsg` / setSysmsg().
|
|
@@ -79,21 +80,10 @@ const withTimeout = (p, ms, fallback) => {
|
|
|
79
80
|
const callArgs = (c) => JSON.stringify(c.args ?? {}, (_k, v) =>
|
|
80
81
|
v && typeof v === 'object' && !Array.isArray(v) ? Object.fromEntries(Object.keys(v).sort().map((k) => [k, v[k]])) : v);
|
|
81
82
|
const callKey = (c) => c.id ? `id:${c.id}` : `${c.tool} ${callArgs(c)}`;
|
|
82
|
-
// Render a host tool's return value as model-facing text (the tool_result content in history, and
|
|
83
|
-
// what LLM adapters feed back to the model). Never throws: the side effect already RAN,
|
|
84
|
-
// so an unserializable result must not retro-fail the call and invite a retry.
|
|
85
|
-
export const toolResultText = (result) => {
|
|
86
|
-
if (result === undefined) return 'ok';
|
|
87
|
-
if (typeof result === 'string') return result;
|
|
88
|
-
if (result && typeof result.text === 'string' && typeof result.ok === 'boolean')
|
|
89
|
-
return result.ok ? result.text : `[failed] ${result.text}`;
|
|
90
|
-
try { return JSON.stringify(result) ?? 'ok'; } catch { return String(result); }
|
|
91
|
-
};
|
|
92
83
|
// One model-facing history record for a settled/pending tool call: the native tool_result block that
|
|
93
84
|
// pairs with its tool_use. Bounded — history is spoken-conversation-sized, not a log. A call whose
|
|
94
85
|
// outcome has not landed yet says so; _runTool patches the SAME block in place when it does.
|
|
95
86
|
const RESULT_MAX = 4000;
|
|
96
|
-
const MAX_TOOL_ROUNDS = 6;
|
|
97
87
|
const PENDING_RESULT = 'still running — the result will follow in a later turn';
|
|
98
88
|
const bound = (text) => text.length > RESULT_MAX ? `${text.slice(0, RESULT_MAX)}… (${text.length} chars)` : text;
|
|
99
89
|
const toolResultBlock = (c) => {
|
|
@@ -314,8 +304,6 @@ export class VoiceAgent {
|
|
|
314
304
|
this.state = 'idle'; // idle | listening | thinking | speaking
|
|
315
305
|
this._abort = null; // aborts the in-flight LLM
|
|
316
306
|
this._replySeq = 0; // bumped per reply-generating turn; a queued turn drops itself if a newer one exists
|
|
317
|
-
this._toolRounds = 0; // tool-result reactions since the user last spoke (see _runTurn react)
|
|
318
|
-
this._unseenResults = false; // a tool_result was patched after the last request was built (see _runTurn react)
|
|
319
307
|
this._preroll = []; this._wasSpeaking = false; this._closed = false; this._destroyed = false;
|
|
320
308
|
// Diagnostic tap: last ~30s of the exact i16 frames handed to STT + delivery-stall gaps, for
|
|
321
309
|
// dumpAudio() (replay any "it misheard me" run and prove capture clean-or-not).
|
|
@@ -637,7 +625,6 @@ export class VoiceAgent {
|
|
|
637
625
|
// history stays ordered (…, assistant-so-far, user, user). Held pushes NEVER start an LLM turn —
|
|
638
626
|
// release (_flush) owns starting the single turn, and waits for all of these to settle first.
|
|
639
627
|
_pushHeld(text) {
|
|
640
|
-
this._toolRounds = 0;
|
|
641
628
|
const p = (async () => { await this._holdBarrier; this.history.push({ role: 'user', content: text }); })();
|
|
642
629
|
this._heldPushes.add(p);
|
|
643
630
|
p.finally(() => this._heldPushes.delete(p));
|
|
@@ -700,7 +687,6 @@ export class VoiceAgent {
|
|
|
700
687
|
// caller (errors surface via onEvent), so it's safe to call without awaiting/catching.
|
|
701
688
|
_onUserTurn(text, { speech = false } = {}) {
|
|
702
689
|
if (!text.trim()) return Promise.resolve();
|
|
703
|
-
this._toolRounds = 0;
|
|
704
690
|
return this._runTurn(text, { speech });
|
|
705
691
|
}
|
|
706
692
|
|
|
@@ -737,8 +723,8 @@ export class VoiceAgent {
|
|
|
737
723
|
_startPrefetch(text) {
|
|
738
724
|
// Speculating is only safe if pulling the first chunk cannot fire a real side effect on a
|
|
739
725
|
// transcript the user is still speaking and may yet change — abort cannot undo a sent email.
|
|
740
|
-
//
|
|
741
|
-
//
|
|
726
|
+
// An LLM whose chunks are inert (no tool execution) is always safe. One that executes tools
|
|
727
|
+
// INSIDE its generator (llm.executesTools) is safe only if it also honors `toolGate`
|
|
742
728
|
// (llm.acceptsToolGate): we hand it a promise it must await before ANY tool runs, so text
|
|
743
729
|
// streams speculatively while tools wait for the turn to commit. Neither → don't speculate.
|
|
744
730
|
if (this.llm.executesTools && !this.llm.acceptsToolGate) return;
|
|
@@ -817,7 +803,7 @@ export class VoiceAgent {
|
|
|
817
803
|
// if nothing newer has queued behind it, and never cut the reply in flight. Anything newer already
|
|
818
804
|
// sees this message in history and answers over the fuller picture — so a burst of tool results
|
|
819
805
|
// collapses into ONE reply instead of one interrupting monologue per result.
|
|
820
|
-
_runTurn(text, { supersede = true, speech = false
|
|
806
|
+
_runTurn(text, { supersede = true, speech = false } = {}) {
|
|
821
807
|
const prev = this._turn;
|
|
822
808
|
if (supersede) {
|
|
823
809
|
this._abort?.abort(); // cut the in-flight reply NOW (barge-in / superseded)
|
|
@@ -843,24 +829,9 @@ export class VoiceAgent {
|
|
|
843
829
|
// Only a SPOKEN final may adopt (it seeded the speculation); typed/notify/held turns drop it.
|
|
844
830
|
const pf = speech && text ? this._takePrefetch(text) : (this._dropPrefetch(), null);
|
|
845
831
|
if (text) this.history.push({ role: 'user', content: text });
|
|
846
|
-
// A reaction turn owes a reply only for results no request has carried yet: either the
|
|
847
|
-
// tool_result record is still the last message, or a late outcome was patched in after the
|
|
848
|
-
// last request was built (_unseenResults; cleared when a request starts) — then a short
|
|
849
|
-
// [EVENT] user turn, the host's channel for out-of-band facts, points the model at the patched
|
|
850
|
-
// block (a request can't end on an assistant message). Bounded per user utterance
|
|
851
|
-
// (_toolRounds, reset on every accepted user turn): a model that keeps calling tools gets
|
|
852
|
-
// MAX_TOOL_ROUNDS reactions, then waits for the user.
|
|
853
|
-
if (react) {
|
|
854
|
-
const last = this.history[this.history.length - 1];
|
|
855
|
-
const owed = (last?.role === 'user' && Array.isArray(last.content)) || this._unseenResults;
|
|
856
|
-
if (!owed || this._toolRounds >= MAX_TOOL_ROUNDS) { this._unseenResults = false; return; }
|
|
857
|
-
this._toolRounds++;
|
|
858
|
-
if (last?.role !== 'user') this.history.push({ role: 'user', content: '[EVENT tool_result] a pending tool finished — see its tool_result above.' });
|
|
859
|
-
}
|
|
860
832
|
// Reply only if the conversation now ends on a user turn (a raced turn may have already
|
|
861
833
|
// replied). pf is always null here: if we pushed a user turn it IS the last entry.
|
|
862
834
|
if (this.history[this.history.length - 1]?.role !== 'user') return;
|
|
863
|
-
this._unseenResults = false; // this request carries every result landed so far
|
|
864
835
|
this._set('thinking'); // LLM stage
|
|
865
836
|
this._abort = pf?.ctl ?? new AbortController(); // adopted prefetch keeps ITS controller so barge-in aborts the right fetch
|
|
866
837
|
await this._speakTurn(this._abort.signal, pf?.gen, seq); // _speakTurn never throws — errors surface via onEvent
|
|
@@ -888,9 +859,9 @@ export class VoiceAgent {
|
|
|
888
859
|
// notation it could imitate. `this.llm(...)` is a lazy generator — its fetch fires only when
|
|
889
860
|
// tts.speak first pulls, by which point any prior turn is aborted; keeps LLM streams serial.
|
|
890
861
|
//
|
|
891
|
-
// Round boundary:
|
|
892
|
-
// the
|
|
893
|
-
//
|
|
862
|
+
// Round boundary: a loop adapter (executesTools) feeds results back inside the stream and marks
|
|
863
|
+
// where the model's NEXT message starts with a { newMessage } chunk. A plain adapter's stream is
|
|
864
|
+
// ONE model message; the agent runs its calls and the NEXT user turn sees the results.
|
|
894
865
|
let answer = '';
|
|
895
866
|
const rounds = [], calls = []; // calls: every act this turn saw, for dedup — outlives recording
|
|
896
867
|
const loop = !!this.llm.executesTools;
|
|
@@ -898,27 +869,23 @@ export class VoiceAgent {
|
|
|
898
869
|
const newRound = () => { const r = rounds[rounds.length - 1]; if (r && (r.text || r.calls.length)) rounds.push({ text: '', calls: [] }); };
|
|
899
870
|
let n = 0;
|
|
900
871
|
// Accept a call once: identity is the provider id, else name+args (an id-less repeat is a
|
|
901
|
-
// provider re-emitting its buffered call).
|
|
902
|
-
// back inside its reply; anything else is agent-run (or agent-reported when the chunk already
|
|
903
|
-
// carries an outcome) and gets a reaction turn.
|
|
872
|
+
// provider re-emitting its buffered call).
|
|
904
873
|
const accept = (item) => {
|
|
905
874
|
const key = callKey(item);
|
|
906
875
|
let c = calls.find((x) => x.key === key);
|
|
907
876
|
if (c) return c;
|
|
908
|
-
c = { ...item, key, id: item.id || `call-${turn}-${++n}
|
|
877
|
+
c = { ...item, key, id: item.id || `call-${turn}-${++n}` };
|
|
909
878
|
calls.push(c); round().calls.push(c);
|
|
910
879
|
return c;
|
|
911
880
|
};
|
|
912
881
|
const outcome = (c, item) => { if ('result' in item) c.result = item.result; else if ('error' in item) c.error = item.error; };
|
|
913
882
|
const hasOutcome = (c) => 'result' in c || 'error' in c;
|
|
914
883
|
// An outcome may land AFTER the turn recorded the call (a hung tool, a barge-in mid-execution):
|
|
915
|
-
// its tool_result block is patched IN PLACE so the next request carries the real result
|
|
916
|
-
// model gets to react to it (see _continue).
|
|
884
|
+
// its tool_result block is patched IN PLACE so the next request carries the real result.
|
|
917
885
|
const settle = (c) => this._runTool(c).then(() => {
|
|
918
886
|
if (!c.block) return; // not recorded yet — record() picks the outcome up
|
|
919
887
|
if (!c.consumed) { Object.assign(c.block, toolResultBlock(c)); c.consumed = true; }
|
|
920
888
|
this._dropPrefetch(); // a speculation serialized the pending block — stale
|
|
921
|
-
this._unseenResults = true; this._continue();
|
|
922
889
|
});
|
|
923
890
|
const record = (keptLen) => {
|
|
924
891
|
let budget = keptLen;
|
|
@@ -936,11 +903,6 @@ export class VoiceAgent {
|
|
|
936
903
|
}
|
|
937
904
|
rounds.length = 0;
|
|
938
905
|
};
|
|
939
|
-
// Follow-up only for calls the AGENT ran: a loop adapter fed its results back inside the reply.
|
|
940
|
-
const recordAndContinue = (keptLen) => {
|
|
941
|
-
record(keptLen);
|
|
942
|
-
if (calls.some((c) => c.owner === 'agent' && c.consumed)) this._continue();
|
|
943
|
-
};
|
|
944
906
|
// Pre-execution markers: an LLM that runs tools inside its own generator (executesTools) can
|
|
945
907
|
// announce a call with `running: true` BEFORE it executes, so the host shows a live spinner chip
|
|
946
908
|
// that the outcome chunk replaces in place (same id). A turn that dies before an announced call's
|
|
@@ -979,7 +941,7 @@ export class VoiceAgent {
|
|
|
979
941
|
if (finalized && !hasOutcome(item)) continue; // late bare call: the user cut this reply off
|
|
980
942
|
const c = accept(item);
|
|
981
943
|
outcome(c, item);
|
|
982
|
-
if (finalized) record(0); // late outcome of an unseen call: give it a record of its own
|
|
944
|
+
if (finalized) record(0); // late outcome of an unseen call: give it a record of its own
|
|
983
945
|
settle(c);
|
|
984
946
|
continue;
|
|
985
947
|
}
|
|
@@ -1043,7 +1005,7 @@ export class VoiceAgent {
|
|
|
1043
1005
|
// Tools fire DURING streaming, so a reply that dies here may already have dispatched one.
|
|
1044
1006
|
// Record what was done and heard so far — dropping it would let the next turn call the
|
|
1045
1007
|
// same tool again.
|
|
1046
|
-
|
|
1008
|
+
record(signal.keepFull ? answer.length : this._replyText.length);
|
|
1047
1009
|
finishInterrupted(); // announced-but-unfinished → failed chip, not a stuck spinner
|
|
1048
1010
|
if (this.state !== 'idle') this._set('listening');
|
|
1049
1011
|
return;
|
|
@@ -1067,7 +1029,7 @@ export class VoiceAgent {
|
|
|
1067
1029
|
// tail aligns). keepFull/normal-finish → whole answer (no tail); a barge-in → the heard prefix
|
|
1068
1030
|
// solid + the unspoken remainder dimmed, showing exactly where TTS got.
|
|
1069
1031
|
const kept = signal.keepFull ? answer : rawPrefix(spoken);
|
|
1070
|
-
|
|
1032
|
+
record(kept.length);
|
|
1071
1033
|
if (kept) {
|
|
1072
1034
|
this.onEvent({ type: 'assistant', text: kept, full: answer, final: true, turn });
|
|
1073
1035
|
} else if (answer) {
|
|
@@ -1085,19 +1047,6 @@ export class VoiceAgent {
|
|
|
1085
1047
|
if (!signal.aborted && this.state !== 'idle') this._set('listening'); // superseded turns don't touch state
|
|
1086
1048
|
}
|
|
1087
1049
|
|
|
1088
|
-
// Native tool semantics: once a tool_result is in history the model gets to react to it. Queues a
|
|
1089
|
-
// SOFT reaction turn (behind the running one; dropped if a newer user turn supersedes it — that
|
|
1090
|
-
// turn sees the result anyway) after the agent ran a call for the default adapter (its stream
|
|
1091
|
-
// ends at the call; the result was never fed back), or when a LATE outcome (hung/slow tool,
|
|
1092
|
-
// barge-in mid-execution) landed in a record. Whether a reply is still owed is decided when the
|
|
1093
|
-
// turn RUNS (see _runTurn `react`), since the predecessor may already have carried the result.
|
|
1094
|
-
// Loop adapters fed the result back inside the reply, so nothing fires for them. Silent while
|
|
1095
|
-
// the user is speaking — their utterance will see the result in history anyway.
|
|
1096
|
-
_continue() {
|
|
1097
|
-
if (this._closed || this._speaking) return;
|
|
1098
|
-
this._runTurn('', { supersede: false, react: true });
|
|
1099
|
-
}
|
|
1100
|
-
|
|
1101
1050
|
// Run one chosen tool call and report it. Fired as soon as its tool_use arrives in the stream, in
|
|
1102
1051
|
// parallel with TTS, and NEVER joined: the turn records the call (tool_result pending) and finishes
|
|
1103
1052
|
// when the speaking does (see _speakTurn), so a tool that hangs costs its own result and nothing
|