@0perator/operator 0.1.353 → 0.1.355-next.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +1 -1
- package/dist/acp/agent.js +2 -0
- package/dist/acp/tool-map.js +1 -1
- package/dist/autonomy/delegate.js +2 -2
- package/dist/autonomy/headless.js +2 -1
- package/dist/autonomy/subagent-model.js +5 -4
- package/dist/cli.js +19 -16
- package/dist/config/persona.js +1 -1
- package/dist/engine/agent.js +104 -17
- package/dist/engine/aurora.js +92 -11
- package/dist/engine/continuation.js +38 -11
- package/dist/engine/contract.js +1 -1
- package/dist/engine/net-error.js +2 -1
- package/dist/engine/selfheal.js +48 -0
- package/dist/router/models.js +7 -0
- package/dist/session.js +25 -1
- package/dist/skills/finder.js +6 -2
- package/dist/tools/registry.js +46 -1
- package/dist/ui/nextStep.js +1 -1
- package/dist/ui/toolicons.js +1 -1
- package/dist/update.js +83 -9
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -71,7 +71,7 @@ npm install -g @0perator/operator # every box runs the release; `operator up
|
|
|
71
71
|
operator # interactive session (`0p` is the short name)
|
|
72
72
|
operator --resume # reload the last conversation in this directory
|
|
73
73
|
```
|
|
74
|
-
Dev: `npm install && npm run dev`, or `scripts/operator-dev.sh` installed as `operator-dev` for unreleased `
|
|
74
|
+
Dev: `npm install && npm run dev`, or `scripts/operator-dev.sh` installed as `operator-dev` for unreleased `develop`.
|
|
75
75
|
|
|
76
76
|
### Headless — `operator run`
|
|
77
77
|
One task, no terminal UI, for SSH, CI, cron and other agents (the shape of `codex exec` and `hermes -z`):
|
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);
|
package/dist/acp/tool-map.js
CHANGED
|
@@ -8,7 +8,7 @@ const KINDS = {
|
|
|
8
8
|
file_read: "read", read_files: "read", list_directory: "read", git_status: "read", session_read: "read",
|
|
9
9
|
skill_fetch: "read", skill_list: "read", task_list: "read", image_analyze: "read", video_analyze: "read",
|
|
10
10
|
grep_search: "search", search: "search", find_files: "search", memory_search: "search", session_search: "search", web_search: "search",
|
|
11
|
-
file_write: "edit", file_edit: "edit", memory_store: "edit", skill_save: "edit", scratchpad: "edit", session_handoff: "edit",
|
|
11
|
+
file_write: "edit", file_edit: "edit", memory_store: "edit", skill_save: "edit", skill_publish: "edit", scratchpad: "edit", session_handoff: "edit",
|
|
12
12
|
bash: "execute", shell_exec: "execute", shell_background: "execute", bash_kill: "execute", bash_output: "execute",
|
|
13
13
|
git_command: "execute", checkpoint: "execute", cronjob: "execute",
|
|
14
14
|
web_fetch: "fetch", http_request: "fetch", browser: "fetch", browser_read: "fetch",
|
|
@@ -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();
|
|
@@ -174,7 +174,7 @@ function sendWithTimeout(send, ms, interrupt) {
|
|
|
174
174
|
const msg = (e) => (e instanceof Error ? e.message : String(e));
|
|
175
175
|
// ── The `delegate_task` tool (registry wires run: runDelegateTask) ──────────
|
|
176
176
|
/**
|
|
177
|
-
* Run `args.task` on a sub-agent backed by `args.model` (default: autonomy/subagent-model.ts — the MoA specialist, the owner's setting, else
|
|
177
|
+
* Run `args.task` on a sub-agent backed by `args.model` (default: autonomy/subagent-model.ts — the MoA specialist, the owner's setting, else the `subagent` capability) and return its final answer, or an
|
|
178
178
|
* `error: ...` string (the tool contract: never throws). Result size is bounded downstream — the executor's
|
|
179
179
|
* capToolResult spills anything over 40KB to disk and hands the planner a re-readable pointer.
|
|
180
180
|
*/
|
|
@@ -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);
|
|
@@ -1,9 +1,10 @@
|
|
|
1
1
|
// Which model a sub-agent runs on — one answer for delegate_task and spawn_agent, resolved per spawn: the MoA
|
|
2
|
-
// specialist under /model moa, else the owner's setting, else
|
|
3
|
-
//
|
|
4
|
-
//
|
|
2
|
+
// specialist under /model moa, else the owner's setting, else the `subagent` capability, the shipped default. A capability
|
|
3
|
+
// is a name the gateway resolves (the portal's aliases), so the fleet picks the best healthy model and no client names one
|
|
4
|
+
// (owner, 11/04; supersedes the 10/31 default of gpt-oss-20b, arena: 35/36 tasks, median 47 s). Every install's registry has
|
|
5
|
+
// it, reached through the local router or api.0perator.co. Node-free (pure).
|
|
5
6
|
import { moaTeam } from "../engine/moa.js";
|
|
6
|
-
export const DEFAULT_SUBAGENT_MODEL = "
|
|
7
|
+
export const DEFAULT_SUBAGENT_MODEL = "subagent";
|
|
7
8
|
export function subagentModelFor(settings, activeModel) {
|
|
8
9
|
activeModel ??= settings.activeModel;
|
|
9
10
|
if (activeModel === "moa") {
|
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";
|
|
@@ -140,7 +141,7 @@ if (process.argv.includes("--version") || process.argv.includes("-V")) {
|
|
|
140
141
|
}
|
|
141
142
|
if (process.argv.includes("--help")) {
|
|
142
143
|
process.stdout.write(mastheadLines(`v${VERSION}`).join("\n") +
|
|
143
|
-
"\n\nUsage:\n operator start the interactive session\n 0p short for operator (every subcommand works)\n operator --resume resume the last session in this directory\n operator update update to the latest release\n operator --fullscreen fullscreen layout: composer pinned to the bottom (or settings.ui.fullscreen)\n operator auth sign in / manage your AXE account\n operator gateway the local model runtime: start | stop | status | health | logs\n operator toolchain the llama-server store: status | verify | install | activate | rollback | migrate | which\n operator run <task>|- run one task headless (--model, --permissions, --output json, --cwd)\n operator selfimprove backfill [--since YYYY-MM-DD] [--dry-run]\n turn looped turns and mentor pairs into lessons\n operator --version print the version\n");
|
|
144
|
+
"\n\nUsage:\n operator start the interactive session\n 0p short for operator (every subcommand works)\n operator --resume resume the last session in this directory\n operator update update to the latest release\n operator update --next install the next prerelease (built from develop); --latest goes back\n operator --fullscreen fullscreen layout: composer pinned to the bottom (or settings.ui.fullscreen)\n operator auth sign in / manage your AXE account\n operator gateway the local model runtime: start | stop | status | health | logs\n operator toolchain the llama-server store: status | verify | install | activate | rollback | migrate | which\n operator run <task>|- run one task headless (--model, --permissions, --output json, --cwd)\n operator selfimprove backfill [--since YYYY-MM-DD] [--dry-run]\n turn looped turns and mentor pairs into lessons\n operator --version print the version\n");
|
|
144
145
|
process.exit(0);
|
|
145
146
|
}
|
|
146
147
|
// `operator selfimprove backfill …` — offline: folds the flywheel's looped turns and the mentor pairs into the global
|
|
@@ -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.
|
|
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.
|
|
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.
|
|
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.
|
|
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 :
|
|
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.
|
|
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
|
-
|
|
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(
|
|
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(
|
|
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,
|
|
@@ -3630,10 +3633,10 @@ if (process.argv[2] === "toolchain") {
|
|
|
3630
3633
|
const { runToolchain } = await import("./toolchain-cli.js");
|
|
3631
3634
|
process.exit(runToolchain(process.argv.slice(3)));
|
|
3632
3635
|
}
|
|
3633
|
-
// `operator update` (bareword) and `operator --update` both self-update.
|
|
3636
|
+
// `operator update` (bareword) and `operator --update` both self-update; `--next` / `--latest` pick the npm channel.
|
|
3634
3637
|
if (process.argv[2] === "update" || process.argv.includes("--update")) {
|
|
3635
3638
|
const { runUpdate } = await import("./update.js");
|
|
3636
|
-
process.exit(await runUpdate());
|
|
3639
|
+
process.exit(await runUpdate(process.argv.slice(2)));
|
|
3637
3640
|
}
|
|
3638
3641
|
// Autonomous operation (autonomy/**): `operator run/loop/board/routine/dream` run headless, WITHOUT the
|
|
3639
3642
|
// Ink TUI — the same pre-shell dispatch pattern as auth/update above. dispatchAutonomy returns an exit
|
package/dist/config/persona.js
CHANGED
|
@@ -250,7 +250,7 @@ export function loadHandoff() {
|
|
|
250
250
|
// cli.tsx (interactive) and the headless factory call it — so an unattended run behaves like the TUI.
|
|
251
251
|
// `ctxTokens` is the active model's real window; `interactive` adds the sections only a foreground
|
|
252
252
|
// session can act on (spawn_agent).
|
|
253
|
-
export function basePersona(
|
|
253
|
+
export function basePersona(_cwd = process.cwd(), opts = {}) {
|
|
254
254
|
const ctx = opts.ctxTokens;
|
|
255
255
|
const ctxLine = ctx !== undefined && Number.isFinite(ctx) && ctx > 0
|
|
256
256
|
? `\nContext window: ${Math.round(ctx).toLocaleString("en-US")} tokens (${Math.round(ctx / 1024)}K) — the real limit of ` +
|
package/dist/engine/agent.js
CHANGED
|
@@ -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,
|
|
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 =
|
|
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 :
|
|
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"
|
|
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
|
-
|
|
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 =
|
|
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
|
|
1338
|
-
// Fail over to a
|
|
1339
|
-
// that's already struggling
|
|
1340
|
-
|
|
1341
|
-
|
|
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(
|
|
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
|
-
(
|
|
1867
|
-
|
|
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
|
package/dist/engine/aurora.js
CHANGED
|
@@ -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
|
-
|
|
466
|
-
|
|
467
|
-
|
|
468
|
-
|
|
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 (!
|
|
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
|
-
|
|
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
|
|
81
|
-
// a final with open tasks and no question or report gets one nudge
|
|
82
|
-
// question — the owner is always left with something
|
|
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-
|
|
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: "
|
|
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
|
|
205
|
-
export function
|
|
206
|
-
const
|
|
207
|
-
return
|
|
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. */
|
package/dist/engine/contract.js
CHANGED
|
@@ -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.
|
|
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)
|
package/dist/engine/net-error.js
CHANGED
|
@@ -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
|
-
|
|
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
|
}
|
package/dist/engine/selfheal.js
CHANGED
|
@@ -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/router/models.js
CHANGED
|
@@ -139,6 +139,13 @@ export const BUILTIN_MODELS = [
|
|
|
139
139
|
// the V1 vendor keys ship, reintroduce a byo:"axe" SKU as a SEPARATE connector id, never by re-gating this one.
|
|
140
140
|
{ id: "axe-aurora-300k", tier: "power", label: "Aurora Code 1", params: "35B-A3B", box: "cloud", kind: "single", desc: "remote shared slot via api.0perator.co (api.axe.onl as fallback) — contended decode measured 1-4.6 tok/s vs local 24-47; cold >~100K prefills can hit the Cloudflare ~125s edge cutoff", endpoint: GATEWAY_BASE, endpoints: [GATEWAY_BASE, LEGACY_GATEWAY_BASE], model: "aurora-code-1", ctx: 307200, transport: "openai", hidden: true },
|
|
141
141
|
{ id: "operator-128k", tier: "economy", label: "Aurora Code 1", params: "35B-A3B", box: "JL2", kind: "single", desc: "128K context, lighter RAM (:8096) — slot not served on this fleet today; hidden from the picker, resolves by id when the slot comes up", endpoint: "http://127.0.0.1:8096/v1", model: "aurora-code-1", ctx: 131072, hidden: true },
|
|
142
|
+
// ── capabilities (0.1.355) ──────────────────────────────────────────────────────────────────────────────
|
|
143
|
+
// A capability is a name the gateway resolves (the portal's aliases and routes), so the owner asks for a KIND of worker and
|
|
144
|
+
// the fleet answers with its best healthy model: the strongest resident one first, parallel delegations spilling down the
|
|
145
|
+
// chain instead of queueing. Swapping or promoting a model moves a pointer on the server and no client changes. Hidden: never
|
|
146
|
+
// a picker row and never offered by tier (profilesByTier skips hidden rows), reached by id (delegate_task, spawn_agent). `ctx`
|
|
147
|
+
// is the smallest window any model in the chain serves, so compaction is safe wherever the request lands.
|
|
148
|
+
{ id: "subagent", tier: "power", label: "Sub-agent", box: "fleet", kind: "single", desc: "capability: the default sub-agent — the gateway picks the best healthy model", endpoint: LOCAL_GATEWAY_BASE, endpoints: [LOCAL_GATEWAY_BASE, GATEWAY_BASE], endpointModels: ["subagent", "subagent"], model: "subagent", ctx: 262144, hidden: true },
|
|
142
149
|
// ── orchestrated ────────────────────────────────────────────────────────────────────────────────────────
|
|
143
150
|
{ id: "moa", tier: "power_turbo", label: "MOA", box: "mixture of agents", kind: "orchestrated", desc: "the team slot — Cortana plans each request into steps and hands them to gpt-oss-20b specialists, checks their work, writes the answer and reads any images (settings.moa overrides)" },
|
|
144
151
|
];
|
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)
|
package/dist/skills/finder.js
CHANGED
|
@@ -12,6 +12,7 @@ import { listLocalSkills } from "../config/skills-index.js";
|
|
|
12
12
|
import { listCatalogue, catalogueDir } from "./catalogue.js";
|
|
13
13
|
import { OPERATOR_URLS, operatorToken, registry } from "../tools/registry.js";
|
|
14
14
|
import { operatorTrustedUrl } from "../engine/aurora.js";
|
|
15
|
+
import { PRODUCT_API_HOST } from "../config/product-hosts.js";
|
|
15
16
|
const words = (q) => q.toLowerCase().split(/\s+/).filter(Boolean);
|
|
16
17
|
/** Every query word appears in the haystack — the same AND rule session search uses. */
|
|
17
18
|
const matches = (q, ...hay) => {
|
|
@@ -63,7 +64,9 @@ export function toolSource() {
|
|
|
63
64
|
},
|
|
64
65
|
};
|
|
65
66
|
}
|
|
66
|
-
/** The hub bases, in the order they are tried.
|
|
67
|
+
/** The hub bases, in the order they are tried.
|
|
68
|
+
* An explicit override (env, then the home's skills.json) wins; otherwise the marketplace gateway (api.0perator.co) is
|
|
69
|
+
* tried first, for signed-in subscribers. An unauthenticated caller or a 401/403/404 falls through to the next base. */
|
|
67
70
|
export function hubBases(env = process.env) {
|
|
68
71
|
const fromEnv = (env.KODE_SKILLS_HUB ?? "").split(",").map((s) => s.trim()).filter(Boolean);
|
|
69
72
|
let fromHome = [];
|
|
@@ -73,7 +76,8 @@ export function hubBases(env = process.env) {
|
|
|
73
76
|
fromHome = cfg.hub.endpoints.filter((x) => typeof x === "string");
|
|
74
77
|
}
|
|
75
78
|
catch { /* no hub config in this home */ }
|
|
76
|
-
|
|
79
|
+
const gateway = `https://${PRODUCT_API_HOST}`;
|
|
80
|
+
return [...new Set([...fromEnv, ...fromHome, gateway, ...OPERATOR_URLS].map((b) => b.replace(/\/+$/, "")))];
|
|
77
81
|
}
|
|
78
82
|
const hubOrigin = (src) => {
|
|
79
83
|
if (!src)
|
package/dist/tools/registry.js
CHANGED
|
@@ -10,6 +10,7 @@ import { indexSessions, readSession, searchSessions } from "../memory/session-in
|
|
|
10
10
|
import { formatHits, indexCatalog, readCatalogSession, searchCatalog, sessionSearchConfig, SESSION_SCOPES } from "../memory/session-catalog.js";
|
|
11
11
|
import { listLocalSkills, localSkillsDir as profileSkillsDir, resolveSkillFile } from "../config/skills-index.js";
|
|
12
12
|
import { operatorPath } from "../config/home.js";
|
|
13
|
+
import { PRODUCT_API_HOST } from "../config/product-hosts.js";
|
|
13
14
|
import { ownChild } from "../util/owned-children.js";
|
|
14
15
|
import { BG_MAX_RUNNING, createJob, finishJob, newJobId, pruneShellJobs, runningJobCount, shellJobs, stopShellJob, trackJobOutput } from "./shell-jobs.js";
|
|
15
16
|
import { pexecFile } from "./exec.js";
|
|
@@ -2791,6 +2792,16 @@ const TOOLS = [
|
|
|
2791
2792
|
}, required: ["name", "content"] },
|
|
2792
2793
|
run: (a) => skillSave(str(a.name), str(a.content)),
|
|
2793
2794
|
},
|
|
2795
|
+
{
|
|
2796
|
+
name: "skill_publish", safe: false,
|
|
2797
|
+
contract: { v: 1, effects: ["read", "egress"], audit: ["name", "version"] },
|
|
2798
|
+
description: "Publish one of your profile skills to the AXE marketplace under your account. Needs sign-in and an active subscription; it lands quarantined and unverified, visible to you (skill_fetch scope mine) until it is reviewed.",
|
|
2799
|
+
parameters: { type: "object", properties: {
|
|
2800
|
+
name: { type: "string", description: "the profile skill to publish (as saved by skill_save)" },
|
|
2801
|
+
version: { type: "string", description: "semantic version, default 1.0.0; a published version cannot be replaced" },
|
|
2802
|
+
}, required: ["name"] },
|
|
2803
|
+
run: (a) => skillPublish(str(a.name), str(a.version).trim() || "1.0.0"),
|
|
2804
|
+
},
|
|
2794
2805
|
{
|
|
2795
2806
|
name: "memory", safe: false,
|
|
2796
2807
|
description: "Batch-edit memories/MEMORY.md or memories/USER.md: each operation adds, replaces or removes text; budget-checked, one atomic write.",
|
|
@@ -2858,7 +2869,7 @@ const TOOLS = [
|
|
|
2858
2869
|
},
|
|
2859
2870
|
{
|
|
2860
2871
|
name: "delegate_task", safe: false,
|
|
2861
|
-
description: `Run ONE self-contained subtask on a sub-agent (a headless Operator session with its own tools) and get its final answer; blocks. It has NO memory of this conversation and cannot ask — \`task\` must carry every path, constraint and the exact output wanted. \`model\`: any /model id; OMIT IT to use the owner's configured default sub-agent (almost always right). Never name a model you have not seen answer in this fleet (an unloaded one fails); tool-heavy work (repo review, exploration, web research, debugging)
|
|
2872
|
+
description: `Run ONE self-contained subtask on a sub-agent (a headless Operator session with its own tools) and get its final answer; blocks. It has NO memory of this conversation and cannot ask — \`task\` must carry every path, constraint and the exact output wanted. \`model\`: any /model id; OMIT IT to use the owner's configured default sub-agent (almost always right). Never name a model you have not seen answer in this fleet (an unloaded one fails); tool-heavy work (repo review, exploration, web research, debugging) belongs on the default, which the gateway fills with a strong tool-driver and spills parallel delegations across the fleet. Connected cloud providers work too ("claude-sonnet", BYO: ${BYO_DELEGATE_PROVIDERS}); one without a stored key is refused with the command to store it. Don't delegate a single tool call; sub-agents cannot delegate further and can mutate the workspace.`,
|
|
2862
2873
|
parameters: { type: "object", properties: {
|
|
2863
2874
|
task: { type: "string", description: "the complete, self-contained subtask — the sub-agent sees only this" },
|
|
2864
2875
|
model: { type: "string", description: "registry model id; omit for the owner's configured default sub-agent" },
|
|
@@ -3159,6 +3170,40 @@ async function skillSave(name, content) {
|
|
|
3159
3170
|
return `error saving skill: ${e.message}`;
|
|
3160
3171
|
}
|
|
3161
3172
|
}
|
|
3173
|
+
const MARKETPLACE_URL = (process.env.KODE_MARKETPLACE_URL ?? `https://${PRODUCT_API_HOST}`).replace(/\/+$/, "");
|
|
3174
|
+
const publishFailures = {
|
|
3175
|
+
401: "sign in first (operator login)",
|
|
3176
|
+
403: "the marketplace needs an active subscription on your account",
|
|
3177
|
+
409: "that version is already published; bump the version",
|
|
3178
|
+
413: "the skill is too large for the marketplace",
|
|
3179
|
+
429: "too many publishes this hour; try again later",
|
|
3180
|
+
};
|
|
3181
|
+
async function skillPublish(name, version) {
|
|
3182
|
+
if (!name)
|
|
3183
|
+
return "error: skill_publish needs a name";
|
|
3184
|
+
const local = (await localSkills()).find((ls) => ls.name === name || slugify(ls.name) === slugify(name));
|
|
3185
|
+
if (!local)
|
|
3186
|
+
return `error: no profile skill '${name}'; save it with skill_save first`;
|
|
3187
|
+
const token = await operatorToken();
|
|
3188
|
+
if (!token)
|
|
3189
|
+
return publishFailures[401];
|
|
3190
|
+
try {
|
|
3191
|
+
const { readFile } = await nodeImport("node:fs/promises");
|
|
3192
|
+
const content = await readFile(local.file, "utf8");
|
|
3193
|
+
const res = await fetch(`${MARKETPLACE_URL}/v1/skills`, {
|
|
3194
|
+
method: "POST",
|
|
3195
|
+
headers: { "Content-Type": "application/json", Authorization: `Bearer ${token}`, "User-Agent": "KODE/0.9 (axe-tsi)" },
|
|
3196
|
+
body: JSON.stringify({ name: slugify(local.name), version, content, format: "skillmd" }),
|
|
3197
|
+
signal: AbortSignal.timeout(20000),
|
|
3198
|
+
});
|
|
3199
|
+
if (res.ok)
|
|
3200
|
+
return `published ${slugify(local.name)}@${version} to the marketplace (quarantined until reviewed; skill_fetch ${slugify(local.name)} scope mine reads it back).`;
|
|
3201
|
+
return `error: ${publishFailures[res.status] ?? `the marketplace answered ${res.status}`}`;
|
|
3202
|
+
}
|
|
3203
|
+
catch (e) {
|
|
3204
|
+
return `error publishing skill: ${e.message}`;
|
|
3205
|
+
}
|
|
3206
|
+
}
|
|
3162
3207
|
export async function localSkills() {
|
|
3163
3208
|
return listLocalSkills();
|
|
3164
3209
|
}
|
package/dist/ui/nextStep.js
CHANGED
|
@@ -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 "
|
|
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/dist/ui/toolicons.js
CHANGED
|
@@ -15,7 +15,7 @@ const KIND_RULES = [
|
|
|
15
15
|
[/(read_file|read_files|^read$|^cat$|open_file|file_read)/i, "read"],
|
|
16
16
|
[/(file_write|write_file|^write$|edit|apply_patch|str_replace|notebook|create_file|insert)/i, "write"],
|
|
17
17
|
[/(web_search|web_fetch|^web|http|browser|^fetch$|curl|^url|download)/i, "web"],
|
|
18
|
-
[/(skill_fetch|skill_save|^skill$)/i, "skill"],
|
|
18
|
+
[/(skill_fetch|skill_save|skill_publish|^skill$)/i, "skill"],
|
|
19
19
|
[/(search|grep|ripgrep|glob|^find$|skill_list|lookup)/i, "search"],
|
|
20
20
|
[/(^git|git_|checkpoint|^commit|^diff|^branch)/i, "git"], // before shell: "git_command" contains "command"
|
|
21
21
|
[/(bash|shell|^run$|exec|command|script)/i, "shell"],
|
package/dist/update.js
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
// `operator update` — self-update (bareword, like a CLI self-updater). Two install shapes:
|
|
2
|
-
// • npm-global → the published package on the registry; update = reinstall @latest
|
|
2
|
+
// • npm-global → the published package on the registry; update = reinstall a channel's dist-tag: @latest (main's
|
|
3
|
+
// releases, the default and `--latest`) or @next (`--next`: 0.1.N-next.K prereleases from develop).
|
|
3
4
|
// • source/dev → a git checkout linked via `npm link`; update = pull + rebuild.
|
|
4
5
|
// We detect the shape from where THIS module resolves: a checkout still has a .git above it;
|
|
5
6
|
// a global install lives under a node_modules tree with no repo around it.
|
|
@@ -8,6 +9,15 @@ import { existsSync, readFileSync } from "node:fs";
|
|
|
8
9
|
import { dirname, join, resolve } from "node:path";
|
|
9
10
|
import { fileURLToPath } from "node:url";
|
|
10
11
|
const PKG = "@0perator/operator"; // published (private) scope/name — keep in sync with package.json
|
|
12
|
+
/** `--next` or `--latest` (the default); `explicit` says a flag picked it. Both flags is a usage error. */
|
|
13
|
+
export function updateChannel(args) {
|
|
14
|
+
const next = args.includes("--next"), latest = args.includes("--latest");
|
|
15
|
+
if (next && latest)
|
|
16
|
+
return { error: "operator update: --next and --latest are two channels — pass one.\n" };
|
|
17
|
+
return { channel: next ? "next" : "latest", explicit: next || latest };
|
|
18
|
+
}
|
|
19
|
+
// A next build is a 0.1.N-next.K prerelease; a release is a plain 0.1.N.
|
|
20
|
+
const channelOf = (version) => (/-next\.\d+$/.test(version) ? "next" : "latest");
|
|
11
21
|
// Walk up from the running file looking for a .git dir (source checkout) before we hit a
|
|
12
22
|
// node_modules boundary (global install). Returns the repo root, or null for a packaged install.
|
|
13
23
|
function findRepoRoot() {
|
|
@@ -28,8 +38,78 @@ function run(cmd, args, cwd) {
|
|
|
28
38
|
const r = spawnSync(cmd, args, { stdio: "inherit", cwd });
|
|
29
39
|
return r.status ?? 1;
|
|
30
40
|
}
|
|
31
|
-
|
|
41
|
+
/** The registry's dist-tags for PKG (`{ latest: "0.1.352", next: "0.1.353-next.0" }`), or why they can't be read. */
|
|
42
|
+
function distTags() {
|
|
43
|
+
const r = spawnSync("npm", ["view", PKG, "dist-tags", "--json"], { encoding: "utf8" });
|
|
44
|
+
let out;
|
|
45
|
+
try {
|
|
46
|
+
const parsed = JSON.parse(r.stdout);
|
|
47
|
+
if (parsed && typeof parsed === "object" && !Array.isArray(parsed))
|
|
48
|
+
out = parsed;
|
|
49
|
+
}
|
|
50
|
+
catch { /* not JSON */ }
|
|
51
|
+
if (r.status === 0 && out && !("error" in out))
|
|
52
|
+
return { tags: out };
|
|
53
|
+
// With --json npm puts its own error on stdout ({ error: { code, summary } }); stderr ends with the log file's path.
|
|
54
|
+
const e = out?.error;
|
|
55
|
+
if (e?.code || e?.summary)
|
|
56
|
+
return { error: [e.code, e.summary].filter(Boolean).join(" ") };
|
|
57
|
+
const lines = `${r.stderr ?? ""}`.split("\n").map((l) => l.trim()).filter((l) => l && !/complete log of this run/i.test(l));
|
|
58
|
+
return { error: lines.slice(0, 2).join(" · ") || `npm exited ${r.status ?? r.signal}` };
|
|
59
|
+
}
|
|
60
|
+
function versionAt(pkgJson) {
|
|
61
|
+
try {
|
|
62
|
+
return JSON.parse(readFileSync(pkgJson, "utf8")).version;
|
|
63
|
+
}
|
|
64
|
+
catch {
|
|
65
|
+
return undefined;
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
/** npm-global update: reinstall PKG@<channel>, naming the channel and version before and after. It never falls back to
|
|
69
|
+
* the other channel: a tag the registry doesn't have, or a registry it can't read, installs nothing and exits 1.
|
|
70
|
+
* Before and after are read from THIS install's package.json (npm replaces it in place), not from `npm root -g`: npm
|
|
71
|
+
* redacts UUID-shaped path segments in its output as `***`. */
|
|
72
|
+
export function installChannel(channel, pkgJson = fileURLToPath(new URL("../package.json", import.meta.url))) {
|
|
73
|
+
const current = versionAt(pkgJson) ?? "?";
|
|
74
|
+
const read = distTags();
|
|
75
|
+
if ("error" in read) {
|
|
76
|
+
process.stderr.write(`operator update: can't read ${PKG}'s channels from the registry (${read.error}) — nothing installed. ` +
|
|
77
|
+
`If ${PKG} is private, run \`npm login\` for the 0perator org first.\n`);
|
|
78
|
+
return 1;
|
|
79
|
+
}
|
|
80
|
+
const target = read.tags[channel];
|
|
81
|
+
if (!target) {
|
|
82
|
+
const has = Object.entries(read.tags).map(([tag, v]) => `${tag} ${v}`).join(", ") || "no tags";
|
|
83
|
+
process.stderr.write(`operator update: ${PKG} has no ${channel} channel on the registry yet (it has ${has}) — nothing installed.\n`);
|
|
84
|
+
return 1;
|
|
85
|
+
}
|
|
86
|
+
process.stderr.write(`operator update: v${current} (${channelOf(current)}) → ${PKG}@${channel} (v${target})\n`);
|
|
87
|
+
const code = run("npm", ["install", "-g", `${PKG}@${channel}`]);
|
|
88
|
+
if (code !== 0) {
|
|
89
|
+
process.stderr.write(`operator update: failed. If ${PKG} is private, run \`npm login\` for the 0perator org first.\n`);
|
|
90
|
+
return code;
|
|
91
|
+
}
|
|
92
|
+
const now = versionAt(pkgJson);
|
|
93
|
+
if (now !== target) {
|
|
94
|
+
process.stderr.write(`operator update: npm finished, but this operator (${dirname(pkgJson)}) is v${now ?? "?"}, not v${target} — npm's ` +
|
|
95
|
+
`global prefix may hold another install: check \`which -a operator\` and \`npm ls -g ${PKG}\`.\n`);
|
|
96
|
+
return 1;
|
|
97
|
+
}
|
|
98
|
+
process.stderr.write(`operator update: done — now v${now} (${channel}).\n`);
|
|
99
|
+
return 0;
|
|
100
|
+
}
|
|
101
|
+
export async function runUpdate(args = []) {
|
|
102
|
+
const pick = updateChannel(args);
|
|
103
|
+
if ("error" in pick) {
|
|
104
|
+
process.stderr.write(pick.error);
|
|
105
|
+
return 2;
|
|
106
|
+
}
|
|
32
107
|
const repo = findRepoRoot();
|
|
108
|
+
if (repo && pick.explicit) {
|
|
109
|
+
process.stderr.write(`operator update: --${pick.channel} picks an npm channel, but this operator runs from the source checkout at ${repo}, ` +
|
|
110
|
+
`which updates by git. To install the ${pick.channel} channel instead: npm install -g ${PKG}@${pick.channel}\n`);
|
|
111
|
+
return 1;
|
|
112
|
+
}
|
|
33
113
|
if (repo) {
|
|
34
114
|
// kode-tsi lives in a subdir of the kode repo; build happens where package.json is.
|
|
35
115
|
const pkgDir = existsSync(join(repo, "kode-tsi", "package.json")) ? join(repo, "kode-tsi") : repo;
|
|
@@ -77,11 +157,5 @@ export async function runUpdate() {
|
|
|
77
157
|
}
|
|
78
158
|
return code;
|
|
79
159
|
}
|
|
80
|
-
|
|
81
|
-
const code = run("npm", ["install", "-g", `${PKG}@latest`]);
|
|
82
|
-
if (code === 0)
|
|
83
|
-
process.stderr.write("operator update: done.\n");
|
|
84
|
-
else
|
|
85
|
-
process.stderr.write(`operator update: failed. If ${PKG} is private, run \`npm login\` for the 0perator org first.\n`);
|
|
86
|
-
return code;
|
|
160
|
+
return installChannel(pick.channel);
|
|
87
161
|
}
|