@livx.cc/agentx 0.99.14 → 0.99.15
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/dist/cli.js +1591 -1512
- package/dist/cli.js.map +1 -1
- package/dist/index.d.ts +3 -549
- package/dist/index.js +1628 -1556
- package/dist/index.js.map +1 -1
- package/package.json +2 -1
package/dist/cli.js
CHANGED
|
@@ -4382,14 +4382,14 @@ function makeScheduleTools(scheduler, os) {
|
|
|
4382
4382
|
backend: { type: "string", enum: ["auto", "session", "os"], description: "Where the job lives (default auto)." }
|
|
4383
4383
|
}
|
|
4384
4384
|
},
|
|
4385
|
-
async run({ prompt, trigger, label, backend }) {
|
|
4385
|
+
async run({ prompt, trigger, label, backend: backend2 }) {
|
|
4386
4386
|
try {
|
|
4387
|
-
if (os && os.route(trigger,
|
|
4387
|
+
if (os && os.route(trigger, backend2) === "os") {
|
|
4388
4388
|
const id2 = `os-${Date.now().toString(36)}`;
|
|
4389
4389
|
const mechanism = os.schedule({ id: id2, prompt, sessionId: os.sessionId, cwd: os.cwd, trigger, label });
|
|
4390
4390
|
return `Scheduled ${id2}${label ? ` (${label})` : ""} on the OS scheduler (${mechanism}) \u2014 survives quitting; fires \`agentx --resume ${os.sessionId}\` headless.`;
|
|
4391
4391
|
}
|
|
4392
|
-
if (
|
|
4392
|
+
if (backend2 === "os") return "Error: no OS scheduler available on this platform \u2014 job not created (use the default in-session backend).";
|
|
4393
4393
|
const id = scheduler.add({ prompt, trigger, label });
|
|
4394
4394
|
const job = scheduler.get(id);
|
|
4395
4395
|
const next = scheduler.nextFire(job);
|
|
@@ -4668,9 +4668,37 @@ function digestRun(messages, maxChars) {
|
|
|
4668
4668
|
import { MemFilesystem as MemFilesystem2 } from "@livx.cc/wcli/core";
|
|
4669
4669
|
init_logging();
|
|
4670
4670
|
|
|
4671
|
-
//
|
|
4672
|
-
|
|
4673
|
-
|
|
4671
|
+
// node_modules/@bod.ee/voice/src/core/logging.ts
|
|
4672
|
+
function consoleForComponent(name) {
|
|
4673
|
+
const debugEnv = typeof process !== "undefined" && process.env?.DEBUG || typeof localStorage !== "undefined" && localStorage.getItem("DEBUG") || "";
|
|
4674
|
+
const gated = debugEnv === "*" || debugEnv.split(",").some((p) => p.trim() === name);
|
|
4675
|
+
const gate = (fn) => gated ? fn : () => {
|
|
4676
|
+
};
|
|
4677
|
+
const tag = `[${name}]`;
|
|
4678
|
+
return {
|
|
4679
|
+
debug: gate((...a) => console.debug(tag, ...a)),
|
|
4680
|
+
verbose: gate((...a) => console.debug(tag, ...a)),
|
|
4681
|
+
info: (...a) => console.info(tag, ...a),
|
|
4682
|
+
warn: (...a) => console.warn(tag, ...a),
|
|
4683
|
+
error: (...a) => console.error(tag, ...a)
|
|
4684
|
+
};
|
|
4685
|
+
}
|
|
4686
|
+
var backend = consoleForComponent;
|
|
4687
|
+
function configureLogging(forComponentImpl) {
|
|
4688
|
+
backend = forComponentImpl;
|
|
4689
|
+
}
|
|
4690
|
+
function forComponent2(name) {
|
|
4691
|
+
return {
|
|
4692
|
+
debug: (...a) => backend(name).debug(...a),
|
|
4693
|
+
verbose: (...a) => backend(name).verbose(...a),
|
|
4694
|
+
info: (...a) => backend(name).info(...a),
|
|
4695
|
+
warn: (...a) => backend(name).warn(...a),
|
|
4696
|
+
error: (...a) => backend(name).error(...a)
|
|
4697
|
+
};
|
|
4698
|
+
}
|
|
4699
|
+
|
|
4700
|
+
// node_modules/@bod.ee/voice/src/core/emotion.ts
|
|
4701
|
+
var log8 = forComponent2("Emotion");
|
|
4674
4702
|
var EMOTIONS = [
|
|
4675
4703
|
// primary (best results)
|
|
4676
4704
|
"neutral",
|
|
@@ -4866,9 +4894,8 @@ var EmotionStream = class {
|
|
|
4866
4894
|
}
|
|
4867
4895
|
};
|
|
4868
4896
|
|
|
4869
|
-
//
|
|
4870
|
-
|
|
4871
|
-
var log9 = forComponent("VoiceEngine");
|
|
4897
|
+
// node_modules/@bod.ee/voice/src/core/engine.ts
|
|
4898
|
+
var log9 = forComponent2("VoiceEngine");
|
|
4872
4899
|
var realClock = {
|
|
4873
4900
|
now: () => performance.now(),
|
|
4874
4901
|
setTimeout: (fn, ms) => setTimeout(fn, ms),
|
|
@@ -5052,6 +5079,13 @@ var VoiceEngine = class _VoiceEngine {
|
|
|
5052
5079
|
// the exact ack text last spoken (fixed OR adaptive) — the echo-leak guard matches it
|
|
5053
5080
|
ackTimer = null;
|
|
5054
5081
|
// one-shot adaptive-ack timer (armed at dispatch, cancelled on first delta)
|
|
5082
|
+
// The adaptive micro-ack ALREADY spoke this turn → the reflex's own leading ack ("Still on it.") is now
|
|
5083
|
+
// redundant (live: host said "On it." then the reflex said "Still on it."). While this is set, speakDelta
|
|
5084
|
+
// probes the reflex's opening sentence and DROPS it if it's purely an acknowledgement; real content passes
|
|
5085
|
+
// through. Reset per turn in beginSpeech()/interrupt().
|
|
5086
|
+
adaptiveAckFired = false;
|
|
5087
|
+
ackProbe = null;
|
|
5088
|
+
// buffered reflex prose while probing the leading ack (null = not probing)
|
|
5055
5089
|
bargeGraceUntil = 0;
|
|
5056
5090
|
// no barge-in until this time — the user's OWN trailing audio (after the
|
|
5057
5091
|
// utterance that JUST dispatched this turn) must not immediately re-interrupt the reply it requested.
|
|
@@ -5194,6 +5228,8 @@ var VoiceEngine = class _VoiceEngine {
|
|
|
5194
5228
|
this.speaking = true;
|
|
5195
5229
|
this.ctxOpen = true;
|
|
5196
5230
|
this.spokeDeltas = false;
|
|
5231
|
+
this.adaptiveAckFired = false;
|
|
5232
|
+
this.ackProbe = null;
|
|
5197
5233
|
this.reply = "";
|
|
5198
5234
|
this.revealText = "";
|
|
5199
5235
|
this.wordStarts = [];
|
|
@@ -5222,6 +5258,8 @@ var VoiceEngine = class _VoiceEngine {
|
|
|
5222
5258
|
this.lastAck = phrase;
|
|
5223
5259
|
for (const w of this.words(phrase)) this.echoWords.add(w);
|
|
5224
5260
|
this.setState("speaking");
|
|
5261
|
+
this.adaptiveAckFired = true;
|
|
5262
|
+
this.ackProbe = "";
|
|
5225
5263
|
this.options.onAdaptiveAck();
|
|
5226
5264
|
}, this.options.adaptiveAckMs);
|
|
5227
5265
|
}
|
|
@@ -5233,6 +5271,25 @@ var VoiceEngine = class _VoiceEngine {
|
|
|
5233
5271
|
speakDelta(text) {
|
|
5234
5272
|
if (this.interrupted) return "";
|
|
5235
5273
|
this.clearAckTimer("first_delta");
|
|
5274
|
+
if (this.adaptiveAckFired && this.ackProbe !== null) {
|
|
5275
|
+
this.ackProbe += text;
|
|
5276
|
+
const probe = this.ackProbe;
|
|
5277
|
+
const bare = probe.replace(/\[emotion[^\]]*\]/gi, "").replace(/^\s+/, "");
|
|
5278
|
+
const m = bare.match(/^([^.!?…\n]*[.!?…\n])([\s\S]*)$/);
|
|
5279
|
+
if (!m && bare.length < 80) return "";
|
|
5280
|
+
this.ackProbe = null;
|
|
5281
|
+
this.adaptiveAckFired = false;
|
|
5282
|
+
const lead = m ? m[1] : bare;
|
|
5283
|
+
const norm2 = lead.replace(/[^a-z ]/gi, " ").replace(/\s+/g, " ").trim().toLowerCase();
|
|
5284
|
+
if (_VoiceEngine.ACK_LEADING.test(norm2)) {
|
|
5285
|
+
const rest = m ? m[2] : "";
|
|
5286
|
+
this.diag("reflex_ack_suppressed", { lead: lead.trim() });
|
|
5287
|
+
if (!rest.trim()) return "";
|
|
5288
|
+
text = rest;
|
|
5289
|
+
} else {
|
|
5290
|
+
text = probe;
|
|
5291
|
+
}
|
|
5292
|
+
}
|
|
5236
5293
|
if (!this.speaking || !this.ctxOpen) this.beginSpeech();
|
|
5237
5294
|
let { speech, display, prose } = this.emo ? this.emo.feed(text) : { speech: text, display: text, prose: text };
|
|
5238
5295
|
if (this.reply && /[.!?…]$/.test(this.reply) && /^[A-Z]/.test(prose)) {
|
|
@@ -5291,6 +5348,14 @@ var VoiceEngine = class _VoiceEngine {
|
|
|
5291
5348
|
endSpeech() {
|
|
5292
5349
|
this.interrupted = false;
|
|
5293
5350
|
this.clearAckTimer("turn_end");
|
|
5351
|
+
const heldProbe = this.ackProbe;
|
|
5352
|
+
this.adaptiveAckFired = false;
|
|
5353
|
+
this.ackProbe = null;
|
|
5354
|
+
if (heldProbe) {
|
|
5355
|
+
const norm2 = heldProbe.replace(/\[emotion[^\]]*\]/gi, "").replace(/[^a-z ]/gi, " ").replace(/\s+/g, " ").trim().toLowerCase();
|
|
5356
|
+
if (_VoiceEngine.ACK_LEADING.test(norm2)) this.diag("reflex_ack_suppressed", { lead: heldProbe.trim() });
|
|
5357
|
+
else this.speakDelta(heldProbe);
|
|
5358
|
+
}
|
|
5294
5359
|
if (!this.speaking) return;
|
|
5295
5360
|
this.diag("tts_turn_end", { spoke: this.spokeDeltas, replyChars: this.reply.length });
|
|
5296
5361
|
this.ctxOpen = false;
|
|
@@ -5372,6 +5437,9 @@ var VoiceEngine = class _VoiceEngine {
|
|
|
5372
5437
|
* No 'Okay.': a genuine user "Okay." within the 6s squash window would be swallowed as ack echo. */
|
|
5373
5438
|
static ACKS_NEUTRAL = ["Mm-hm.", "One sec.", "Right.", "Sec.", "On it.", "Sure, moment.", "Uh, one moment.", "Let me see."];
|
|
5374
5439
|
static ACKS_QUESTION = ["Hmm.", "Let me think.", "Hm, let me see.", "Good question.", "Mm, one sec.", "Let's see."];
|
|
5440
|
+
/** A reflex opening sentence that is PURELY an acknowledgement (no content) — dropped when the adaptive
|
|
5441
|
+
* micro-ack already spoke one. Anchored end-to-end so only a whole ack-only clause matches. */
|
|
5442
|
+
static ACK_LEADING = /^(?:(?:okay|ok|alright|sure|yeah|yep|right|got it|on it|still|still on it|still working on it|working on it|checking|one sec|one moment|mm hm|mmhm|hmm|let me (?:see|check|think))[ ,]*)+$/;
|
|
5375
5443
|
recentAcks = [];
|
|
5376
5444
|
pickAck() {
|
|
5377
5445
|
const pool = this.lastDispatchWasQuestion ? _VoiceEngine.ACKS_QUESTION : _VoiceEngine.ACKS_NEUTRAL;
|
|
@@ -5396,6 +5464,8 @@ var VoiceEngine = class _VoiceEngine {
|
|
|
5396
5464
|
/** barge-in: stop audio NOW, cancel generation, reset for the user's utterance */
|
|
5397
5465
|
interrupt() {
|
|
5398
5466
|
this.clearAckTimer("interrupt");
|
|
5467
|
+
this.adaptiveAckFired = false;
|
|
5468
|
+
this.ackProbe = null;
|
|
5399
5469
|
if (this.uttQueue.length) log9.info(`barge-in dropped ${this.uttQueue.length} queued worker utterance(s)`);
|
|
5400
5470
|
const droppedQueued = this.uttQueue.length;
|
|
5401
5471
|
this.uttQueue = [];
|
|
@@ -5856,7 +5926,14 @@ var VoiceEngine = class _VoiceEngine {
|
|
|
5856
5926
|
}
|
|
5857
5927
|
};
|
|
5858
5928
|
|
|
5859
|
-
//
|
|
5929
|
+
// node_modules/@bod.ee/voice/src/core/types.ts
|
|
5930
|
+
var STT_SAMPLE_RATE = 16e3;
|
|
5931
|
+
var TTS_SAMPLE_RATE = 44100;
|
|
5932
|
+
async function resolveAuth(auth) {
|
|
5933
|
+
return typeof auth === "function" ? await auth() : auth;
|
|
5934
|
+
}
|
|
5935
|
+
|
|
5936
|
+
// node_modules/@bod.ee/voice/src/core/spokenSplitter.ts
|
|
5860
5937
|
var OPEN = "<spoken>";
|
|
5861
5938
|
var CLOSE = "</spoken>";
|
|
5862
5939
|
var CLOSERS = `"')]}\xBB\u201D\u2019`;
|
|
@@ -5928,1594 +6005,1589 @@ var SpokenSplitter = class {
|
|
|
5928
6005
|
}
|
|
5929
6006
|
};
|
|
5930
6007
|
|
|
5931
|
-
// src/
|
|
5932
|
-
var log10 =
|
|
5933
|
-
|
|
5934
|
-
|
|
5935
|
-
|
|
5936
|
-
|
|
5937
|
-
|
|
5938
|
-
|
|
5939
|
-
/**
|
|
5940
|
-
|
|
5941
|
-
|
|
5942
|
-
|
|
5943
|
-
|
|
5944
|
-
|
|
5945
|
-
// (and misfiring Hold). 120b is the same price tier (~$0.15/$0.60) — the quality/cost trade is free.
|
|
5946
|
-
reflexModel = "groq/openai/gpt-oss-120b";
|
|
5947
|
-
actModel = "anthropic/claude-sonnet-4-6";
|
|
5948
|
-
/** Premium reasoning model. Set to `false` to disable the Think tier entirely. */
|
|
5949
|
-
thinkModel = "anthropic/claude-opus-4-8";
|
|
5950
|
-
/** Per-worker providerOptions, derived from the worker's actual model at spawn time (IoC — keeps duplex
|
|
5951
|
-
* provider-agnostic). Workers override the reflex/main model, so provider-specific options (e.g. cursor's
|
|
5952
|
-
* cwd/cursorSession) must be recomputed for the worker's model, never inherited from the main template —
|
|
5953
|
-
* leaking cursor options to an anthropic worker is a hard 400. Returns undefined → no providerOptions. */
|
|
5954
|
-
providerOptionsFor;
|
|
5955
|
-
/** Escape hatches merged over the derived per-agent options. */
|
|
5956
|
-
reflexOptions;
|
|
5957
|
-
actOptions;
|
|
5958
|
-
thinkOptions;
|
|
5959
|
-
/** Fresh-context check on each successful Act task: a NEW agent (no self-confirmation bias) re-reads
|
|
5960
|
-
* the file state against the brief and fixes any gap before the result is re-voiced. Bounded to one
|
|
5961
|
-
* pass; ~2x Act cost so default OFF. The self-verify FOOTER (same context) was measured ineffective —
|
|
5962
|
-
* this is the structural fix (see mind/10). Think tasks are pure reasoning, never checked. */
|
|
5963
|
-
verifyActTasks = false;
|
|
5964
|
-
/** Receives the voice text_delta stream + task lifecycle events. */
|
|
5965
|
-
host;
|
|
5966
|
-
/** How many recent transcript messages are rendered into a worker's brief. */
|
|
5967
|
-
excerptTurns = 6;
|
|
5968
|
-
/** Voice register: 'neutral' = clean spoken style; 'conversational' = human-like — fillers,
|
|
5969
|
-
* backchannels, impulsive first reactions before content (mimics real duplex conversation). */
|
|
5970
|
-
voiceStyle = "neutral";
|
|
5971
|
-
/** Teach the model to emit inline `[emotion]` tags for Cartesia emotion control. Only set when the
|
|
5972
|
-
* TTS actually speaks them — text-duplex (no TTS) would otherwise print literal tags. */
|
|
5973
|
-
emotionTags = false;
|
|
5974
|
-
/** Awaited BEFORE a worker spawns — open a per-task checkpoint frame, audit, etc.
|
|
5975
|
-
* (post-spawn would race the worker's first edits). */
|
|
5976
|
-
onTaskStart;
|
|
5977
|
-
/** Re-voice throttled worker progress asides ('[task t1 progress] …') so long tasks aren't dead
|
|
5978
|
-
* air. Off by default — each update costs a voice turn (LLM call + speech). */
|
|
5979
|
-
progressUpdates = false;
|
|
5980
|
-
/** Min ms between progress re-voices per task. */
|
|
5981
|
-
progressIntervalMs = 25e3;
|
|
5982
|
-
/** Relay worker questions (AskUserQuestion + permission asks via parkQuestion) through the VOICE:
|
|
5983
|
-
* the question re-voices as '[task <id> asks] …', the user answers conversationally, and the
|
|
5984
|
-
* voice model resolves it with the AnswerTask tool. Off → host.ask passthrough (text menus). */
|
|
5985
|
-
askRelay = false;
|
|
5986
|
-
/** Parked questions auto-resolve empty after this long (callers map '' to deny/best-judgment). */
|
|
5987
|
-
askTimeoutMs = 12e4;
|
|
5988
|
-
/** Max retained task records: oldest SETTLED tasks (and their activity tails) are evicted past this,
|
|
5989
|
-
* bounding memory over a long-lived session. Running tasks are never evicted. */
|
|
5990
|
-
maxTaskRecords = 50;
|
|
5991
|
-
/** Host overrides for QuickLook lookups (keyed by `what`). The engine's defaults go through the
|
|
5992
|
-
* (possibly jailed) fs — e.g. `.git/**` is deny-listed, so the CLI supplies 'branch' itself. */
|
|
5993
|
-
quickLook;
|
|
5994
|
-
/** Memory directory/directories on the WORKER fs. If set, the voice agent gets Remember + Recall
|
|
5995
|
-
* tools directly (no delegation needed) and implicit capture guidance. */
|
|
5996
|
-
memoryDir;
|
|
5997
|
-
/** User-scope memory dir for global facts (type=user/feedback). Forwarded to Remember's routing. */
|
|
5998
|
-
memoryUserDir;
|
|
6008
|
+
// node_modules/@bod.ee/voice/src/adapters/soniox.ts
|
|
6009
|
+
var log10 = forComponent2("SonioxSTT");
|
|
6010
|
+
var now = () => performance.now();
|
|
6011
|
+
var SonioxSTTOptions = class {
|
|
6012
|
+
auth = "";
|
|
6013
|
+
source;
|
|
6014
|
+
model = "stt-rt-preview";
|
|
6015
|
+
languageHints = ["en"];
|
|
6016
|
+
/** Client-side endpoint: finalized text + no new tokens for this long = utterance (don't wait for
|
|
6017
|
+
* Soniox's semantic <end>, which adds 0.5-1.5s — the difference between ping-pong and lag). */
|
|
6018
|
+
silenceEndpointMs = 500;
|
|
6019
|
+
/** No-audio watchdog: if the mic source stops delivering chunks for this long, capture is dead →
|
|
6020
|
+
* fire onFatal + stop (else Soniox idle-timeouts and reconnect-loops forever). 0 = disable. */
|
|
6021
|
+
noAudioTimeoutMs = 1e4;
|
|
5999
6022
|
};
|
|
6000
|
-
var
|
|
6001
|
-
var RESERVED_EVENT_OPENER = /\[\s*task\b/i;
|
|
6002
|
-
var STAGE_DIRECTION_RE = /^\(\s*(?:(?:waiting|checking|searching|thinking|processing|loading|working|fetching|looking)\b[^)]*|[^)]*(?:\.\.\.|…)\s*)\)$/i;
|
|
6003
|
-
function nowLine() {
|
|
6004
|
-
return `Current date and time: ${(/* @__PURE__ */ new Date()).toLocaleString("en-US", { weekday: "long", year: "numeric", month: "long", day: "numeric", hour: "numeric", minute: "2-digit", timeZoneName: "short" })}`;
|
|
6005
|
-
}
|
|
6006
|
-
function isTrivialBarge(text) {
|
|
6007
|
-
const t = text.trim().toLowerCase().replace(/[.,!?…\s]+$/g, "").replace(/^[.,!?…\s]+/, "");
|
|
6008
|
-
if (!t) return false;
|
|
6009
|
-
if (/\b(stop|cancel|no|nope|nah|never\s?mind|nvm|forget it|drop it|don'?t|quiet|shut up|enough|hold on|wait|pause|hang on|actually)\b/.test(t)) return false;
|
|
6010
|
-
const core = t.replace(/^(?:oh|um+|uh+|er+|hmm+|ah+|well|so|okay|ok|yeah|yep)[\s,]+/, "").trim();
|
|
6011
|
-
return /^(?:oh|um+|uh+|er+|hmm+|ah+|sorry|oops|whoops|my bad|pardon|excuse me|apologies|go on|go ahead|continue|keep going|carry on|as you were|please continue|you were saying|sorry go on|sorry continue|go on then|go on please)$/.test(core || t);
|
|
6012
|
-
}
|
|
6013
|
-
var VOICE_SYSTEM_PROMPT = 'You are a spoken voice assistant \u2014 the user HEARS everything you say. Use short sentences. One idea per sentence. No markdown, no bullet lists, no code blocks, no headings, no emoji. Never emit stage directions or parenthetical asides about your own process \u2014 nothing like "(waiting for the result...)" or "(checking)"; while work runs, either say it as plain speech or end your turn.\nThis holds even when asked to "print", "list", "show", or "make a table" \u2014 there is no screen for the spoken channel. Speak it as flowing prose ("Tuesday is half a meter, Wednesday a bit less\u2026"), or if they truly need it on screen, route it to Act to render. Never emit dashes or pipes into speech.\nKeep turns SHORT \u2014 one to three sentences, then stop. Never lecture, enumerate cases, or add caveats unprompted. Conversation is a fast exchange: give the one thing asked, and let the user pull more if they want it.\nYou have three cognitive tiers \u2014 like a human brain:\n\u2022 YOU (reflex) \u2014 instant, lightweight. Handle greetings, simple questions, status checks, QuickLook.\n\u2022 `Act` \u2014 your hands. A background worker with its own configured tools and access to the user\'s environment (files and shell{{WORKER_WEB}}). Use for reading, editing, searching, running tasks, building \u2014 any real work.\n{{THINK_SLOT}}\nWhen you are unsure whether you can do or access something, do NOT assume and do NOT claim a capability you have not confirmed. To check what you can do, QuickLook `capabilities` (instant \u2014 it lists your worker\'s real tools) and answer from that. Never promise an ability that is not in your capabilities; if it is not there, tell the user plainly you can\'t. To actually DO real work, call `Act`. When the user mentions their project, folder, files, or environment ("this project", "the current folder", "my code"), call `Act` IMMEDIATELY \u2014 do not ask for paths or details the worker can discover itself. Never pretend to have done the work or invent results \u2014 the worker\'s report is your only source.\nYou cannot mute the microphone or stop voice capture yourself \u2014 no tool does it. If the user asks you to stop listening or turn the voice off, never claim you did: tell them to say exactly "voice off" (handled by the app directly), or type /voice.\nYou are NOT a knowledge base. For any question whose answer needs SPECIFIC verifiable facts you do not already have in hand \u2014 how to build/configure/implement something, exact API, library, entitlement, command or option names, current events, or particular numbers, dates, or names \u2014 do NOT answer from your own memory: you will confidently make things up (a fake API, a wrong entitlement, an event that did not happen). Route it to `Act`, which can search and verify, and speak only what its report says. DELEGATION RULE \u2014 decide for yourself, the user never has to push: if you cannot answer confidently from the conversation plus trivial well-known knowledge, do NOT refuse and do NOT guess \u2014 dispatch `Act` immediately with a clear brief and say you are checking. Anything needing CURRENT data (weather, news, prices, dates, sky/astronomy, "right now"), real computation, or verification is an automatic dispatch \u2014 never a refusal. The user should never need to say "search the web" or "think harder" to make you act; needing fresh or verified information IS the trigger. Refuse only what your worker genuinely cannot do (check `capabilities`), and say why. Answer inline ONLY for general conversation, chit-chat, and trivia you are sure of, or facts you can see via QuickLook. When elaborating on a completed task ("tell me more", "the gist"), stay strictly within what that result actually said \u2014 if the user asks for something the result did not cover, that is NEW information: dispatch `Act`, do not improvise.\nALWAYS react before you work: the FIRST thing in your turn is a brief spoken acknowledgement of what you heard and what you are about to do ("got it \u2014 opening that now", "sure, let me pull it up", "okay, checking"). NEVER call a tool (Act, Think, QuickLook) silently \u2014 the user must hear you react before you go quiet to work. After dispatching Act or Think, that same one short sentence IS your turn \u2014 end it and do not wait for the result. Exactly ONE short line: never stack a second acknowledgement, and never narrate your own presence or status while waiting ("I\'m here", "let me see", "still checking" right after you already acked). One clean ack then silence reads as competent; repeated check-ins read as nervous.\nA completed task speaks its OWN result to the user (the worker voices what matters as it finishes) \u2014 you do NOT re-voice clean task results. A FAILED or INCOMPLETE task still arrives as a "[task t1 failed] \u2026" event for you to handle. The completed result stays in YOUR context \u2014 it is yours to draw on. When the user follows up ("tell me more", "what else", "and?"), answer FROM that result first: you already have the detail, so elaborate on what you have. Do NOT spawn a fresh worker to re-search or re-gather what you were just handed. Re-dispatch ONLY when genuinely new information is needed \u2014 e.g. the user wants the full contents of a SPECIFIC source, which is one WebFetch of that URL, not a brand-new search. "[task t1 progress] \u2026" events are interim status, NOT results \u2014 on a genuinely LONG wait you MAY give one brief half-sentence aside, but only occasionally; silence while working is normal and fine (the user knows you are on it). Do NOT narrate every step or re-announce yourself. Never present progress as a finished result.\nCRITICAL: while a task is still running you have NO answer yet \u2014 never state a specific result of any kind (a number, size, count, name, path, or value). The real answer arrives ONLY in the "[task \u2026 completed]" event; inventing one meanwhile (a made-up disk size, commit count, etc.) is a serious error. Until then, only acknowledge and wait.\nNever read raw file paths, diffs, or code aloud verbatim.\nDo NOT end every turn with the same canned offer ("want a rundown?", "want the steps?"). Offer once at most; if the user pushes back, repeats themselves, or sounds unsatisfied ("you know what I mean?", "think deeper", "are you sure?"), do NOT re-offer the same thing \u2014 change approach: dispatch `Act`/`Think` to actually dig in, or ask one concrete clarifying question. Repeating a non-answer is worse than silence.\n"[task t1 asks] \u2026" events are QUESTIONS from a background task \u2014 relay to the user in your own words, short, then end your turn. When the user answers, call `AnswerTask` with that id and their answer. NEVER answer on the user\'s behalf for permissions or risky operations; if their reply is ambiguous, confirm first.\nIf the user\'s message sounds INCOMPLETE \u2014 trailing off mid-sentence, a fragment that needs more context ("and then we", "but the problem is"), hesitation fillers ("uh", "um") \u2014 call `Hold` instead of answering. This keeps listening for the rest of their thought. Only respond with substance when you have a complete question or request.\nDispatch discipline: send ONE self-contained task per request \u2014 a single worker with the full brief beats several workers with fragments (each worker starts fresh and re-discovers context). NEVER dispatch a worker just to read files or gather information \u2014 workers explore and discover context themselves; pass on what you already know and let one worker do the whole job. Split into parallel tasks only when the user asks for genuinely independent things. When a task completes, report its result and stop \u2014 do NOT dispatch follow-up work (verification, polish, extras) the user did not ask for, unless the report itself signals failure or doubt.\nDo not fire a second Act/Think for work already in flight, and NEVER spawn a second task to re-count, cross-check, or verify a result a worker already gave you \u2014 trust its answer; a single question gets ONE task. Call `TaskStatus` at most ONCE per turn; if a task is still running, just say "still on it" and end the turn \u2014 never poll it again and again in a loop. Use `CancelTask` when the user asks to stop something.\nPRIORITY: when the user says goodbye or wants to end/finish/wrap up the session ("ok bye", "that\'s all", "let\'s finish", "let\'s end", "goodnight", "exit", "wrap up"), call `ExitSession` IMMEDIATELY \u2014 do not act, do not check status, just exit.\nFor TRIVIAL instant lookups only \u2014 current time, git branch, listing a folder, peeking at a small file, or checking your own `capabilities`/tools \u2014 use `QuickLook` (instant, no task). Whenever the user asks what you can do or whether you have some ability, QuickLook `capabilities` and answer from that \u2014 never guess. Anything requiring searching, reasoning, running commands, or editing goes through `Act`.\n{{MEMORY_SLOT}}\nUser messages may arrive via speech-to-text and can carry transcription artifacts \u2014 odd words, cut-offs, homophones ("for you" vs "folder"). Read for INTENT, not surface text. If a message seems garbled, surprising, or only half-parses, do NOT guess an action or improvise content from it \u2014 briefly confirm what they meant ("did you mean\u2026?") and wait. A one-line confirm beats a confident wrong answer or an invented response to a request you did not actually understand.';
|
|
6014
|
-
var THINK_GUIDANCE = "\u2022 `Think` \u2014 your brain. A premium reasoning model, FAR more expensive than Act. Reserve it for open-ended architecture/design questions, or a problem Act already FAILED at. ALL implementation work \u2014 coding, refactoring, debugging, edge cases, tests \u2014 goes to Act; Act is highly capable. Never send the same work to both.";
|
|
6015
|
-
var THINK_DISABLED_GUIDANCE = "(Think tier is not available \u2014 use Act for all escalations.)";
|
|
6016
|
-
var VOICE_STYLE_CONVERSATIONAL = `Speak like a person in a live conversation, not an assistant reading a script. React first, then deliver: a quick impulsive beat ("oh nice", "hmm, hold on", "ah, got it") before the substance. Use contractions always. Vary sentence length \u2014 some very short. Light fillers and backchannels are fine ("mm-hm", "right", "let's see") but at most one per reply \u2014 never stack them. When you escalate to Act or Think, say it like a human would ("hang on, let me actually dig into that \u2014 gimme a minute") instead of announcing a task. When a result comes back, react to it like you just found out ("okay so \u2014 turns out\u2026"). Match the user's energy: a quick question gets a quick answer \u2014 a few words is a perfectly good turn. Prefer a short answer plus an offer ("want the details?") over covering everything. Never narrate your own mechanics (no "I will now act", no task ids out loud).`;
|
|
6017
|
-
var EMOTION_TAGS_GUIDANCE = `EMOTION: your voice is synthesized with emotion control. Prefix a sentence with an inline [emotion] tag, placed directly before the sentence it colors, to shape how it is spoken. Use it ONLY when the emotion genuinely fits the words (it amplifies real feeling, it cannot fake it) \u2014 do not tag every sentence; reserve it for moments that carry feeling, and vary which one you use. You may also drop [laughter] for a natural laugh. Available emotions: ${EMOTIONS.join(", ")}.`;
|
|
6018
|
-
var DuplexAgent = class _DuplexAgent {
|
|
6023
|
+
var SonioxSTT = class {
|
|
6019
6024
|
options;
|
|
6020
|
-
|
|
6021
|
-
|
|
6022
|
-
|
|
6023
|
-
|
|
6024
|
-
|
|
6025
|
-
|
|
6026
|
-
|
|
6027
|
-
|
|
6028
|
-
|
|
6029
|
-
|
|
6030
|
-
/**
|
|
6031
|
-
*
|
|
6032
|
-
|
|
6033
|
-
|
|
6034
|
-
|
|
6035
|
-
*
|
|
6036
|
-
|
|
6037
|
-
|
|
6038
|
-
|
|
6039
|
-
|
|
6040
|
-
|
|
6041
|
-
|
|
6042
|
-
|
|
6043
|
-
|
|
6044
|
-
|
|
6045
|
-
|
|
6046
|
-
// an Act/Think fired this turn
|
|
6047
|
-
spokeBeforeDispatch = false;
|
|
6048
|
-
// the reflex ALREADY acked before dispatching — the forced post-dispatch text step must stay silent (live: "Got it…" twice)
|
|
6049
|
-
turnBriefs = /* @__PURE__ */ new Set();
|
|
6050
|
-
// briefs dispatched this turn (detect identical re-dispatch)
|
|
6051
|
-
spokeThisTurn = false;
|
|
6052
|
-
// any non-empty text_delta streamed this turn
|
|
6053
|
-
externalSpeech = false;
|
|
6054
|
-
// host spoke on our behalf (adaptive micro-ack) — not reflex output
|
|
6055
|
-
heldThisTurn = false;
|
|
6056
|
-
// Hold called this turn → turn is INTENTIONALLY silent (suppress reflex text + no dead-air ack)
|
|
6057
|
-
nudging = false;
|
|
6058
|
-
// re-ack pass in flight: block ALL tools, prevent recursion
|
|
6059
|
-
reflexBuf = "";
|
|
6060
|
-
// accumulated reflex text this turn (fabricated-event detection)
|
|
6061
|
-
reflexForwarded = 0;
|
|
6062
|
-
// chars of reflexBuf already forwarded to the host/TTS
|
|
6063
|
-
fabricationCut = false;
|
|
6064
|
-
// reflex emitted a reserved [task …] marker → suppress its tail
|
|
6065
|
-
/** TRUE for the duration of a re-voice turn that is integrating ≥1 NON-CLEAN task (turn-eligibility,
|
|
6066
|
-
* carried out-of-band — NOT derived from any worker/brief string). ANY Act/Think dispatched in such a
|
|
6067
|
-
* turn is stamped followUp:true. This GUARANTEES the dangerous direction is impossible: a genuine
|
|
6068
|
-
* escalation (even one with a paraphrased brief) ALWAYS lands in a non-clean integration turn, so it is
|
|
6069
|
-
* ALWAYS recognized as a follow-up and CANNOT re-escalate (one hop). The single-dispatch-per-turn guard
|
|
6070
|
-
* means at most one dispatch happens per flush, so realistically "the one dispatch IS the escalation".
|
|
6071
|
-
* ACCEPTED SAFE-DIRECTION ERROR: if the reflex instead dispatches FRESH unrelated work during a non-clean
|
|
6072
|
-
* flush (rare — and only possible when it batches multiple calls in one step, bypassing the guard), that
|
|
6073
|
-
* fresh task is over-stamped followUp:true and forgoes ONE future auto-escalation. That is SAFE (it only
|
|
6074
|
-
* ever REMOVES a future escalation, never adds one — no runaway) and is the correct side to err on. */
|
|
6075
|
-
turnFollowUp = false;
|
|
6076
|
-
/** Hard absolute backstop against runaway regardless of attribution: total automatic escalations across
|
|
6077
|
-
* the whole conversation. Once it hits MAX_AUTO_ESCALATIONS, no integration turn offers escalate/re-delegate. */
|
|
6078
|
-
autoEscalations = 0;
|
|
6079
|
-
static MAX_AUTO_ESCALATIONS = 8;
|
|
6080
|
-
/** Parked worker questions awaiting a (voice-relayed) user answer, keyed by ask id. */
|
|
6081
|
-
pendingAsks = /* @__PURE__ */ new Map();
|
|
6082
|
-
/** SPECULATIVE REFLEX (VoiceEngine.onSpeculate → speculate()): the reflex turn starts on a stable
|
|
6083
|
-
* PARTIAL transcript, its spoken output buffered — nothing reaches TTS until the endpointed final
|
|
6084
|
-
* confirms via send() (which flushes the buffer and adopts the call as THE turn). A divergent final
|
|
6085
|
-
* aborts it: output dropped, history rolled back, the final dispatches normally. */
|
|
6086
|
-
spec;
|
|
6087
|
-
/** Aborted speculative calls (double-billing visibility — each one paid for tokens never spoken). */
|
|
6088
|
-
speculativeAbortedCalls = 0;
|
|
6089
|
-
/** Tools the reflex may execute on UNCONFIRMED (speculated) input — read-only lookups and the
|
|
6090
|
-
* intentionally-silent Hold. Anything else (Act/Think/AnswerTask/CancelTask/ExitSession/memory
|
|
6091
|
-
* writes/…) is a side effect on input the user may not have said: the guard ABORTS the speculation
|
|
6092
|
-
* instead (the endpointed final then dispatches normally and may use the tool for real). */
|
|
6093
|
-
static SPEC_SAFE_TOOLS = /* @__PURE__ */ new Set(["QuickLook", "TaskStatus", "Hold"]);
|
|
6094
|
-
/** Lazily resolved memory tools (async loadMemory runs in initMemory). */
|
|
6095
|
-
memoryReady;
|
|
6096
|
-
constructor(options) {
|
|
6097
|
-
this.options = { ...new DuplexAgentOptions(), ...options };
|
|
6098
|
-
const o = this.options;
|
|
6099
|
-
if (o.memoryDir && o.fs) {
|
|
6100
|
-
this.memoryReady = loadMemory(o.fs, o.memoryDir, { maxWritesPerSession: 10, userDir: o.memoryUserDir });
|
|
6025
|
+
ws;
|
|
6026
|
+
stopped = false;
|
|
6027
|
+
sourceStarted = false;
|
|
6028
|
+
onPartial = () => {
|
|
6029
|
+
};
|
|
6030
|
+
onUtterance = () => {
|
|
6031
|
+
};
|
|
6032
|
+
/** mic energy (RMS) per chunk — drives the energy-based heuristic barge-in tier */
|
|
6033
|
+
onLevel = () => {
|
|
6034
|
+
};
|
|
6035
|
+
/** Unrecoverable: the mic source stopped delivering audio (Soniox starves → idle-timeout reconnect
|
|
6036
|
+
* loop). The host tears voice down instead of spinning forever. */
|
|
6037
|
+
onFatal = () => {
|
|
6038
|
+
};
|
|
6039
|
+
/** Diagnostic tap (provider errors, ws reconnects, no-audio watchdog). Fire-and-forget: a throwing
|
|
6040
|
+
* handler disables itself — never affects transcription. Wired by VoiceIO / the lab bridge. */
|
|
6041
|
+
onDiag = () => {
|
|
6042
|
+
};
|
|
6043
|
+
diagOn = true;
|
|
6044
|
+
diag(kind, fields) {
|
|
6045
|
+
if (!this.diagOn) return;
|
|
6046
|
+
try {
|
|
6047
|
+
this.onDiag({ t: now(), kind, ...fields });
|
|
6048
|
+
} catch (e) {
|
|
6049
|
+
this.diagOn = false;
|
|
6050
|
+
log10.debug(`onDiag threw \u2014 STT diagnostics disabled: ${e instanceof Error ? e.message : e}`);
|
|
6101
6051
|
}
|
|
6102
|
-
const memSlot = o.memoryDir && o.fs ? VOICE_MEMORY_PROMPT : "NEVER claim to have stored, saved, or remembered something durably \u2014 you cannot. Anything the user wants persisted (their name, preferences, notes) must go through Act so a worker writes it to memory.";
|
|
6103
|
-
const thinkSlot = o.thinkModel !== false ? THINK_GUIDANCE : THINK_DISABLED_GUIDANCE;
|
|
6104
|
-
const workerToolNames = (o.actOptions?.tools ?? []).map((t) => t.name);
|
|
6105
|
-
const canSearch = workerToolNames.some((n) => /WebSearch/i.test(n));
|
|
6106
|
-
const canFetch = workerToolNames.some((n) => /WebFetch/i.test(n));
|
|
6107
|
-
const workerWeb = canSearch ? `, and it CAN search the web and read web pages \u2014 so when the user gives you something specific to look up ("search for X", "find me\u2026", "what's the latest on\u2026"), route it to Act. But a bare capability QUESTION like "can you search the web?" just gets a short spoken "yes, I can" \u2014 do NOT dispatch and NEVER invent a query the user did not give you` : canFetch ? ", and it can fetch a specific web page URL (but cannot search the web)" : "";
|
|
6108
|
-
const mcpNames = [
|
|
6109
|
-
...Object.keys(o.actOptions?.providerOptions?.mcpServers ?? {}),
|
|
6110
|
-
...new Set(workerToolNames.filter((n) => n.startsWith("mcp__")).map((n) => n.slice(5).split("__")[0]))
|
|
6111
|
-
];
|
|
6112
|
-
const workerMcp = mcpNames.length ? `, and it can use these MCP servers: ${[...new Set(mcpNames)].join(", ")}` + (mcpNames.some((n) => /browser/i.test(n)) ? ' \u2014 including driving a REAL browser (open tabs, navigate, click, screenshot), so answer "yes" if asked whether you can control/drive a browser and route an actual browse to Act' : "") : "";
|
|
6113
|
-
const prompt = VOICE_SYSTEM_PROMPT.replace("{{MEMORY_SLOT}}", memSlot).replace("{{THINK_SLOT}}", thinkSlot).replace("{{WORKER_WEB}}", workerWeb + workerMcp) + (o.voiceStyle === "conversational" ? "\n" + VOICE_STYLE_CONVERSATIONAL : "") + (o.emotionTags ? "\n" + EMOTION_TAGS_GUIDANCE : "") + `
|
|
6114
|
-
${nowLine()}. Anchor every relative or time-sensitive reference \u2014 "today", "now", "current", "recent", "latest", "this year" \u2014 to THIS moment. When the user asks about something recent (news, sports, events), they mean near this date, not a well-known past instance; brief your worker with the current year so it searches for what is happening NOW, not a famous older event.`;
|
|
6115
|
-
const tools = [
|
|
6116
|
-
...o.reflexOptions?.tools ?? [],
|
|
6117
|
-
this.actTool(),
|
|
6118
|
-
...o.thinkModel !== false ? [this.thinkTool()] : [],
|
|
6119
|
-
this.taskStatusTool(),
|
|
6120
|
-
this.cancelTaskTool(),
|
|
6121
|
-
this.quickLookTool(),
|
|
6122
|
-
this.answerTaskTool(),
|
|
6123
|
-
this.holdTool()
|
|
6124
|
-
];
|
|
6125
|
-
const host = o.host;
|
|
6126
|
-
const voiceHost = host && {
|
|
6127
|
-
ask: host.ask ? (q2) => host.ask(q2) : void 0,
|
|
6128
|
-
confirm: host.confirm ? (p, m) => host.confirm(p, m) : void 0,
|
|
6129
|
-
notify: (ev) => {
|
|
6130
|
-
if (ev?.kind === "text_delta" && typeof ev.message === "string") {
|
|
6131
|
-
if (this.heldThisTurn) return;
|
|
6132
|
-
if (this.fabricationCut) return;
|
|
6133
|
-
if (this.turnDispatched && this.spokeBeforeDispatch) return;
|
|
6134
|
-
const msg = ev.message;
|
|
6135
|
-
this.reflexBuf += msg;
|
|
6136
|
-
this.scrubStageDirections();
|
|
6137
|
-
const m = this.reflexBuf.match(RESERVED_EVENT_MARKER) ?? this.reflexBuf.match(RESERVED_EVENT_OPENER);
|
|
6138
|
-
if (m) {
|
|
6139
|
-
this.fabricationCut = true;
|
|
6140
|
-
log10.warn(`reflex fabricated a [task \u2026] event in its spoken stream \u2014 cutting it (kept ${m.index} chars)`);
|
|
6141
|
-
const safe = this.reflexBuf.slice(this.reflexForwarded, m.index);
|
|
6142
|
-
if (!safe) return;
|
|
6143
|
-
if (safe.trim()) this.spokeThisTurn = true;
|
|
6144
|
-
this.emitHost({ ...ev, message: safe });
|
|
6145
|
-
return;
|
|
6146
|
-
}
|
|
6147
|
-
const held = this.reflexBuf.length - this.reflexForwarded;
|
|
6148
|
-
const partial = held > 0 && /\[\s*t?a?s?k?$/i.test(this.reflexBuf.slice(-Math.min(held, 6)));
|
|
6149
|
-
let upto = partial ? this.reflexBuf.length - this.reflexBuf.slice(-6).match(/\[\s*t?a?s?k?$/i)[0].length : this.reflexBuf.length;
|
|
6150
|
-
const paren = this.reflexBuf.lastIndexOf("(");
|
|
6151
|
-
if (paren >= this.reflexForwarded && !this.reflexBuf.includes(")", paren) && this.reflexBuf.length - paren <= 80)
|
|
6152
|
-
upto = Math.min(upto, paren);
|
|
6153
|
-
const out = this.reflexBuf.slice(this.reflexForwarded, upto);
|
|
6154
|
-
this.reflexForwarded = upto;
|
|
6155
|
-
if (!out) return;
|
|
6156
|
-
if (out.trim()) this.spokeThisTurn = true;
|
|
6157
|
-
this.emitHost({ ...ev, message: out });
|
|
6158
|
-
return;
|
|
6159
|
-
}
|
|
6160
|
-
host.notify?.(ev);
|
|
6161
|
-
}
|
|
6162
|
-
};
|
|
6163
|
-
this.voice = new Agent({
|
|
6164
|
-
ai: o.ai,
|
|
6165
|
-
fs: new MemFilesystem2(),
|
|
6166
|
-
model: o.reflexModel,
|
|
6167
|
-
stream: true,
|
|
6168
|
-
host: voiceHost,
|
|
6169
|
-
// The reflex IS the conversational channel — it confirms ambiguity inline ("did you mean…?"),
|
|
6170
|
-
// never via the blocking AskUserQuestion tool (Agent auto-adds it whenever a host is set). Left in,
|
|
6171
|
-
// it stalls a voice turn until the kill-switch. Worker questions still reach the user via parkQuestion.
|
|
6172
|
-
askUserQuestion: false,
|
|
6173
|
-
systemPrompt: prompt,
|
|
6174
|
-
instructionFiles: false,
|
|
6175
|
-
maxSteps: 8,
|
|
6176
|
-
timeoutMs: 3e4,
|
|
6177
|
-
...o.reflexOptions,
|
|
6178
|
-
tools,
|
|
6179
|
-
// Composed AFTER the spread so the dispatch guard can't be dropped by reflexOptions.
|
|
6180
|
-
hooks: composeHooks(this.dispatchGuard(), o.reflexOptions?.hooks)
|
|
6181
|
-
});
|
|
6182
|
-
}
|
|
6183
|
-
/** Resolve memory tools + inject index into voice system prompt (once). */
|
|
6184
|
-
async initMemory() {
|
|
6185
|
-
if (!this.memoryReady) return;
|
|
6186
|
-
const mem = await this.memoryReady;
|
|
6187
|
-
this.memoryReady = void 0;
|
|
6188
|
-
this.voice.options.tools.push(...mem.tools);
|
|
6189
|
-
if (mem.index) this.voice.options.systemPrompt += "\n\n" + mem.index;
|
|
6190
6052
|
}
|
|
6191
|
-
|
|
6192
|
-
|
|
6193
|
-
|
|
6194
|
-
|
|
6195
|
-
|
|
6196
|
-
|
|
6197
|
-
|
|
6198
|
-
|
|
6199
|
-
|
|
6200
|
-
|
|
6053
|
+
lastChunkAt = 0;
|
|
6054
|
+
// timestamp of the most recent mic chunk (0 = none yet)
|
|
6055
|
+
startedChunksAt = 0;
|
|
6056
|
+
// when capture started (grace before the first chunk)
|
|
6057
|
+
noAudioTimer = null;
|
|
6058
|
+
finalText = "";
|
|
6059
|
+
partialText = "";
|
|
6060
|
+
lastChangeAt = 0;
|
|
6061
|
+
lastCombined = "";
|
|
6062
|
+
endpointTimer = null;
|
|
6063
|
+
firstTokenAt = 0;
|
|
6064
|
+
// first speech token in current utterance
|
|
6065
|
+
constructor(options) {
|
|
6066
|
+
this.options = { ...new SonioxSTTOptions(), ...options };
|
|
6201
6067
|
}
|
|
6202
|
-
|
|
6203
|
-
|
|
6204
|
-
* reflexForwarded would corrupt the forward offset. */
|
|
6205
|
-
scrubStageDirections() {
|
|
6206
|
-
if (this.reflexForwarded >= this.reflexBuf.length) return;
|
|
6207
|
-
const region = this.reflexBuf.slice(this.reflexForwarded);
|
|
6208
|
-
const scrubbed = region.replace(/\([^()]*\)/g, (s) => STAGE_DIRECTION_RE.test(s) ? "" : s);
|
|
6209
|
-
if (scrubbed !== region) this.reflexBuf = this.reflexBuf.slice(0, this.reflexForwarded) + scrubbed;
|
|
6068
|
+
get usingAec() {
|
|
6069
|
+
return this.options.source?.aec ?? false;
|
|
6210
6070
|
}
|
|
6211
|
-
|
|
6212
|
-
|
|
6213
|
-
this.
|
|
6214
|
-
|
|
6215
|
-
|
|
6216
|
-
|
|
6217
|
-
|
|
6218
|
-
this.
|
|
6219
|
-
|
|
6220
|
-
|
|
6221
|
-
|
|
6222
|
-
|
|
6223
|
-
|
|
6071
|
+
async connectWs() {
|
|
6072
|
+
const apiKey = await resolveAuth(this.options.auth);
|
|
6073
|
+
this.ws = new WebSocket("wss://stt-rt.soniox.com/transcribe-websocket");
|
|
6074
|
+
await new Promise((res, rej) => {
|
|
6075
|
+
this.ws.onopen = () => res();
|
|
6076
|
+
this.ws.onerror = (e) => rej(new Error(`soniox ws: ${e.message || "connect failed"}`));
|
|
6077
|
+
});
|
|
6078
|
+
this.ws.send(
|
|
6079
|
+
JSON.stringify({
|
|
6080
|
+
api_key: apiKey,
|
|
6081
|
+
model: this.options.model,
|
|
6082
|
+
audio_format: "pcm_s16le",
|
|
6083
|
+
sample_rate: STT_SAMPLE_RATE,
|
|
6084
|
+
num_channels: 1,
|
|
6085
|
+
language_hints: this.options.languageHints,
|
|
6086
|
+
enable_endpoint_detection: true
|
|
6087
|
+
})
|
|
6088
|
+
);
|
|
6089
|
+
this.ws.onmessage = (ev) => this.handle(JSON.parse(String(ev.data)));
|
|
6090
|
+
this.ws.onclose = (ev) => {
|
|
6091
|
+
if (this.stopped) return;
|
|
6092
|
+
log10.warn(`soniox ws closed (${ev.code} ${ev.reason || ""}) \u2014 reconnecting`);
|
|
6093
|
+
this.diag("stt_ws_closed", { code: ev.code, reason: String(ev.reason || ""), reconnecting: true });
|
|
6094
|
+
this.reset();
|
|
6095
|
+
this.connectWs().catch((e) => {
|
|
6096
|
+
log10.error(`soniox reconnect failed: ${e.message}`);
|
|
6097
|
+
this.diag("stt_reconnect_failed", { message: e.message });
|
|
6098
|
+
});
|
|
6099
|
+
};
|
|
6224
6100
|
}
|
|
6225
|
-
|
|
6226
|
-
|
|
6227
|
-
|
|
6228
|
-
|
|
6229
|
-
|
|
6230
|
-
|
|
6231
|
-
|
|
6232
|
-
|
|
6233
|
-
|
|
6234
|
-
|
|
6235
|
-
|
|
6101
|
+
async start() {
|
|
6102
|
+
await this.connectWs();
|
|
6103
|
+
if (this.sourceStarted) return;
|
|
6104
|
+
this.sourceStarted = true;
|
|
6105
|
+
this.endpointTimer = setInterval(() => {
|
|
6106
|
+
const combined = (this.finalText + this.partialText).trim();
|
|
6107
|
+
if (!combined || now() - this.lastChangeAt < this.options.silenceEndpointMs) return;
|
|
6108
|
+
if (this.firstTokenAt) log10.debug(`stt: ${Math.round(now() - this.firstTokenAt)}ms first-token\u2192silence-endpoint, "${combined.slice(0, 60)}"`);
|
|
6109
|
+
this.reset();
|
|
6110
|
+
this.onUtterance(combined, now());
|
|
6111
|
+
}, 120);
|
|
6112
|
+
this.endpointTimer.unref?.();
|
|
6113
|
+
this.startedChunksAt = now();
|
|
6114
|
+
const noAudioMs = this.options.noAudioTimeoutMs;
|
|
6115
|
+
if (noAudioMs > 0) {
|
|
6116
|
+
this.noAudioTimer = setInterval(() => {
|
|
6117
|
+
if (this.stopped) return;
|
|
6118
|
+
const ref = this.lastChunkAt || this.startedChunksAt;
|
|
6119
|
+
if (now() - ref > noAudioMs) {
|
|
6120
|
+
log10.error(`stt: no mic audio for >${Math.round(noAudioMs / 1e3)}s \u2014 capture device stopped delivering`);
|
|
6121
|
+
this.diag("stt_watchdog_fatal", { noAudioMs });
|
|
6122
|
+
this.onFatal("microphone stopped delivering audio (try a different input device, e.g. AirPods, or check System Settings \u2192 Sound \u2192 Input)");
|
|
6123
|
+
this.stop();
|
|
6236
6124
|
}
|
|
6237
|
-
|
|
6238
|
-
|
|
6239
|
-
|
|
6240
|
-
|
|
6241
|
-
|
|
6242
|
-
|
|
6125
|
+
}, Math.max(250, Math.min(2e3, noAudioMs / 4)));
|
|
6126
|
+
this.noAudioTimer.unref?.();
|
|
6127
|
+
}
|
|
6128
|
+
await this.options.source.start((chunk) => {
|
|
6129
|
+
this.lastChunkAt = now();
|
|
6130
|
+
let sum = 0;
|
|
6131
|
+
const view = new DataView(chunk.buffer, chunk.byteOffset, chunk.byteLength);
|
|
6132
|
+
for (let i = 0; i + 1 < chunk.byteLength; i += 2) {
|
|
6133
|
+
const v = view.getInt16(i, true);
|
|
6134
|
+
sum += v * v;
|
|
6243
6135
|
}
|
|
6244
|
-
|
|
6245
|
-
|
|
6246
|
-
|
|
6247
|
-
* micro-ack). For a DISPATCHED turn that's a sufficient ack (don't stack a second one); for an
|
|
6248
|
-
* inline turn whose reply came back empty it is NOT — "One sec." followed by permanent silence is
|
|
6249
|
-
* still dead air, so silentTurn ignores external speech unless work was dispatched. */
|
|
6250
|
-
noteExternalSpeech() {
|
|
6251
|
-
this.externalSpeech = true;
|
|
6252
|
-
}
|
|
6253
|
-
/** True when the just-finished turn voiced NOTHING — dead air to repair. Two ways this happens:
|
|
6254
|
-
* (a) a dispatch with no spoken ack, and (b) an INLINE turn whose `final` channel came back empty —
|
|
6255
|
-
* gpt-oss harmony sometimes puts the whole reply in `analysis` (→ thinking_delta, suppressed in
|
|
6256
|
-
* voice) and emits an empty `final`, so no text_delta ever streams. Both ship silence; both repair.
|
|
6257
|
-
* Requires a host: without one there's no stream to detect speech on (and no one to speak to). */
|
|
6258
|
-
get silentTurn() {
|
|
6259
|
-
const ackedByHost = this.externalSpeech && this.turnDispatched;
|
|
6260
|
-
return !!this.options.host && !this.spokeThisTurn && !ackedByHost && !this.heldThisTurn;
|
|
6136
|
+
this.onLevel(Math.sqrt(sum / (chunk.byteLength / 2)));
|
|
6137
|
+
if (this.ws.readyState === WebSocket.OPEN) this.ws.send(chunk);
|
|
6138
|
+
});
|
|
6261
6139
|
}
|
|
6262
|
-
|
|
6263
|
-
|
|
6264
|
-
|
|
6265
|
-
|
|
6266
|
-
const dispatched = this.turnDispatched;
|
|
6267
|
-
this.nudging = true;
|
|
6268
|
-
try {
|
|
6269
|
-
await this.voice.send(fallback ? "[reminder] You said nothing to the user this turn. Tell them, in ONE short spoken sentence, what just happened \u2014 no tools." : dispatched ? "[reminder] You dispatched a task but said nothing to the user. Say ONE short spoken acknowledgement now \u2014 no tools." : "[reminder] You said nothing to the user this turn. Give your ONE short spoken reply now \u2014 no tools.");
|
|
6270
|
-
} catch (e) {
|
|
6271
|
-
log10.warn(`ack nudge failed: ${e instanceof Error ? e.message : e}`);
|
|
6272
|
-
} finally {
|
|
6273
|
-
this.nudging = false;
|
|
6140
|
+
handle(m) {
|
|
6141
|
+
if (m.error_message) {
|
|
6142
|
+
this.diag("stt_error", { message: String(m.error_message), code: m.error_code });
|
|
6143
|
+
return log10.error(`soniox: ${m.error_message}`);
|
|
6274
6144
|
}
|
|
6275
|
-
|
|
6276
|
-
|
|
6277
|
-
|
|
6278
|
-
|
|
6279
|
-
this.lastFallback = line;
|
|
6280
|
-
this.emitHost({ kind: "text_delta", message: line });
|
|
6145
|
+
let endpoint = false;
|
|
6146
|
+
for (const t of m.tokens ?? []) {
|
|
6147
|
+
if (t.text === "<end>") endpoint = true;
|
|
6148
|
+
else if (t.is_final) this.finalText += t.text;
|
|
6281
6149
|
}
|
|
6282
|
-
|
|
6283
|
-
|
|
6284
|
-
|
|
6285
|
-
|
|
6286
|
-
|
|
6287
|
-
|
|
6288
|
-
/** One user turn: the voice agent streams the reply (and may Act/Think). Serialized with re-voice turns.
|
|
6289
|
-
* If a speculative reflex call is pending and this content CONFIRMS it (the final matches the
|
|
6290
|
-
* speculated partial), the in-flight call is adopted as THE turn: its buffered output flushes to the
|
|
6291
|
-
* host NOW (this is the latency win) and streaming continues live. Any other content aborts the
|
|
6292
|
-
* speculation first (rolled back silently) and runs a normal turn behind it. */
|
|
6293
|
-
send(content) {
|
|
6294
|
-
if (typeof content === "string" && isTrivialBarge(content) && this.hasParkedDelivery()) {
|
|
6295
|
-
if (this.spec) this.abortSpeculation();
|
|
6296
|
-
return this.enqueue(async () => {
|
|
6297
|
-
this.resetTurn();
|
|
6298
|
-
if (!this.redeliverParked()) this.awaitTrivialRedeliver = true;
|
|
6299
|
-
return { text: "", steps: 0, finishReason: "stop", messages: [] };
|
|
6300
|
-
});
|
|
6150
|
+
this.partialText = (m.tokens ?? []).filter((t) => !t.is_final && t.text !== "<end>").map((t) => t.text).join("");
|
|
6151
|
+
const combined = this.finalText + this.partialText;
|
|
6152
|
+
if (combined !== this.lastCombined) {
|
|
6153
|
+
this.lastCombined = combined;
|
|
6154
|
+
this.lastChangeAt = now();
|
|
6155
|
+
if (!this.firstTokenAt && combined.trim()) this.firstTokenAt = now();
|
|
6301
6156
|
}
|
|
6302
|
-
|
|
6303
|
-
if (
|
|
6304
|
-
|
|
6305
|
-
|
|
6306
|
-
|
|
6307
|
-
|
|
6308
|
-
spec.decide("confirm");
|
|
6309
|
-
this.notify("diag", "speculation_confirmed", { text: spec.text.slice(0, 80) });
|
|
6310
|
-
return spec.done;
|
|
6311
|
-
}
|
|
6312
|
-
this.abortSpeculation();
|
|
6157
|
+
this.onPartial(combined);
|
|
6158
|
+
if (endpoint && this.finalText.trim()) {
|
|
6159
|
+
const utterance = this.finalText.trim();
|
|
6160
|
+
if (this.firstTokenAt) log10.debug(`stt: ${Math.round(now() - this.firstTokenAt)}ms first-token\u2192endpoint, "${utterance.slice(0, 60)}"`);
|
|
6161
|
+
this.reset();
|
|
6162
|
+
this.onUtterance(utterance, now());
|
|
6313
6163
|
}
|
|
6314
|
-
return this.enqueue(async () => {
|
|
6315
|
-
await this.initMemory();
|
|
6316
|
-
this.resetTurn();
|
|
6317
|
-
this.awaitTrivialRedeliver = false;
|
|
6318
|
-
this.parkedRedeliver = [];
|
|
6319
|
-
this.suppressParkedResume = true;
|
|
6320
|
-
const res = await this.voice.send(content);
|
|
6321
|
-
this.flushHeldReflexTail();
|
|
6322
|
-
if (this.silentTurn) await this.ackIfSilent();
|
|
6323
|
-
return res;
|
|
6324
|
-
});
|
|
6325
6164
|
}
|
|
6326
|
-
|
|
6327
|
-
|
|
6328
|
-
|
|
6329
|
-
|
|
6330
|
-
|
|
6331
|
-
|
|
6332
|
-
|
|
6333
|
-
|
|
6334
|
-
|
|
6335
|
-
|
|
6165
|
+
reset() {
|
|
6166
|
+
this.finalText = "";
|
|
6167
|
+
this.partialText = "";
|
|
6168
|
+
this.lastCombined = "";
|
|
6169
|
+
this.firstTokenAt = 0;
|
|
6170
|
+
}
|
|
6171
|
+
stop() {
|
|
6172
|
+
this.stopped = true;
|
|
6173
|
+
if (this.endpointTimer) clearInterval(this.endpointTimer);
|
|
6174
|
+
if (this.noAudioTimer) clearInterval(this.noAudioTimer);
|
|
6175
|
+
this.options.source?.stop();
|
|
6176
|
+
if (this.ws) this.ws.onclose = null;
|
|
6177
|
+
this.ws?.close();
|
|
6178
|
+
}
|
|
6179
|
+
};
|
|
6180
|
+
|
|
6181
|
+
// node_modules/@bod.ee/voice/src/adapters/cartesia.ts
|
|
6182
|
+
var log11 = forComponent2("CartesiaTTS");
|
|
6183
|
+
var now2 = () => performance.now();
|
|
6184
|
+
var CartesiaTTSOptions = class {
|
|
6185
|
+
auth = "";
|
|
6186
|
+
voiceId = "";
|
|
6187
|
+
model = "sonic-3.5";
|
|
6188
|
+
/** 'apiKey' (server/CLI) → `api_key=` URL param; 'token' (browser, BE-minted) → `access_token=`. */
|
|
6189
|
+
authMode = "apiKey";
|
|
6190
|
+
};
|
|
6191
|
+
var CartesiaTTS = class _CartesiaTTS {
|
|
6192
|
+
options;
|
|
6193
|
+
ws;
|
|
6194
|
+
ctxSeq = 0;
|
|
6195
|
+
ctxId = "";
|
|
6196
|
+
onAudio = () => {
|
|
6197
|
+
};
|
|
6198
|
+
onDone = () => {
|
|
6199
|
+
};
|
|
6200
|
+
/** Word-level timestamps for karaoke reveal: `start[i]` = seconds from turn-audio start (absolute
|
|
6201
|
+
* across continuation chunks). Fired only when a consumer opts into reveal (see `wantTimestamps`). */
|
|
6202
|
+
onTimestamps = () => {
|
|
6203
|
+
};
|
|
6204
|
+
/** Request `add_timestamps` from Cartesia. Off by default (saves bandwidth) — the engine sets it
|
|
6205
|
+
* when revealMode==='word'. */
|
|
6206
|
+
wantTimestamps = false;
|
|
6207
|
+
/** Diagnostic tap (provider errors, circuit-breaker open/close, ws reconnects). Fire-and-forget:
|
|
6208
|
+
* a throwing handler disables itself — never affects synthesis. Wired by VoiceIO / the lab bridge. */
|
|
6209
|
+
onDiag = () => {
|
|
6210
|
+
};
|
|
6211
|
+
diagOn = true;
|
|
6212
|
+
diag(kind, fields) {
|
|
6213
|
+
if (!this.diagOn) return;
|
|
6214
|
+
try {
|
|
6215
|
+
this.onDiag({ t: now2(), kind, ...fields });
|
|
6216
|
+
} catch (e) {
|
|
6217
|
+
this.diagOn = false;
|
|
6218
|
+
log11.debug(`onDiag threw \u2014 TTS diagnostics disabled: ${e instanceof Error ? e.message : e}`);
|
|
6219
|
+
}
|
|
6220
|
+
}
|
|
6221
|
+
firstAudioAt = 0;
|
|
6222
|
+
/** Circuit breaker: consecutive error count + down flag. */
|
|
6223
|
+
consecutiveErrors = 0;
|
|
6224
|
+
consecutiveOk = 0;
|
|
6225
|
+
down = false;
|
|
6226
|
+
downAt = 0;
|
|
6227
|
+
probeTimer = null;
|
|
6228
|
+
static CB_THRESHOLD = 3;
|
|
6229
|
+
// open after 3 consecutive errors
|
|
6230
|
+
static CB_RECOVER_OK = 2;
|
|
6231
|
+
// close only after 2 consecutive good frames (no single-frame flap)
|
|
6232
|
+
static CB_PROBE_MS = 3e4;
|
|
6233
|
+
constructor(options) {
|
|
6234
|
+
this.options = { ...new CartesiaTTSOptions(), ...options };
|
|
6235
|
+
}
|
|
6236
|
+
closed = false;
|
|
6237
|
+
connecting = null;
|
|
6238
|
+
async connect() {
|
|
6239
|
+
this.closed = false;
|
|
6240
|
+
this.connecting = this.doConnect();
|
|
6241
|
+
await this.connecting;
|
|
6242
|
+
this.connecting = null;
|
|
6243
|
+
}
|
|
6244
|
+
async doConnect() {
|
|
6245
|
+
const key = await resolveAuth(this.options.auth);
|
|
6246
|
+
const param = this.options.authMode === "token" ? "access_token" : "api_key";
|
|
6247
|
+
this.ws = new WebSocket(`wss://api.cartesia.ai/tts/websocket?cartesia_version=2026-03-01&${param}=${key}`);
|
|
6248
|
+
await new Promise((res, rej) => {
|
|
6249
|
+
this.ws.onopen = () => res();
|
|
6250
|
+
this.ws.onerror = (e) => rej(new Error(`cartesia ws: ${e.message || "connect failed"}`));
|
|
6336
6251
|
});
|
|
6337
|
-
|
|
6338
|
-
|
|
6339
|
-
|
|
6340
|
-
|
|
6341
|
-
|
|
6342
|
-
|
|
6343
|
-
|
|
6344
|
-
|
|
6345
|
-
};
|
|
6346
|
-
this.spec = spec;
|
|
6347
|
-
spec.done = this.enqueue(async () => {
|
|
6348
|
-
const empty = { text: "", steps: 0, finishReason: "aborted", messages: this.voice.transcript };
|
|
6349
|
-
if (spec.state === "aborted") {
|
|
6350
|
-
this.speculativeAbortedCalls++;
|
|
6351
|
-
if (this.spec === spec) this.spec = void 0;
|
|
6352
|
-
return empty;
|
|
6353
|
-
}
|
|
6354
|
-
await this.initMemory();
|
|
6355
|
-
this.resetTurn();
|
|
6356
|
-
const base = this.voice.transcript.length;
|
|
6357
|
-
const prevSignal = this.voice.options.signal;
|
|
6358
|
-
this.voice.options.signal = spec.ctl.signal;
|
|
6359
|
-
let res;
|
|
6360
|
-
try {
|
|
6361
|
-
res = await this.voice.send(spec.text);
|
|
6362
|
-
} catch (e) {
|
|
6363
|
-
log10.warn(`speculative turn failed: ${e instanceof Error ? e.message : e}`);
|
|
6364
|
-
} finally {
|
|
6365
|
-
this.voice.options.signal = prevSignal;
|
|
6366
|
-
}
|
|
6367
|
-
const timer = setTimeout(() => {
|
|
6368
|
-
spec.state = spec.state === "pending" ? "aborted" : spec.state;
|
|
6369
|
-
spec.decide("abort");
|
|
6370
|
-
}, 1e4);
|
|
6371
|
-
timer.unref?.();
|
|
6372
|
-
const d = await spec.decision;
|
|
6373
|
-
clearTimeout(timer);
|
|
6374
|
-
if (d === "abort") {
|
|
6375
|
-
if (this.voice.transcript.length > base) this.voice.transcript.length = base;
|
|
6376
|
-
this.speculativeAbortedCalls++;
|
|
6377
|
-
log10.verbose(`speculation aborted (${this.speculativeAbortedCalls} total): "${spec.text.slice(0, 50)}"`);
|
|
6378
|
-
if (this.spec === spec) this.spec = void 0;
|
|
6379
|
-
return res ?? empty;
|
|
6252
|
+
this.ws.onclose = (ev) => {
|
|
6253
|
+
log11.warn(`cartesia ws closed (${ev.code} ${ev.reason || ""})`);
|
|
6254
|
+
this.diag("tts_ws_closed", { code: ev.code, reason: String(ev.reason || ""), reconnecting: !this.closed });
|
|
6255
|
+
if (!this.closed) {
|
|
6256
|
+
this.connecting = this.doConnect().catch((e) => {
|
|
6257
|
+
log11.error(`cartesia reconnect failed: ${e.message}`);
|
|
6258
|
+
this.diag("tts_reconnect_failed", { message: e.message });
|
|
6259
|
+
});
|
|
6380
6260
|
}
|
|
6381
|
-
|
|
6382
|
-
|
|
6383
|
-
|
|
6384
|
-
|
|
6385
|
-
|
|
6261
|
+
};
|
|
6262
|
+
this.ws.onmessage = (ev) => {
|
|
6263
|
+
const m = JSON.parse(String(ev.data));
|
|
6264
|
+
if (m.context_id && m.context_id !== this.ctxId) return;
|
|
6265
|
+
if (m.type === "chunk" && m.data) {
|
|
6266
|
+
this.consecutiveErrors = 0;
|
|
6267
|
+
this.markRecovered();
|
|
6268
|
+
if (!this.firstAudioAt) this.firstAudioAt = now2();
|
|
6269
|
+
this.onAudio(base64ToBytes(m.data));
|
|
6270
|
+
} else if (m.type === "done") {
|
|
6271
|
+
this.consecutiveErrors = 0;
|
|
6272
|
+
this.markRecovered();
|
|
6273
|
+
this.onDone();
|
|
6274
|
+
} else if (m.type === "timestamps" && m.word_timestamps) {
|
|
6275
|
+
const wt = m.word_timestamps;
|
|
6276
|
+
if (wt.words?.length && wt.start?.length) this.onTimestamps(wt.words, wt.start);
|
|
6277
|
+
} else if (m.type === "error") {
|
|
6278
|
+
if (/already been cancelled|does not exist/.test(m.message || "")) return;
|
|
6279
|
+
this.consecutiveErrors++;
|
|
6280
|
+
this.diag("tts_error", { message: String(m.message || ""), code: m.status_code, contextId: m.context_id, consecutive: this.consecutiveErrors });
|
|
6281
|
+
if (!this.down && this.consecutiveErrors >= _CartesiaTTS.CB_THRESHOLD) {
|
|
6282
|
+
this.down = true;
|
|
6283
|
+
this.downAt = now2();
|
|
6284
|
+
this.consecutiveOk = 0;
|
|
6285
|
+
log11.warn(`TTS circuit breaker open \u2014 ${this.consecutiveErrors} consecutive errors, switching to text-only`);
|
|
6286
|
+
this.diag("tts_breaker_open", { errors: this.consecutiveErrors });
|
|
6287
|
+
this.onDone();
|
|
6288
|
+
this.startProbe();
|
|
6289
|
+
} else if (!this.down) {
|
|
6290
|
+
(/No valid transcripts/i.test(m.message || "") ? log11.debug : log11.warn)(`cartesia: ${JSON.stringify(m)}`);
|
|
6386
6291
|
}
|
|
6387
6292
|
}
|
|
6388
|
-
|
|
6389
|
-
this.flushHeldReflexTail();
|
|
6390
|
-
if (this.silentTurn) await this.ackIfSilent();
|
|
6391
|
-
return res ?? empty;
|
|
6392
|
-
});
|
|
6393
|
-
}
|
|
6394
|
-
/** Abort a pending speculation (idempotent): kill the in-flight call, drop its buffered output.
|
|
6395
|
-
* Called on divergence (send), a stale partial (VoiceEngine.onSpeculateAbort), a side-effect tool
|
|
6396
|
-
* attempt (dispatchGuard), or host paths that will never dispatch a final (commands, voice-off). */
|
|
6397
|
-
abortSpeculation() {
|
|
6398
|
-
const spec = this.spec;
|
|
6399
|
-
if (spec?.state !== "pending") return;
|
|
6400
|
-
spec.state = "aborted";
|
|
6401
|
-
spec.buf.length = 0;
|
|
6402
|
-
spec.ctl.abort();
|
|
6403
|
-
spec.decide("abort");
|
|
6404
|
-
this.notify("diag", "speculation_aborted", { text: spec.text.slice(0, 80) });
|
|
6293
|
+
};
|
|
6405
6294
|
}
|
|
6406
|
-
/**
|
|
6407
|
-
|
|
6408
|
-
|
|
6409
|
-
if (!
|
|
6410
|
-
if (
|
|
6411
|
-
|
|
6412
|
-
|
|
6413
|
-
|
|
6295
|
+
/** Close the breaker only after CB_RECOVER_OK consecutive good frames, so a single straggler chunk
|
|
6296
|
+
* after a 503 burst doesn't flap open→recover in <1s. A sub-2s down-window is a transient blip → debug. */
|
|
6297
|
+
markRecovered() {
|
|
6298
|
+
if (!this.down) return;
|
|
6299
|
+
if (++this.consecutiveOk < _CartesiaTTS.CB_RECOVER_OK) return;
|
|
6300
|
+
this.down = false;
|
|
6301
|
+
this.consecutiveOk = 0;
|
|
6302
|
+
this.stopProbe();
|
|
6303
|
+
const downMs = this.downAt ? now2() - this.downAt : 0;
|
|
6304
|
+
this.diag("tts_breaker_close", { downMs: Math.round(downMs) });
|
|
6305
|
+
(downMs < 2e3 ? log11.debug : log11.info)(`TTS recovered${downMs ? ` (down ${downMs}ms)` : ""}`);
|
|
6414
6306
|
}
|
|
6415
|
-
/**
|
|
6416
|
-
|
|
6417
|
-
|
|
6418
|
-
|
|
6419
|
-
parkInFlightDeliveries() {
|
|
6420
|
-
this.suppressParkedResume = false;
|
|
6421
|
-
const parked = [];
|
|
6422
|
-
for (const rec of this.tasks.values())
|
|
6423
|
-
if (rec.status === "running" && !rec.deliveryParked) {
|
|
6424
|
-
rec.deliveryParked = true;
|
|
6425
|
-
parked.push(rec.id);
|
|
6426
|
-
}
|
|
6427
|
-
return parked;
|
|
6307
|
+
/** Ensure the WS is open before sending — reconnects if idle-closed. */
|
|
6308
|
+
async ensureConnected() {
|
|
6309
|
+
if (this.connecting) await this.connecting;
|
|
6310
|
+
if (this.ws?.readyState !== WebSocket.OPEN) await this.connect();
|
|
6428
6311
|
}
|
|
6429
|
-
/**
|
|
6430
|
-
*
|
|
6431
|
-
|
|
6432
|
-
|
|
6312
|
+
/** Prime the synthesis pipeline on a throwaway context right after connect: the FIRST synthesis on
|
|
6313
|
+
* a fresh WS pays Cartesia's cold spin-up (~1s+ live) — absorb it at mic-on instead of turn one.
|
|
6314
|
+
* The returned audio is discarded (engine drops onAudio while not speaking; once a real turn calls
|
|
6315
|
+
* newContext() any stragglers are stale-context-filtered). Respects the circuit breaker. */
|
|
6316
|
+
warmup() {
|
|
6317
|
+
if (this.down) return;
|
|
6318
|
+
this.newContext();
|
|
6319
|
+
if (this.ws?.readyState === WebSocket.OPEN) this.ws.send(this.frame("Ok.", false));
|
|
6433
6320
|
}
|
|
6434
|
-
|
|
6435
|
-
|
|
6436
|
-
|
|
6437
|
-
|
|
6438
|
-
const text = this.parkedRedeliver.splice(0).join(" ").trim();
|
|
6439
|
-
if (text) {
|
|
6440
|
-
this.options.host?.notify?.({ kind: "speak_utterance", message: text });
|
|
6441
|
-
this.notify("diag", "parked_redelivered", { chars: text.length });
|
|
6442
|
-
}
|
|
6443
|
-
return true;
|
|
6444
|
-
}
|
|
6445
|
-
/** Resolve when all queued voice turns AND all in-flight worker tasks have settled (tests, graceful shutdown). */
|
|
6446
|
-
async idle() {
|
|
6447
|
-
while (true) {
|
|
6448
|
-
const q2 = this.queue;
|
|
6449
|
-
await q2.catch(() => {
|
|
6450
|
-
});
|
|
6451
|
-
await Promise.all([...this.tasks.values()].map((t) => t.promise));
|
|
6452
|
-
if (this.queue === q2 && ![...this.tasks.values()].some((t) => t.status === "running")) return;
|
|
6453
|
-
}
|
|
6321
|
+
newContext() {
|
|
6322
|
+
this.ctxId = `ctx-${++this.ctxSeq}`;
|
|
6323
|
+
this.firstAudioAt = 0;
|
|
6324
|
+
return this.ctxId;
|
|
6454
6325
|
}
|
|
6455
|
-
|
|
6456
|
-
|
|
6457
|
-
|
|
6458
|
-
|
|
6459
|
-
|
|
6326
|
+
frame(transcript, cont) {
|
|
6327
|
+
return JSON.stringify({
|
|
6328
|
+
model_id: this.options.model,
|
|
6329
|
+
transcript,
|
|
6330
|
+
voice: { mode: "id", id: this.options.voiceId },
|
|
6331
|
+
output_format: { container: "raw", encoding: "pcm_s16le", sample_rate: TTS_SAMPLE_RATE },
|
|
6332
|
+
context_id: this.ctxId,
|
|
6333
|
+
continue: cont,
|
|
6334
|
+
...this.wantTimestamps ? { add_timestamps: true } : {}
|
|
6460
6335
|
});
|
|
6461
|
-
return run;
|
|
6462
6336
|
}
|
|
6463
|
-
|
|
6464
|
-
this.
|
|
6337
|
+
speak(text, cont) {
|
|
6338
|
+
if (this.down) return;
|
|
6339
|
+
if (cont && !text) return;
|
|
6340
|
+
if (this.ws?.readyState === WebSocket.OPEN) this.ws.send(this.frame(text, cont));
|
|
6341
|
+
else void this.ensureConnected().then(() => this.ws?.readyState === WebSocket.OPEN && this.ws.send(this.frame(text, cont)));
|
|
6465
6342
|
}
|
|
6466
|
-
|
|
6467
|
-
|
|
6468
|
-
|
|
6469
|
-
|
|
6470
|
-
emitHost(ev) {
|
|
6471
|
-
const spec = this.spec;
|
|
6472
|
-
if (spec && (ev.kind === "text_delta" || ev.kind === "hold_filler")) {
|
|
6473
|
-
if (spec.state === "pending") {
|
|
6474
|
-
spec.buf.push(ev);
|
|
6475
|
-
return;
|
|
6476
|
-
}
|
|
6477
|
-
if (spec.state === "aborted") return;
|
|
6343
|
+
end() {
|
|
6344
|
+
if (this.down) {
|
|
6345
|
+
this.onDone();
|
|
6346
|
+
return;
|
|
6478
6347
|
}
|
|
6479
|
-
this.
|
|
6480
|
-
}
|
|
6481
|
-
/** Queue a `[task …]` event for re-voicing. Events arriving while the voice is busy coalesce into ONE turn.
|
|
6482
|
-
* `nonClean` (out-of-band boolean, set by the caller that KNOWS this event integrates a NON-CLEAN outcome)
|
|
6483
|
-
* marks the coalesced flush as a non-clean integration turn — turn-eligibility, never inferred from event
|
|
6484
|
-
* text and never keyed on a (re-authored) brief string. Any dispatch in such a turn is a follow-up. */
|
|
6485
|
-
queueRevoice(event, nonClean = false) {
|
|
6486
|
-
this.pendingEvents.push(event);
|
|
6487
|
-
if (nonClean) this.pendingNonClean = true;
|
|
6488
|
-
if (this.flushQueued) return;
|
|
6489
|
-
this.flushQueued = true;
|
|
6490
|
-
void this.enqueue(async () => {
|
|
6491
|
-
this.flushQueued = false;
|
|
6492
|
-
const events = this.pendingEvents.splice(0);
|
|
6493
|
-
const nonCleanTurn = this.pendingNonClean;
|
|
6494
|
-
this.pendingNonClean = false;
|
|
6495
|
-
if (!events.length) return;
|
|
6496
|
-
const failed = events.find((e) => /^\[task\b[^\]\n]*\bfailed\b/i.test(e));
|
|
6497
|
-
this.resetTurn();
|
|
6498
|
-
this.turnFollowUp = nonCleanTurn;
|
|
6499
|
-
await this.voice.send(events.join("\n"));
|
|
6500
|
-
this.flushHeldReflexTail();
|
|
6501
|
-
if (this.silentTurn) await this.ackIfSilent(failed ? "Sorry, that didn't work \u2014 the task failed." : void 0);
|
|
6502
|
-
this.notify("revoice_done", "");
|
|
6503
|
-
});
|
|
6348
|
+
if (this.ws?.readyState === WebSocket.OPEN) this.ws.send(this.frame("", false));
|
|
6504
6349
|
}
|
|
6505
|
-
|
|
6506
|
-
|
|
6507
|
-
* must check its own work before reporting (nearly free under prompt caching; measured honest:
|
|
6508
|
-
* it does NOT fix one-shot logic bugs — see mind/10). Think tasks are pure reasoning — no footer. */
|
|
6509
|
-
buildBrief(brief, tier = "act", deliver = true) {
|
|
6510
|
-
const recent = this.voice.transcript.filter((m) => (m.role === "user" || m.role === "assistant") && contentText(m.content).trim()).slice(-this.options.excerptTurns).map((m) => `${m.role}: ${contentText(m.content)}`).join("\n");
|
|
6511
|
-
const verify = tier === "act" ? "\n\nBefore reporting done: re-read what you changed and check it against EVERY requirement above \u2014 fix any gap first. Your report is trusted without review." : "";
|
|
6512
|
-
const deliverContract = deliver ? `
|
|
6513
|
-
|
|
6514
|
-
## DELIVER (spoken delivery)
|
|
6515
|
-
You are reporting back to a user who is LISTENING. Stream your work normally \u2014 your prose is the written work record and detail, and is NOT spoken. Wrap anything the user should HEAR in <spoken>\u2026</spoken> tags. LEAD WITH the actual content they asked for: if they asked for a specific piece of content \u2014 a value, a name, the actual lines, the writing itself \u2014 that content goes INSIDE the <spoken> tags, not a remark about it. Your FIRST <spoken> segment is substantive \u2014 never a greeting or an acknowledgement (the front-end has already acked; do not double-ack). Keep spoken text concise and natural for the ear: short sentences, no markdown. NEVER enumerate in speech \u2014 no numbered or bulleted lists ("One. \u2026 Two. \u2026" is robotic). Deliver multiple items as flowing conversation with brief connective phrasing ("here's one\u2026", "and another\u2026", "oh, and\u2026"), pausing between items with sentence breaks, not numbers.` + (this.options.emotionTags ? " Inside <spoken>, you may prefix a sentence with an inline [emotion] tag (e.g. [excited], [curious]) to color how it is voiced \u2014 only when it genuinely fits, and vary it; [laughter] gives a natural laugh." : "") : "";
|
|
6516
|
-
return `${nowLine()}.
|
|
6517
|
-
|
|
6518
|
-
` + (recent ? `${brief}
|
|
6519
|
-
|
|
6520
|
-
## Recent conversation (for context)
|
|
6521
|
-
${recent}` : brief) + verify + deliverContract;
|
|
6350
|
+
cancel() {
|
|
6351
|
+
if (this.ws?.readyState === WebSocket.OPEN) this.ws.send(JSON.stringify({ context_id: this.ctxId, cancel: true }));
|
|
6522
6352
|
}
|
|
6523
|
-
|
|
6524
|
-
|
|
6525
|
-
|
|
6526
|
-
|
|
6527
|
-
|
|
6528
|
-
|
|
6529
|
-
const base = tierOpts?.hooks ?? o.actOptions?.hooks;
|
|
6530
|
-
const report = o.progressUpdates ? this.progressReporter(id) : void 0;
|
|
6531
|
-
const tail = [];
|
|
6532
|
-
const pushTail = (line) => {
|
|
6533
|
-
tail.push(line.slice(0, 200));
|
|
6534
|
-
if (tail.length > 120) tail.splice(0, tail.length - 120);
|
|
6535
|
-
};
|
|
6536
|
-
const hooks = {
|
|
6537
|
-
...base,
|
|
6538
|
-
preToolUse: async (call, meta) => {
|
|
6539
|
-
const d = await base?.preToolUse?.(call, meta);
|
|
6540
|
-
pushTail(`\u2699 ${describeCall(call)}`);
|
|
6541
|
-
report?.pre(call);
|
|
6542
|
-
return d;
|
|
6543
|
-
},
|
|
6544
|
-
postToolUse: async (call, result, meta) => {
|
|
6545
|
-
await base?.postToolUse?.(call, result, meta);
|
|
6546
|
-
const last = result?.trim().split("\n").filter(Boolean).pop();
|
|
6547
|
-
if (last) pushTail(` \u21B3 ${last}`);
|
|
6548
|
-
report?.post(call);
|
|
6549
|
-
},
|
|
6550
|
-
onToolOutput: (call, chunk, meta) => {
|
|
6551
|
-
base?.onToolOutput?.(call, chunk, meta);
|
|
6552
|
-
report?.output(chunk);
|
|
6553
|
-
}
|
|
6554
|
-
};
|
|
6555
|
-
const relayAsk = async (q2) => {
|
|
6556
|
-
const opts = q2.options?.length ? ` Options: ${q2.options.map((x) => x.label).join(", ")}.` : "";
|
|
6557
|
-
const a = await this.parkQuestion(id, `${q2.question}${opts}`);
|
|
6558
|
-
return a || "(no answer from the user \u2014 use your best judgment and note the assumption)";
|
|
6559
|
-
};
|
|
6560
|
-
const splitter = new SpokenSplitter();
|
|
6561
|
-
const speak = (seg) => {
|
|
6562
|
-
if (!seg) return;
|
|
6563
|
-
const r = this.tasks.get(id);
|
|
6564
|
-
if (r) r.spokenText = (r.spokenText ? r.spokenText + " " : "") + seg;
|
|
6565
|
-
if (!r?.deliveryParked) o.host?.notify?.({ kind: "speak_utterance", message: seg });
|
|
6566
|
-
};
|
|
6567
|
-
const coalescer = new SentenceCoalescer();
|
|
6568
|
-
const feedSpoken = (s) => {
|
|
6569
|
-
const ready = coalescer.feed(s);
|
|
6570
|
-
if (ready) speak(ready);
|
|
6571
|
-
};
|
|
6572
|
-
const flushSpoken = () => speak(coalescer.flush());
|
|
6573
|
-
const askBridge = o.askRelay ? { ask: relayAsk } : o.host?.ask ? { ask: (q2) => o.host.ask(q2) } : {};
|
|
6574
|
-
const workerHost = {
|
|
6575
|
-
...askBridge,
|
|
6576
|
-
notify: (ev) => {
|
|
6577
|
-
if (ev?.kind === "text_delta" && typeof ev.message === "string") {
|
|
6578
|
-
const { spoken, detail } = splitter.feed(ev.message);
|
|
6579
|
-
feedSpoken(spoken);
|
|
6580
|
-
if (detail.trim()) pushTail(detail.trim());
|
|
6581
|
-
return;
|
|
6582
|
-
}
|
|
6583
|
-
}
|
|
6584
|
-
};
|
|
6585
|
-
const agentOpts = {
|
|
6586
|
-
ai: o.ai,
|
|
6587
|
-
fs: o.fs,
|
|
6588
|
-
model: tierModel,
|
|
6589
|
-
...tier === "think" ? { reasoning: tierOpts?.reasoning ?? "high" } : {},
|
|
6590
|
-
...tierOpts,
|
|
6591
|
-
// Recompute providerOptions for THIS worker's model (after tierOpts so it wins over any inherited
|
|
6592
|
-
// main-template value) — prevents cursor-only cwd/cursorSession leaking onto an anthropic worker.
|
|
6593
|
-
providerOptions: o.providerOptionsFor?.(tierModel),
|
|
6594
|
-
stream: true,
|
|
6595
|
-
// worker streams text_delta so the splitter can extract <spoken> live (after tierOpts: never overridden off)
|
|
6596
|
-
host: workerHost,
|
|
6597
|
-
// carries BOTH ask AND the <spoken>-splitting notify
|
|
6598
|
-
...hooks ? { hooks } : {},
|
|
6599
|
-
signal: controller.signal
|
|
6600
|
-
// shared with the checker so a cancel tears down both
|
|
6601
|
-
};
|
|
6602
|
-
const promise = new Agent(agentOpts).run(briefText).then((res) => {
|
|
6603
|
-
const { spoken, detail } = splitter.flush();
|
|
6604
|
-
feedSpoken(spoken);
|
|
6605
|
-
if (detail.trim()) pushTail(detail.trim());
|
|
6606
|
-
flushSpoken();
|
|
6607
|
-
return res;
|
|
6608
|
-
}).then((res) => this.maybeVerify(id, brief, res, tier, agentOpts, askBridge)).then((res) => this.onWorkerSettled(id, res)).catch((err2) => this.onWorkerFailed(id, err2));
|
|
6609
|
-
this.tasks.set(id, { id, label, status: "running", controller, promise, tail, brief, followUp, splitter });
|
|
6610
|
-
if (this.tasks.size > this.options.maxTaskRecords)
|
|
6611
|
-
for (const [tid, rec] of this.tasks) {
|
|
6612
|
-
if (this.tasks.size <= this.options.maxTaskRecords) break;
|
|
6613
|
-
if (rec.status !== "running") this.tasks.delete(tid);
|
|
6353
|
+
startProbe() {
|
|
6354
|
+
if (this.probeTimer) return;
|
|
6355
|
+
this.probeTimer = setInterval(() => {
|
|
6356
|
+
if (!this.down) {
|
|
6357
|
+
this.stopProbe();
|
|
6358
|
+
return;
|
|
6614
6359
|
}
|
|
6360
|
+
this.consecutiveErrors = 0;
|
|
6361
|
+
this.newContext();
|
|
6362
|
+
if (this.ws?.readyState === WebSocket.OPEN) this.ws.send(this.frame("Ok.", false));
|
|
6363
|
+
}, _CartesiaTTS.CB_PROBE_MS);
|
|
6364
|
+
this.probeTimer.unref?.();
|
|
6615
6365
|
}
|
|
6616
|
-
|
|
6617
|
-
|
|
6618
|
-
|
|
6619
|
-
|
|
6620
|
-
* cancelled tasks. Usage is merged so /cost reflects the real (worker + checker) spend. */
|
|
6621
|
-
async maybeVerify(id, brief, res, tier, agentOpts, askBridge) {
|
|
6622
|
-
if (!this.options.verifyActTasks || tier !== "act" || res.finishReason !== "stop") return res;
|
|
6623
|
-
if (this.tasks.get(id)?.status === "cancelled") return res;
|
|
6624
|
-
const { stream: _stream, host: _host, ...restOpts } = agentOpts;
|
|
6625
|
-
const checkerOpts = {
|
|
6626
|
-
...restOpts,
|
|
6627
|
-
...askBridge.ask ? { host: { ask: askBridge.ask } } : {}
|
|
6628
|
-
};
|
|
6629
|
-
const checkBrief = `${this.buildBrief(brief, tier, false)}
|
|
6630
|
-
|
|
6631
|
-
## VERIFY MODE
|
|
6632
|
-
Another agent just implemented the above. Independently check the CURRENT state of the files against EVERY requirement. Fix any gap you find. If everything is already correct, make NO changes \u2014 do not refactor or improve \u2014 and report "verified".`;
|
|
6633
|
-
this.notify("task_verify", `task ${id}: verifying`, { id });
|
|
6634
|
-
const cres = await new Agent(checkerOpts).run(checkBrief);
|
|
6635
|
-
if (cres.finishReason !== "stop") {
|
|
6636
|
-
log10.warn(`task ${id}: verify inconclusive (${cres.finishReason})`);
|
|
6637
|
-
this.notify("task_verify", `task ${id}: verify inconclusive (${cres.finishReason})`, { id, finishReason: cres.finishReason });
|
|
6366
|
+
stopProbe() {
|
|
6367
|
+
if (this.probeTimer) {
|
|
6368
|
+
clearInterval(this.probeTimer);
|
|
6369
|
+
this.probeTimer = null;
|
|
6638
6370
|
}
|
|
6639
|
-
const sum = (a = 0, b = 0) => a + b;
|
|
6640
|
-
return {
|
|
6641
|
-
...res,
|
|
6642
|
-
steps: res.steps + cres.steps,
|
|
6643
|
-
// Merge the checker's messages so downstream tool-call/step accounting includes BOTH agents
|
|
6644
|
-
// (else a verified task's toolCalls would undercount vs its steps/usage).
|
|
6645
|
-
messages: [...res.messages, ...cres.messages],
|
|
6646
|
-
usageEstimated: res.usageEstimated || cres.usageEstimated,
|
|
6647
|
-
usage: res.usage && cres.usage ? {
|
|
6648
|
-
promptTokens: sum(res.usage.promptTokens, cres.usage.promptTokens),
|
|
6649
|
-
completionTokens: sum(res.usage.completionTokens, cres.usage.completionTokens),
|
|
6650
|
-
totalTokens: sum(res.usage.totalTokens, cres.usage.totalTokens),
|
|
6651
|
-
cacheCreationTokens: sum(res.usage.cacheCreationTokens, cres.usage.cacheCreationTokens),
|
|
6652
|
-
cacheReadTokens: sum(res.usage.cacheReadTokens, cres.usage.cacheReadTokens)
|
|
6653
|
-
} : res.usage ?? cres.usage
|
|
6654
|
-
};
|
|
6655
6371
|
}
|
|
6656
|
-
|
|
6657
|
-
|
|
6658
|
-
|
|
6659
|
-
|
|
6660
|
-
|
|
6661
|
-
let lastAt = Date.now();
|
|
6662
|
-
let steps = 0;
|
|
6663
|
-
let inflight = null;
|
|
6664
|
-
const due = () => {
|
|
6665
|
-
if (this.pendingAsks.size) return void 0;
|
|
6666
|
-
const rec = this.tasks.get(id);
|
|
6667
|
-
return rec && rec.status === "running" && Date.now() - lastAt >= this.options.progressIntervalMs ? rec : void 0;
|
|
6668
|
-
};
|
|
6669
|
-
const emit = (rec, line, call) => {
|
|
6670
|
-
lastAt = Date.now();
|
|
6671
|
-
this.notify("task_progress", `task ${id} (${rec.label}): ${line}`, { id, steps, call: call.name });
|
|
6672
|
-
this.queueRevoice(`[task ${id} progress] ${line}`);
|
|
6673
|
-
};
|
|
6674
|
-
const timer = setInterval(() => {
|
|
6675
|
-
const rec = this.tasks.get(id);
|
|
6676
|
-
if (!rec || rec.status !== "running") return clearInterval(timer);
|
|
6677
|
-
if (!inflight || !due()) return;
|
|
6678
|
-
const last = inflight.tail.trim().split("\n").filter(Boolean).pop()?.slice(-80);
|
|
6679
|
-
emit(rec, `still inside ${describeCall(inflight.call)} \u2014 ${Math.round((Date.now() - inflight.at) / 1e3)}s on this step${last ? `, last output: ${last}` : ""}`, inflight.call);
|
|
6680
|
-
}, Math.max(this.options.progressIntervalMs, 250));
|
|
6681
|
-
timer.unref?.();
|
|
6682
|
-
return {
|
|
6683
|
-
pre: (call) => {
|
|
6684
|
-
inflight = { call, at: Date.now(), tail: "" };
|
|
6685
|
-
},
|
|
6686
|
-
output: (chunk) => {
|
|
6687
|
-
if (inflight) inflight.tail = (inflight.tail + chunk).slice(-500);
|
|
6688
|
-
},
|
|
6689
|
-
// digest only — NEVER re-voices directly
|
|
6690
|
-
post: (call) => {
|
|
6691
|
-
steps++;
|
|
6692
|
-
inflight = null;
|
|
6693
|
-
const rec = due();
|
|
6694
|
-
if (rec) emit(rec, `still running \u2014 ${steps} steps so far, now: ${describeCall(call)}`, call);
|
|
6695
|
-
}
|
|
6696
|
-
};
|
|
6697
|
-
}
|
|
6698
|
-
/** Park a question under `askId` (a task id, or any unique key for permission asks): re-voices
|
|
6699
|
-
* '[task <id> asks] …' and resolves with the user's answer via AnswerTask — or '' on timeout/
|
|
6700
|
-
* task settle (callers map '' to deny / best-judgment). Workers never block forever. */
|
|
6701
|
-
parkQuestion(askId, question) {
|
|
6702
|
-
return new Promise((resolve4) => {
|
|
6703
|
-
let settled = false;
|
|
6704
|
-
const finish = (answer) => {
|
|
6705
|
-
if (settled) return;
|
|
6706
|
-
settled = true;
|
|
6707
|
-
clearTimeout(timer);
|
|
6708
|
-
this.pendingAsks.delete(askId);
|
|
6709
|
-
resolve4(answer);
|
|
6710
|
-
};
|
|
6711
|
-
const timer = setTimeout(() => {
|
|
6712
|
-
this.notify("task_ask_timeout", `task ${askId}: question timed out \u2014 proceeding without an answer`);
|
|
6713
|
-
finish("");
|
|
6714
|
-
}, this.options.askTimeoutMs);
|
|
6715
|
-
this.pendingAsks.set(askId, { question, resolve: finish });
|
|
6716
|
-
this.notify("task_ask", `task ${askId} asks: ${question}`, { id: askId, question });
|
|
6717
|
-
this.queueRevoice(`[task ${askId} asks] ${question}
|
|
6718
|
-
(Relay this to the user in your own words. When they answer, call AnswerTask with id "${askId}" and their answer.)`);
|
|
6719
|
-
});
|
|
6720
|
-
}
|
|
6721
|
-
/** Resolve any question a settling/cancelled task left parked (its answer can no longer matter). */
|
|
6722
|
-
dropAsk(id) {
|
|
6723
|
-
this.pendingAsks.get(id)?.resolve("");
|
|
6724
|
-
}
|
|
6725
|
-
/** Build the INTEGRATION TURN prompt for a NON-CLEAN settled worker (early stop / failure). A clean
|
|
6726
|
-
* success never reaches here — it streams its own `<spoken>` delivery during the run. For a partial
|
|
6727
|
-
* or failed result the outcome re-enters the reflex as a decision (like a tool_result flowing back
|
|
6728
|
-
* into a normal agent loop): the reflex evaluates the outcome against the original intent and chooses
|
|
6729
|
-
* what to do next.
|
|
6730
|
-
*
|
|
6731
|
-
* Decision branches (the reflex acts on them with EXISTING tools — no new surface):
|
|
6732
|
-
* • accept → SPEAK the (partial) result plainly — don't dress a failure up as success.
|
|
6733
|
-
* • escalate → call `Think` with the SAME brief — only when Act failed/stalled AND a Think tier
|
|
6734
|
-
* exists AND this task wasn't already a follow-up (one hop max). Wires the dead
|
|
6735
|
-
* "Reserve Think for a problem Act already FAILED at" promise.
|
|
6736
|
-
* • re-delegate→ call `Act` with a CORRECTED brief — for a recoverable error / partial result.
|
|
6737
|
-
* • ask → ask the user ONE concrete question if genuinely blocked.
|
|
6738
|
-
*
|
|
6739
|
-
* Keeps the `[task <id> completed]` / `[task <id> failed]` opener so existing coalescing + the
|
|
6740
|
-
* failed-revoice fallback still fire, and the per-event transcript markers stay intact. */
|
|
6741
|
-
integrationPrompt(rec, outcome, body, finishReason) {
|
|
6742
|
-
const opener = outcome === "error" ? `[task ${rec.id} failed]` : `[task ${rec.id} completed]`;
|
|
6743
|
-
const underCap = this.autoEscalations < _DuplexAgent.MAX_AUTO_ESCALATIONS;
|
|
6744
|
-
const canEscalate = (outcome === "error" || outcome === "incomplete") && underCap;
|
|
6745
|
-
const hasThink = this.options.thinkModel !== false;
|
|
6746
|
-
const options = [];
|
|
6747
|
-
if (!rec.followUp && canEscalate && hasThink)
|
|
6748
|
-
options.push("ESCALATE to the Think tier (call Think with the same brief) if this is a hard/architectural problem the Act worker stalled or failed on");
|
|
6749
|
-
if (!rec.followUp && canEscalate)
|
|
6750
|
-
options.push("RE-DELEGATE to Act with a corrected brief if the failure looks recoverable (a wrong path, a fixable mistake)");
|
|
6751
|
-
options.push("ASK the user one short, concrete question if you genuinely cannot proceed without their input");
|
|
6752
|
-
options.push("ACCEPT and tell the user plainly what happened (don't dress a failure up as success)");
|
|
6753
|
-
const decision = options.length > 1 ? ` You must decide what to do next \u2014 choose ONE: ${options.map((o, i) => `(${i + 1}) ${o}`).join("; ")}. Pick exactly one and act on it; do not voice this as a finished success.` : ` Tell the user plainly what happened \u2014 do not present this as a finished success.`;
|
|
6754
|
-
const state = outcome === "error" ? `the worker FAILED with: ${body}` : `the worker STOPPED EARLY (${finishReason}) \u2014 its result is PARTIAL, not a finished success: ${body}`;
|
|
6755
|
-
return `${opener} Original request: "${rec.brief}". Outcome: ${state}.${decision}`;
|
|
6372
|
+
close() {
|
|
6373
|
+
this.closed = true;
|
|
6374
|
+
this.stopProbe();
|
|
6375
|
+
if (this.ws) this.ws.onclose = null;
|
|
6376
|
+
this.ws?.close();
|
|
6756
6377
|
}
|
|
6757
|
-
|
|
6758
|
-
|
|
6759
|
-
|
|
6760
|
-
|
|
6761
|
-
|
|
6762
|
-
|
|
6763
|
-
|
|
6764
|
-
|
|
6765
|
-
|
|
6766
|
-
|
|
6767
|
-
|
|
6378
|
+
};
|
|
6379
|
+
function base64ToBytes(b64) {
|
|
6380
|
+
if (typeof Buffer !== "undefined") return Buffer.from(b64, "base64");
|
|
6381
|
+
const bin = atob(b64);
|
|
6382
|
+
const out = new Uint8Array(bin.length);
|
|
6383
|
+
for (let i = 0; i < bin.length; i++) out[i] = bin.charCodeAt(i);
|
|
6384
|
+
return out;
|
|
6385
|
+
}
|
|
6386
|
+
|
|
6387
|
+
// src/voice/engine.ts
|
|
6388
|
+
init_logging();
|
|
6389
|
+
configureLogging((name) => {
|
|
6390
|
+
const l = forComponent(name);
|
|
6391
|
+
const at = (m) => (...a) => l[m]?.(...a);
|
|
6392
|
+
return { debug: at("debug"), verbose: at("verbose"), info: at("info"), warn: at("warn"), error: at("error") };
|
|
6393
|
+
});
|
|
6394
|
+
|
|
6395
|
+
// src/duplex.ts
|
|
6396
|
+
var log12 = forComponent("DuplexAgent");
|
|
6397
|
+
function describeCall(call) {
|
|
6398
|
+
const v = call.args && Object.values(call.args).find((x) => typeof x === "string" && x.trim());
|
|
6399
|
+
const hint = v ? ` (${String(v).replace(/\s+/g, " ").trim().slice(0, 48)})` : "";
|
|
6400
|
+
return `${call.name}${hint}`;
|
|
6401
|
+
}
|
|
6402
|
+
var DuplexAgentOptions = class {
|
|
6403
|
+
/** Any ai.libx.js AIClient — shared by all tiers (routed by model). */
|
|
6404
|
+
ai;
|
|
6405
|
+
/** The WORKER's filesystem (act + think). If omitted the worker keeps Agent's jailed-disk-at-cwd default. */
|
|
6406
|
+
fs;
|
|
6407
|
+
// The reflex IS the voice. 120b (not 20b) for channel discipline + instruction-following: the 20b
|
|
6408
|
+
// mislabels gpt-oss harmony channels under load, leaking raw analysis into the spoken `final` channel
|
|
6409
|
+
// (and misfiring Hold). 120b is the same price tier (~$0.15/$0.60) — the quality/cost trade is free.
|
|
6410
|
+
reflexModel = "groq/openai/gpt-oss-120b";
|
|
6411
|
+
actModel = "anthropic/claude-sonnet-4-6";
|
|
6412
|
+
/** Premium reasoning model. Set to `false` to disable the Think tier entirely. */
|
|
6413
|
+
thinkModel = "anthropic/claude-opus-4-8";
|
|
6414
|
+
/** Per-worker providerOptions, derived from the worker's actual model at spawn time (IoC — keeps duplex
|
|
6415
|
+
* provider-agnostic). Workers override the reflex/main model, so provider-specific options (e.g. cursor's
|
|
6416
|
+
* cwd/cursorSession) must be recomputed for the worker's model, never inherited from the main template —
|
|
6417
|
+
* leaking cursor options to an anthropic worker is a hard 400. Returns undefined → no providerOptions. */
|
|
6418
|
+
providerOptionsFor;
|
|
6419
|
+
/** Escape hatches merged over the derived per-agent options. */
|
|
6420
|
+
reflexOptions;
|
|
6421
|
+
actOptions;
|
|
6422
|
+
thinkOptions;
|
|
6423
|
+
/** Fresh-context check on each successful Act task: a NEW agent (no self-confirmation bias) re-reads
|
|
6424
|
+
* the file state against the brief and fixes any gap before the result is re-voiced. Bounded to one
|
|
6425
|
+
* pass; ~2x Act cost so default OFF. The self-verify FOOTER (same context) was measured ineffective —
|
|
6426
|
+
* this is the structural fix (see mind/10). Think tasks are pure reasoning, never checked. */
|
|
6427
|
+
verifyActTasks = false;
|
|
6428
|
+
/** Receives the voice text_delta stream + task lifecycle events. */
|
|
6429
|
+
host;
|
|
6430
|
+
/** How many recent transcript messages are rendered into a worker's brief. */
|
|
6431
|
+
excerptTurns = 6;
|
|
6432
|
+
/** Voice register: 'neutral' = clean spoken style; 'conversational' = human-like — fillers,
|
|
6433
|
+
* backchannels, impulsive first reactions before content (mimics real duplex conversation). */
|
|
6434
|
+
voiceStyle = "neutral";
|
|
6435
|
+
/** Teach the model to emit inline `[emotion]` tags for Cartesia emotion control. Only set when the
|
|
6436
|
+
* TTS actually speaks them — text-duplex (no TTS) would otherwise print literal tags. */
|
|
6437
|
+
emotionTags = false;
|
|
6438
|
+
/** Awaited BEFORE a worker spawns — open a per-task checkpoint frame, audit, etc.
|
|
6439
|
+
* (post-spawn would race the worker's first edits). */
|
|
6440
|
+
onTaskStart;
|
|
6441
|
+
/** Re-voice throttled worker progress asides ('[task t1 progress] …') so long tasks aren't dead
|
|
6442
|
+
* air. Off by default — each update costs a voice turn (LLM call + speech). */
|
|
6443
|
+
progressUpdates = false;
|
|
6444
|
+
/** Min ms between progress re-voices per task. */
|
|
6445
|
+
progressIntervalMs = 25e3;
|
|
6446
|
+
/** Relay worker questions (AskUserQuestion + permission asks via parkQuestion) through the VOICE:
|
|
6447
|
+
* the question re-voices as '[task <id> asks] …', the user answers conversationally, and the
|
|
6448
|
+
* voice model resolves it with the AnswerTask tool. Off → host.ask passthrough (text menus). */
|
|
6449
|
+
askRelay = false;
|
|
6450
|
+
/** Parked questions auto-resolve empty after this long (callers map '' to deny/best-judgment). */
|
|
6451
|
+
askTimeoutMs = 12e4;
|
|
6452
|
+
/** Max retained task records: oldest SETTLED tasks (and their activity tails) are evicted past this,
|
|
6453
|
+
* bounding memory over a long-lived session. Running tasks are never evicted. */
|
|
6454
|
+
maxTaskRecords = 50;
|
|
6455
|
+
/** Host overrides for QuickLook lookups (keyed by `what`). The engine's defaults go through the
|
|
6456
|
+
* (possibly jailed) fs — e.g. `.git/**` is deny-listed, so the CLI supplies 'branch' itself. */
|
|
6457
|
+
quickLook;
|
|
6458
|
+
/** Memory directory/directories on the WORKER fs. If set, the voice agent gets Remember + Recall
|
|
6459
|
+
* tools directly (no delegation needed) and implicit capture guidance. */
|
|
6460
|
+
memoryDir;
|
|
6461
|
+
/** User-scope memory dir for global facts (type=user/feedback). Forwarded to Remember's routing. */
|
|
6462
|
+
memoryUserDir;
|
|
6463
|
+
};
|
|
6464
|
+
var RESERVED_EVENT_MARKER = /\[task\b[^\]\n]*\b(?:completed|failed|progress|asks)\b/i;
|
|
6465
|
+
var RESERVED_EVENT_OPENER = /\[\s*task\b/i;
|
|
6466
|
+
var STAGE_DIRECTION_RE = /^\(\s*(?:(?:waiting|checking|searching|thinking|processing|loading|working|fetching|looking)\b[^)]*|[^)]*(?:\.\.\.|…)\s*)\)$/i;
|
|
6467
|
+
function nowLine() {
|
|
6468
|
+
return `Current date and time: ${(/* @__PURE__ */ new Date()).toLocaleString("en-US", { weekday: "long", year: "numeric", month: "long", day: "numeric", hour: "numeric", minute: "2-digit", timeZoneName: "short" })}`;
|
|
6469
|
+
}
|
|
6470
|
+
function isTrivialBarge(text) {
|
|
6471
|
+
const t = text.trim().toLowerCase().replace(/[.,!?…\s]+$/g, "").replace(/^[.,!?…\s]+/, "");
|
|
6472
|
+
if (!t) return false;
|
|
6473
|
+
if (/\b(stop|cancel|no|nope|nah|never\s?mind|nvm|forget it|drop it|don'?t|quiet|shut up|enough|hold on|wait|pause|hang on|actually)\b/.test(t)) return false;
|
|
6474
|
+
const core = t.replace(/^(?:oh|um+|uh+|er+|hmm+|ah+|well|so|okay|ok|yeah|yep)[\s,]+/, "").trim();
|
|
6475
|
+
return /^(?:oh|um+|uh+|er+|hmm+|ah+|sorry|oops|whoops|my bad|pardon|excuse me|apologies|go on|go ahead|continue|keep going|carry on|as you were|please continue|you were saying|sorry go on|sorry continue|go on then|go on please)$/.test(core || t);
|
|
6476
|
+
}
|
|
6477
|
+
var VOICE_SYSTEM_PROMPT = 'You are a spoken voice assistant \u2014 the user HEARS everything you say. Use short sentences. One idea per sentence. No markdown, no bullet lists, no code blocks, no headings, no emoji. Never emit stage directions or parenthetical asides about your own process \u2014 nothing like "(waiting for the result...)" or "(checking)"; while work runs, either say it as plain speech or end your turn.\nThis holds even when asked to "print", "list", "show", or "make a table" \u2014 there is no screen for the spoken channel. Speak it as flowing prose ("Tuesday is half a meter, Wednesday a bit less\u2026"), or if they truly need it on screen, route it to Act to render. Never emit dashes or pipes into speech.\nKeep turns SHORT \u2014 one to three sentences, then stop. Never lecture, enumerate cases, or add caveats unprompted. Conversation is a fast exchange: give the one thing asked, and let the user pull more if they want it.\nYou have three cognitive tiers \u2014 like a human brain:\n\u2022 YOU (reflex) \u2014 instant, lightweight. Handle greetings, simple questions, status checks, QuickLook.\n\u2022 `Act` \u2014 your hands. A background worker with its own configured tools and access to the user\'s environment (files and shell{{WORKER_WEB}}). Use for reading, editing, searching, running tasks, building \u2014 any real work.\n{{THINK_SLOT}}\nWhen you are unsure whether you can do or access something, do NOT assume and do NOT claim a capability you have not confirmed. To check what you can do, QuickLook `capabilities` (instant \u2014 it lists your worker\'s real tools) and answer from that. Never promise an ability that is not in your capabilities; if it is not there, tell the user plainly you can\'t. To actually DO real work, call `Act`. When the user mentions their project, folder, files, or environment ("this project", "the current folder", "my code"), call `Act` IMMEDIATELY \u2014 do not ask for paths or details the worker can discover itself. Never pretend to have done the work or invent results \u2014 the worker\'s report is your only source.\nYou cannot mute the microphone or stop voice capture yourself \u2014 no tool does it. If the user asks you to stop listening or turn the voice off, never claim you did: tell them to say exactly "voice off" (handled by the app directly), or type /voice.\nYou are NOT a knowledge base. For any question whose answer needs SPECIFIC verifiable facts you do not already have in hand \u2014 how to build/configure/implement something, exact API, library, entitlement, command or option names, current events, or particular numbers, dates, or names \u2014 do NOT answer from your own memory: you will confidently make things up (a fake API, a wrong entitlement, an event that did not happen). Route it to `Act`, which can search and verify, and speak only what its report says. DELEGATION RULE \u2014 decide for yourself, the user never has to push: if you cannot answer confidently from the conversation plus trivial well-known knowledge, do NOT refuse and do NOT guess \u2014 dispatch `Act` immediately with a clear brief and say you are checking. Anything needing CURRENT data (weather, news, prices, dates, sky/astronomy, "right now"), real computation, or verification is an automatic dispatch \u2014 never a refusal. The user should never need to say "search the web" or "think harder" to make you act; needing fresh or verified information IS the trigger. Refuse only what your worker genuinely cannot do (check `capabilities`), and say why. Answer inline ONLY for general conversation, chit-chat, and trivia you are sure of, or facts you can see via QuickLook. When elaborating on a completed task ("tell me more", "the gist"), stay strictly within what that result actually said \u2014 if the user asks for something the result did not cover, that is NEW information: dispatch `Act`, do not improvise.\nALWAYS react before you work: the FIRST thing in your turn is a brief spoken acknowledgement of what you heard and what you are about to do ("got it \u2014 opening that now", "sure, let me pull it up", "okay, checking"). NEVER call a tool (Act, Think, QuickLook) silently \u2014 the user must hear you react before you go quiet to work. After dispatching Act or Think, that same one short sentence IS your turn \u2014 end it and do not wait for the result. Exactly ONE short line: never stack a second acknowledgement, and never narrate your own presence or status while waiting ("I\'m here", "let me see", "still checking" right after you already acked). One clean ack then silence reads as competent; repeated check-ins read as nervous.\nA completed task speaks its OWN result to the user (the worker voices what matters as it finishes) \u2014 you do NOT re-voice clean task results. A FAILED or INCOMPLETE task still arrives as a "[task t1 failed] \u2026" event for you to handle. The completed result stays in YOUR context \u2014 it is yours to draw on. When the user follows up ("tell me more", "what else", "and?"), answer FROM that result first: you already have the detail, so elaborate on what you have. Do NOT spawn a fresh worker to re-search or re-gather what you were just handed. Re-dispatch ONLY when genuinely new information is needed \u2014 e.g. the user wants the full contents of a SPECIFIC source, which is one WebFetch of that URL, not a brand-new search. "[task t1 progress] \u2026" events are interim status, NOT results \u2014 on a genuinely LONG wait you MAY give one brief half-sentence aside, but only occasionally; silence while working is normal and fine (the user knows you are on it). Do NOT narrate every step or re-announce yourself. Never present progress as a finished result.\nCRITICAL: while a task is still running you have NO answer yet \u2014 never state a specific result of any kind (a number, size, count, name, path, or value). The real answer arrives ONLY in the "[task \u2026 completed]" event; inventing one meanwhile (a made-up disk size, commit count, etc.) is a serious error. Until then, only acknowledge and wait.\nNever read raw file paths, diffs, or code aloud verbatim.\nDo NOT end every turn with the same canned offer ("want a rundown?", "want the steps?"). Offer once at most; if the user pushes back, repeats themselves, or sounds unsatisfied ("you know what I mean?", "think deeper", "are you sure?"), do NOT re-offer the same thing \u2014 change approach: dispatch `Act`/`Think` to actually dig in, or ask one concrete clarifying question. Repeating a non-answer is worse than silence.\n"[task t1 asks] \u2026" events are QUESTIONS from a background task \u2014 relay to the user in your own words, short, then end your turn. When the user answers, call `AnswerTask` with that id and their answer. NEVER answer on the user\'s behalf for permissions or risky operations; if their reply is ambiguous, confirm first.\nIf the user\'s message sounds INCOMPLETE \u2014 trailing off mid-sentence, a fragment that needs more context ("and then we", "but the problem is"), hesitation fillers ("uh", "um") \u2014 call `Hold` instead of answering. This keeps listening for the rest of their thought. Only respond with substance when you have a complete question or request.\nDispatch discipline: send ONE self-contained task per request \u2014 a single worker with the full brief beats several workers with fragments (each worker starts fresh and re-discovers context). NEVER dispatch a worker just to read files or gather information \u2014 workers explore and discover context themselves; pass on what you already know and let one worker do the whole job. Split into parallel tasks only when the user asks for genuinely independent things. When a task completes, report its result and stop \u2014 do NOT dispatch follow-up work (verification, polish, extras) the user did not ask for, unless the report itself signals failure or doubt.\nDo not fire a second Act/Think for work already in flight, and NEVER spawn a second task to re-count, cross-check, or verify a result a worker already gave you \u2014 trust its answer; a single question gets ONE task. Call `TaskStatus` at most ONCE per turn; if a task is still running, give one brief status aside and end the turn \u2014 never poll it again and again in a loop. "Still on it" is ONLY for a repeat check on a task you already acknowledged earlier \u2014 NEVER as the ack when you first dispatch work ("still" is wrong when nothing was running yet; use a fresh "on it"/"got it, checking" instead). Use `CancelTask` when the user asks to stop something.\nPRIORITY: when the user says goodbye or wants to end/finish/wrap up the session ("ok bye", "that\'s all", "let\'s finish", "let\'s end", "goodnight", "exit", "wrap up"), call `ExitSession` IMMEDIATELY \u2014 do not act, do not check status, just exit.\nFor TRIVIAL instant lookups only \u2014 current time, git branch, listing a folder, peeking at a small file, or checking your own `capabilities`/tools \u2014 use `QuickLook` (instant, no task). Whenever the user asks what you can do or whether you have some ability, QuickLook `capabilities` and answer from that \u2014 never guess. Anything requiring searching, reasoning, running commands, or editing goes through `Act`.\n{{MEMORY_SLOT}}\nUser messages may arrive via speech-to-text and can carry transcription artifacts \u2014 odd words, cut-offs, homophones ("for you" vs "folder"). Read for INTENT, not surface text. If a message seems garbled, surprising, or only half-parses, do NOT guess an action or improvise content from it \u2014 briefly confirm what they meant ("did you mean\u2026?") and wait. A one-line confirm beats a confident wrong answer or an invented response to a request you did not actually understand.';
|
|
6478
|
+
var THINK_GUIDANCE = "\u2022 `Think` \u2014 your brain. A premium reasoning model, FAR more expensive than Act. Reserve it for open-ended architecture/design questions, or a problem Act already FAILED at. ALL implementation work \u2014 coding, refactoring, debugging, edge cases, tests \u2014 goes to Act; Act is highly capable. Never send the same work to both.";
|
|
6479
|
+
var THINK_DISABLED_GUIDANCE = "(Think tier is not available \u2014 use Act for all escalations.)";
|
|
6480
|
+
var VOICE_STYLE_CONVERSATIONAL = `Speak like a person in a live conversation, not an assistant reading a script. React first, then deliver: a quick impulsive beat ("oh nice", "hmm, hold on", "ah, got it") before the substance. Use contractions always. Vary sentence length \u2014 some very short. Light fillers and backchannels are fine ("mm-hm", "right", "let's see") but at most one per reply \u2014 never stack them. When you escalate to Act or Think, say it like a human would ("hang on, let me actually dig into that \u2014 gimme a minute") instead of announcing a task. When a result comes back, react to it like you just found out ("okay so \u2014 turns out\u2026"). Match the user's energy: a quick question gets a quick answer \u2014 a few words is a perfectly good turn. Prefer a short answer plus an offer ("want the details?") over covering everything. Never narrate your own mechanics (no "I will now act", no task ids out loud).`;
|
|
6481
|
+
var EMOTION_TAGS_GUIDANCE = `EMOTION: your voice is synthesized with emotion control. Prefix a sentence with an inline [emotion] tag, placed directly before the sentence it colors, to shape how it is spoken. Use it ONLY when the emotion genuinely fits the words (it amplifies real feeling, it cannot fake it) \u2014 do not tag every sentence; reserve it for moments that carry feeling, and vary which one you use. You may also drop [laughter] for a natural laugh. Available emotions: ${EMOTIONS.join(", ")}.`;
|
|
6482
|
+
var DuplexAgent = class _DuplexAgent {
|
|
6483
|
+
options;
|
|
6484
|
+
voice;
|
|
6485
|
+
tasks = /* @__PURE__ */ new Map();
|
|
6486
|
+
queue = Promise.resolve();
|
|
6487
|
+
seq = 0;
|
|
6488
|
+
pendingEvents = [];
|
|
6489
|
+
/** Spoken text of parked deliveries that have SETTLED, awaiting a trivial-barge resume decision on the
|
|
6490
|
+
* next turn (a substantive turn clears it — the result stays in the transcript, recoverable by asking). */
|
|
6491
|
+
parkedRedeliver = [];
|
|
6492
|
+
/** A trivial barge arrived while a parked delivery was STILL RUNNING → resume it the moment it settles. */
|
|
6493
|
+
awaitTrivialRedeliver = false;
|
|
6494
|
+
/** Set by a SUBSTANTIVE turn after a barge: the user moved on, so a parked delivery that settles LATER
|
|
6495
|
+
* must NOT arm a resume (else a much-later "go on" replays a stale result). Reset by a fresh barge. */
|
|
6496
|
+
suppressParkedResume = false;
|
|
6497
|
+
/** Out-of-band follow-up attribution for the events coalescing into the next flush turn: TRUE iff ≥1 of
|
|
6498
|
+
* the tasks being integrated was NON-CLEAN (early-stop/failure). Carried out-of-band on the enqueue call
|
|
6499
|
+
* by the caller that KNOWS the outcome — a plain boolean the MODEL CANNOT PERTURB. It is NOT scanned from
|
|
6500
|
+
* worker-authored event text (v1: an "Outcome:" substring over-stamped siblings) and NOT keyed on a brief
|
|
6501
|
+
* string the reflex re-authors (v2: a paraphrased escalation brief missed the Set → followUp:false →
|
|
6502
|
+
* RE-ENABLED unbounded auto-escalation, the dangerous runaway direction). See [[wrong-discriminator]] /
|
|
6503
|
+
* [[drive-real-reflex]] / [[fakeaiclient-blind-to-wire-format]]. */
|
|
6504
|
+
pendingNonClean = false;
|
|
6505
|
+
flushQueued = false;
|
|
6506
|
+
/** Per-voice-turn guards (reset by resetTurn at each turn's start). The reflex is a weak model:
|
|
6507
|
+
* left unguarded it polls TaskStatus after a dispatch and/or dispatches silently (dead air).
|
|
6508
|
+
* Like CC's Task tool, a dispatch is "said my piece, now wait for the push" — these enforce that. */
|
|
6509
|
+
turnDispatched = false;
|
|
6510
|
+
// an Act/Think fired this turn
|
|
6511
|
+
spokeBeforeDispatch = false;
|
|
6512
|
+
// the reflex ALREADY acked before dispatching — the forced post-dispatch text step must stay silent (live: "Got it…" twice)
|
|
6513
|
+
turnBriefs = /* @__PURE__ */ new Set();
|
|
6514
|
+
// briefs dispatched this turn (detect identical re-dispatch)
|
|
6515
|
+
spokeThisTurn = false;
|
|
6516
|
+
// any non-empty text_delta streamed this turn
|
|
6517
|
+
externalSpeech = false;
|
|
6518
|
+
// host spoke on our behalf (adaptive micro-ack) — not reflex output
|
|
6519
|
+
heldThisTurn = false;
|
|
6520
|
+
// Hold called this turn → turn is INTENTIONALLY silent (suppress reflex text + no dead-air ack)
|
|
6521
|
+
nudging = false;
|
|
6522
|
+
// re-ack pass in flight: block ALL tools, prevent recursion
|
|
6523
|
+
reflexBuf = "";
|
|
6524
|
+
// accumulated reflex text this turn (fabricated-event detection)
|
|
6525
|
+
reflexForwarded = 0;
|
|
6526
|
+
// chars of reflexBuf already forwarded to the host/TTS
|
|
6527
|
+
fabricationCut = false;
|
|
6528
|
+
// reflex emitted a reserved [task …] marker → suppress its tail
|
|
6529
|
+
/** TRUE for the duration of a re-voice turn that is integrating ≥1 NON-CLEAN task (turn-eligibility,
|
|
6530
|
+
* carried out-of-band — NOT derived from any worker/brief string). ANY Act/Think dispatched in such a
|
|
6531
|
+
* turn is stamped followUp:true. This GUARANTEES the dangerous direction is impossible: a genuine
|
|
6532
|
+
* escalation (even one with a paraphrased brief) ALWAYS lands in a non-clean integration turn, so it is
|
|
6533
|
+
* ALWAYS recognized as a follow-up and CANNOT re-escalate (one hop). The single-dispatch-per-turn guard
|
|
6534
|
+
* means at most one dispatch happens per flush, so realistically "the one dispatch IS the escalation".
|
|
6535
|
+
* ACCEPTED SAFE-DIRECTION ERROR: if the reflex instead dispatches FRESH unrelated work during a non-clean
|
|
6536
|
+
* flush (rare — and only possible when it batches multiple calls in one step, bypassing the guard), that
|
|
6537
|
+
* fresh task is over-stamped followUp:true and forgoes ONE future auto-escalation. That is SAFE (it only
|
|
6538
|
+
* ever REMOVES a future escalation, never adds one — no runaway) and is the correct side to err on. */
|
|
6539
|
+
turnFollowUp = false;
|
|
6540
|
+
/** Hard absolute backstop against runaway regardless of attribution: total automatic escalations across
|
|
6541
|
+
* the whole conversation. Once it hits MAX_AUTO_ESCALATIONS, no integration turn offers escalate/re-delegate. */
|
|
6542
|
+
autoEscalations = 0;
|
|
6543
|
+
static MAX_AUTO_ESCALATIONS = 8;
|
|
6544
|
+
/** Parked worker questions awaiting a (voice-relayed) user answer, keyed by ask id. */
|
|
6545
|
+
pendingAsks = /* @__PURE__ */ new Map();
|
|
6546
|
+
/** SPECULATIVE REFLEX (VoiceEngine.onSpeculate → speculate()): the reflex turn starts on a stable
|
|
6547
|
+
* PARTIAL transcript, its spoken output buffered — nothing reaches TTS until the endpointed final
|
|
6548
|
+
* confirms via send() (which flushes the buffer and adopts the call as THE turn). A divergent final
|
|
6549
|
+
* aborts it: output dropped, history rolled back, the final dispatches normally. */
|
|
6550
|
+
spec;
|
|
6551
|
+
/** Aborted speculative calls (double-billing visibility — each one paid for tokens never spoken). */
|
|
6552
|
+
speculativeAbortedCalls = 0;
|
|
6553
|
+
/** Tools the reflex may execute on UNCONFIRMED (speculated) input — read-only lookups and the
|
|
6554
|
+
* intentionally-silent Hold. Anything else (Act/Think/AnswerTask/CancelTask/ExitSession/memory
|
|
6555
|
+
* writes/…) is a side effect on input the user may not have said: the guard ABORTS the speculation
|
|
6556
|
+
* instead (the endpointed final then dispatches normally and may use the tool for real). */
|
|
6557
|
+
static SPEC_SAFE_TOOLS = /* @__PURE__ */ new Set(["QuickLook", "TaskStatus", "Hold"]);
|
|
6558
|
+
/** Lazily resolved memory tools (async loadMemory runs in initMemory). */
|
|
6559
|
+
memoryReady;
|
|
6560
|
+
constructor(options) {
|
|
6561
|
+
this.options = { ...new DuplexAgentOptions(), ...options };
|
|
6562
|
+
const o = this.options;
|
|
6563
|
+
if (o.memoryDir && o.fs) {
|
|
6564
|
+
this.memoryReady = loadMemory(o.fs, o.memoryDir, { maxWritesPerSession: 10, userDir: o.memoryUserDir });
|
|
6768
6565
|
}
|
|
6769
|
-
|
|
6770
|
-
|
|
6771
|
-
const
|
|
6772
|
-
|
|
6773
|
-
|
|
6774
|
-
|
|
6775
|
-
|
|
6776
|
-
|
|
6777
|
-
|
|
6778
|
-
|
|
6779
|
-
|
|
6780
|
-
|
|
6566
|
+
const memSlot = o.memoryDir && o.fs ? VOICE_MEMORY_PROMPT : "NEVER claim to have stored, saved, or remembered something durably \u2014 you cannot. Anything the user wants persisted (their name, preferences, notes) must go through Act so a worker writes it to memory.";
|
|
6567
|
+
const thinkSlot = o.thinkModel !== false ? THINK_GUIDANCE : THINK_DISABLED_GUIDANCE;
|
|
6568
|
+
const workerToolNames = (o.actOptions?.tools ?? []).map((t) => t.name);
|
|
6569
|
+
const canSearch = workerToolNames.some((n) => /WebSearch/i.test(n));
|
|
6570
|
+
const canFetch = workerToolNames.some((n) => /WebFetch/i.test(n));
|
|
6571
|
+
const workerWeb = canSearch ? `, and it CAN search the web and read web pages \u2014 so when the user gives you something specific to look up ("search for X", "find me\u2026", "what's the latest on\u2026"), route it to Act. But a bare capability QUESTION like "can you search the web?" just gets a short spoken "yes, I can" \u2014 do NOT dispatch and NEVER invent a query the user did not give you` : canFetch ? ", and it can fetch a specific web page URL (but cannot search the web)" : "";
|
|
6572
|
+
const mcpNames = [
|
|
6573
|
+
...Object.keys(o.actOptions?.providerOptions?.mcpServers ?? {}),
|
|
6574
|
+
...new Set(workerToolNames.filter((n) => n.startsWith("mcp__")).map((n) => n.slice(5).split("__")[0]))
|
|
6575
|
+
];
|
|
6576
|
+
const workerMcp = mcpNames.length ? `, and it can use these MCP servers: ${[...new Set(mcpNames)].join(", ")}` + (mcpNames.some((n) => /browser/i.test(n)) ? ' \u2014 including driving a REAL browser (open tabs, navigate, click, screenshot), so answer "yes" if asked whether you can control/drive a browser and route an actual browse to Act' : "") : "";
|
|
6577
|
+
const prompt = VOICE_SYSTEM_PROMPT.replace("{{MEMORY_SLOT}}", memSlot).replace("{{THINK_SLOT}}", thinkSlot).replace("{{WORKER_WEB}}", workerWeb + workerMcp) + (o.voiceStyle === "conversational" ? "\n" + VOICE_STYLE_CONVERSATIONAL : "") + (o.emotionTags ? "\n" + EMOTION_TAGS_GUIDANCE : "") + `
|
|
6578
|
+
${nowLine()}. Anchor every relative or time-sensitive reference \u2014 "today", "now", "current", "recent", "latest", "this year" \u2014 to THIS moment. When the user asks about something recent (news, sports, events), they mean near this date, not a well-known past instance; brief your worker with the current year so it searches for what is happening NOW, not a famous older event.`;
|
|
6579
|
+
const tools = [
|
|
6580
|
+
...o.reflexOptions?.tools ?? [],
|
|
6581
|
+
this.actTool(),
|
|
6582
|
+
...o.thinkModel !== false ? [this.thinkTool()] : [],
|
|
6583
|
+
this.taskStatusTool(),
|
|
6584
|
+
this.cancelTaskTool(),
|
|
6585
|
+
this.quickLookTool(),
|
|
6586
|
+
this.answerTaskTool(),
|
|
6587
|
+
this.holdTool()
|
|
6588
|
+
];
|
|
6589
|
+
const host = o.host;
|
|
6590
|
+
const voiceHost = host && {
|
|
6591
|
+
ask: host.ask ? (q2) => host.ask(q2) : void 0,
|
|
6592
|
+
confirm: host.confirm ? (p, m) => host.confirm(p, m) : void 0,
|
|
6593
|
+
notify: (ev) => {
|
|
6594
|
+
if (ev?.kind === "text_delta" && typeof ev.message === "string") {
|
|
6595
|
+
if (this.heldThisTurn) return;
|
|
6596
|
+
if (this.fabricationCut) return;
|
|
6597
|
+
if (this.turnDispatched && this.spokeBeforeDispatch) return;
|
|
6598
|
+
const msg = ev.message;
|
|
6599
|
+
this.reflexBuf += msg;
|
|
6600
|
+
this.scrubStageDirections();
|
|
6601
|
+
const m = this.reflexBuf.match(RESERVED_EVENT_MARKER) ?? this.reflexBuf.match(RESERVED_EVENT_OPENER);
|
|
6602
|
+
if (m) {
|
|
6603
|
+
this.fabricationCut = true;
|
|
6604
|
+
log12.warn(`reflex fabricated a [task \u2026] event in its spoken stream \u2014 cutting it (kept ${m.index} chars)`);
|
|
6605
|
+
const safe = this.reflexBuf.slice(this.reflexForwarded, m.index);
|
|
6606
|
+
if (!safe) return;
|
|
6607
|
+
if (safe.trim()) this.spokeThisTurn = true;
|
|
6608
|
+
this.emitHost({ ...ev, message: safe });
|
|
6609
|
+
return;
|
|
6610
|
+
}
|
|
6611
|
+
const held = this.reflexBuf.length - this.reflexForwarded;
|
|
6612
|
+
const partial = held > 0 && /\[\s*t?a?s?k?$/i.test(this.reflexBuf.slice(-Math.min(held, 6)));
|
|
6613
|
+
let upto = partial ? this.reflexBuf.length - this.reflexBuf.slice(-6).match(/\[\s*t?a?s?k?$/i)[0].length : this.reflexBuf.length;
|
|
6614
|
+
const paren = this.reflexBuf.lastIndexOf("(");
|
|
6615
|
+
if (paren >= this.reflexForwarded && !this.reflexBuf.includes(")", paren) && this.reflexBuf.length - paren <= 80)
|
|
6616
|
+
upto = Math.min(upto, paren);
|
|
6617
|
+
const out = this.reflexBuf.slice(this.reflexForwarded, upto);
|
|
6618
|
+
this.reflexForwarded = upto;
|
|
6619
|
+
if (!out) return;
|
|
6620
|
+
if (out.trim()) this.spokeThisTurn = true;
|
|
6621
|
+
this.emitHost({ ...ev, message: out });
|
|
6622
|
+
return;
|
|
6623
|
+
}
|
|
6624
|
+
host.notify?.(ev);
|
|
6625
|
+
}
|
|
6626
|
+
};
|
|
6627
|
+
this.voice = new Agent({
|
|
6628
|
+
ai: o.ai,
|
|
6629
|
+
fs: new MemFilesystem2(),
|
|
6630
|
+
model: o.reflexModel,
|
|
6631
|
+
stream: true,
|
|
6632
|
+
host: voiceHost,
|
|
6633
|
+
// The reflex IS the conversational channel — it confirms ambiguity inline ("did you mean…?"),
|
|
6634
|
+
// never via the blocking AskUserQuestion tool (Agent auto-adds it whenever a host is set). Left in,
|
|
6635
|
+
// it stalls a voice turn until the kill-switch. Worker questions still reach the user via parkQuestion.
|
|
6636
|
+
askUserQuestion: false,
|
|
6637
|
+
systemPrompt: prompt,
|
|
6638
|
+
instructionFiles: false,
|
|
6639
|
+
maxSteps: 8,
|
|
6640
|
+
timeoutMs: 3e4,
|
|
6641
|
+
...o.reflexOptions,
|
|
6642
|
+
tools,
|
|
6643
|
+
// Composed AFTER the spread so the dispatch guard can't be dropped by reflexOptions.
|
|
6644
|
+
hooks: composeHooks(this.dispatchGuard(), o.reflexOptions?.hooks)
|
|
6781
6645
|
});
|
|
6782
|
-
if (incomplete) {
|
|
6783
|
-
return this.queueRevoice(this.integrationPrompt(rec, "incomplete", res.text, res.finishReason), true);
|
|
6784
|
-
}
|
|
6785
|
-
const tail = rec.splitter?.flush();
|
|
6786
|
-
if (tail?.spoken && !rec.deliveryParked) this.options.host?.notify?.({ kind: "speak_utterance", message: tail.spoken });
|
|
6787
|
-
if (res.text.trim()) this.voice.transcript.push({ role: "assistant", content: res.text });
|
|
6788
|
-
if (rec.deliveryParked && !this.suppressParkedResume) {
|
|
6789
|
-
const gist = (rec.spokenText ?? "").trim() || res.text.trim();
|
|
6790
|
-
if (gist) {
|
|
6791
|
-
if (this.awaitTrivialRedeliver) {
|
|
6792
|
-
this.awaitTrivialRedeliver = false;
|
|
6793
|
-
this.options.host?.notify?.({ kind: "speak_utterance", message: gist });
|
|
6794
|
-
this.notify("diag", "parked_redelivered", { chars: gist.length });
|
|
6795
|
-
} else this.parkedRedeliver.push(gist);
|
|
6796
|
-
}
|
|
6797
|
-
}
|
|
6798
|
-
if (!rec.splitter?.spokeAny && res.text.trim() && !rec.deliveryParked)
|
|
6799
|
-
this.options.host?.notify?.({ kind: "speak_utterance", message: res.text });
|
|
6800
6646
|
}
|
|
6801
|
-
|
|
6802
|
-
|
|
6647
|
+
/** Resolve memory tools + inject index into voice system prompt (once). */
|
|
6648
|
+
async initMemory() {
|
|
6649
|
+
if (!this.memoryReady) return;
|
|
6650
|
+
const mem = await this.memoryReady;
|
|
6651
|
+
this.memoryReady = void 0;
|
|
6652
|
+
this.voice.options.tools.push(...mem.tools);
|
|
6653
|
+
if (mem.index) this.voice.options.systemPrompt += "\n\n" + mem.index;
|
|
6803
6654
|
}
|
|
6804
|
-
|
|
6805
|
-
|
|
6806
|
-
|
|
6807
|
-
|
|
6808
|
-
|
|
6809
|
-
|
|
6810
|
-
this.
|
|
6655
|
+
/** Flush any held-back trailing fragment (a possible `[task` opener that never completed) once the
|
|
6656
|
+
* turn's stream is done — so a legit message ending in "[t" isn't silently dropped. */
|
|
6657
|
+
flushHeldReflexTail() {
|
|
6658
|
+
if (this.fabricationCut) return;
|
|
6659
|
+
this.scrubStageDirections();
|
|
6660
|
+
const tail = this.reflexBuf.slice(this.reflexForwarded);
|
|
6661
|
+
this.reflexForwarded = this.reflexBuf.length;
|
|
6662
|
+
if (!tail) return;
|
|
6663
|
+
if (tail.trim()) this.spokeThisTurn = true;
|
|
6664
|
+
this.emitHost({ kind: "text_delta", message: tail });
|
|
6811
6665
|
}
|
|
6812
|
-
|
|
6813
|
-
|
|
6814
|
-
*
|
|
6815
|
-
|
|
6816
|
-
|
|
6817
|
-
|
|
6818
|
-
|
|
6819
|
-
|
|
6820
|
-
const i = tools.findIndex((t) => t.name === "Think");
|
|
6821
|
-
if (model === false && i >= 0) tools.splice(i, 1);
|
|
6822
|
-
else if (model !== false && i < 0) tools.push(this.thinkTool());
|
|
6666
|
+
/** Remove complete stage-direction parentheticals from the UNFORWARDED reflex text (STAGE_DIRECTION_RE).
|
|
6667
|
+
* Only the unforwarded region is touched — already-spoken audio can't be unsent, and splicing before
|
|
6668
|
+
* reflexForwarded would corrupt the forward offset. */
|
|
6669
|
+
scrubStageDirections() {
|
|
6670
|
+
if (this.reflexForwarded >= this.reflexBuf.length) return;
|
|
6671
|
+
const region = this.reflexBuf.slice(this.reflexForwarded);
|
|
6672
|
+
const scrubbed = region.replace(/\([^()]*\)/g, (s) => STAGE_DIRECTION_RE.test(s) ? "" : s);
|
|
6673
|
+
if (scrubbed !== region) this.reflexBuf = this.reflexBuf.slice(0, this.reflexForwarded) + scrubbed;
|
|
6823
6674
|
}
|
|
6824
|
-
/**
|
|
6825
|
-
|
|
6826
|
-
|
|
6827
|
-
|
|
6828
|
-
|
|
6829
|
-
|
|
6830
|
-
|
|
6831
|
-
|
|
6832
|
-
|
|
6833
|
-
this.
|
|
6834
|
-
this.
|
|
6835
|
-
|
|
6675
|
+
/** Clear the per-turn guards. Called at the head of every voice turn (user send + re-voice flush). */
|
|
6676
|
+
resetTurn() {
|
|
6677
|
+
this.turnDispatched = false;
|
|
6678
|
+
this.spokeBeforeDispatch = false;
|
|
6679
|
+
this.turnBriefs.clear();
|
|
6680
|
+
this.spokeThisTurn = false;
|
|
6681
|
+
this.externalSpeech = false;
|
|
6682
|
+
this.heldThisTurn = false;
|
|
6683
|
+
this.reflexBuf = "";
|
|
6684
|
+
this.reflexForwarded = 0;
|
|
6685
|
+
this.fabricationCut = false;
|
|
6686
|
+
this.turnFollowUp = false;
|
|
6687
|
+
this.voice.options.toolChoice = void 0;
|
|
6836
6688
|
}
|
|
6837
|
-
|
|
6689
|
+
/** preToolUse guard on the reflex: once it has dispatched this turn, a dispatch is "said my piece,
|
|
6690
|
+
* now wait for the push" (CC's Task model). Block the temptations — TaskStatus polling and identical
|
|
6691
|
+
* re-dispatch — so the only remaining move is to voice a short ack and end. A genuinely NEW Act is
|
|
6692
|
+
* still allowed (parallel independent work). During a re-ack pass, block every tool. */
|
|
6693
|
+
dispatchGuard() {
|
|
6838
6694
|
return {
|
|
6839
|
-
|
|
6840
|
-
|
|
6841
|
-
|
|
6842
|
-
|
|
6843
|
-
|
|
6844
|
-
properties: {
|
|
6845
|
-
brief: { type: "string", description: "full, self-contained instructions for the worker" },
|
|
6846
|
-
label: { type: "string", description: "a short (2-4 word) label for the task" }
|
|
6695
|
+
preToolUse: (call) => {
|
|
6696
|
+
if (this.spec?.state === "pending" && !_DuplexAgent.SPEC_SAFE_TOOLS.has(call.name)) {
|
|
6697
|
+
log12.verbose(`speculation aborted: reflex called ${call.name} on unconfirmed input`);
|
|
6698
|
+
this.abortSpeculation();
|
|
6699
|
+
return { block: true, reason: "Speculative turn aborted." };
|
|
6847
6700
|
}
|
|
6848
|
-
|
|
6849
|
-
|
|
6850
|
-
|
|
6851
|
-
|
|
6852
|
-
this.turnBriefs.
|
|
6853
|
-
|
|
6854
|
-
const id = await this.dispatch(String(brief ?? ""), "act", label ? String(label) : void 0, this.turnFollowUp);
|
|
6855
|
-
return this.spokeBeforeDispatch ? `Acting on task ${id}. You already acknowledged \u2014 end your turn now with NO further text; the result will arrive as a [task ${id} completed] event.` : `Acting on task ${id}. Acknowledge briefly; the result will arrive as a [task ${id} completed] event.`;
|
|
6701
|
+
if (this.nudging) return { block: true, reason: "Just say one short spoken acknowledgement \u2014 no tools this turn." };
|
|
6702
|
+
if (!this.turnDispatched) return;
|
|
6703
|
+
if (call.name === "TaskStatus")
|
|
6704
|
+
return { block: true, reason: "You just dispatched a task this turn \u2014 do NOT poll. Give one short spoken acknowledgement and end your turn; the result arrives later as a [task \u2026] event." };
|
|
6705
|
+
if ((call.name === "Act" || call.name === "Think") && this.turnBriefs.has(String(call.args?.brief ?? "")))
|
|
6706
|
+
return { block: true, reason: "You already dispatched this exact task \u2014 acknowledge briefly and end your turn." };
|
|
6856
6707
|
}
|
|
6857
6708
|
};
|
|
6858
6709
|
}
|
|
6859
|
-
|
|
6860
|
-
|
|
6861
|
-
|
|
6862
|
-
|
|
6863
|
-
|
|
6864
|
-
|
|
6865
|
-
required: ["brief"],
|
|
6866
|
-
properties: {
|
|
6867
|
-
brief: { type: "string", description: "the question or problem to reason about deeply" },
|
|
6868
|
-
label: { type: "string", description: "a short (2-4 word) label for the task" }
|
|
6869
|
-
}
|
|
6870
|
-
},
|
|
6871
|
-
run: async ({ brief, label }) => {
|
|
6872
|
-
this.spokeBeforeDispatch = this.spokeThisTurn;
|
|
6873
|
-
this.turnDispatched = true;
|
|
6874
|
-
this.turnBriefs.add(String(brief ?? ""));
|
|
6875
|
-
this.voice.options.toolChoice = "none";
|
|
6876
|
-
const id = await this.dispatch(String(brief ?? ""), "think", label ? String(label) : void 0, this.turnFollowUp);
|
|
6877
|
-
return this.spokeBeforeDispatch ? `Thinking on task ${id}. You already acknowledged \u2014 end your turn now with NO further text; the result will arrive as a [task ${id} completed] event.` : `Thinking on task ${id}. Acknowledge briefly; the result will arrive as a [task ${id} completed] event.`;
|
|
6878
|
-
}
|
|
6879
|
-
};
|
|
6710
|
+
/** The host spoke on this turn's behalf OUTSIDE the reflex stream (e.g. the voice engine's adaptive
|
|
6711
|
+
* micro-ack). For a DISPATCHED turn that's a sufficient ack (don't stack a second one); for an
|
|
6712
|
+
* inline turn whose reply came back empty it is NOT — "One sec." followed by permanent silence is
|
|
6713
|
+
* still dead air, so silentTurn ignores external speech unless work was dispatched. */
|
|
6714
|
+
noteExternalSpeech() {
|
|
6715
|
+
this.externalSpeech = true;
|
|
6880
6716
|
}
|
|
6881
|
-
|
|
6882
|
-
|
|
6883
|
-
|
|
6884
|
-
|
|
6885
|
-
|
|
6886
|
-
|
|
6887
|
-
|
|
6888
|
-
|
|
6889
|
-
return list.map((t) => `${t.id} (${t.label}): ${t.status}`).join("\n");
|
|
6890
|
-
}
|
|
6891
|
-
};
|
|
6717
|
+
/** True when the just-finished turn voiced NOTHING — dead air to repair. Two ways this happens:
|
|
6718
|
+
* (a) a dispatch with no spoken ack, and (b) an INLINE turn whose `final` channel came back empty —
|
|
6719
|
+
* gpt-oss harmony sometimes puts the whole reply in `analysis` (→ thinking_delta, suppressed in
|
|
6720
|
+
* voice) and emits an empty `final`, so no text_delta ever streams. Both ship silence; both repair.
|
|
6721
|
+
* Requires a host: without one there's no stream to detect speech on (and no one to speak to). */
|
|
6722
|
+
get silentTurn() {
|
|
6723
|
+
const ackedByHost = this.externalSpeech && this.turnDispatched;
|
|
6724
|
+
return !!this.options.host && !this.spokeThisTurn && !ackedByHost && !this.heldThisTurn;
|
|
6892
6725
|
}
|
|
6893
|
-
/**
|
|
6894
|
-
*
|
|
6895
|
-
*
|
|
6896
|
-
|
|
6897
|
-
const
|
|
6898
|
-
|
|
6899
|
-
|
|
6900
|
-
|
|
6901
|
-
|
|
6902
|
-
|
|
6903
|
-
|
|
6904
|
-
|
|
6905
|
-
|
|
6906
|
-
|
|
6907
|
-
|
|
6908
|
-
|
|
6909
|
-
|
|
6910
|
-
|
|
6911
|
-
|
|
6912
|
-
|
|
6913
|
-
const over = this.options.quickLook?.[String(what)];
|
|
6914
|
-
if (over) return await over(path ? String(path) : void 0);
|
|
6915
|
-
switch (String(what)) {
|
|
6916
|
-
case "capabilities": {
|
|
6917
|
-
const actTools = this.options.actOptions?.tools ?? [];
|
|
6918
|
-
const names = actTools.map((t) => t.name);
|
|
6919
|
-
const mcpServers = Object.keys(this.options.actOptions?.providerOptions?.mcpServers ?? {});
|
|
6920
|
-
const mcpNote = mcpServers.length ? ` Plus MCP servers your worker can use: ${mcpServers.join(", ")} (e.g. browser-bridge \u2192 drive a real browser: open tabs, navigate, click, screenshot).` : "";
|
|
6921
|
-
if (!names.length)
|
|
6922
|
-
return "Your worker uses Act's default local toolset (reading/editing files, running shell commands). No extra tools (e.g. web/internet) are configured; if a request is not a basic file or shell operation, assume you can't do it and say so." + mcpNote;
|
|
6923
|
-
const hasFetch = names.some((n) => /WebFetch/i.test(n));
|
|
6924
|
-
const hasBrowser = names.some((n) => /browser.*(navigate|click|page|type)/i.test(n));
|
|
6925
|
-
const hasSearch = names.some((n) => /(^|_)WebSearch$|search/i.test(n) && !/WebFetch|browser/i.test(n));
|
|
6926
|
-
const notes = [];
|
|
6927
|
-
if (hasFetch) notes.push("WebFetch retrieves ONE specific URL you are given \u2014 it is not a search engine.");
|
|
6928
|
-
if (hasBrowser) notes.push("The browser tools drive a real browser: you CAN open a site and, if needed, navigate to a search engine and search there \u2014 but it is manual and takes a moment, not an instant lookup.");
|
|
6929
|
-
else if (!hasSearch && hasFetch) notes.push('You have no general web-search tool, so for an instant "search the web" you can only fetch a URL they provide.');
|
|
6930
|
-
const webNote = notes.length ? " NOTE: " + notes.join(" ") : "";
|
|
6931
|
-
return `Tools your background worker (Act) can actually use: ${names.join(", ")}. Read each name literally and match the request to a SPECIFIC tool; if none fits, you do NOT have that ability \u2014 say so honestly.` + webNote + mcpNote;
|
|
6932
|
-
}
|
|
6933
|
-
case "time":
|
|
6934
|
-
return (/* @__PURE__ */ new Date()).toString();
|
|
6935
|
-
case "branch": {
|
|
6936
|
-
if (!fs) return "unavailable (no filesystem)";
|
|
6937
|
-
const head = (await fs.readFile(".git/HEAD")).trim();
|
|
6938
|
-
return head.startsWith("ref: refs/heads/") ? `branch: ${head.slice("ref: refs/heads/".length)}` : `detached HEAD at ${head.slice(0, 12)}`;
|
|
6939
|
-
}
|
|
6940
|
-
case "ls": {
|
|
6941
|
-
if (!fs) return "unavailable (no filesystem)";
|
|
6942
|
-
const p = String(path ?? ".");
|
|
6943
|
-
try {
|
|
6944
|
-
const names = await fs.readDir(p);
|
|
6945
|
-
return names.slice(0, 50).join("\n") + (names.length > 50 ? `
|
|
6946
|
-
\u2026 (+${names.length - 50} more)` : "");
|
|
6947
|
-
} catch {
|
|
6948
|
-
const names = await fs.readDir(".").catch(() => []);
|
|
6949
|
-
return `'${p}' not found here \u2014 you are likely already inside it. Current directory listing:
|
|
6950
|
-
` + names.slice(0, 50).join("\n") + (names.length > 50 ? `
|
|
6951
|
-
\u2026 (+${names.length - 50} more)` : "");
|
|
6952
|
-
}
|
|
6953
|
-
}
|
|
6954
|
-
case "file": {
|
|
6955
|
-
if (!fs) return "unavailable (no filesystem)";
|
|
6956
|
-
if (!path) return "file lookup needs a path";
|
|
6957
|
-
try {
|
|
6958
|
-
const text = await fs.readFile(String(path));
|
|
6959
|
-
return text.length > CAP2 ? text.slice(0, CAP2) + `
|
|
6960
|
-
\u2026 (truncated \u2014 ${text.length} chars total; Act for the full file)` : text;
|
|
6961
|
-
} catch {
|
|
6962
|
-
const names = await fs.readDir(".").catch(() => []);
|
|
6963
|
-
return `'${path}' not found. Current directory contains:
|
|
6964
|
-
` + names.slice(0, 50).join("\n");
|
|
6965
|
-
}
|
|
6966
|
-
}
|
|
6967
|
-
default:
|
|
6968
|
-
return `unknown lookup '${what}'`;
|
|
6969
|
-
}
|
|
6970
|
-
} catch (e) {
|
|
6971
|
-
return `lookup failed: ${e?.message ?? e}`;
|
|
6972
|
-
}
|
|
6973
|
-
}
|
|
6974
|
-
};
|
|
6726
|
+
/** A turn that voiced nothing is dead air. Re-prompt the reflex ONCE so the LLM itself voices a short
|
|
6727
|
+
* line (no template). If it STILL says nothing, fall back to a minimal line so silence never ships.
|
|
6728
|
+
* Wording adapts to whether work was dispatched (an ack) or the inline reply was simply lost. */
|
|
6729
|
+
async ackIfSilent(fallback) {
|
|
6730
|
+
const dispatched = this.turnDispatched;
|
|
6731
|
+
this.nudging = true;
|
|
6732
|
+
try {
|
|
6733
|
+
await this.voice.send(fallback ? "[reminder] You said nothing to the user this turn. Tell them, in ONE short spoken sentence, what just happened \u2014 no tools." : dispatched ? "[reminder] You dispatched a task but said nothing to the user. Say ONE short spoken acknowledgement now \u2014 no tools." : "[reminder] You said nothing to the user this turn. Give your ONE short spoken reply now \u2014 no tools.");
|
|
6734
|
+
} catch (e) {
|
|
6735
|
+
log12.warn(`ack nudge failed: ${e instanceof Error ? e.message : e}`);
|
|
6736
|
+
} finally {
|
|
6737
|
+
this.nudging = false;
|
|
6738
|
+
}
|
|
6739
|
+
if (!this.spokeThisTurn) {
|
|
6740
|
+
const pool = fallback ? [fallback] : dispatched ? _DuplexAgent.FALLBACK_ACKS : _DuplexAgent.FALLBACK_RETRY;
|
|
6741
|
+
const fresh = pool.filter((p) => p !== this.lastFallback);
|
|
6742
|
+
const line = (fresh.length ? fresh : pool)[Math.floor(Math.random() * (fresh.length || pool.length))];
|
|
6743
|
+
this.lastFallback = line;
|
|
6744
|
+
this.emitHost({ kind: "text_delta", message: line });
|
|
6745
|
+
}
|
|
6975
6746
|
}
|
|
6976
|
-
|
|
6977
|
-
|
|
6978
|
-
|
|
6979
|
-
|
|
6980
|
-
|
|
6981
|
-
|
|
6982
|
-
|
|
6983
|
-
|
|
6984
|
-
|
|
6985
|
-
|
|
6986
|
-
|
|
6987
|
-
|
|
6988
|
-
|
|
6989
|
-
|
|
6747
|
+
/** Dead-air fallback pools (see ackIfSilent). Both retry lines keep the 'say that again' phrase —
|
|
6748
|
+
* hosts/tests key on it. */
|
|
6749
|
+
static FALLBACK_ACKS = ["Okay, on it.", "On it.", "Alright, working on it."];
|
|
6750
|
+
static FALLBACK_RETRY = ["Sorry, could you say that again?", "Hm, I missed that \u2014 could you say that again?"];
|
|
6751
|
+
lastFallback = "";
|
|
6752
|
+
/** One user turn: the voice agent streams the reply (and may Act/Think). Serialized with re-voice turns.
|
|
6753
|
+
* If a speculative reflex call is pending and this content CONFIRMS it (the final matches the
|
|
6754
|
+
* speculated partial), the in-flight call is adopted as THE turn: its buffered output flushes to the
|
|
6755
|
+
* host NOW (this is the latency win) and streaming continues live. Any other content aborts the
|
|
6756
|
+
* speculation first (rolled back silently) and runs a normal turn behind it. */
|
|
6757
|
+
send(content) {
|
|
6758
|
+
if (typeof content === "string" && isTrivialBarge(content) && this.hasParkedDelivery()) {
|
|
6759
|
+
if (this.spec) this.abortSpeculation();
|
|
6760
|
+
return this.enqueue(async () => {
|
|
6761
|
+
this.resetTurn();
|
|
6762
|
+
if (!this.redeliverParked()) this.awaitTrivialRedeliver = true;
|
|
6763
|
+
return { text: "", steps: 0, finishReason: "stop", messages: [] };
|
|
6764
|
+
});
|
|
6765
|
+
}
|
|
6766
|
+
const spec = this.spec;
|
|
6767
|
+
if (spec?.state === "pending") {
|
|
6768
|
+
if (typeof content === "string" && speculationConfirms(spec.text, content)) {
|
|
6769
|
+
spec.state = "confirmed";
|
|
6770
|
+
spec.finalText = content;
|
|
6771
|
+
for (const ev of spec.buf.splice(0)) this.options.host?.notify?.(ev);
|
|
6772
|
+
spec.decide("confirm");
|
|
6773
|
+
this.notify("diag", "speculation_confirmed", { text: spec.text.slice(0, 80) });
|
|
6774
|
+
return spec.done;
|
|
6990
6775
|
}
|
|
6991
|
-
|
|
6776
|
+
this.abortSpeculation();
|
|
6777
|
+
}
|
|
6778
|
+
return this.enqueue(async () => {
|
|
6779
|
+
await this.initMemory();
|
|
6780
|
+
this.resetTurn();
|
|
6781
|
+
this.awaitTrivialRedeliver = false;
|
|
6782
|
+
this.parkedRedeliver = [];
|
|
6783
|
+
this.suppressParkedResume = true;
|
|
6784
|
+
const res = await this.voice.send(content);
|
|
6785
|
+
this.flushHeldReflexTail();
|
|
6786
|
+
if (this.silentTurn) await this.ackIfSilent();
|
|
6787
|
+
return res;
|
|
6788
|
+
});
|
|
6992
6789
|
}
|
|
6993
|
-
|
|
6994
|
-
|
|
6995
|
-
|
|
6996
|
-
|
|
6997
|
-
|
|
6998
|
-
|
|
6999
|
-
|
|
7000
|
-
|
|
6790
|
+
/** Start a HELD speculative reflex turn on a stable partial (VoiceEngine.onSpeculate). Its spoken
|
|
6791
|
+
* output buffers in emitHost; send() later confirms (flush + adopt) or aborts it. The turn holds the
|
|
6792
|
+
* voice mutex until that decision (bounded by a safety timeout), so no other turn can interleave
|
|
6793
|
+
* into the transcript between the speculative messages and their rollback. No-op if a speculation
|
|
6794
|
+
* is already in flight. */
|
|
6795
|
+
speculate(text) {
|
|
6796
|
+
if (!text.trim() || this.spec) return;
|
|
6797
|
+
let decide;
|
|
6798
|
+
const decision = new Promise((r) => {
|
|
6799
|
+
decide = r;
|
|
6800
|
+
});
|
|
6801
|
+
const spec = {
|
|
6802
|
+
text,
|
|
6803
|
+
state: "pending",
|
|
6804
|
+
buf: [],
|
|
6805
|
+
ctl: new AbortController(),
|
|
6806
|
+
decide,
|
|
6807
|
+
decision,
|
|
6808
|
+
done: void 0
|
|
6809
|
+
};
|
|
6810
|
+
this.spec = spec;
|
|
6811
|
+
spec.done = this.enqueue(async () => {
|
|
6812
|
+
const empty = { text: "", steps: 0, finishReason: "aborted", messages: this.voice.transcript };
|
|
6813
|
+
if (spec.state === "aborted") {
|
|
6814
|
+
this.speculativeAbortedCalls++;
|
|
6815
|
+
if (this.spec === spec) this.spec = void 0;
|
|
6816
|
+
return empty;
|
|
6817
|
+
}
|
|
6818
|
+
await this.initMemory();
|
|
6819
|
+
this.resetTurn();
|
|
6820
|
+
const base = this.voice.transcript.length;
|
|
6821
|
+
const prevSignal = this.voice.options.signal;
|
|
6822
|
+
this.voice.options.signal = spec.ctl.signal;
|
|
6823
|
+
let res;
|
|
6824
|
+
try {
|
|
6825
|
+
res = await this.voice.send(spec.text);
|
|
6826
|
+
} catch (e) {
|
|
6827
|
+
log12.warn(`speculative turn failed: ${e instanceof Error ? e.message : e}`);
|
|
6828
|
+
} finally {
|
|
6829
|
+
this.voice.options.signal = prevSignal;
|
|
6830
|
+
}
|
|
6831
|
+
const timer = setTimeout(() => {
|
|
6832
|
+
spec.state = spec.state === "pending" ? "aborted" : spec.state;
|
|
6833
|
+
spec.decide("abort");
|
|
6834
|
+
}, 1e4);
|
|
6835
|
+
timer.unref?.();
|
|
6836
|
+
const d = await spec.decision;
|
|
6837
|
+
clearTimeout(timer);
|
|
6838
|
+
if (d === "abort") {
|
|
6839
|
+
if (this.voice.transcript.length > base) this.voice.transcript.length = base;
|
|
6840
|
+
this.speculativeAbortedCalls++;
|
|
6841
|
+
log12.verbose(`speculation aborted (${this.speculativeAbortedCalls} total): "${spec.text.slice(0, 50)}"`);
|
|
6842
|
+
if (this.spec === spec) this.spec = void 0;
|
|
6843
|
+
return res ?? empty;
|
|
6844
|
+
}
|
|
6845
|
+
for (let i = base; i < this.voice.transcript.length; i++) {
|
|
6846
|
+
const m = this.voice.transcript[i];
|
|
6847
|
+
if (m.role === "user" && contentText(m.content) === spec.text) {
|
|
6848
|
+
m.content = spec.finalText;
|
|
6849
|
+
break;
|
|
7001
6850
|
}
|
|
7002
|
-
},
|
|
7003
|
-
run: async ({ filler }) => {
|
|
7004
|
-
this.heldThisTurn = true;
|
|
7005
|
-
this.notify("hold_filler", filler ? String(filler) : "");
|
|
7006
|
-
return "Holding \u2014 listening for the rest of the user's thought. Do not respond further this turn.";
|
|
7007
6851
|
}
|
|
7008
|
-
|
|
6852
|
+
this.spec = void 0;
|
|
6853
|
+
this.flushHeldReflexTail();
|
|
6854
|
+
if (this.silentTurn) await this.ackIfSilent();
|
|
6855
|
+
return res ?? empty;
|
|
6856
|
+
});
|
|
7009
6857
|
}
|
|
7010
|
-
|
|
7011
|
-
|
|
7012
|
-
|
|
7013
|
-
|
|
7014
|
-
|
|
7015
|
-
|
|
7016
|
-
|
|
6858
|
+
/** Abort a pending speculation (idempotent): kill the in-flight call, drop its buffered output.
|
|
6859
|
+
* Called on divergence (send), a stale partial (VoiceEngine.onSpeculateAbort), a side-effect tool
|
|
6860
|
+
* attempt (dispatchGuard), or host paths that will never dispatch a final (commands, voice-off). */
|
|
6861
|
+
abortSpeculation() {
|
|
6862
|
+
const spec = this.spec;
|
|
6863
|
+
if (spec?.state !== "pending") return;
|
|
6864
|
+
spec.state = "aborted";
|
|
6865
|
+
spec.buf.length = 0;
|
|
6866
|
+
spec.ctl.abort();
|
|
6867
|
+
spec.decide("abort");
|
|
6868
|
+
this.notify("diag", "speculation_aborted", { text: spec.text.slice(0, 80) });
|
|
7017
6869
|
}
|
|
7018
|
-
|
|
7019
|
-
|
|
7020
|
-
|
|
7021
|
-
|
|
7022
|
-
|
|
7023
|
-
|
|
7024
|
-
|
|
7025
|
-
|
|
7026
|
-
|
|
7027
|
-
|
|
7028
|
-
|
|
7029
|
-
|
|
7030
|
-
|
|
7031
|
-
|
|
7032
|
-
|
|
7033
|
-
|
|
7034
|
-
|
|
6870
|
+
/** Cancel a running background task — shared by the CancelTask tool and the CLI /tasks picker. */
|
|
6871
|
+
cancelTask(id) {
|
|
6872
|
+
const rec = this.tasks.get(id);
|
|
6873
|
+
if (!rec) return `No task '${id}'.`;
|
|
6874
|
+
if (rec.status !== "running") return `Task ${rec.id} is already ${rec.status}.`;
|
|
6875
|
+
rec.status = "cancelled";
|
|
6876
|
+
rec.controller.abort();
|
|
6877
|
+
return `Task ${rec.id} (${rec.label}) cancelled.`;
|
|
6878
|
+
}
|
|
6879
|
+
/** Barge-in: the user took the floor while task(s) were running. Suppress those tasks' remaining SPOKEN
|
|
6880
|
+
* delivery so a superseded topic never talks over the new one (the debt-after-jokes regression). The
|
|
6881
|
+
* tasks keep running and still fold their result into the transcript — recoverable, just not spoken.
|
|
6882
|
+
* Returns the parked ids (for logging). Does NOT cancel: that's a deliberate reflex/user action. */
|
|
6883
|
+
parkInFlightDeliveries() {
|
|
6884
|
+
this.suppressParkedResume = false;
|
|
6885
|
+
const parked = [];
|
|
6886
|
+
for (const rec of this.tasks.values())
|
|
6887
|
+
if (rec.status === "running" && !rec.deliveryParked) {
|
|
6888
|
+
rec.deliveryParked = true;
|
|
6889
|
+
parked.push(rec.id);
|
|
7035
6890
|
}
|
|
7036
|
-
|
|
7037
|
-
const text = texts.join("\n");
|
|
7038
|
-
if (text || images.length) return { text, ...images.length ? { images } : {} };
|
|
6891
|
+
return parked;
|
|
7039
6892
|
}
|
|
7040
|
-
|
|
7041
|
-
|
|
7042
|
-
|
|
7043
|
-
|
|
7044
|
-
|
|
7045
|
-
|
|
7046
|
-
|
|
7047
|
-
|
|
7048
|
-
|
|
7049
|
-
|
|
6893
|
+
/** True while there is a parked delivery to potentially resume: either one already settled (queued) or
|
|
6894
|
+
* one still running that was parked by a barge. */
|
|
6895
|
+
hasParkedDelivery() {
|
|
6896
|
+
return this.parkedRedeliver.length > 0 || [...this.tasks.values()].some((t) => t.status === "running" && t.deliveryParked);
|
|
6897
|
+
}
|
|
6898
|
+
/** Speak any settled-and-queued parked delivery now (trivial-barge resume). Returns false if nothing was
|
|
6899
|
+
* queued yet (the caller then arms awaitTrivialRedeliver so the task resumes the instant it settles). */
|
|
6900
|
+
redeliverParked() {
|
|
6901
|
+
if (!this.parkedRedeliver.length) return false;
|
|
6902
|
+
const text = this.parkedRedeliver.splice(0).join(" ").trim();
|
|
6903
|
+
if (text) {
|
|
6904
|
+
this.options.host?.notify?.({ kind: "speak_utterance", message: text });
|
|
6905
|
+
this.notify("diag", "parked_redelivered", { chars: text.length });
|
|
7050
6906
|
}
|
|
7051
|
-
|
|
7052
|
-
}
|
|
7053
|
-
|
|
7054
|
-
|
|
7055
|
-
|
|
7056
|
-
|
|
7057
|
-
|
|
7058
|
-
|
|
7059
|
-
|
|
7060
|
-
|
|
7061
|
-
function makeMcpToolSearch(specs, callTool, options = {}) {
|
|
7062
|
-
const maxResults = options.maxResults ?? 10;
|
|
7063
|
-
const byName = new Map(specs.map((s) => [s.name, s]));
|
|
7064
|
-
const catalogLine = `${specs.length} MCP tool(s) available \u2014 search by keyword, then call by exact name.`;
|
|
7065
|
-
const searchTool = {
|
|
7066
|
-
name: "ToolSearch",
|
|
7067
|
-
description: `Search the available MCP tools by keyword (${catalogLine}). Returns matching tool names + their argument schemas; call one with \`McpCall\`.`,
|
|
7068
|
-
parameters: { type: "object", required: ["query"], properties: { query: { type: "string", description: "keywords to match against tool name + description" } } },
|
|
7069
|
-
async run({ query }) {
|
|
7070
|
-
const q2 = String(query ?? "").trim();
|
|
7071
|
-
if (!q2) return catalogLine;
|
|
7072
|
-
const { kept } = topByRelevance(specs, q2, (s) => `${s.name} ${s.description ?? ""}`, maxResults);
|
|
7073
|
-
if (!kept.length) return `(no MCP tool matches "${q2}" \u2014 try broader keywords)`;
|
|
7074
|
-
return kept.map(describeSpec).join("\n");
|
|
6907
|
+
return true;
|
|
6908
|
+
}
|
|
6909
|
+
/** Resolve when all queued voice turns AND all in-flight worker tasks have settled (tests, graceful shutdown). */
|
|
6910
|
+
async idle() {
|
|
6911
|
+
while (true) {
|
|
6912
|
+
const q2 = this.queue;
|
|
6913
|
+
await q2.catch(() => {
|
|
6914
|
+
});
|
|
6915
|
+
await Promise.all([...this.tasks.values()].map((t) => t.promise));
|
|
6916
|
+
if (this.queue === q2 && ![...this.tasks.values()].some((t) => t.status === "running")) return;
|
|
7075
6917
|
}
|
|
7076
|
-
}
|
|
7077
|
-
|
|
7078
|
-
|
|
7079
|
-
|
|
7080
|
-
|
|
7081
|
-
|
|
7082
|
-
|
|
7083
|
-
|
|
7084
|
-
|
|
7085
|
-
|
|
6918
|
+
}
|
|
6919
|
+
/** Promise-chain mutex: turns run strictly one at a time; a failed turn doesn't poison the chain. */
|
|
6920
|
+
enqueue(fn) {
|
|
6921
|
+
const run = this.queue.then(fn, fn);
|
|
6922
|
+
this.queue = run.then(() => {
|
|
6923
|
+
}, () => {
|
|
6924
|
+
});
|
|
6925
|
+
return run;
|
|
6926
|
+
}
|
|
6927
|
+
notify(kind, message, data) {
|
|
6928
|
+
this.emitHost({ kind, message, data });
|
|
6929
|
+
}
|
|
6930
|
+
/** Host-boundary emit for the reflex's spoken channel: during a PENDING speculation, text_delta and
|
|
6931
|
+
* hold_filler are BUFFERED (nothing may reach TTS on unconfirmed input); confirm flushes them in
|
|
6932
|
+
* order, abort drops them silently. Everything else (task_* lifecycle, worker speak_utterance —
|
|
6933
|
+
* which bypasses this via host.notify directly) passes through untouched. */
|
|
6934
|
+
emitHost(ev) {
|
|
6935
|
+
const spec = this.spec;
|
|
6936
|
+
if (spec && (ev.kind === "text_delta" || ev.kind === "hold_filler")) {
|
|
6937
|
+
if (spec.state === "pending") {
|
|
6938
|
+
spec.buf.push(ev);
|
|
6939
|
+
return;
|
|
7086
6940
|
}
|
|
7087
|
-
|
|
7088
|
-
async run({ name, args }) {
|
|
7089
|
-
const n = String(name ?? "");
|
|
7090
|
-
if (!byName.has(n)) return `Error: unknown MCP tool '${n}'. Use ToolSearch to find valid names.`;
|
|
7091
|
-
const r = toResult(await callTool(n, args ?? {}));
|
|
7092
|
-
return r.images?.length ? r : r.text;
|
|
7093
|
-
}
|
|
7094
|
-
};
|
|
7095
|
-
return [searchTool, callMcpTool];
|
|
7096
|
-
}
|
|
7097
|
-
function buildMcpCatalog(servers) {
|
|
7098
|
-
const specs = [];
|
|
7099
|
-
const routes = /* @__PURE__ */ new Map();
|
|
7100
|
-
for (const m of servers) {
|
|
7101
|
-
for (const s of m.specs) {
|
|
7102
|
-
const base = `mcp__${m.name}__${s.name}`.replace(/[^a-zA-Z0-9_-]/g, "_").slice(0, 128);
|
|
7103
|
-
let display = base;
|
|
7104
|
-
for (let i = 2; routes.has(display); i++) display = `${base.slice(0, 128 - String(i).length - 1)}_${i}`;
|
|
7105
|
-
specs.push({ name: display, description: s.description, inputSchema: s.inputSchema });
|
|
7106
|
-
routes.set(display, { server: m.name, rawName: s.name });
|
|
6941
|
+
if (spec.state === "aborted") return;
|
|
7107
6942
|
}
|
|
6943
|
+
this.options.host?.notify?.(ev);
|
|
7108
6944
|
}
|
|
7109
|
-
|
|
7110
|
-
|
|
7111
|
-
|
|
7112
|
-
|
|
7113
|
-
|
|
7114
|
-
|
|
7115
|
-
|
|
7116
|
-
|
|
7117
|
-
|
|
7118
|
-
|
|
7119
|
-
|
|
7120
|
-
|
|
7121
|
-
|
|
7122
|
-
|
|
7123
|
-
|
|
7124
|
-
|
|
7125
|
-
|
|
7126
|
-
|
|
6945
|
+
/** Queue a `[task …]` event for re-voicing. Events arriving while the voice is busy coalesce into ONE turn.
|
|
6946
|
+
* `nonClean` (out-of-band boolean, set by the caller that KNOWS this event integrates a NON-CLEAN outcome)
|
|
6947
|
+
* marks the coalesced flush as a non-clean integration turn — turn-eligibility, never inferred from event
|
|
6948
|
+
* text and never keyed on a (re-authored) brief string. Any dispatch in such a turn is a follow-up. */
|
|
6949
|
+
queueRevoice(event, nonClean = false) {
|
|
6950
|
+
this.pendingEvents.push(event);
|
|
6951
|
+
if (nonClean) this.pendingNonClean = true;
|
|
6952
|
+
if (this.flushQueued) return;
|
|
6953
|
+
this.flushQueued = true;
|
|
6954
|
+
void this.enqueue(async () => {
|
|
6955
|
+
this.flushQueued = false;
|
|
6956
|
+
const events = this.pendingEvents.splice(0);
|
|
6957
|
+
const nonCleanTurn = this.pendingNonClean;
|
|
6958
|
+
this.pendingNonClean = false;
|
|
6959
|
+
if (!events.length) return;
|
|
6960
|
+
const failed = events.find((e) => /^\[task\b[^\]\n]*\bfailed\b/i.test(e));
|
|
6961
|
+
this.resetTurn();
|
|
6962
|
+
this.turnFollowUp = nonCleanTurn;
|
|
6963
|
+
await this.voice.send(events.join("\n"));
|
|
6964
|
+
this.flushHeldReflexTail();
|
|
6965
|
+
if (this.silentTurn) await this.ackIfSilent(failed ? "Sorry, that didn't work \u2014 the task failed." : void 0);
|
|
6966
|
+
this.notify("revoice_done", "");
|
|
6967
|
+
});
|
|
6968
|
+
}
|
|
6969
|
+
/** The worker's brief: the Act/Think args + a STATIC text snapshot of the recent conversation.
|
|
6970
|
+
* Act briefs get a self-verify footer — the worker's report is trusted without review, so it
|
|
6971
|
+
* must check its own work before reporting (nearly free under prompt caching; measured honest:
|
|
6972
|
+
* it does NOT fix one-shot logic bugs — see mind/10). Think tasks are pure reasoning — no footer. */
|
|
6973
|
+
buildBrief(brief, tier = "act", deliver = true) {
|
|
6974
|
+
const recent = this.voice.transcript.filter((m) => (m.role === "user" || m.role === "assistant") && contentText(m.content).trim()).slice(-this.options.excerptTurns).map((m) => `${m.role}: ${contentText(m.content)}`).join("\n");
|
|
6975
|
+
const verify = tier === "act" ? "\n\nBefore reporting done: re-read what you changed and check it against EVERY requirement above \u2014 fix any gap first. Your report is trusted without review." : "";
|
|
6976
|
+
const deliverContract = deliver ? `
|
|
7127
6977
|
|
|
7128
|
-
|
|
7129
|
-
|
|
6978
|
+
## DELIVER (spoken delivery)
|
|
6979
|
+
You are reporting back to a user who is LISTENING. Stream your work normally \u2014 your prose is the written work record and detail, and is NOT spoken. Wrap anything the user should HEAR in <spoken>\u2026</spoken> tags. LEAD WITH the actual content they asked for: if they asked for a specific piece of content \u2014 a value, a name, the actual lines, the writing itself \u2014 that content goes INSIDE the <spoken> tags, not a remark about it. Your FIRST <spoken> segment is substantive \u2014 never a greeting or an acknowledgement (the front-end has already acked; do not double-ack). Keep spoken text concise and natural for the ear: short sentences, no markdown. NEVER enumerate in speech \u2014 no numbered or bulleted lists ("One. \u2026 Two. \u2026" is robotic). Deliver multiple items as flowing conversation with brief connective phrasing ("here's one\u2026", "and another\u2026", "oh, and\u2026"), pausing between items with sentence breaks, not numbers.` + (this.options.emotionTags ? " Inside <spoken>, you may prefix a sentence with an inline [emotion] tag (e.g. [excited], [curious]) to color how it is voiced \u2014 only when it genuinely fits, and vary it; [laughter] gives a natural laugh." : "") : "";
|
|
6980
|
+
return `${nowLine()}.
|
|
7130
6981
|
|
|
7131
|
-
|
|
7132
|
-
var STT_SAMPLE_RATE = 16e3;
|
|
7133
|
-
var TTS_SAMPLE_RATE = 44100;
|
|
7134
|
-
async function resolveAuth(auth) {
|
|
7135
|
-
return typeof auth === "function" ? await auth() : auth;
|
|
7136
|
-
}
|
|
6982
|
+
` + (recent ? `${brief}
|
|
7137
6983
|
|
|
7138
|
-
|
|
7139
|
-
|
|
7140
|
-
var now = () => performance.now();
|
|
7141
|
-
var SonioxSTTOptions = class {
|
|
7142
|
-
auth = "";
|
|
7143
|
-
source;
|
|
7144
|
-
model = "stt-rt-preview";
|
|
7145
|
-
languageHints = ["en"];
|
|
7146
|
-
/** Client-side endpoint: finalized text + no new tokens for this long = utterance (don't wait for
|
|
7147
|
-
* Soniox's semantic <end>, which adds 0.5-1.5s — the difference between ping-pong and lag). */
|
|
7148
|
-
silenceEndpointMs = 500;
|
|
7149
|
-
/** No-audio watchdog: if the mic source stops delivering chunks for this long, capture is dead →
|
|
7150
|
-
* fire onFatal + stop (else Soniox idle-timeouts and reconnect-loops forever). 0 = disable. */
|
|
7151
|
-
noAudioTimeoutMs = 1e4;
|
|
7152
|
-
};
|
|
7153
|
-
var SonioxSTT = class {
|
|
7154
|
-
options;
|
|
7155
|
-
ws;
|
|
7156
|
-
stopped = false;
|
|
7157
|
-
sourceStarted = false;
|
|
7158
|
-
onPartial = () => {
|
|
7159
|
-
};
|
|
7160
|
-
onUtterance = () => {
|
|
7161
|
-
};
|
|
7162
|
-
/** mic energy (RMS) per chunk — drives the energy-based heuristic barge-in tier */
|
|
7163
|
-
onLevel = () => {
|
|
7164
|
-
};
|
|
7165
|
-
/** Unrecoverable: the mic source stopped delivering audio (Soniox starves → idle-timeout reconnect
|
|
7166
|
-
* loop). The host tears voice down instead of spinning forever. */
|
|
7167
|
-
onFatal = () => {
|
|
7168
|
-
};
|
|
7169
|
-
/** Diagnostic tap (provider errors, ws reconnects, no-audio watchdog). Fire-and-forget: a throwing
|
|
7170
|
-
* handler disables itself — never affects transcription. Wired by VoiceIO / the lab bridge. */
|
|
7171
|
-
onDiag = () => {
|
|
7172
|
-
};
|
|
7173
|
-
diagOn = true;
|
|
7174
|
-
diag(kind, fields) {
|
|
7175
|
-
if (!this.diagOn) return;
|
|
7176
|
-
try {
|
|
7177
|
-
this.onDiag({ t: now(), kind, ...fields });
|
|
7178
|
-
} catch (e) {
|
|
7179
|
-
this.diagOn = false;
|
|
7180
|
-
log11.debug(`onDiag threw \u2014 STT diagnostics disabled: ${e instanceof Error ? e.message : e}`);
|
|
7181
|
-
}
|
|
7182
|
-
}
|
|
7183
|
-
lastChunkAt = 0;
|
|
7184
|
-
// timestamp of the most recent mic chunk (0 = none yet)
|
|
7185
|
-
startedChunksAt = 0;
|
|
7186
|
-
// when capture started (grace before the first chunk)
|
|
7187
|
-
noAudioTimer = null;
|
|
7188
|
-
finalText = "";
|
|
7189
|
-
partialText = "";
|
|
7190
|
-
lastChangeAt = 0;
|
|
7191
|
-
lastCombined = "";
|
|
7192
|
-
endpointTimer = null;
|
|
7193
|
-
firstTokenAt = 0;
|
|
7194
|
-
// first speech token in current utterance
|
|
7195
|
-
constructor(options) {
|
|
7196
|
-
this.options = { ...new SonioxSTTOptions(), ...options };
|
|
7197
|
-
}
|
|
7198
|
-
get usingAec() {
|
|
7199
|
-
return this.options.source?.aec ?? false;
|
|
6984
|
+
## Recent conversation (for context)
|
|
6985
|
+
${recent}` : brief) + verify + deliverContract;
|
|
7200
6986
|
}
|
|
7201
|
-
|
|
7202
|
-
|
|
7203
|
-
|
|
7204
|
-
|
|
7205
|
-
|
|
7206
|
-
|
|
7207
|
-
|
|
7208
|
-
this.
|
|
7209
|
-
|
|
7210
|
-
|
|
7211
|
-
|
|
7212
|
-
|
|
7213
|
-
|
|
7214
|
-
|
|
7215
|
-
|
|
7216
|
-
|
|
7217
|
-
|
|
7218
|
-
|
|
7219
|
-
|
|
7220
|
-
|
|
7221
|
-
|
|
7222
|
-
|
|
7223
|
-
|
|
7224
|
-
|
|
7225
|
-
|
|
7226
|
-
|
|
7227
|
-
|
|
7228
|
-
|
|
6987
|
+
/** Spawn a detached worker for task `id`; its settlement notifies + enqueues the re-voice turn. */
|
|
6988
|
+
spawnWorker(id, label, briefText, tier, brief, followUp) {
|
|
6989
|
+
const o = this.options;
|
|
6990
|
+
const tierOpts = tier === "think" ? o.thinkOptions : o.actOptions;
|
|
6991
|
+
const tierModel = tier === "think" ? o.thinkModel : o.actModel;
|
|
6992
|
+
const controller = new AbortController();
|
|
6993
|
+
const base = tierOpts?.hooks ?? o.actOptions?.hooks;
|
|
6994
|
+
const report = o.progressUpdates ? this.progressReporter(id) : void 0;
|
|
6995
|
+
const tail = [];
|
|
6996
|
+
const pushTail = (line) => {
|
|
6997
|
+
tail.push(line.slice(0, 200));
|
|
6998
|
+
if (tail.length > 120) tail.splice(0, tail.length - 120);
|
|
6999
|
+
};
|
|
7000
|
+
const hooks = {
|
|
7001
|
+
...base,
|
|
7002
|
+
preToolUse: async (call, meta) => {
|
|
7003
|
+
const d = await base?.preToolUse?.(call, meta);
|
|
7004
|
+
pushTail(`\u2699 ${describeCall(call)}`);
|
|
7005
|
+
report?.pre(call);
|
|
7006
|
+
return d;
|
|
7007
|
+
},
|
|
7008
|
+
postToolUse: async (call, result, meta) => {
|
|
7009
|
+
await base?.postToolUse?.(call, result, meta);
|
|
7010
|
+
const last = result?.trim().split("\n").filter(Boolean).pop();
|
|
7011
|
+
if (last) pushTail(` \u21B3 ${last}`);
|
|
7012
|
+
report?.post(call);
|
|
7013
|
+
},
|
|
7014
|
+
onToolOutput: (call, chunk, meta) => {
|
|
7015
|
+
base?.onToolOutput?.(call, chunk, meta);
|
|
7016
|
+
report?.output(chunk);
|
|
7017
|
+
}
|
|
7018
|
+
};
|
|
7019
|
+
const relayAsk = async (q2) => {
|
|
7020
|
+
const opts = q2.options?.length ? ` Options: ${q2.options.map((x) => x.label).join(", ")}.` : "";
|
|
7021
|
+
const a = await this.parkQuestion(id, `${q2.question}${opts}`);
|
|
7022
|
+
return a || "(no answer from the user \u2014 use your best judgment and note the assumption)";
|
|
7023
|
+
};
|
|
7024
|
+
const splitter = new SpokenSplitter();
|
|
7025
|
+
const speak = (seg) => {
|
|
7026
|
+
if (!seg) return;
|
|
7027
|
+
const r = this.tasks.get(id);
|
|
7028
|
+
if (r) r.spokenText = (r.spokenText ? r.spokenText + " " : "") + seg;
|
|
7029
|
+
if (!r?.deliveryParked) o.host?.notify?.({ kind: "speak_utterance", message: seg });
|
|
7030
|
+
};
|
|
7031
|
+
const coalescer = new SentenceCoalescer();
|
|
7032
|
+
const feedSpoken = (s) => {
|
|
7033
|
+
const ready = coalescer.feed(s);
|
|
7034
|
+
if (ready) speak(ready);
|
|
7035
|
+
};
|
|
7036
|
+
const flushSpoken = () => speak(coalescer.flush());
|
|
7037
|
+
const askBridge = o.askRelay ? { ask: relayAsk } : o.host?.ask ? { ask: (q2) => o.host.ask(q2) } : {};
|
|
7038
|
+
const workerHost = {
|
|
7039
|
+
...askBridge,
|
|
7040
|
+
notify: (ev) => {
|
|
7041
|
+
if (ev?.kind === "text_delta" && typeof ev.message === "string") {
|
|
7042
|
+
const { spoken, detail } = splitter.feed(ev.message);
|
|
7043
|
+
feedSpoken(spoken);
|
|
7044
|
+
if (detail.trim()) pushTail(detail.trim());
|
|
7045
|
+
return;
|
|
7046
|
+
}
|
|
7047
|
+
}
|
|
7048
|
+
};
|
|
7049
|
+
const agentOpts = {
|
|
7050
|
+
ai: o.ai,
|
|
7051
|
+
fs: o.fs,
|
|
7052
|
+
model: tierModel,
|
|
7053
|
+
...tier === "think" ? { reasoning: tierOpts?.reasoning ?? "high" } : {},
|
|
7054
|
+
...tierOpts,
|
|
7055
|
+
// Recompute providerOptions for THIS worker's model (after tierOpts so it wins over any inherited
|
|
7056
|
+
// main-template value) — prevents cursor-only cwd/cursorSession leaking onto an anthropic worker.
|
|
7057
|
+
providerOptions: o.providerOptionsFor?.(tierModel),
|
|
7058
|
+
stream: true,
|
|
7059
|
+
// worker streams text_delta so the splitter can extract <spoken> live (after tierOpts: never overridden off)
|
|
7060
|
+
host: workerHost,
|
|
7061
|
+
// carries BOTH ask AND the <spoken>-splitting notify
|
|
7062
|
+
...hooks ? { hooks } : {},
|
|
7063
|
+
signal: controller.signal
|
|
7064
|
+
// shared with the checker so a cancel tears down both
|
|
7229
7065
|
};
|
|
7066
|
+
const promise = new Agent(agentOpts).run(briefText).then((res) => {
|
|
7067
|
+
const { spoken, detail } = splitter.flush();
|
|
7068
|
+
feedSpoken(spoken);
|
|
7069
|
+
if (detail.trim()) pushTail(detail.trim());
|
|
7070
|
+
flushSpoken();
|
|
7071
|
+
return res;
|
|
7072
|
+
}).then((res) => this.maybeVerify(id, brief, res, tier, agentOpts, askBridge)).then((res) => this.onWorkerSettled(id, res)).catch((err2) => this.onWorkerFailed(id, err2));
|
|
7073
|
+
this.tasks.set(id, { id, label, status: "running", controller, promise, tail, brief, followUp, splitter });
|
|
7074
|
+
if (this.tasks.size > this.options.maxTaskRecords)
|
|
7075
|
+
for (const [tid, rec] of this.tasks) {
|
|
7076
|
+
if (this.tasks.size <= this.options.maxTaskRecords) break;
|
|
7077
|
+
if (rec.status !== "running") this.tasks.delete(tid);
|
|
7078
|
+
}
|
|
7230
7079
|
}
|
|
7231
|
-
|
|
7232
|
-
|
|
7233
|
-
|
|
7234
|
-
|
|
7235
|
-
|
|
7236
|
-
|
|
7237
|
-
|
|
7238
|
-
|
|
7239
|
-
|
|
7240
|
-
|
|
7241
|
-
|
|
7242
|
-
|
|
7243
|
-
|
|
7244
|
-
const
|
|
7245
|
-
|
|
7246
|
-
|
|
7247
|
-
|
|
7248
|
-
|
|
7249
|
-
|
|
7250
|
-
|
|
7251
|
-
|
|
7252
|
-
|
|
7253
|
-
this.stop();
|
|
7254
|
-
}
|
|
7255
|
-
}, Math.max(250, Math.min(2e3, noAudioMs / 4)));
|
|
7256
|
-
this.noAudioTimer.unref?.();
|
|
7080
|
+
/** Fresh-context check of a successful Act task: a NEW agent (same model/fs/tools, but NO shared
|
|
7081
|
+
* conversation context) re-reads the file state against the brief and fixes any gap. The fix lands
|
|
7082
|
+
* on the shared fs automatically (workers write fs directly, no overlay), so grading sees the
|
|
7083
|
+
* corrected state. Bounded to ONE pass. Off unless `verifyActTasks`; never runs for think/failed/
|
|
7084
|
+
* cancelled tasks. Usage is merged so /cost reflects the real (worker + checker) spend. */
|
|
7085
|
+
async maybeVerify(id, brief, res, tier, agentOpts, askBridge) {
|
|
7086
|
+
if (!this.options.verifyActTasks || tier !== "act" || res.finishReason !== "stop") return res;
|
|
7087
|
+
if (this.tasks.get(id)?.status === "cancelled") return res;
|
|
7088
|
+
const { stream: _stream, host: _host, ...restOpts } = agentOpts;
|
|
7089
|
+
const checkerOpts = {
|
|
7090
|
+
...restOpts,
|
|
7091
|
+
...askBridge.ask ? { host: { ask: askBridge.ask } } : {}
|
|
7092
|
+
};
|
|
7093
|
+
const checkBrief = `${this.buildBrief(brief, tier, false)}
|
|
7094
|
+
|
|
7095
|
+
## VERIFY MODE
|
|
7096
|
+
Another agent just implemented the above. Independently check the CURRENT state of the files against EVERY requirement. Fix any gap you find. If everything is already correct, make NO changes \u2014 do not refactor or improve \u2014 and report "verified".`;
|
|
7097
|
+
this.notify("task_verify", `task ${id}: verifying`, { id });
|
|
7098
|
+
const cres = await new Agent(checkerOpts).run(checkBrief);
|
|
7099
|
+
if (cres.finishReason !== "stop") {
|
|
7100
|
+
log12.warn(`task ${id}: verify inconclusive (${cres.finishReason})`);
|
|
7101
|
+
this.notify("task_verify", `task ${id}: verify inconclusive (${cres.finishReason})`, { id, finishReason: cres.finishReason });
|
|
7257
7102
|
}
|
|
7258
|
-
|
|
7259
|
-
|
|
7260
|
-
|
|
7261
|
-
|
|
7262
|
-
|
|
7263
|
-
|
|
7264
|
-
|
|
7103
|
+
const sum = (a = 0, b = 0) => a + b;
|
|
7104
|
+
return {
|
|
7105
|
+
...res,
|
|
7106
|
+
steps: res.steps + cres.steps,
|
|
7107
|
+
// Merge the checker's messages so downstream tool-call/step accounting includes BOTH agents
|
|
7108
|
+
// (else a verified task's toolCalls would undercount vs its steps/usage).
|
|
7109
|
+
messages: [...res.messages, ...cres.messages],
|
|
7110
|
+
usageEstimated: res.usageEstimated || cres.usageEstimated,
|
|
7111
|
+
usage: res.usage && cres.usage ? {
|
|
7112
|
+
promptTokens: sum(res.usage.promptTokens, cres.usage.promptTokens),
|
|
7113
|
+
completionTokens: sum(res.usage.completionTokens, cres.usage.completionTokens),
|
|
7114
|
+
totalTokens: sum(res.usage.totalTokens, cres.usage.totalTokens),
|
|
7115
|
+
cacheCreationTokens: sum(res.usage.cacheCreationTokens, cres.usage.cacheCreationTokens),
|
|
7116
|
+
cacheReadTokens: sum(res.usage.cacheReadTokens, cres.usage.cacheReadTokens)
|
|
7117
|
+
} : res.usage ?? cres.usage
|
|
7118
|
+
};
|
|
7119
|
+
}
|
|
7120
|
+
/** Throttled per-task progress: worker tool calls → at most one progress re-voice per interval.
|
|
7121
|
+
* Two sources, one throttle: completed steps (post) and a heartbeat for a SINGLE long tool call
|
|
7122
|
+
* (pre records the in-flight call; a self-cleaning timer narrates "still inside Bash — 70s").
|
|
7123
|
+
* Completion supersedes: nothing is emitted once the task has settled. */
|
|
7124
|
+
progressReporter(id) {
|
|
7125
|
+
let lastAt = Date.now();
|
|
7126
|
+
let steps = 0;
|
|
7127
|
+
let inflight = null;
|
|
7128
|
+
const due = () => {
|
|
7129
|
+
if (this.pendingAsks.size) return void 0;
|
|
7130
|
+
const rec = this.tasks.get(id);
|
|
7131
|
+
return rec && rec.status === "running" && Date.now() - lastAt >= this.options.progressIntervalMs ? rec : void 0;
|
|
7132
|
+
};
|
|
7133
|
+
const emit = (rec, line, call) => {
|
|
7134
|
+
lastAt = Date.now();
|
|
7135
|
+
this.notify("task_progress", `task ${id} (${rec.label}): ${line}`, { id, steps, call: call.name });
|
|
7136
|
+
this.queueRevoice(`[task ${id} progress] ${line}`);
|
|
7137
|
+
};
|
|
7138
|
+
const timer = setInterval(() => {
|
|
7139
|
+
const rec = this.tasks.get(id);
|
|
7140
|
+
if (!rec || rec.status !== "running") return clearInterval(timer);
|
|
7141
|
+
if (!inflight || !due()) return;
|
|
7142
|
+
const last = inflight.tail.trim().split("\n").filter(Boolean).pop()?.slice(-80);
|
|
7143
|
+
emit(rec, `still inside ${describeCall(inflight.call)} \u2014 ${Math.round((Date.now() - inflight.at) / 1e3)}s on this step${last ? `, last output: ${last}` : ""}`, inflight.call);
|
|
7144
|
+
}, Math.max(this.options.progressIntervalMs, 250));
|
|
7145
|
+
timer.unref?.();
|
|
7146
|
+
return {
|
|
7147
|
+
pre: (call) => {
|
|
7148
|
+
inflight = { call, at: Date.now(), tail: "" };
|
|
7149
|
+
},
|
|
7150
|
+
output: (chunk) => {
|
|
7151
|
+
if (inflight) inflight.tail = (inflight.tail + chunk).slice(-500);
|
|
7152
|
+
},
|
|
7153
|
+
// digest only — NEVER re-voices directly
|
|
7154
|
+
post: (call) => {
|
|
7155
|
+
steps++;
|
|
7156
|
+
inflight = null;
|
|
7157
|
+
const rec = due();
|
|
7158
|
+
if (rec) emit(rec, `still running \u2014 ${steps} steps so far, now: ${describeCall(call)}`, call);
|
|
7265
7159
|
}
|
|
7266
|
-
|
|
7267
|
-
|
|
7160
|
+
};
|
|
7161
|
+
}
|
|
7162
|
+
/** Park a question under `askId` (a task id, or any unique key for permission asks): re-voices
|
|
7163
|
+
* '[task <id> asks] …' and resolves with the user's answer via AnswerTask — or '' on timeout/
|
|
7164
|
+
* task settle (callers map '' to deny / best-judgment). Workers never block forever. */
|
|
7165
|
+
parkQuestion(askId, question) {
|
|
7166
|
+
return new Promise((resolve4) => {
|
|
7167
|
+
let settled = false;
|
|
7168
|
+
const finish = (answer) => {
|
|
7169
|
+
if (settled) return;
|
|
7170
|
+
settled = true;
|
|
7171
|
+
clearTimeout(timer);
|
|
7172
|
+
this.pendingAsks.delete(askId);
|
|
7173
|
+
resolve4(answer);
|
|
7174
|
+
};
|
|
7175
|
+
const timer = setTimeout(() => {
|
|
7176
|
+
this.notify("task_ask_timeout", `task ${askId}: question timed out \u2014 proceeding without an answer`);
|
|
7177
|
+
finish("");
|
|
7178
|
+
}, this.options.askTimeoutMs);
|
|
7179
|
+
this.pendingAsks.set(askId, { question, resolve: finish });
|
|
7180
|
+
this.notify("task_ask", `task ${askId} asks: ${question}`, { id: askId, question });
|
|
7181
|
+
this.queueRevoice(`[task ${askId} asks] ${question}
|
|
7182
|
+
(Relay this to the user in your own words. When they answer, call AnswerTask with id "${askId}" and their answer.)`);
|
|
7268
7183
|
});
|
|
7269
7184
|
}
|
|
7270
|
-
|
|
7271
|
-
|
|
7272
|
-
|
|
7273
|
-
|
|
7185
|
+
/** Resolve any question a settling/cancelled task left parked (its answer can no longer matter). */
|
|
7186
|
+
dropAsk(id) {
|
|
7187
|
+
this.pendingAsks.get(id)?.resolve("");
|
|
7188
|
+
}
|
|
7189
|
+
/** Build the INTEGRATION TURN prompt for a NON-CLEAN settled worker (early stop / failure). A clean
|
|
7190
|
+
* success never reaches here — it streams its own `<spoken>` delivery during the run. For a partial
|
|
7191
|
+
* or failed result the outcome re-enters the reflex as a decision (like a tool_result flowing back
|
|
7192
|
+
* into a normal agent loop): the reflex evaluates the outcome against the original intent and chooses
|
|
7193
|
+
* what to do next.
|
|
7194
|
+
*
|
|
7195
|
+
* Decision branches (the reflex acts on them with EXISTING tools — no new surface):
|
|
7196
|
+
* • accept → SPEAK the (partial) result plainly — don't dress a failure up as success.
|
|
7197
|
+
* • escalate → call `Think` with the SAME brief — only when Act failed/stalled AND a Think tier
|
|
7198
|
+
* exists AND this task wasn't already a follow-up (one hop max). Wires the dead
|
|
7199
|
+
* "Reserve Think for a problem Act already FAILED at" promise.
|
|
7200
|
+
* • re-delegate→ call `Act` with a CORRECTED brief — for a recoverable error / partial result.
|
|
7201
|
+
* • ask → ask the user ONE concrete question if genuinely blocked.
|
|
7202
|
+
*
|
|
7203
|
+
* Keeps the `[task <id> completed]` / `[task <id> failed]` opener so existing coalescing + the
|
|
7204
|
+
* failed-revoice fallback still fire, and the per-event transcript markers stay intact. */
|
|
7205
|
+
integrationPrompt(rec, outcome, body, finishReason) {
|
|
7206
|
+
const opener = outcome === "error" ? `[task ${rec.id} failed]` : `[task ${rec.id} completed]`;
|
|
7207
|
+
const underCap = this.autoEscalations < _DuplexAgent.MAX_AUTO_ESCALATIONS;
|
|
7208
|
+
const canEscalate = (outcome === "error" || outcome === "incomplete") && underCap;
|
|
7209
|
+
const hasThink = this.options.thinkModel !== false;
|
|
7210
|
+
const options = [];
|
|
7211
|
+
if (!rec.followUp && canEscalate && hasThink)
|
|
7212
|
+
options.push("ESCALATE to the Think tier (call Think with the same brief) if this is a hard/architectural problem the Act worker stalled or failed on");
|
|
7213
|
+
if (!rec.followUp && canEscalate)
|
|
7214
|
+
options.push("RE-DELEGATE to Act with a corrected brief if the failure looks recoverable (a wrong path, a fixable mistake)");
|
|
7215
|
+
options.push("ASK the user one short, concrete question if you genuinely cannot proceed without their input");
|
|
7216
|
+
options.push("ACCEPT and tell the user plainly what happened (don't dress a failure up as success)");
|
|
7217
|
+
const decision = options.length > 1 ? ` You must decide what to do next \u2014 choose ONE: ${options.map((o, i) => `(${i + 1}) ${o}`).join("; ")}. Pick exactly one and act on it; do not voice this as a finished success.` : ` Tell the user plainly what happened \u2014 do not present this as a finished success.`;
|
|
7218
|
+
const state = outcome === "error" ? `the worker FAILED with: ${body}` : `the worker STOPPED EARLY (${finishReason}) \u2014 its result is PARTIAL, not a finished success: ${body}`;
|
|
7219
|
+
return `${opener} Original request: "${rec.brief}". Outcome: ${state}.${decision}`;
|
|
7220
|
+
}
|
|
7221
|
+
onWorkerSettled(id, res) {
|
|
7222
|
+
this.dropAsk(id);
|
|
7223
|
+
const rec = this.tasks.get(id);
|
|
7224
|
+
if (res.finishReason === "aborted" || rec.status === "cancelled") {
|
|
7225
|
+
rec.status = "cancelled";
|
|
7226
|
+
this.notify("task_cancelled", `task ${id} (${rec.label}) cancelled`);
|
|
7227
|
+
return;
|
|
7274
7228
|
}
|
|
7275
|
-
|
|
7276
|
-
|
|
7277
|
-
|
|
7278
|
-
else if (t.is_final) this.finalText += t.text;
|
|
7229
|
+
if (res.finishReason === "error") {
|
|
7230
|
+
const msg = res.error instanceof Error ? res.error.message : String(res.error ?? "unknown error");
|
|
7231
|
+
return this.failTask(rec, msg);
|
|
7279
7232
|
}
|
|
7280
|
-
|
|
7281
|
-
|
|
7282
|
-
|
|
7283
|
-
|
|
7284
|
-
|
|
7285
|
-
|
|
7233
|
+
rec.status = "done";
|
|
7234
|
+
rec.result = res.text;
|
|
7235
|
+
const incomplete = res.finishReason !== "stop";
|
|
7236
|
+
log12.verbose(`task ${id} done (${res.steps} steps${incomplete ? `, INCOMPLETE: ${res.finishReason}` : ""})`);
|
|
7237
|
+
this.notify("task_done", `task ${id} (${rec.label}) completed`, {
|
|
7238
|
+
id,
|
|
7239
|
+
text: res.text,
|
|
7240
|
+
usage: res.usage,
|
|
7241
|
+
usageEstimated: res.usageEstimated,
|
|
7242
|
+
finishReason: res.finishReason,
|
|
7243
|
+
steps: res.steps,
|
|
7244
|
+
toolCalls: res.messages.filter((m) => m.role === "tool").length
|
|
7245
|
+
});
|
|
7246
|
+
if (incomplete) {
|
|
7247
|
+
return this.queueRevoice(this.integrationPrompt(rec, "incomplete", res.text, res.finishReason), true);
|
|
7286
7248
|
}
|
|
7287
|
-
|
|
7288
|
-
if (
|
|
7289
|
-
|
|
7290
|
-
|
|
7291
|
-
|
|
7292
|
-
|
|
7249
|
+
const tail = rec.splitter?.flush();
|
|
7250
|
+
if (tail?.spoken && !rec.deliveryParked) this.options.host?.notify?.({ kind: "speak_utterance", message: tail.spoken });
|
|
7251
|
+
if (res.text.trim()) this.voice.transcript.push({ role: "assistant", content: res.text });
|
|
7252
|
+
if (rec.deliveryParked && !this.suppressParkedResume) {
|
|
7253
|
+
const gist = (rec.spokenText ?? "").trim() || res.text.trim();
|
|
7254
|
+
if (gist) {
|
|
7255
|
+
if (this.awaitTrivialRedeliver) {
|
|
7256
|
+
this.awaitTrivialRedeliver = false;
|
|
7257
|
+
this.options.host?.notify?.({ kind: "speak_utterance", message: gist });
|
|
7258
|
+
this.notify("diag", "parked_redelivered", { chars: gist.length });
|
|
7259
|
+
} else this.parkedRedeliver.push(gist);
|
|
7260
|
+
}
|
|
7293
7261
|
}
|
|
7262
|
+
if (!rec.splitter?.spokeAny && res.text.trim() && !rec.deliveryParked)
|
|
7263
|
+
this.options.host?.notify?.({ kind: "speak_utterance", message: res.text });
|
|
7294
7264
|
}
|
|
7295
|
-
|
|
7296
|
-
this.
|
|
7297
|
-
this.partialText = "";
|
|
7298
|
-
this.lastCombined = "";
|
|
7299
|
-
this.firstTokenAt = 0;
|
|
7265
|
+
onWorkerFailed(id, err2) {
|
|
7266
|
+
this.failTask(this.tasks.get(id), err2 instanceof Error ? err2.message : String(err2));
|
|
7300
7267
|
}
|
|
7301
|
-
|
|
7302
|
-
this.
|
|
7303
|
-
|
|
7304
|
-
|
|
7305
|
-
|
|
7306
|
-
|
|
7307
|
-
this.
|
|
7268
|
+
failTask(rec, msg) {
|
|
7269
|
+
this.dropAsk(rec.id);
|
|
7270
|
+
rec.status = "error";
|
|
7271
|
+
rec.result = msg;
|
|
7272
|
+
log12.warn(`task ${rec.id} failed: ${msg}`);
|
|
7273
|
+
this.notify("task_error", `task ${rec.id} (${rec.label}) failed: ${msg}`);
|
|
7274
|
+
this.queueRevoice(this.integrationPrompt(rec, "error", msg, "error"), true);
|
|
7308
7275
|
}
|
|
7309
|
-
|
|
7310
|
-
|
|
7311
|
-
|
|
7312
|
-
|
|
7313
|
-
|
|
7314
|
-
|
|
7315
|
-
|
|
7316
|
-
|
|
7317
|
-
|
|
7318
|
-
|
|
7319
|
-
|
|
7320
|
-
authMode = "apiKey";
|
|
7321
|
-
};
|
|
7322
|
-
var CartesiaTTS = class _CartesiaTTS {
|
|
7323
|
-
options;
|
|
7324
|
-
ws;
|
|
7325
|
-
ctxSeq = 0;
|
|
7326
|
-
ctxId = "";
|
|
7327
|
-
onAudio = () => {
|
|
7328
|
-
};
|
|
7329
|
-
onDone = () => {
|
|
7330
|
-
};
|
|
7331
|
-
/** Word-level timestamps for karaoke reveal: `start[i]` = seconds from turn-audio start (absolute
|
|
7332
|
-
* across continuation chunks). Fired only when a consumer opts into reveal (see `wantTimestamps`). */
|
|
7333
|
-
onTimestamps = () => {
|
|
7334
|
-
};
|
|
7335
|
-
/** Request `add_timestamps` from Cartesia. Off by default (saves bandwidth) — the engine sets it
|
|
7336
|
-
* when revealMode==='word'. */
|
|
7337
|
-
wantTimestamps = false;
|
|
7338
|
-
/** Diagnostic tap (provider errors, circuit-breaker open/close, ws reconnects). Fire-and-forget:
|
|
7339
|
-
* a throwing handler disables itself — never affects synthesis. Wired by VoiceIO / the lab bridge. */
|
|
7340
|
-
onDiag = () => {
|
|
7341
|
-
};
|
|
7342
|
-
diagOn = true;
|
|
7343
|
-
diag(kind, fields) {
|
|
7344
|
-
if (!this.diagOn) return;
|
|
7345
|
-
try {
|
|
7346
|
-
this.onDiag({ t: now2(), kind, ...fields });
|
|
7347
|
-
} catch (e) {
|
|
7348
|
-
this.diagOn = false;
|
|
7349
|
-
log12.debug(`onDiag threw \u2014 TTS diagnostics disabled: ${e instanceof Error ? e.message : e}`);
|
|
7350
|
-
}
|
|
7276
|
+
// --- voice tools (closures over this instance) ---
|
|
7277
|
+
/** Live-switch the think tier: `false` disables (removes the Think tool from the voice agent),
|
|
7278
|
+
* a model id enables (adds the tool if missing). The system-prompt THINK_SLOT text is frozen at
|
|
7279
|
+
* construction — the tool's own description carries the routing guidance, so a live enable works;
|
|
7280
|
+
* dispatch()'s think→act fallback covers any straggler calls after a live disable. */
|
|
7281
|
+
setThinkModel(model) {
|
|
7282
|
+
this.options.thinkModel = model;
|
|
7283
|
+
const tools = this.voice.options.tools;
|
|
7284
|
+
const i = tools.findIndex((t) => t.name === "Think");
|
|
7285
|
+
if (model === false && i >= 0) tools.splice(i, 1);
|
|
7286
|
+
else if (model !== false && i < 0) tools.push(this.thinkTool());
|
|
7351
7287
|
}
|
|
7352
|
-
|
|
7353
|
-
|
|
7354
|
-
|
|
7355
|
-
|
|
7356
|
-
|
|
7357
|
-
|
|
7358
|
-
|
|
7359
|
-
|
|
7360
|
-
|
|
7361
|
-
|
|
7362
|
-
|
|
7363
|
-
|
|
7364
|
-
constructor(options) {
|
|
7365
|
-
this.options = { ...new CartesiaTTSOptions(), ...options };
|
|
7288
|
+
/** User/programmatic spawn: the CLI's /act and /think commands. Returns the task id.
|
|
7289
|
+
* `followUp` marks an automatic escalation/re-delegation (set by the integration turn) so the new
|
|
7290
|
+
* task's own integration turn won't escalate again — capping auto-follow-ups to one hop. */
|
|
7291
|
+
async dispatch(brief, tier = "act", label, followUp = false) {
|
|
7292
|
+
if (tier === "think" && this.options.thinkModel === false) tier = "act";
|
|
7293
|
+
if (followUp) this.autoEscalations++;
|
|
7294
|
+
const id = `t${++this.seq}`;
|
|
7295
|
+
const lbl = label ?? tier;
|
|
7296
|
+
await this.options.onTaskStart?.(id, lbl);
|
|
7297
|
+
this.spawnWorker(id, lbl, this.buildBrief(brief, tier), tier, brief, followUp);
|
|
7298
|
+
this.notify("task_started", `task ${id} (${lbl}) started`, { id, brief, tier });
|
|
7299
|
+
return id;
|
|
7366
7300
|
}
|
|
7367
|
-
|
|
7368
|
-
|
|
7369
|
-
|
|
7370
|
-
|
|
7371
|
-
|
|
7372
|
-
|
|
7373
|
-
|
|
7301
|
+
actTool() {
|
|
7302
|
+
return {
|
|
7303
|
+
name: "Act",
|
|
7304
|
+
description: 'Escalate real work (reading/editing files, searching, running tasks, building) to a standard background worker. Returns immediately with a task id; the result arrives later as a "[task <id> completed]" event. Provide a clear, self-contained `brief` (the worker does not hear the live conversation).',
|
|
7305
|
+
parameters: {
|
|
7306
|
+
type: "object",
|
|
7307
|
+
required: ["brief"],
|
|
7308
|
+
properties: {
|
|
7309
|
+
brief: { type: "string", description: "full, self-contained instructions for the worker" },
|
|
7310
|
+
label: { type: "string", description: "a short (2-4 word) label for the task" }
|
|
7311
|
+
}
|
|
7312
|
+
},
|
|
7313
|
+
run: async ({ brief, label }) => {
|
|
7314
|
+
this.spokeBeforeDispatch = this.spokeThisTurn;
|
|
7315
|
+
this.turnDispatched = true;
|
|
7316
|
+
this.turnBriefs.add(String(brief ?? ""));
|
|
7317
|
+
this.voice.options.toolChoice = "none";
|
|
7318
|
+
const id = await this.dispatch(String(brief ?? ""), "act", label ? String(label) : void 0, this.turnFollowUp);
|
|
7319
|
+
return this.spokeBeforeDispatch ? `Acting on task ${id}. You already acknowledged \u2014 end your turn now with NO further text; the result will arrive as a [task ${id} completed] event.` : `Acting on task ${id}. Acknowledge briefly; the result will arrive as a [task ${id} completed] event.`;
|
|
7320
|
+
}
|
|
7321
|
+
};
|
|
7374
7322
|
}
|
|
7375
|
-
|
|
7376
|
-
|
|
7377
|
-
|
|
7378
|
-
|
|
7379
|
-
|
|
7380
|
-
|
|
7381
|
-
|
|
7382
|
-
|
|
7383
|
-
|
|
7384
|
-
|
|
7385
|
-
|
|
7386
|
-
|
|
7387
|
-
|
|
7388
|
-
|
|
7389
|
-
|
|
7390
|
-
|
|
7323
|
+
thinkTool() {
|
|
7324
|
+
return {
|
|
7325
|
+
name: "Think",
|
|
7326
|
+
description: "Escalate to a premium deep-reasoning agent for complex analysis, architecture decisions, hard debugging, or planning. Same async pattern as Act \u2014 returns a task id. Use when the problem needs careful thought before (or instead of) action. Do not use Think for simple tasks \u2014 Act is cheaper and faster.",
|
|
7327
|
+
parameters: {
|
|
7328
|
+
type: "object",
|
|
7329
|
+
required: ["brief"],
|
|
7330
|
+
properties: {
|
|
7331
|
+
brief: { type: "string", description: "the question or problem to reason about deeply" },
|
|
7332
|
+
label: { type: "string", description: "a short (2-4 word) label for the task" }
|
|
7333
|
+
}
|
|
7334
|
+
},
|
|
7335
|
+
run: async ({ brief, label }) => {
|
|
7336
|
+
this.spokeBeforeDispatch = this.spokeThisTurn;
|
|
7337
|
+
this.turnDispatched = true;
|
|
7338
|
+
this.turnBriefs.add(String(brief ?? ""));
|
|
7339
|
+
this.voice.options.toolChoice = "none";
|
|
7340
|
+
const id = await this.dispatch(String(brief ?? ""), "think", label ? String(label) : void 0, this.turnFollowUp);
|
|
7341
|
+
return this.spokeBeforeDispatch ? `Thinking on task ${id}. You already acknowledged \u2014 end your turn now with NO further text; the result will arrive as a [task ${id} completed] event.` : `Thinking on task ${id}. Acknowledge briefly; the result will arrive as a [task ${id} completed] event.`;
|
|
7391
7342
|
}
|
|
7392
7343
|
};
|
|
7393
|
-
|
|
7394
|
-
|
|
7395
|
-
|
|
7396
|
-
|
|
7397
|
-
|
|
7398
|
-
|
|
7399
|
-
|
|
7400
|
-
this.
|
|
7401
|
-
|
|
7402
|
-
|
|
7403
|
-
|
|
7404
|
-
|
|
7405
|
-
|
|
7406
|
-
|
|
7407
|
-
|
|
7408
|
-
|
|
7409
|
-
|
|
7410
|
-
|
|
7411
|
-
|
|
7412
|
-
|
|
7413
|
-
|
|
7414
|
-
|
|
7415
|
-
|
|
7416
|
-
|
|
7417
|
-
|
|
7418
|
-
|
|
7419
|
-
|
|
7420
|
-
|
|
7421
|
-
|
|
7344
|
+
}
|
|
7345
|
+
taskStatusTool() {
|
|
7346
|
+
return {
|
|
7347
|
+
name: "TaskStatus",
|
|
7348
|
+
description: "Status of background tasks. Pass `id` for one task, or omit it to list all.",
|
|
7349
|
+
parameters: { type: "object", properties: { id: { type: "string" } } },
|
|
7350
|
+
run: async ({ id }) => {
|
|
7351
|
+
const list = id ? [this.tasks.get(String(id))].filter(Boolean) : [...this.tasks.values()];
|
|
7352
|
+
if (!list.length) return id ? `No task '${id}'.` : "No background tasks.";
|
|
7353
|
+
return list.map((t) => `${t.id} (${t.label}): ${t.status}`).join("\n");
|
|
7354
|
+
}
|
|
7355
|
+
};
|
|
7356
|
+
}
|
|
7357
|
+
/** Sub-100ms read-only lookups the voice may do itself — everything else stays Act-only.
|
|
7358
|
+
* fs-only (no shell; the engine is VFS-abstracted): time, git branch (.git/HEAD read), ls, file
|
|
7359
|
+
* head. Output is hard-capped so a lookup can never bloat the skinny voice context. */
|
|
7360
|
+
quickLookTool() {
|
|
7361
|
+
const CAP2 = 2e3;
|
|
7362
|
+
const kinds = [.../* @__PURE__ */ new Set(["time", "branch", "ls", "file", "capabilities", ...Object.keys(this.options.quickLook ?? {})])];
|
|
7363
|
+
return {
|
|
7364
|
+
name: "QuickLook",
|
|
7365
|
+
description: `Instant read-only lookup \u2014 one of: ${kinds.join(", ")}. For trivial facts only; anything needing search, commands, or reasoning goes through Act.`,
|
|
7366
|
+
parameters: {
|
|
7367
|
+
type: "object",
|
|
7368
|
+
required: ["what"],
|
|
7369
|
+
properties: {
|
|
7370
|
+
what: { type: "string", enum: kinds, description: "what to look up" },
|
|
7371
|
+
path: { type: "string", description: "for ls/file: the path to look at" }
|
|
7372
|
+
}
|
|
7373
|
+
},
|
|
7374
|
+
run: async ({ what, path }) => {
|
|
7375
|
+
const fs = this.options.fs;
|
|
7376
|
+
try {
|
|
7377
|
+
const over = this.options.quickLook?.[String(what)];
|
|
7378
|
+
if (over) return await over(path ? String(path) : void 0);
|
|
7379
|
+
switch (String(what)) {
|
|
7380
|
+
case "capabilities": {
|
|
7381
|
+
const actTools = this.options.actOptions?.tools ?? [];
|
|
7382
|
+
const names = actTools.map((t) => t.name);
|
|
7383
|
+
const mcpServers = Object.keys(this.options.actOptions?.providerOptions?.mcpServers ?? {});
|
|
7384
|
+
const mcpNote = mcpServers.length ? ` Plus MCP servers your worker can use: ${mcpServers.join(", ")} (e.g. browser-bridge \u2192 drive a real browser: open tabs, navigate, click, screenshot).` : "";
|
|
7385
|
+
if (!names.length)
|
|
7386
|
+
return "Your worker uses Act's default local toolset (reading/editing files, running shell commands). No extra tools (e.g. web/internet) are configured; if a request is not a basic file or shell operation, assume you can't do it and say so." + mcpNote;
|
|
7387
|
+
const hasFetch = names.some((n) => /WebFetch/i.test(n));
|
|
7388
|
+
const hasBrowser = names.some((n) => /browser.*(navigate|click|page|type)/i.test(n));
|
|
7389
|
+
const hasSearch = names.some((n) => /(^|_)WebSearch$|search/i.test(n) && !/WebFetch|browser/i.test(n));
|
|
7390
|
+
const notes = [];
|
|
7391
|
+
if (hasFetch) notes.push("WebFetch retrieves ONE specific URL you are given \u2014 it is not a search engine.");
|
|
7392
|
+
if (hasBrowser) notes.push("The browser tools drive a real browser: you CAN open a site and, if needed, navigate to a search engine and search there \u2014 but it is manual and takes a moment, not an instant lookup.");
|
|
7393
|
+
else if (!hasSearch && hasFetch) notes.push('You have no general web-search tool, so for an instant "search the web" you can only fetch a URL they provide.');
|
|
7394
|
+
const webNote = notes.length ? " NOTE: " + notes.join(" ") : "";
|
|
7395
|
+
return `Tools your background worker (Act) can actually use: ${names.join(", ")}. Read each name literally and match the request to a SPECIFIC tool; if none fits, you do NOT have that ability \u2014 say so honestly.` + webNote + mcpNote;
|
|
7396
|
+
}
|
|
7397
|
+
case "time":
|
|
7398
|
+
return (/* @__PURE__ */ new Date()).toString();
|
|
7399
|
+
case "branch": {
|
|
7400
|
+
if (!fs) return "unavailable (no filesystem)";
|
|
7401
|
+
const head = (await fs.readFile(".git/HEAD")).trim();
|
|
7402
|
+
return head.startsWith("ref: refs/heads/") ? `branch: ${head.slice("ref: refs/heads/".length)}` : `detached HEAD at ${head.slice(0, 12)}`;
|
|
7403
|
+
}
|
|
7404
|
+
case "ls": {
|
|
7405
|
+
if (!fs) return "unavailable (no filesystem)";
|
|
7406
|
+
const p = String(path ?? ".");
|
|
7407
|
+
try {
|
|
7408
|
+
const names = await fs.readDir(p);
|
|
7409
|
+
return names.slice(0, 50).join("\n") + (names.length > 50 ? `
|
|
7410
|
+
\u2026 (+${names.length - 50} more)` : "");
|
|
7411
|
+
} catch {
|
|
7412
|
+
const names = await fs.readDir(".").catch(() => []);
|
|
7413
|
+
return `'${p}' not found here \u2014 you are likely already inside it. Current directory listing:
|
|
7414
|
+
` + names.slice(0, 50).join("\n") + (names.length > 50 ? `
|
|
7415
|
+
\u2026 (+${names.length - 50} more)` : "");
|
|
7416
|
+
}
|
|
7417
|
+
}
|
|
7418
|
+
case "file": {
|
|
7419
|
+
if (!fs) return "unavailable (no filesystem)";
|
|
7420
|
+
if (!path) return "file lookup needs a path";
|
|
7421
|
+
try {
|
|
7422
|
+
const text = await fs.readFile(String(path));
|
|
7423
|
+
return text.length > CAP2 ? text.slice(0, CAP2) + `
|
|
7424
|
+
\u2026 (truncated \u2014 ${text.length} chars total; Act for the full file)` : text;
|
|
7425
|
+
} catch {
|
|
7426
|
+
const names = await fs.readDir(".").catch(() => []);
|
|
7427
|
+
return `'${path}' not found. Current directory contains:
|
|
7428
|
+
` + names.slice(0, 50).join("\n");
|
|
7429
|
+
}
|
|
7430
|
+
}
|
|
7431
|
+
default:
|
|
7432
|
+
return `unknown lookup '${what}'`;
|
|
7433
|
+
}
|
|
7434
|
+
} catch (e) {
|
|
7435
|
+
return `lookup failed: ${e?.message ?? e}`;
|
|
7422
7436
|
}
|
|
7423
7437
|
}
|
|
7424
7438
|
};
|
|
7425
7439
|
}
|
|
7426
|
-
|
|
7427
|
-
|
|
7428
|
-
|
|
7429
|
-
|
|
7430
|
-
|
|
7431
|
-
|
|
7432
|
-
|
|
7433
|
-
|
|
7434
|
-
|
|
7435
|
-
|
|
7436
|
-
|
|
7437
|
-
|
|
7438
|
-
|
|
7439
|
-
|
|
7440
|
-
|
|
7441
|
-
|
|
7442
|
-
}
|
|
7443
|
-
/** Prime the synthesis pipeline on a throwaway context right after connect: the FIRST synthesis on
|
|
7444
|
-
* a fresh WS pays Cartesia's cold spin-up (~1s+ live) — absorb it at mic-on instead of turn one.
|
|
7445
|
-
* The returned audio is discarded (engine drops onAudio while not speaking; once a real turn calls
|
|
7446
|
-
* newContext() any stragglers are stale-context-filtered). Respects the circuit breaker. */
|
|
7447
|
-
warmup() {
|
|
7448
|
-
if (this.down) return;
|
|
7449
|
-
this.newContext();
|
|
7450
|
-
if (this.ws?.readyState === WebSocket.OPEN) this.ws.send(this.frame("Ok.", false));
|
|
7451
|
-
}
|
|
7452
|
-
newContext() {
|
|
7453
|
-
this.ctxId = `ctx-${++this.ctxSeq}`;
|
|
7454
|
-
this.firstAudioAt = 0;
|
|
7455
|
-
return this.ctxId;
|
|
7440
|
+
answerTaskTool() {
|
|
7441
|
+
return {
|
|
7442
|
+
name: "AnswerTask",
|
|
7443
|
+
description: `Relay the user's answer to a pending question from a background task (the "[task <id> asks]" events). Pass the id from the event and the user's answer.`,
|
|
7444
|
+
parameters: {
|
|
7445
|
+
type: "object",
|
|
7446
|
+
required: ["id", "answer"],
|
|
7447
|
+
properties: { id: { type: "string" }, answer: { type: "string", description: "the user's answer, verbatim or faithfully summarized" } }
|
|
7448
|
+
},
|
|
7449
|
+
run: async ({ id, answer }) => {
|
|
7450
|
+
const ask = this.pendingAsks.get(String(id));
|
|
7451
|
+
if (!ask) return `No pending question for '${id}' \u2014 it may have been answered already or timed out.`;
|
|
7452
|
+
ask.resolve(String(answer ?? ""));
|
|
7453
|
+
return `Answer relayed \u2014 task ${id} resumes.`;
|
|
7454
|
+
}
|
|
7455
|
+
};
|
|
7456
7456
|
}
|
|
7457
|
-
|
|
7458
|
-
return
|
|
7459
|
-
|
|
7460
|
-
|
|
7461
|
-
|
|
7462
|
-
|
|
7463
|
-
|
|
7464
|
-
|
|
7465
|
-
|
|
7466
|
-
|
|
7457
|
+
holdTool() {
|
|
7458
|
+
return {
|
|
7459
|
+
name: "Hold",
|
|
7460
|
+
description: 'The user seems mid-thought \u2014 hold the turn (stay listening) instead of answering. Optionally pass a short filler ("mhm", "go on") to speak while waiting. Use when the message sounds incomplete, trailing off, or like they paused to think.',
|
|
7461
|
+
parameters: {
|
|
7462
|
+
type: "object",
|
|
7463
|
+
properties: {
|
|
7464
|
+
filler: { type: "string", description: 'optional short filler to speak ("mhm", "go on", "mm-hm")' }
|
|
7465
|
+
}
|
|
7466
|
+
},
|
|
7467
|
+
run: async ({ filler }) => {
|
|
7468
|
+
this.heldThisTurn = true;
|
|
7469
|
+
this.notify("hold_filler", filler ? String(filler) : "");
|
|
7470
|
+
return "Holding \u2014 listening for the rest of the user's thought. Do not respond further this turn.";
|
|
7471
|
+
}
|
|
7472
|
+
};
|
|
7467
7473
|
}
|
|
7468
|
-
|
|
7469
|
-
|
|
7470
|
-
|
|
7471
|
-
|
|
7472
|
-
|
|
7474
|
+
cancelTaskTool() {
|
|
7475
|
+
return {
|
|
7476
|
+
name: "CancelTask",
|
|
7477
|
+
description: "Cancel a running background task by id.",
|
|
7478
|
+
parameters: { type: "object", required: ["id"], properties: { id: { type: "string" } } },
|
|
7479
|
+
run: async ({ id }) => this.cancelTask(String(id))
|
|
7480
|
+
};
|
|
7473
7481
|
}
|
|
7474
|
-
|
|
7475
|
-
|
|
7476
|
-
|
|
7477
|
-
|
|
7482
|
+
};
|
|
7483
|
+
|
|
7484
|
+
// src/mcp.ts
|
|
7485
|
+
function toResult(result) {
|
|
7486
|
+
if (result == null) return { text: "" };
|
|
7487
|
+
if (typeof result === "string") return { text: result };
|
|
7488
|
+
const content = result.content;
|
|
7489
|
+
if (Array.isArray(content)) {
|
|
7490
|
+
const texts = [];
|
|
7491
|
+
const images = [];
|
|
7492
|
+
for (const c of content) {
|
|
7493
|
+
if (c?.type === "image" && typeof c.data === "string" && c.mimeType) {
|
|
7494
|
+
images.push({ mimeType: c.mimeType, data: c.data });
|
|
7495
|
+
} else if (typeof c?.text === "string") {
|
|
7496
|
+
texts.push(c.text);
|
|
7497
|
+
} else {
|
|
7498
|
+
texts.push(JSON.stringify(c));
|
|
7499
|
+
}
|
|
7478
7500
|
}
|
|
7479
|
-
|
|
7480
|
-
|
|
7481
|
-
cancel() {
|
|
7482
|
-
if (this.ws?.readyState === WebSocket.OPEN) this.ws.send(JSON.stringify({ context_id: this.ctxId, cancel: true }));
|
|
7501
|
+
const text = texts.join("\n");
|
|
7502
|
+
if (text || images.length) return { text, ...images.length ? { images } : {} };
|
|
7483
7503
|
}
|
|
7484
|
-
|
|
7485
|
-
|
|
7486
|
-
|
|
7487
|
-
|
|
7488
|
-
|
|
7489
|
-
|
|
7504
|
+
return { text: JSON.stringify(result) };
|
|
7505
|
+
}
|
|
7506
|
+
function mcpToolToAgentTool(spec, callTool, prefix = "mcp__") {
|
|
7507
|
+
return {
|
|
7508
|
+
name: `${prefix}${spec.name}`,
|
|
7509
|
+
description: spec.description ?? `MCP tool ${spec.name}`,
|
|
7510
|
+
parameters: spec.inputSchema ?? { type: "object", properties: {} },
|
|
7511
|
+
async run(args, _ctx) {
|
|
7512
|
+
const r = toResult(await callTool(spec.name, args ?? {}));
|
|
7513
|
+
return r.images?.length ? r : r.text;
|
|
7514
|
+
}
|
|
7515
|
+
};
|
|
7516
|
+
}
|
|
7517
|
+
function mcpToolsToAgentTools(specs, callTool, prefix = "mcp__", filter) {
|
|
7518
|
+
return (filter ? specs.filter(filter) : specs).map((s) => mcpToolToAgentTool(s, callTool, prefix));
|
|
7519
|
+
}
|
|
7520
|
+
function describeSpec(s) {
|
|
7521
|
+
const schema = s.inputSchema ? `
|
|
7522
|
+
args: ${JSON.stringify(s.inputSchema)}` : "";
|
|
7523
|
+
return `${s.name} \u2014 ${s.description ?? "(no description)"}${schema}`;
|
|
7524
|
+
}
|
|
7525
|
+
function makeMcpToolSearch(specs, callTool, options = {}) {
|
|
7526
|
+
const maxResults = options.maxResults ?? 10;
|
|
7527
|
+
const byName = new Map(specs.map((s) => [s.name, s]));
|
|
7528
|
+
const catalogLine = `${specs.length} MCP tool(s) available \u2014 search by keyword, then call by exact name.`;
|
|
7529
|
+
const searchTool = {
|
|
7530
|
+
name: "ToolSearch",
|
|
7531
|
+
description: `Search the available MCP tools by keyword (${catalogLine}). Returns matching tool names + their argument schemas; call one with \`McpCall\`.`,
|
|
7532
|
+
parameters: { type: "object", required: ["query"], properties: { query: { type: "string", description: "keywords to match against tool name + description" } } },
|
|
7533
|
+
async run({ query }) {
|
|
7534
|
+
const q2 = String(query ?? "").trim();
|
|
7535
|
+
if (!q2) return catalogLine;
|
|
7536
|
+
const { kept } = topByRelevance(specs, q2, (s) => `${s.name} ${s.description ?? ""}`, maxResults);
|
|
7537
|
+
if (!kept.length) return `(no MCP tool matches "${q2}" \u2014 try broader keywords)`;
|
|
7538
|
+
return kept.map(describeSpec).join("\n");
|
|
7539
|
+
}
|
|
7540
|
+
};
|
|
7541
|
+
const callMcpTool = {
|
|
7542
|
+
name: "McpCall",
|
|
7543
|
+
description: "Call an MCP tool discovered via `ToolSearch`, by its exact name. Pass its arguments as `args`.",
|
|
7544
|
+
parameters: {
|
|
7545
|
+
type: "object",
|
|
7546
|
+
required: ["name"],
|
|
7547
|
+
properties: {
|
|
7548
|
+
name: { type: "string", description: "exact tool name from ToolSearch" },
|
|
7549
|
+
args: { type: "object", description: "arguments object for the tool (per its schema)" }
|
|
7490
7550
|
}
|
|
7491
|
-
|
|
7492
|
-
|
|
7493
|
-
|
|
7494
|
-
|
|
7495
|
-
|
|
7496
|
-
|
|
7497
|
-
|
|
7498
|
-
|
|
7499
|
-
|
|
7500
|
-
|
|
7551
|
+
},
|
|
7552
|
+
async run({ name, args }) {
|
|
7553
|
+
const n = String(name ?? "");
|
|
7554
|
+
if (!byName.has(n)) return `Error: unknown MCP tool '${n}'. Use ToolSearch to find valid names.`;
|
|
7555
|
+
const r = toResult(await callTool(n, args ?? {}));
|
|
7556
|
+
return r.images?.length ? r : r.text;
|
|
7557
|
+
}
|
|
7558
|
+
};
|
|
7559
|
+
return [searchTool, callMcpTool];
|
|
7560
|
+
}
|
|
7561
|
+
function buildMcpCatalog(servers) {
|
|
7562
|
+
const specs = [];
|
|
7563
|
+
const routes = /* @__PURE__ */ new Map();
|
|
7564
|
+
for (const m of servers) {
|
|
7565
|
+
for (const s of m.specs) {
|
|
7566
|
+
const base = `mcp__${m.name}__${s.name}`.replace(/[^a-zA-Z0-9_-]/g, "_").slice(0, 128);
|
|
7567
|
+
let display = base;
|
|
7568
|
+
for (let i = 2; routes.has(display); i++) display = `${base.slice(0, 128 - String(i).length - 1)}_${i}`;
|
|
7569
|
+
specs.push({ name: display, description: s.description, inputSchema: s.inputSchema });
|
|
7570
|
+
routes.set(display, { server: m.name, rawName: s.name });
|
|
7501
7571
|
}
|
|
7502
7572
|
}
|
|
7503
|
-
|
|
7504
|
-
|
|
7505
|
-
|
|
7506
|
-
|
|
7507
|
-
|
|
7508
|
-
|
|
7509
|
-
};
|
|
7510
|
-
|
|
7511
|
-
|
|
7512
|
-
|
|
7513
|
-
|
|
7514
|
-
|
|
7515
|
-
|
|
7573
|
+
return { specs, routes };
|
|
7574
|
+
}
|
|
7575
|
+
function searchOverCatalog(servers, specs, routes, resolve4, options) {
|
|
7576
|
+
const tools = specs.length ? makeMcpToolSearch(specs, (name, args) => {
|
|
7577
|
+
const r = routes.get(name);
|
|
7578
|
+
if (!r) throw new Error(`unknown MCP tool '${name}' \u2014 use ToolSearch to find valid names`);
|
|
7579
|
+
return resolve4(r.server, r.rawName, args ?? {});
|
|
7580
|
+
}, options) : [];
|
|
7581
|
+
return { tools, serverNames: servers, toolCount: specs.length };
|
|
7582
|
+
}
|
|
7583
|
+
function makeMcpToolSearchFromMounted(mounted, options) {
|
|
7584
|
+
const { specs, routes } = buildMcpCatalog(mounted);
|
|
7585
|
+
const byName = new Map(mounted.map((m) => [m.name, m]));
|
|
7586
|
+
return searchOverCatalog(mounted.map((m) => m.name), specs, routes, (server, rawName, args) => byName.get(server).client.callTool(rawName, args), options);
|
|
7516
7587
|
}
|
|
7517
7588
|
|
|
7518
7589
|
// src/index.ts
|
|
7590
|
+
init_logging();
|
|
7519
7591
|
init_worktree();
|
|
7520
7592
|
import { MemFilesystem as MemFilesystem3, IndexedDbFilesystem, CommandExecutor as CommandExecutor2, registerHeadlessCommands as registerHeadlessCommands2 } from "@livx.cc/wcli/core";
|
|
7521
7593
|
|
|
@@ -10803,8 +10875,8 @@ function applyKey(s, key, str) {
|
|
|
10803
10875
|
}
|
|
10804
10876
|
return "none";
|
|
10805
10877
|
}
|
|
10806
|
-
function createLineEditor(out) {
|
|
10807
|
-
const isTTY = !!out.isTTY && !!
|
|
10878
|
+
function createLineEditor(out, input = keyInput) {
|
|
10879
|
+
const isTTY = !!out.isTTY && !!input.isTTY;
|
|
10808
10880
|
const dim2 = (x) => `\x1B[2m${x}\x1B[0m`;
|
|
10809
10881
|
const inverse = (x) => `\x1B[7m${x}\x1B[0m`;
|
|
10810
10882
|
const COLOR = {
|
|
@@ -10892,9 +10964,9 @@ function createLineEditor(out) {
|
|
|
10892
10964
|
curRow = 0;
|
|
10893
10965
|
if (opts.initial) s.insert(opts.initial);
|
|
10894
10966
|
s.refresh();
|
|
10895
|
-
emitKeypressEvents(
|
|
10896
|
-
|
|
10897
|
-
|
|
10967
|
+
emitKeypressEvents(input);
|
|
10968
|
+
input.setRawMode(true);
|
|
10969
|
+
input.resume();
|
|
10898
10970
|
out.write("\x1B[?2004h");
|
|
10899
10971
|
const promptOf = () => typeof opts.prompt === "function" ? opts.prompt() : opts.prompt;
|
|
10900
10972
|
render(s, promptOf(), maxVisible, opts.status);
|
|
@@ -10978,9 +11050,9 @@ function createLineEditor(out) {
|
|
|
10978
11050
|
return;
|
|
10979
11051
|
}
|
|
10980
11052
|
if (key?.meta && key.name === "p" && opts.onPickModel) {
|
|
10981
|
-
|
|
11053
|
+
input.off("keypress", onKey);
|
|
10982
11054
|
void opts.onPickModel().finally(() => {
|
|
10983
|
-
|
|
11055
|
+
input.on("keypress", onKey);
|
|
10984
11056
|
curRow = 0;
|
|
10985
11057
|
redraw();
|
|
10986
11058
|
});
|
|
@@ -11017,7 +11089,7 @@ function createLineEditor(out) {
|
|
|
11017
11089
|
activeRedraw = void 0;
|
|
11018
11090
|
activeAbort = void 0;
|
|
11019
11091
|
if (ticker) clearInterval(ticker);
|
|
11020
|
-
|
|
11092
|
+
input.off("keypress", onKey);
|
|
11021
11093
|
process.removeListener("SIGWINCH", onResize);
|
|
11022
11094
|
s.closeMenu();
|
|
11023
11095
|
if (suspended) {
|
|
@@ -11034,7 +11106,7 @@ function createLineEditor(out) {
|
|
|
11034
11106
|
out.write([prompt + lines[0], ...lines.slice(1)].map((l) => wrapAnsi(l, cols, " ")).join("\r\n") + "\r\n");
|
|
11035
11107
|
curRow = 0;
|
|
11036
11108
|
};
|
|
11037
|
-
|
|
11109
|
+
input.on("keypress", onKey);
|
|
11038
11110
|
});
|
|
11039
11111
|
}
|
|
11040
11112
|
return {
|
|
@@ -11053,6 +11125,7 @@ function createLineEditor(out) {
|
|
|
11053
11125
|
curRow = 0;
|
|
11054
11126
|
activeRedraw?.();
|
|
11055
11127
|
},
|
|
11128
|
+
isSuspended: () => suspended,
|
|
11056
11129
|
abort: () => activeAbort?.()
|
|
11057
11130
|
};
|
|
11058
11131
|
}
|
|
@@ -12929,6 +13002,12 @@ async function repl(args, ai, cfg, cwd) {
|
|
|
12929
13002
|
};
|
|
12930
13003
|
let toggleVoice;
|
|
12931
13004
|
let editorRef;
|
|
13005
|
+
const emitChrome = (write) => {
|
|
13006
|
+
const wasSusp = editorRef?.isSuspended() ?? true;
|
|
13007
|
+
editorRef?.suspend();
|
|
13008
|
+
write();
|
|
13009
|
+
if (!wasSusp) editorRef?.resume();
|
|
13010
|
+
};
|
|
12932
13011
|
let repaintStash = () => {
|
|
12933
13012
|
};
|
|
12934
13013
|
let workerOptions;
|
|
@@ -13050,23 +13129,23 @@ async function repl(args, ai, cfg, cwd) {
|
|
|
13050
13129
|
if (e.kind === "task_done" && e.data?.text) {
|
|
13051
13130
|
const lines = String(e.data.text).split("\n");
|
|
13052
13131
|
const shown = lines.slice(0, previewLines());
|
|
13053
|
-
|
|
13132
|
+
emitChrome(() => {
|
|
13133
|
+
err("\n" + dim(` \u29BF ${e.message}
|
|
13054
13134
|
`) + shown.map((l) => dim(` ${plainLine(l)}
|
|
13055
13135
|
`)).join(""));
|
|
13056
|
-
|
|
13136
|
+
if (lines.length > shown.length) err(dim(` \u2026 (+${lines.length - shown.length} more lines)
|
|
13057
13137
|
`));
|
|
13138
|
+
});
|
|
13058
13139
|
duplexAccount(e.data);
|
|
13059
|
-
editorRef?.redrawNow();
|
|
13060
13140
|
repaintStash();
|
|
13061
13141
|
return;
|
|
13062
13142
|
}
|
|
13063
13143
|
if (typeof e.kind === "string" && e.kind.startsWith("task_")) {
|
|
13064
13144
|
spinner.stop();
|
|
13065
|
-
|
|
13145
|
+
emitChrome(() => err(e.kind === "task_ask" ? yellow(` ? ${e.message} \u2014 answer by voice or type yes/no
|
|
13066
13146
|
`) : e.kind === "task_error" ? yellow(` \u2717 ${e.message}
|
|
13067
13147
|
`) : dim(` \xB7 ${e.message}
|
|
13068
13148
|
`)));
|
|
13069
|
-
editorRef?.redrawNow();
|
|
13070
13149
|
repaintStash();
|
|
13071
13150
|
return;
|
|
13072
13151
|
}
|