@0perator/operator 0.1.353 → 0.1.354

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/acp/agent.js CHANGED
@@ -19,6 +19,7 @@ import { moaTeam } from "../engine/moa.js";
19
19
  import { hasByoToken } from "../auth/byo.js";
20
20
  import { operatorPath } from "../config/home.js";
21
21
  import { redactSecrets } from "../engine/redact.js";
22
+ import { fallbackNotice } from "../engine/continuation.js";
22
23
  import { EventSink } from "../telemetry/events.js";
23
24
  import { centralRecording } from "../telemetry/ingest.js";
24
25
  import { PermissionPolicy } from "../permissions/index.js";
@@ -354,6 +355,7 @@ export function acpHandlers(emit, ctx = {}) {
354
355
  return {
355
356
  onDelta: (chunk) => emit({ sessionUpdate: "agent_message_chunk", content: { type: "text", text: chunk } }),
356
357
  onReasoning: (chunk) => emit({ sessionUpdate: "agent_thought_chunk", content: { type: "text", text: chunk } }),
358
+ onFallback: (e) => emit({ sessionUpdate: "agent_message_chunk", content: { type: "text", text: `\n\n${fallbackNotice(e)}\n\n` } }), // its own paragraph, apart from the answer
357
359
  onToolStart: (calls) => {
358
360
  for (const c of calls) {
359
361
  ctx.calls?.start(c.id, c.name, c.args);
@@ -112,7 +112,7 @@ function briefFor(task) {
112
112
  * flywheel-prefix contract, _ai-docs/conventions) and the two parenthesized empty-reply notes in engine/agent.ts.
113
113
  * Returned verbatim they would reach the planner AS the sub-agent's answer — seen live: Scout on a tool task
114
114
  * emitted whitespace twice and the planner would have been told "(the model returned an empty response…)". */
115
- const NO_ANSWER = /^\s*(\[(stopped|paused|no reply came back from the model|declined by the provider)\b|\((the model returned an empty response|hit the output limit before an answer landed))/;
115
+ const NO_ANSWER = /^\s*(\[(stopped|paused|no answer|no reply came back from the model|declined by the provider)\b|\((the model returned an empty response|hit the output limit before an answer landed))/;
116
116
  let _seq = 0;
117
117
  const TIMED_OUT = Symbol("delegate-timeout");
118
118
  const progressListeners = new Set();
@@ -18,6 +18,7 @@ function handlersFor(reporter, json, prompt = "", onDelta) {
18
18
  onServed: (s) => reporter.event("fallback", { from: s.fallbackFrom, servedBy: s.backend ?? null }), // the selected model was down; another box answered
19
19
  onAutoContinue: (round) => reporter.event("auto_continue", { round }),
20
20
  onSelfHeal: (kind, attempt) => reporter.event("self_heal", { kind, attempt }),
21
+ onFallback: (e) => reporter.event("model_fallback", { from: e.from, servedBy: e.to, reason: e.reason, note: e.line }), // every leg of the model failed; its fallback answered
21
22
  onLoopCompaction: (e) => reporter.event("loop_compaction", { ...e }),
22
23
  onLoopRecovery: (e) => reporter.event("loop_recovery", { attempt: e.attempt, max: e.max, rounds: e.rounds, replaced: e.replaced, calls: e.repeated.length }),
23
24
  onToolBatch: (events, durationMs) => {
@@ -106,7 +107,7 @@ export async function runHeadless(settings, prompt, opts = {}) {
106
107
  } // an engine stop always ends on its question, even after a cut-off stream
107
108
  answer(outcome.display ?? outcome.content);
108
109
  await session.flushRouteShadow(); // MOA phase-0: headless one-shot exits before fire-and-forget would land
109
- return finish(outcome.interrupted ? 130 : 0);
110
+ return finish(outcome.interrupted ? 130 : outcome.stopKind === "unanswered" ? 1 : 0); // nothing answered: a failed run, with each leg's cause as the result
110
111
  }
111
112
  catch (e) {
112
113
  const message = e instanceof Error ? e.message : String(e);
package/dist/cli.js CHANGED
@@ -51,6 +51,7 @@ import { modelCtxFor, leanHarnessFor, selectModel, modelRegistry, fmtCtx, shortN
51
51
  import { fetchPortalModels, offlineNote, portalIdFor } from "./router/portal.js";
52
52
  import { fetchFreeModels } from "./router/free-models.js";
53
53
  import { describeTurnError } from "./engine/net-error.js";
54
+ import { fallbackNotice, recoveryLine } from "./engine/continuation.js";
54
55
  import { hasByoToken, setByoToken } from "./auth/byo.js";
55
56
  import { getDiscoveredModels } from "./router/discovery.js";
56
57
  import { disposeShellSession, getAgentTasks, registry } from "./tools/registry.js";
@@ -1271,7 +1272,7 @@ function Root() {
1271
1272
  const newRound = () => { roundStartRef.current = Date.now(); readRingRef.current = []; firstTokenRef.current = false; readReceiptRef.current = false; sentAtRef.current = null; gateQueueRef.current = null; noteRound(ledgerRef.current); decodeRound(decodeRef.current, liveTokRef.current); };
1272
1273
  // A round's stream ended: its average rate at its depth joins this model's history (the "earlier this session" figure).
1273
1274
  const endRoundDecode = () => {
1274
- noteRoundRate(decodeRef.current, routeLabel(session.currentModel()), depthRef.current, liveTokRef.current, Date.now());
1275
+ noteRoundRate(decodeRef.current, routeLabel(session.answeringModel()), depthRef.current, liveTokRef.current, Date.now());
1275
1276
  decodeRef.current.roundStartAt = undefined;
1276
1277
  };
1277
1278
  // The request's first progress chunk: the server's own time_ms says how long it has been reading, so the rest of the
@@ -1286,7 +1287,7 @@ function Root() {
1286
1287
  noteWait(ledgerRef.current, Math.max(0, held));
1287
1288
  if (held < HOLD_RECEIPT_MS)
1288
1289
  return;
1289
- sys(holdReceipt(routeLabel(session.currentModel()), held, termCols()));
1290
+ sys(holdReceipt(routeLabel(session.answeringModel()), held, termCols()));
1290
1291
  };
1291
1292
  // The round's first reasoning/content chunk: a read of RECEIPT_MIN_MS or more settles one dim receipt into scrollback
1292
1293
  // (and to followers) — what was read, how fast, what was cached, when the first token came.
@@ -1298,13 +1299,13 @@ function Root() {
1298
1299
  expectRef.current = null;
1299
1300
  if (st) {
1300
1301
  noteRead(ledgerRef.current, { ms: st.elapsedMs, fresh: st.fresh, cache: st.cache });
1301
- noteColdRead(coldReadsRef.current, routeLabel(session.currentModel()), st);
1302
+ noteColdRead(coldReadsRef.current, routeLabel(session.answeringModel()), st);
1302
1303
  depthRef.current = st.total;
1303
1304
  }
1304
1305
  if (!st || st.elapsedMs < RECEIPT_MIN_MS)
1305
1306
  return;
1306
1307
  readReceiptRef.current = true;
1307
- sys(readReceipt(st, termCols(), { model: routeLabel(session.currentModel()), firstTokenMs: Date.now() - turnStartRef.current }));
1308
+ sys(readReceipt(st, termCols(), { model: routeLabel(session.answeringModel()), firstTokenMs: Date.now() - turnStartRef.current }));
1308
1309
  };
1309
1310
  const startTurn = useCallback(async (text, opts) => {
1310
1311
  setNextSteps(null); // a new turn retires the last stop's one-key strip
@@ -1377,7 +1378,7 @@ function Root() {
1377
1378
  setRoute(model);
1378
1379
  setCtxPct(pct);
1379
1380
  remoteRef.current?.setStatus(pct, model, session.sessionTokens());
1380
- rateFeed.route(model === "moa" ? label : model); // a MoA round runs on the planner or the specialist: label names it
1381
+ rateFeed.route(model === "moa" ? label : session.answeringModel()); // a MoA round runs on the planner or the specialist: label names it; a fallback round, on the default row
1381
1382
  actRef.current = { guard: actRef.current.guard }; // a new request: its stream and its read start over
1382
1383
  // GW-06 oracle seed (once, fire-and-forget): a fresh meter cold-starts at chars/4 (4.0) — measured
1383
1384
  // truth on agent traffic is ~2.15 (aurora-tier0/calibrate-token-meter.py), i.e. the gate fires LATE
@@ -1434,7 +1435,7 @@ function Root() {
1434
1435
  if (c)
1435
1436
  noteCompaction(ledgerRef.current, Date.now() - c.startedAt);
1436
1437
  if (c && after < before) {
1437
- const f = forecast(coldReadsRef.current, routeLabel(session.currentModel()), after); // after a compaction the summary is a new prefix
1438
+ const f = forecast(coldReadsRef.current, routeLabel(session.answeringModel()), after); // after a compaction the summary is a new prefix
1438
1439
  expectRef.current = f;
1439
1440
  sys(compactReceipt(before, after, Date.now() - c.startedAt, termCols(), forecastTail(f)));
1440
1441
  }
@@ -1531,6 +1532,7 @@ function Root() {
1531
1532
  lastFallbackRef.current = key;
1532
1533
  sys(`⚠ ${fallbackFrom} is unavailable — this answer came from ${backend ?? "another backend"} (gateway fallback)`);
1533
1534
  },
1535
+ onFallback: (e) => sys(fallbackNotice(e)), // every leg of the model failed: which model answered this turn, and why
1534
1536
  onCompaction: (e) => {
1535
1537
  if (!e.skipped) {
1536
1538
  compactionWarnedRef.current = false;
@@ -1554,10 +1556,11 @@ function Root() {
1554
1556
  onAutoContinue: (round) => {
1555
1557
  push({ kind: "message", message: { id: nextId(), role: "assistant", content: `↻ still working — auto-continuing past ${round} tool rounds`, reasoning: "" } });
1556
1558
  },
1557
- onSelfHeal: (kind) => {
1559
+ onSelfHeal: (kind, _attempt, step) => {
1558
1560
  // A recovery reads as the agent working it out, NOT an error — show the calm "adjusting"
1559
- // animation instead of surfacing a raw http 400/5xx. The next delta/tool flips status back.
1560
- setStepLabel(kind === "context_exceeded" ? "adjusting context" : kind === "unavailable" ? "reconnecting" : "recovering");
1561
+ // animation instead of surfacing a raw http 400/5xx. The next delta/tool flips status back. A server
1562
+ // failure names the leg, its cause and the next move, so a slow answer never reads as a broken model.
1563
+ setStepLabel(step ? recoveryLine(step) : kind === "context_exceeded" ? "adjusting context" : kind === "unavailable" ? "reconnecting" : "recovering");
1561
1564
  if (draftRowsRef.current.length || draftPendingRef.current.size) {
1562
1565
  draftRowsRef.current = [];
1563
1566
  draftPendingRef.current.clear();
@@ -1734,8 +1737,8 @@ function Root() {
1734
1737
  const tps = outcome.genMs && outcome.genMs > 0 ? Math.round(tok / (outcome.genMs / 1000)) : 0;
1735
1738
  if (tps > 0)
1736
1739
  tokHist.current = [...tokHist.current, tps].slice(-40); // keep the last 40 turns' throughput
1737
- if (session.currentModel() !== "moa")
1738
- rateFeed.decode(session.currentModel(), outcome.tokens, outcome.genMs);
1740
+ if (session.currentModel() !== "moa" && session.answeringModel() === session.currentModel())
1741
+ rateFeed.decode(session.currentModel(), outcome.tokens, outcome.genMs); // a turn the fallback took mixes two models' decode
1739
1742
  const prefill = outcome.promptTokens ?? 0;
1740
1743
  const parts = [fmtDuration(secs), `${fmtTokens(tok).replace(/ tokens?$/, " tok")}${tps ? ` @ ${tps} tok/s` : ""}`];
1741
1744
  if (prefill)
@@ -3582,12 +3585,12 @@ function Root() {
3582
3585
  // The main turn as a lane (TUI plan #11): its model, its plan step and phase, its clock and tokens.
3583
3586
  const stepAt = tasks.findIndex((t) => t.status === "in_progress");
3584
3587
  const mainLane = status !== "idle" && shownPhase
3585
- ? { model: routeLabel(route), activity: `${stepVerb && stepAt >= 0 ? `step ${stepAt + 1}/${tasks.length} · ` : ""}${phaseWord(shownPhase)}`, elapsedMs: elapsed * 1000, tokens: liveTok }
3588
+ ? { model: routeLabel(session.answeringModel()), activity: `${stepVerb && stepAt >= 0 ? `step ${stepAt + 1}/${tasks.length} · ` : ""}${phaseWord(shownPhase)}`, elapsedMs: elapsed * 1000, tokens: liveTok }
3586
3589
  : null;
3587
3590
  const compactRead = compactRef.current ? readStats(compactRef.current.ring) : undefined;
3588
3591
  const phaseView = shownPhase
3589
3592
  ? {
3590
- phase: shownPhase, model: routeLabel(route), tokens: liveTok, label: stepLabel,
3593
+ phase: shownPhase, model: routeLabel(session.answeringModel()), tokens: liveTok, label: stepLabel,
3591
3594
  read: shownPhase === "reading" ? readStats(readRingRef.current, roundStartRef.current) : undefined,
3592
3595
  queue: shownPhase === "queued" ? gateQueueRef.current ?? undefined : undefined,
3593
3596
  compaction: shownPhase === "compacting" && compactRef.current ? { before: compactRef.current.before, read: compactRead, wrote: compactRef.current.wrote, approx: vendorStream } : undefined,
@@ -2,13 +2,14 @@
2
2
  // text tool-call recovery (toolcalls.ts) and compaction (compaction.ts). Tools and routing are
3
3
  // NOT implemented here — this file depends only on the two interfaces below, which the
4
4
  // kode-tsi/src/tools/** + kode-tsi/src/router/** lane implements.
5
- import { chat, endpointSlots, getOperatorToken, requiresOperatorToken } from "./aurora.js";
5
+ import { chat, endpointSlots, getOperatorToken, requiresOperatorToken, StreamServerError } from "./aurora.js";
6
6
  import { parseToolArgs } from "./json-repair.js";
7
7
  import { buildMessages } from "./messages.js";
8
8
  import { recoverToolCalls, cleanAssistantProse } from "./toolcalls.js";
9
9
  import { compact, needsCompaction, shouldProactivelyCompact, fitToWindow, clampMaxTokens, outputRoom, headroomTargetRatio, effectiveCeilingTokens, fullRequestEstimate, TOOL_CALL_HEADROOM_TOKENS } from "./compaction.js";
10
10
  import { globalTokenMeter, endpointKey, requestChars } from "./token-meter.js";
11
- import { classifyFailure, servedContextLimit, outputCeilingLimit, learnOutputCeiling, learnedOutputCeiling, backoffMs, sleep } from "./selfheal.js";
11
+ import { classifyFailure, failureCause, servedContextLimit, outputCeilingLimit, learnOutputCeiling, learnedOutputCeiling, backoffMs, sleep } from "./selfheal.js";
12
+ import { hostOf } from "./net-error.js";
12
13
  import { TaskVerification, VERIFY_REMINDER, NOT_VERIFIED_BANNER, unrunCheckBanner, unrunCheckReminder } from "./verify-gate.js";
13
14
  import { detectRefusal, buildAffirmativeRetry, UNRESTRICTED_MAX_RETRIES } from "./unrestricted.js";
14
15
  import { ComputerEventStream, ComputerEventTracker } from "./computer-event.js";
@@ -33,7 +34,7 @@ import { MUTATING_TOOLS, mutationLanded } from "../tools/mutating.js"; // single
33
34
  /** The executor's identical-call refusal, exactly (tools/executor.ts): a tool's own output that merely starts with
34
35
  * "loop guard:" (a log, a grep of this source) is real output, not a refusal to be counted and replaced. */
35
36
  export const EXECUTOR_REPEAT_REFUSAL = /^loop guard: "[^"]+" called \d+x with identical args this turn/;
36
- import { ANNOUNCE_NUDGE, ANNOUNCE_NUDGE_MAX, DELEGATION_NUDGE, detectAnnouncedDelegation, detectUnfinishedAction, engineNote, detectSelfDialogue, SELF_DIALOGUE_NUDGE, SELF_DIALOGUE_NUDGE_MAX, needsClosingSteer, CLOSING_NUDGE, CLOSING_NUDGE_UNATTENDED, EMPTY_REPLY_NUDGE, emptyReplyStatus, closeStopNote, stopQuestion, stopKind, stripEngineEcho, isEngineFinal } from "./continuation.js";
37
+ import { ANNOUNCE_NUDGE, ANNOUNCE_NUDGE_MAX, DELEGATION_NUDGE, detectAnnouncedDelegation, detectUnfinishedAction, engineNote, detectSelfDialogue, SELF_DIALOGUE_NUDGE, SELF_DIALOGUE_NUDGE_MAX, needsClosingSteer, CLOSING_NUDGE, CLOSING_NUDGE_UNATTENDED, EMPTY_REPLY_NUDGE, fallbackLine, noAnswer, closeStopNote, stopQuestion, stopKind, stripEngineEcho, isEngineFinal } from "./continuation.js";
37
38
  // Poll/status tools are meant to be called repeatedly while waiting on async work — NEVER a spin, so the
38
39
  // loop guard skips them entirely (agent_status polls sub-agents, bash_output polls a background job).
39
40
  const LOOP_GUARD_EXEMPT = new Set(["agent_status", "bash_output"]);
@@ -805,6 +806,52 @@ export async function runTurn(userInput, conversation, opts) {
805
806
  conversation.assistant(text);
806
807
  return { content: text, display: stopQuestion(note, opts.preservedState?.()), stopKind: stopKind(note), rounds: roundsRun, toolCalls: toolCallTotal, stopReason, tokens: tokensTotal, genMs: genMsTotal, promptTokens: promptTokensTotal, promptMs: promptMsTotal, loop: loopEv.evidence() };
807
808
  };
809
+ // Never silent (11/04): a router's legs are each tried once per round. When all of them fail, or the model keeps
810
+ // finishing with nothing in its reply, the model's fallback (TurnModel) takes the rest of THIS turn; a turn nothing
811
+ // answers ends naming each leg's cause and the next step (noAnswer).
812
+ let router = opts.router;
813
+ let fallback;
814
+ let fallbackPending; // reported when the fallback's first reply with something in it lands
815
+ const legFailures = []; // this turn's failed legs, in the order tried
816
+ const failedLeg = (ep, cause, detail) => {
817
+ const model = fallback?.name ?? opts.model?.name ?? ep.label ?? ep.model;
818
+ const host = hostOf(ep.base);
819
+ const seen = legFailures.find((l) => l.model === model && l.host === host);
820
+ if (seen)
821
+ return Object.assign(seen, { cause, detail, tries: seen.tries + 1 });
822
+ const leg = { model, host, cause, detail, tries: 1 };
823
+ legFailures.push(leg);
824
+ return leg;
825
+ };
826
+ const serverFailed = (ep, err) => {
827
+ const inBand = err instanceof StreamServerError; // the server's own error, sent with a 200
828
+ return failedLeg(ep, failureCause(err) + (inBand && ep.provider ? ` on ${ep.provider}` : ""), inBand && err.via !== "empty" ? "inside an HTTP 200" : undefined);
829
+ };
830
+ /** Hand the rest of the turn to the model's fallback, once: its router and a fresh self-heal budget. */
831
+ const takeFallback = (reason, silent) => {
832
+ const fb = fallback || !opts.model?.fallback ? undefined : opts.model.fallback();
833
+ if (!fb || !opts.model)
834
+ return undefined;
835
+ const from = opts.model.name;
836
+ const legs = legFailures.filter((l) => l.model === from).map((l) => ({ ...l }));
837
+ const cause = [...new Set(legs.map((l) => l.cause))].join("; ");
838
+ fallbackPending = { from, to: fb.name, reason, line: fallbackLine({ from, to: fb.name, cause, silent }), legs };
839
+ fallback = fb;
840
+ router = fb.router;
841
+ selfHealBudget = MAX_SELF_HEAL_PER_TURN;
842
+ return router.select(buildMessages(opts.systemPrompt, conversation.all), opts.toolSchemas);
843
+ };
844
+ const fallbackLanded = () => {
845
+ if (!fallbackPending)
846
+ return;
847
+ opts.onFallback?.(fallbackPending);
848
+ fallbackPending = undefined;
849
+ };
850
+ const unanswered = (roundsRun) => {
851
+ const na = noAnswer({ tried: legFailures, owner: opts.model?.name ?? legFailures[0]?.model ?? "the model", fallback: fallback?.name, tasks: opts.preservedState?.() });
852
+ conversation.assistant(na.note);
853
+ return { content: na.note, display: na.display, stopKind: "unanswered", rounds: roundsRun, toolCalls: toolCallTotal, tokens: tokensTotal, genMs: genMsTotal, promptTokens: promptTokensTotal, promptMs: promptMsTotal, loop: loopEv.evidence() };
854
+ };
808
855
  /** A loop-family nudge: injected, or — when it is the Nth ignored one — replaced by a loop reset before the next
809
856
  * request. While a reset is pending, further nudges are absorbed: its note supersedes them. */
810
857
  const loopNudge = (kind, text) => {
@@ -1058,8 +1105,9 @@ export async function runTurn(userInput, conversation, opts) {
1058
1105
  noEditNudged = true;
1059
1106
  loopNudge("no_edit_streak", noEditNudge(noEditStreak));
1060
1107
  }
1061
- let endpoint = opts.router.select(buildMessages(opts.systemPrompt, conversation.all), opts.toolSchemas);
1108
+ let endpoint = router.select(buildMessages(opts.systemPrompt, conversation.all), opts.toolSchemas);
1062
1109
  opts.onRoute?.(endpoint);
1110
+ const failedThisRound = new Set(); // legs (bases) whose request failed in this round's failover
1063
1111
  // Endpoint-aware (SPEC §5): rebuild against whichever endpoint is current, since self-heal
1064
1112
  // failover below can swap endpoints mid-round and each has its own ctx_window.
1065
1113
  const compactionOptsFor = (ep) => ({
@@ -1285,7 +1333,7 @@ export async function runTurn(userInput, conversation, opts) {
1285
1333
  // model that needs no token) can still answer — JL1 over SSH has a locked keychain, so no token loads and
1286
1334
  // the gateway says 401 while Cortana sits on localhost. One hop per turn; then fail with the cause.
1287
1335
  if (recovery === "auth") {
1288
- const next = authFailedOver ? null : opts.router.recover(endpoint, "unavailable");
1336
+ const next = authFailedOver ? null : router.recover(endpoint, "unavailable");
1289
1337
  if (next) {
1290
1338
  authFailedOver = true;
1291
1339
  endpoint = next;
@@ -1296,8 +1344,21 @@ export async function runTurn(userInput, conversation, opts) {
1296
1344
  }
1297
1345
  // Non-retryable: a malformed request (a bad tool call) won't be fixed by resending — fail fast rather
1298
1346
  // than spin (that futile-retry storm is what burned minutes).
1299
- if (recovery === "bad_request" || selfHealBudget <= 0)
1347
+ if (recovery === "bad_request")
1300
1348
  throw err;
1349
+ if (selfHealBudget <= 0) {
1350
+ if (recovery !== "transient")
1351
+ throw err;
1352
+ const failed = { ...serverFailed(endpoint, err) };
1353
+ const fb = takeFallback("server");
1354
+ if (!fb)
1355
+ return unanswered(rounds + 1);
1356
+ opts.onSelfHeal?.("server_error", 1, { failed, next: { kind: "fallback", to: fallback.name } });
1357
+ endpoint = fb;
1358
+ failedThisRound.clear();
1359
+ opts.onRoute?.(endpoint);
1360
+ continue;
1361
+ }
1301
1362
  const attempt = MAX_SELF_HEAL_PER_TURN - selfHealBudget; // 0-based
1302
1363
  selfHealBudget -= 1;
1303
1364
  if (recovery === "context") {
@@ -1307,14 +1368,14 @@ export async function runTurn(userInput, conversation, opts) {
1307
1368
  // both the routing choice and the compaction below size to the truth, not the roster's lie.
1308
1369
  const served = servedContextLimit(err);
1309
1370
  if (served !== undefined) {
1310
- opts.router.observeContext?.(endpoint, served); // persist the learned window for the rest of the session
1371
+ router.observeContext?.(endpoint, served); // persist the learned window for the rest of the session
1311
1372
  if (served < endpoint.ctxWindow)
1312
1373
  endpoint = { ...endpoint, ctxWindow: served };
1313
1374
  }
1314
1375
  opts.onSelfHeal?.("context_exceeded", attempt + 1);
1315
1376
  // Prefer a genuinely BIGGER healthy endpoint; ignore a "recovery" that isn't larger (escalate can
1316
1377
  // hand back a same-size endpoint, which would just overflow again).
1317
- const bigger = opts.router.recover(endpoint, "context_exceeded");
1378
+ const bigger = router.recover(endpoint, "context_exceeded");
1318
1379
  if (bigger && bigger.ctxWindow > endpoint.ctxWindow) {
1319
1380
  endpoint = bigger;
1320
1381
  opts.onRoute?.(endpoint);
@@ -1334,20 +1395,37 @@ export async function runTurn(userInput, conversation, opts) {
1334
1395
  engineUser(rehydrationNote(touchedFiles)); // rehydrate after a forced compaction
1335
1396
  continue;
1336
1397
  }
1337
- // transient (429 / 5xx / network drop): a busy or unhealthy backend, NOT a context problem.
1338
- // Fail over to a healthy endpoint AND back off (exponential + jitter) so we don't storm a server
1339
- // that's already struggling. NEVER compact here — that was the "compacted at 0%" wasted work.
1340
- opts.onSelfHeal?.("server_error", attempt + 1);
1341
- const healthy = opts.router.recover(endpoint, "server_error");
1398
+ // transient (429 / 5xx / network drop / a server error inside a 200): a busy or unhealthy backend, NOT a
1399
+ // context problem. Fail over to a leg not yet tried this round AND back off (exponential + jitter) so we
1400
+ // don't storm a server that's already struggling — two legs can reach the same box. When every leg has
1401
+ // failed, the fallback answers instead of another request to a broken upstream; only a router with one
1402
+ // leg retries it. NEVER compact here — that was the "compacted at 0%" wasted work.
1403
+ const failed = { ...serverFailed(endpoint, err) };
1404
+ failedThisRound.add(endpoint.base);
1405
+ const healthy = router.recover(endpoint, "server_error");
1406
+ if (healthy && failedThisRound.has(healthy.base)) {
1407
+ const fb = takeFallback("server");
1408
+ if (!fb)
1409
+ return unanswered(rounds + 1);
1410
+ opts.onSelfHeal?.("server_error", attempt + 1, { failed, next: { kind: "fallback", to: fallback.name } });
1411
+ endpoint = fb;
1412
+ failedThisRound.clear();
1413
+ opts.onRoute?.(endpoint);
1414
+ continue;
1415
+ }
1416
+ const wait = backoffMs(attempt, err);
1417
+ opts.onSelfHeal?.("server_error", attempt + 1, { failed, next: healthy ? { kind: "leg", host: hostOf(healthy.base) } : { kind: "retry", waitMs: wait } });
1342
1418
  if (healthy) {
1343
1419
  endpoint = healthy;
1344
1420
  opts.onRoute?.(endpoint);
1345
1421
  }
1346
- await sleep(backoffMs(attempt, err), opts.signal, () => new TurnAbortedError());
1422
+ await sleep(wait, opts.signal, () => new TurnAbortedError());
1347
1423
  continue;
1348
1424
  }
1349
1425
  }
1350
1426
  loopEv.responded(); // the warnings injected before this request have been seen
1427
+ if (response.content?.trim() || response.toolCalls?.length)
1428
+ fallbackLanded();
1351
1429
  // Unrestricted mode (engine/unrestricted.ts, owner's private system): this round's `response` just came
1352
1430
  // back clean (no self-heal error) — if it has no tool calls AND its text/stopReason reads as a
1353
1431
  // POLICY/MORAL refusal (not a capability limit), re-issue the SAME request with an affirmative-prefill
@@ -1791,6 +1869,16 @@ export async function runTurn(userInput, conversation, opts) {
1791
1869
  continue;
1792
1870
  }
1793
1871
  }
1872
+ // Still nothing after the retries — not in the reply, its reasoning, or an earlier empty round's: the model's own
1873
+ // silence. Its fallback answers the rest of this turn; with none, the turn ends saying what was tried.
1874
+ if (!final && response.stopReason !== "length" && !stripScratchpad(response.reasoningContent ?? "") && !stripScratchpad(lastReasoning)) {
1875
+ failedLeg(endpoint, `${emptyRetries + 1} replies with nothing in them`);
1876
+ if (takeFallback("silence", emptyRetries + 1)) {
1877
+ emptyRetries = 0;
1878
+ continue;
1879
+ }
1880
+ return unanswered(rounds + 1);
1881
+ }
1794
1882
  // Turn-continuation: a text-only round whose tail is an unperformed action announcement ("Let me implement
1795
1883
  // these now.") is NOT a finished turn — finalizing here would leave the work undone and make the owner type
1796
1884
  // "continue". Record the model's text, nudge it (user role — real content + tool context exist, so it is
@@ -1863,9 +1951,8 @@ export async function runTurn(userInput, conversation, opts) {
1863
1951
  const unverified = verifyEnabled && verify.gate(); // changed files, still no passing check after the nudge
1864
1952
  const answer = (unverified ? NOT_VERIFIED_BANNER : unrunChecks.length ? unrunCheckBanner(unrunChecks) : "") +
1865
1953
  (final || stripScratchpad(response.reasoningContent ?? "") || stripScratchpad(lastReasoning) ||
1866
- (response.stopReason === "length"
1867
- ? "(hit the output limit before an answer landed — ask me to continue and I'll pick up where I left off.)"
1868
- : emptyReplyStatus(opts.preservedState?.(), emptyRetries + 1)));
1954
+ "(hit the output limit before an answer landed — ask me to continue and I'll pick up where I left off.)");
1955
+ fallbackLanded(); // an answer from the fallback's reasoning channel
1869
1956
  conversation.assistant(answer);
1870
1957
  // a recovered loop moved on to an answer: reported here, where the answer is final — an announcement the continuation
1871
1958
  // check sent back, or a closing the nudge rewrote, never became the step that moved the turn on
@@ -135,6 +135,41 @@ export function authHeaders(o) {
135
135
  const token = o.token ?? (isOperatorTrustedHost(hostOf(o.base)) ? _operatorToken : undefined);
136
136
  return token ? { Authorization: `Bearer ${token}` } : {};
137
137
  }
138
+ /** A server error that came INSIDE an HTTP 200: an SSE error event (`data: {"error":…}`, llama-server's `error: {…}` line,
139
+ * an `event: error` frame), a JSON error body, or a stream that ended with no content and no finish_reason. 11/04: JL1's
140
+ * Metal backend failed and llama-server answered every request 200 with "Compute error." in the stream — /health stayed
141
+ * ok, the router logged 200s, and chat() returned an empty reply. It carries the server's own status (500 when it names
142
+ * none; 502 for an empty stream), so selfheal.ts classifies it like that status and the router marks the leg unhealthy. */
143
+ export class StreamServerError extends Error {
144
+ serverMessage;
145
+ via;
146
+ status;
147
+ constructor(serverMessage, via, status, label) {
148
+ super(`${label} ${status}: ${serverMessage} (${via === "empty" ? "an HTTP 200 stream with no content and no finish_reason" : `server error inside an HTTP 200 ${via === "body" ? "body" : "stream"}`})`);
149
+ this.serverMessage = serverMessage;
150
+ this.via = via;
151
+ this.name = "StreamServerError";
152
+ this.status = status;
153
+ }
154
+ }
155
+ function streamError(o, payload, via) {
156
+ const e = payload && typeof payload === "object" && "error" in payload ? payload.error : payload;
157
+ const f = e && typeof e === "object" ? e : {};
158
+ const text = typeof e === "string" ? e : typeof f.message === "string" ? f.message : JSON.stringify(e);
159
+ const code = Number(f.code ?? f.status);
160
+ const status = Number.isInteger(code) && code >= 400 && code <= 599 ? code : 500;
161
+ return new StreamServerError((text || "server error").slice(0, 300), via, status, httpErrorLabel(o));
162
+ }
163
+ function parseJson(s) {
164
+ try {
165
+ return JSON.parse(s);
166
+ }
167
+ catch {
168
+ return undefined;
169
+ }
170
+ }
171
+ const SSE_FIELD = /^(?:data|event|error|id|retry):/;
172
+ const HEAD_MAX = 65_536; // a non-SSE body is read whole up to this: a JSON error body or a one-shot reply is one object
138
173
  // ---------------------------------------------------------------------------
139
174
  // Decode-time degeneration guard (SPEC §1). This is NOT a sampling penalty — it changes no
140
175
  // logits and touches no request knob, so a healthy model is completely unaffected. It only
@@ -436,9 +471,13 @@ async function* streamDeltas(messages, o) {
436
471
  const decodeMon = createDecodeMonitor(); // GAP 2: abort a CPU-fallback-slow decode so self-heal fails over
437
472
  const startedAt = Date.now();
438
473
  let lastByteAt = Date.now();
474
+ let event = ""; // the SSE `event:` name of the frame being read: an `event: error` frame's data is the error
475
+ let sse = false; // the body has sent an SSE field; until then it is kept whole in `head`
476
+ let head = "";
477
+ let answered = false; // a delta carried content, reasoning, a tool call or a finish_reason
439
478
  // finally: if a consumer breaks early (loop breaker, abort, first-answer), tear the socket down.
440
479
  try {
441
- for (;;) {
480
+ read: for (;;) {
442
481
  const idleLeft = idleMs > 0 ? idleMs - (Date.now() - lastByteAt) : Infinity;
443
482
  const wallLeft = wallMs > 0 ? wallMs - (Date.now() - startedAt) : Infinity;
444
483
  const budget = Math.min(idleLeft, wallLeft);
@@ -462,18 +501,40 @@ async function* streamDeltas(messages, o) {
462
501
  }
463
502
  const { value, done } = raced;
464
503
  lastByteAt = Date.now();
465
- if (done)
466
- break;
467
- buf += dec.decode(value, { stream: true });
468
- for (const line of buf.split("\n")) {
504
+ buf += done ? dec.decode() : dec.decode(value, { stream: true });
505
+ // Whole lines only: the tail waits for its newline, so a line split across two reads is read once.
506
+ const lines = buf.split("\n");
507
+ buf = done ? "" : lines.pop() ?? "";
508
+ for (const line of lines) {
469
509
  const t = line.trim();
470
- if (!t.startsWith("data:"))
510
+ if (!sse) {
511
+ if (!SSE_FIELD.test(t)) {
512
+ if (head.length < HEAD_MAX)
513
+ head += line + "\n";
514
+ continue;
515
+ }
516
+ sse = true;
517
+ }
518
+ if (!t) {
519
+ event = "";
520
+ continue;
521
+ }
522
+ if (t.startsWith("event:")) {
523
+ event = t.slice(6).trim();
524
+ continue;
525
+ }
526
+ const errorLine = t.startsWith("error:"); // llama-server before its 2025 rewrite sent an in-stream error as an `error:` line
527
+ if (!errorLine && !t.startsWith("data:"))
528
+ continue;
529
+ const d = t.slice(errorLine ? 6 : 5).trim();
530
+ if (!errorLine && d === "[DONE]")
531
+ break read;
532
+ const j = parseJson(d);
533
+ if (errorLine || event === "error" || j?.error)
534
+ throw streamError(o, j ?? d, "event");
535
+ if (j === undefined)
471
536
  continue;
472
- const d = t.slice(5).trim();
473
- if (d === "[DONE]")
474
- return;
475
537
  try {
476
- const j = JSON.parse(d);
477
538
  // llama.cpp sends a final chunk carrying `timings` (predicted_n/_ms); OpenAI servers send `usage`.
478
539
  // cache_n / prompt_tokens_details.cached_tokens = how much of the prompt the server SERVED FROM
479
540
  // ITS PREFIX CACHE this round (vs re-prefilled) — GW-05: parse it, don't throw away the truth.
@@ -502,17 +563,37 @@ async function* streamDeltas(messages, o) {
502
563
  void reader.cancel().catch(() => { });
503
564
  throw new Error(`aurora endpoint degraded — decode ${slowRate.toFixed(1)} tok/s under the ${DECODE_FLOOR_TPS} tok/s floor (CPU fallback; transient)`);
504
565
  }
566
+ if (delta.content || delta.reasoning_content || delta.tool_calls?.length || delta.finish_reason)
567
+ answered = true;
505
568
  yield delta;
506
569
  }
507
570
  }
508
571
  catch { }
509
572
  }
510
- buf = buf.slice(buf.lastIndexOf("\n") + 1);
573
+ if (done)
574
+ break;
511
575
  }
512
576
  }
513
577
  finally {
514
578
  await reader.cancel().catch(() => { });
515
579
  }
580
+ if (!sse) {
581
+ // No SSE at all: a JSON error body, or a server that answered the stream request with one whole reply.
582
+ const j = parseJson(head.trim());
583
+ if (j?.error)
584
+ throw streamError(o, j, "body");
585
+ const choice = j?.choices?.[0];
586
+ const m = choice?.message;
587
+ if (m && (m.content || m.reasoning_content || m.tool_calls?.length || choice.finish_reason)) {
588
+ answered = true;
589
+ yield {
590
+ content: m.content ?? undefined, reasoning_content: m.reasoning_content ?? undefined, finish_reason: choice.finish_reason ?? undefined,
591
+ tool_calls: m.tool_calls?.map((tc, index) => ({ ...tc, index })),
592
+ };
593
+ }
594
+ }
595
+ if (!answered)
596
+ throw new StreamServerError("empty stream", "empty", 502, httpErrorLabel(o));
516
597
  }
517
598
  finally {
518
599
  _releaseSlot(); // free the endpoint slot for the next (interactive-first) waiter
@@ -77,9 +77,9 @@ export function detectAnnouncedDelegation(content, calledTools) {
77
77
  // 1. an engine note is MARKED as such, so the model can tell it from the owner;
78
78
  // 2. a reply that reacts to a speaker who did not speak (after round 0 nothing but tool results and engine notes
79
79
  // arrive) is redirected into a one-line status for the owner;
80
- // 3. a turn never ends on nothing: an empty reply gets one reframed retry and then an engine-composed status, and
81
- // a final with open tasks and no question or report gets one nudge to close with a status plus a steering
82
- // question — the owner is always left with something to answer, never a silent stop.
80
+ // 3. a turn never ends on nothing: an empty reply gets one reframed retry, then the model's fallback answers or the
81
+ // turn ends naming what was tried (noAnswer), and a final with open tasks and no question or report gets one nudge
82
+ // to close with a status plus a steering question — the owner is always left with something, never a silent stop.
83
83
  /** Prefix every engine-injected user-role message so the model never mistakes it for the owner. */
84
84
  export const ENGINE_NOTE_PREFIX = "[engine note — automatic, not from the owner] ";
85
85
  export function engineNote(text) {
@@ -166,10 +166,11 @@ export function needsClosingSteer(content, hasOpenTasks) {
166
166
  return false;
167
167
  return true;
168
168
  }
169
- /** True for a final the ENGINE wrote (a stop/pause/yield note or the no-reply status) rather than the model — the
170
- * flywheel must not grade it as the model's answer and a planner must not accept it as a sub-agent's result. */
169
+ /** True for a final the ENGINE wrote (a stop/pause/yield note or the no-answer note) rather than the model — the
170
+ * flywheel must not grade it as the model's answer and a planner must not accept it as a sub-agent's result. "no reply
171
+ * came back" is the no-answer note before 11/04, still in saved conversations and flywheel rows. */
171
172
  export function isEngineFinal(content) {
172
- return /^\s*(?:\[(?:stopped|paused|turn ended|no reply came back from the model|declined by the provider)\b|\((?:the model returned an empty response|hit the output limit before an answer landed))/i.test(content ?? "");
173
+ return /^\s*(?:\[(?:stopped|paused|turn ended|no answer|no reply came back from the model|declined by the provider)\b|\((?:the model returned an empty response|hit the output limit before an answer landed))/i.test(content ?? "");
173
174
  }
174
175
  export const EMPTY_REPLY_NUDGE = "Your reply was empty. Answer the owner now in plain text: what is done, what you are doing or about to do, and " +
175
176
  "one question if you are blocked. If a tool call is needed, make the call — but never return nothing.";
@@ -185,7 +186,7 @@ const STOP_QUESTIONS = [
185
186
  { key: "paused", match: /^\[paused/i, lead: "This is taking longer than I expected.", ask: "Want me to keep going from here?" },
186
187
  { key: "window", match: /over this model's window/i, lead: "This conversation has grown too long for me to keep working in it.", ask: "Want me to compact it (/compact) and carry on?" },
187
188
  { key: "rounds", match: /stopped after \d+ tool rounds/i, lead: "I've worked through a lot of steps and may not be finished.", ask: "Want me to continue from here?" },
188
- { key: "empty", match: /no reply came back/i, lead: "I didn't get a response back that time.", ask: "Want me to try again?" },
189
+ { key: "unanswered", match: /^\[no answer\b/i, lead: "Nothing answered this turn.", ask: "" },
189
190
  { key: "length", match: /hit the output limit/i, lead: "I ran out of room before finishing that answer.", ask: "Want me to continue?" },
190
191
  { key: "owner", match: /owner asked for an answer/i, lead: "You asked me to answer with what I had, and I kept reaching for tools instead.", ask: "Want me to answer from what I have now, or keep working on it?" },
191
192
  { key: "stopped", match: /^\[stopped/i, lead: "I'm not making progress with the approach I was taking.", ask: "Should I try a different way, or can you tell me which part matters most?" },
@@ -201,10 +202,36 @@ export function stopQuestion(note, activeTasks) {
201
202
  export function stopKind(note) {
202
203
  return STOP_QUESTIONS.find((x) => x.match.test(note.trim()))?.key;
203
204
  }
204
- /** The engine's own closing status when the model gives nothing: the active task list (when any) and a steer. */
205
- export function emptyReplyStatus(activeTasks, tries) {
206
- const tasks = tasksBlock(activeTasks) || "\n\nNo open items on the task list.";
207
- return `[no reply came back from the model after ${tries} tries. Where things stand:${tasks}\n\nTell me which step to take next, or say "continue" to resume from here.]`;
205
+ /** The owner's one line when the model's fallback answered this turn: what failed, why, and what answered. */
206
+ export function fallbackLine(o) {
207
+ const what = o.silent ? `${o.from} sent ${o.silent} empty replies` : `${o.from}'s server is failing (${o.cause})`;
208
+ return `${what} — ${o.to} answered this turn`;
209
+ }
210
+ /** The live line while a request recovers (the TUI's recovering phase): what failed and what happens next, so a slow
211
+ * answer never reads as a broken model. */
212
+ export function recoveryLine(s) {
213
+ const n = s.next;
214
+ const next = n.kind === "leg" ? `reconnecting via ${n.host}` : n.kind === "fallback" ? `${n.to} takes this turn` : `retrying in ${Math.max(1, Math.round(n.waitMs / 1000))} s`;
215
+ return `${s.failed.model} at ${s.failed.host}: ${s.failed.cause} — ${next}`;
216
+ }
217
+ /** The fallback line as a notice on screen: the TUI (mirrored to followers), ACP. */
218
+ export function fallbackNotice(e) {
219
+ return `⚠ ${e.line}`;
220
+ }
221
+ /** A turn nothing answered — every leg of the owner's model and of its fallback failed, or finished with nothing in the
222
+ * reply: each leg's cause in the order tried, and what the next turn does. `note` stays in history (the next turn's model
223
+ * reads it, isEngineFinal keys on it); `display` is what the owner reads. Never "want me to try again?". */
224
+ export function noAnswer(o) {
225
+ const legs = o.tried.map((l) => {
226
+ const more = [l.detail, l.tries > 1 ? `${l.tries} tries` : undefined].filter(Boolean);
227
+ return `- ${l.model} at ${l.host}: ${l.cause}${more.length ? ` (${more.join(", ")})` : ""}`;
228
+ }).join("\n");
229
+ const next = `Next: the next turn tries ${o.owner} first again${o.fallback ? `, then ${o.fallback}` : ""}.`;
230
+ const tasks = tasksBlock(o.tasks);
231
+ return {
232
+ note: `[no answer — nothing answered this turn. Tried, in order:\n${legs}\n${next}]${tasks}`,
233
+ display: `Nothing answered this turn. I tried, in order:\n${legs}\n${next}${tasks}`,
234
+ };
208
235
  }
209
236
  /** Append the active task list and a steer to an engine stop note. A yield note (sub-agents will resume the turn)
210
237
  * gets its own steer: the owner can always take the delegated work back. */
@@ -5,6 +5,6 @@
5
5
  // PATCH internal fix, no contract change (e.g. clampMaxTokens)
6
6
  // Bump MAJOR only when a host must change how it calls the engine. This is the single source of truth;
7
7
  // both barrels (index.ts, index.browser.ts) re-export it, and the SPEC conformance fixtures pin it.
8
- export const ENGINE_CONTRACT = "1.6.0"; // 1.6.0: + AgentOpts.ownerText / request / owner / ownerSteer / ownerAct and the turn-signal callbacks onTurnState, onQueued, onSent, onToolDraft, onToolCallStart, onCompactionStart / onCompactionEnd, onLoopRecovery / onLoopCompaction / onLoopProceed, onOwnerAct — all optional, so older hosts keep working (0.1.353). 1.5.0: + AgentOpts.onComputerEvent / computerEnv — runTurn now EMITS each typed ComputerEvent (start/end) through an optional host callback, so a prebuilt host that only sees bridge callbacks (the mobile JSCore bundle) gets the stream without wiring a tracker; additive (opt-in, default off)
8
+ export const ENGINE_CONTRACT = "1.7.0"; // 1.7.0: + AgentOpts.model (TurnModel: the owner's name for the model and its fallback) / onFallback, and onSelfHeal's optional third argument (RecoveryStep); a server error inside an HTTP 200 throws StreamServerError; a turn nothing answers returns stopKind "unanswered" (was "empty") instead of throwing — all optional, so older hosts keep working (0.1.354). 1.6.0: + AgentOpts.ownerText / request / owner / ownerSteer / ownerAct and the turn-signal callbacks onTurnState, onQueued, onSent, onToolDraft, onToolCallStart, onCompactionStart / onCompactionEnd, onLoopRecovery / onLoopCompaction / onLoopProceed, onOwnerAct — all optional, so older hosts keep working (0.1.353). 1.5.0: + AgentOpts.onComputerEvent / computerEnv — runTurn now EMITS each typed ComputerEvent (start/end) through an optional host callback, so a prebuilt host that only sees bridge callbacks (the mobile JSCore bundle) gets the stream without wiring a tracker; additive (opt-in, default off)
9
9
  // 1.4.0: + 0perator Computer event stream (ComputerEvent, ComputerEventStream, ComputerEventTracker) — a typed, retained, replayable action log a surface feeds from the existing tool callbacks; runTurn/AgentOpts unchanged, so additive (older hosts ignore it)
10
10
  // 1.3.0: + permissions surface (withPermissions, PermissionPolicy, ApproveFn) for client-side gating (additive)
@@ -6,7 +6,8 @@ const NET_RE = /fetch failed|ECONNREFUSED|ECONNRESET|ETIMEDOUT|ENOTFOUND|EHOSTUN
6
6
  export function isNetworkFailure(message) {
7
7
  return NET_RE.test(message);
8
8
  }
9
- function hostOf(base) {
9
+ /** A base URL's host:port, for naming an endpoint to the owner. */
10
+ export function hostOf(base) {
10
11
  try {
11
12
  return new URL(base).host;
12
13
  }
@@ -109,6 +109,54 @@ export function classifyFailure(err) {
109
109
  return "transient"; // network drop / timeout — back off + retry
110
110
  return "bad_request"; // any other 4xx — don't spin on it
111
111
  }
112
+ const NET_CAUSES = {
113
+ ECONNREFUSED: "connection refused", ECONNRESET: "connection reset", ETIMEDOUT: "connection timed out", ENOTFOUND: "host not found",
114
+ EAI_AGAIN: "DNS lookup failed", EHOSTUNREACH: "host unreachable", ENETUNREACH: "network unreachable", UND_ERR_SOCKET: "connection dropped",
115
+ UND_ERR_CONNECT_TIMEOUT: "connection timed out", UND_ERR_HEADERS_TIMEOUT: "no response headers",
116
+ };
117
+ /** A server's words as a short phrase: "Compute error." → "compute error"; an acronym or a name keeps its case. */
118
+ function phrase(s) {
119
+ const t = s.replace(/\s+/g, " ").trim().replace(/[.!]+$/, "");
120
+ const p = /^[A-Z][a-z]/.test(t) ? t[0].toLowerCase() + t.slice(1) : t;
121
+ return p.length > 80 ? `${p.slice(0, 79)}…` : p;
122
+ }
123
+ /** The message an HTTP error body names (`{"error":{"message":…}}`, `{"error":"…"}`, `{"message":…}`), if any. */
124
+ function bodyMessage(msg) {
125
+ const at = msg.indexOf("{");
126
+ if (at < 0)
127
+ return undefined;
128
+ try {
129
+ const j = JSON.parse(msg.slice(at));
130
+ const e = j.error && typeof j.error === "object" ? j.error.message : j.error ?? j.message;
131
+ return typeof e === "string" && e.trim() ? phrase(e) : undefined;
132
+ }
133
+ catch {
134
+ return undefined;
135
+ }
136
+ }
137
+ /** What failed, in a few words for the owner: the server's own message ("compute error"), an HTTP status ("HTTP 503:
138
+ * loading model") or a network cause ("connection refused"). The model fallback line and the no-answer note name each
139
+ * leg by it. Never the request or the reply. */
140
+ export function failureCause(err) {
141
+ const e = err;
142
+ if (typeof e?.serverMessage === "string")
143
+ return phrase(e.serverMessage);
144
+ const code = e?.cause?.code ?? e?.cause?.errors?.find((x) => x?.code)?.code;
145
+ if (typeof code === "string" && NET_CAUSES[code])
146
+ return NET_CAUSES[code];
147
+ const msg = err instanceof Error ? err.message : String(err);
148
+ if (DEGRADED_RE.test(msg))
149
+ return /degraded/i.test(msg) ? "decode too slow" : "the stream stalled";
150
+ const status = err?.status;
151
+ if (typeof status === "number") {
152
+ const said = bodyMessage(msg);
153
+ return said ? `HTTP ${status}: ${said}` : `HTTP ${status}`;
154
+ }
155
+ const why = e?.cause?.message; // fetch's own reason under "fetch failed": "bad port"
156
+ if (typeof why === "string" && why.trim() && !msg.includes(why))
157
+ return `${phrase(msg)}: ${phrase(why)}`;
158
+ return phrase(msg) || "unknown error";
159
+ }
112
160
  const BASE_BACKOFF_MS = 400;
113
161
  const MAX_BACKOFF_MS = 8000;
114
162
  /** Exponential backoff with full jitter (attempt is 0-based); honors a server Retry-After when present. */
package/dist/session.js CHANGED
@@ -345,6 +345,7 @@ export class Session {
345
345
  fastStartConfig;
346
346
  fastStartEnabled;
347
347
  modelId = DEFAULT_MODEL_ID; // active /model selection
348
+ turnFellBack = false; // this turn's model fallback took over (turnModel): its rounds run on the default row
348
349
  executor;
349
350
  shellKey; // this session's persistent-shell key (see disposeShell)
350
351
  localSchemas;
@@ -1019,6 +1020,11 @@ export class Session {
1019
1020
  currentModel() {
1020
1021
  return this.modelId;
1021
1022
  }
1023
+ /** The model answering this turn — the /model pick, or the default row once the pick's fallback took the turn — so a
1024
+ * read or decode rate is credited to the model that did the work, never to the owner's pick. */
1025
+ answeringModel() {
1026
+ return this.turnFellBack ? DEFAULT_MODEL_ID : this.modelId;
1027
+ }
1022
1028
  /** The endpoint chain for a single-endpoint profile (/model, and the MoA specialist's fast path). */
1023
1029
  routerForProfile(profile) {
1024
1030
  // BYO connectors carry their vendor bearer (never the Operator token — see authHeaders scoping);
@@ -1045,6 +1051,20 @@ export class Session {
1045
1051
  }));
1046
1052
  return new AuroraRouter(eps);
1047
1053
  }
1054
+ /** A turn's model as the owner reads it, and its fallback (runTurn's TurnModel): when every leg of another model
1055
+ * fails, or it keeps finishing with nothing, the default Aurora row answers that turn — the owner's choice stays, so
1056
+ * the next turn tries the chosen model first again. A row with `fallback: false` keeps its turns on its own legs. */
1057
+ turnModel(id) {
1058
+ const reg = this.liveRegistry();
1059
+ const profile = findModel(reg, id);
1060
+ if (profile?.kind !== "single")
1061
+ return undefined;
1062
+ const aurora = profile.id === DEFAULT_MODEL_ID || profile.fallback === false ? undefined : findModel(reg, DEFAULT_MODEL_ID);
1063
+ return {
1064
+ name: profile.label,
1065
+ fallback: aurora ? () => { this.turnFellBack = true; return { name: aurora.label, router: this.wrap(this.chain ?? this.routerForProfile(aurora)) }; } : undefined,
1066
+ };
1067
+ }
1048
1068
  /** Switch the active model (/model). A "single" profile rebuilds the router to point at that
1049
1069
  * endpoint — no server is started/stopped, this only changes which endpoint THIS session talks
1050
1070
  * to. "moa" has no endpoint of its own; send() special-cases it (sendMoa) instead. Returns an
@@ -1373,6 +1393,7 @@ export class Session {
1373
1393
  if (!this.wakeTurn)
1374
1394
  this.lastRequest = servedTask(text);
1375
1395
  this.turnThinkOff = flags?.thinkOff === true;
1396
+ this.turnFellBack = false; // a new turn starts on the owner's model, whichever path answers it
1376
1397
  this.ownerAct.reset();
1377
1398
  // Arm the interrupt controller BEFORE maybeRecall. The host flips status to "thinking" the instant send() is
1378
1399
  // called, so an esc during first-turn memory recall / MCP discovery (which hit the network and can be slow)
@@ -1548,6 +1569,7 @@ export class Session {
1548
1569
  text = `${carry}\n\n${text}`;
1549
1570
  const turn = { text, task, convoStart, t0: _t0 };
1550
1571
  this.inflight = turn;
1572
+ const turnModelId = routeLabel ?? this.modelId; // the MoA specialist's own id, else the /model pick
1551
1573
  try {
1552
1574
  const res = await runTurn(text, this.convo, {
1553
1575
  ownerText,
@@ -1594,7 +1616,9 @@ export class Session {
1594
1616
  onAutoContinue: h.onAutoContinue,
1595
1617
  onCacheStats: h.onCacheStats,
1596
1618
  onServed: h.onServed,
1597
- onSelfHeal: (kind, attempt) => { this.telemetry.record({ type: "self_heal", kind, attempt }); h.onSelfHeal?.(kind, attempt); },
1619
+ onSelfHeal: (kind, attempt, step) => { this.telemetry.record({ type: "self_heal", kind, attempt }); h.onSelfHeal?.(kind, attempt, step); },
1620
+ model: this.turnModel(turnModelId),
1621
+ onFallback: (e) => { this.telemetry.record({ type: "model_fallback", from: turnModelId, to: DEFAULT_MODEL_ID, reason: e.reason, legs: e.legs.length }); h.onFallback?.(e); },
1598
1622
  onCompaction: (e) => { this.telemetry.record({ type: "compaction", ...e }); h.onCompaction?.(e); },
1599
1623
  onLoopCompaction: (e) => {
1600
1624
  if (e.replaced > 0)
@@ -51,7 +51,7 @@ function stopSteps(kind, o) {
51
51
  case "paused": return [send("keep going", "go", "Keep going from here."), ...compactStep("compact, then keep going", "Keep going from here.")];
52
52
  case "window": return compactStep("compact, then carry on", "Carry on from here.");
53
53
  case "rounds": return [send("continue", "continue", "Continue from here."), send("continue, think off", "no-think", "Continue from here.", true)];
54
- case "empty": return [send("try again", "retry", "Try again."), send("try again, think off", "no-think", "Try again.", true)];
54
+ case "unanswered": return [send("send it again", "again", "Answer my last message — nothing answered it last time."), { label: "model…", short: "model", action: { kind: "model" } }];
55
55
  case "length": return [send("continue", "continue", "Continue exactly where you stopped.")];
56
56
  case "yield": return [
57
57
  send("keep going meanwhile", "go", "Keep going on the next step meanwhile."),
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@0perator/operator",
3
- "version": "0.1.353",
3
+ "version": "0.1.354",
4
4
  "type": "module",
5
5
  "bin": {
6
6
  "operator": "dist/cli.js",