@0perator/operator 0.1.285 → 0.1.321

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (118) hide show
  1. package/README.md +24 -2
  2. package/dist/acp/agent.js +2 -1
  3. package/dist/acp/config-options.js +3 -1
  4. package/dist/acp/tool-map.js +2 -1
  5. package/dist/auth/commands.js +69 -13
  6. package/dist/autonomy/agent-cli.js +308 -0
  7. package/dist/autonomy/cloud-agent.js +439 -0
  8. package/dist/autonomy/cron-lifecycle.js +78 -0
  9. package/dist/autonomy/cron-lock.js +121 -0
  10. package/dist/autonomy/cron.js +217 -44
  11. package/dist/autonomy/delegate.js +34 -5
  12. package/dist/autonomy/incidents.js +135 -0
  13. package/dist/autonomy/index.js +22 -0
  14. package/dist/autonomy/profile.js +1 -1
  15. package/dist/autonomy/session-factory.js +25 -16
  16. package/dist/background/index.js +40 -0
  17. package/dist/browser/cdp.js +1 -1
  18. package/dist/bus/inbox.js +20 -0
  19. package/dist/classifier/config.js +47 -0
  20. package/dist/classifier/modes.js +41 -0
  21. package/dist/classifier/types.js +1 -0
  22. package/dist/cli.js +645 -93
  23. package/dist/config/features.js +69 -0
  24. package/dist/config/persona.js +143 -107
  25. package/dist/config/scaffold.js +15 -0
  26. package/dist/config/settings.js +107 -12
  27. package/dist/consolidation/sleep.js +73 -11
  28. package/dist/engine/agent.js +279 -20
  29. package/dist/engine/anthropic-chat.js +343 -0
  30. package/dist/engine/aurora.js +109 -16
  31. package/dist/engine/batch-scheduler.js +41 -9
  32. package/dist/engine/classifier.js +85 -0
  33. package/dist/engine/compaction.js +25 -6
  34. package/dist/engine/fast-start.js +25 -0
  35. package/dist/engine/loop-guard.js +448 -0
  36. package/dist/engine/net-error.js +24 -0
  37. package/dist/engine/repetition-guard.js +180 -0
  38. package/dist/engine/router-adapter.js +1 -0
  39. package/dist/engine/selfheal.js +8 -0
  40. package/dist/engine/toolcalls.js +51 -1
  41. package/dist/engine/verify-gate.js +2 -0
  42. package/dist/flywheel/processor.js +78 -31
  43. package/dist/flywheel/srft.js +13 -0
  44. package/dist/hooks/index.js +196 -0
  45. package/dist/idle/activity.js +20 -0
  46. package/dist/idle/index.js +5 -0
  47. package/dist/idle/monitor.js +71 -0
  48. package/dist/idle/policy.js +66 -0
  49. package/dist/idle/proc.js +22 -0
  50. package/dist/idle/reaper.js +69 -0
  51. package/dist/idle/session-record.js +59 -0
  52. package/dist/index.js +1 -1
  53. package/dist/mcp/config.js +93 -15
  54. package/dist/mcp/index.js +9 -2
  55. package/dist/memory/index.js +0 -0
  56. package/dist/memory/providers.js +210 -0
  57. package/dist/memory/session-catalog.js +422 -0
  58. package/dist/memory/session-providers.js +121 -0
  59. package/dist/memory/session-sources.js +335 -0
  60. package/dist/memory/skylark.js +131 -0
  61. package/dist/models/bench.js +103 -0
  62. package/dist/models/registry.js +144 -0
  63. package/dist/models/switch.js +69 -0
  64. package/dist/observability/blackbox.js +37 -0
  65. package/dist/permissions/index.js +22 -7
  66. package/dist/permissions/policy.js +31 -6
  67. package/dist/permissions/tier.js +1 -1
  68. package/dist/remote/host.js +20 -2
  69. package/dist/remote/safe-commands.js +38 -0
  70. package/dist/router/discovery.js +127 -0
  71. package/dist/router/models.js +107 -16
  72. package/dist/router/portal.js +100 -0
  73. package/dist/router/router.js +1 -1
  74. package/dist/services/preflight.js +108 -8
  75. package/dist/services/store-sync.js +111 -0
  76. package/dist/session-teardown.js +10 -1
  77. package/dist/session.js +338 -46
  78. package/dist/skills/catalogue.js +1 -1
  79. package/dist/tools/chauffeur-native.js +155 -0
  80. package/dist/tools/chauffeur.js +26 -3
  81. package/dist/tools/download.js +229 -0
  82. package/dist/tools/executor.js +19 -9
  83. package/dist/tools/find-files.js +483 -0
  84. package/dist/tools/git-pr.js +94 -0
  85. package/dist/tools/incident-tools.js +82 -0
  86. package/dist/tools/memory.js +12 -2
  87. package/dist/tools/monitoring-tools.js +312 -0
  88. package/dist/tools/paths.js +154 -0
  89. package/dist/tools/registry.js +582 -95
  90. package/dist/tools/semantic-compress.js +124 -0
  91. package/dist/tools/shell-context.js +1 -0
  92. package/dist/tools/shell-jobs.js +163 -0
  93. package/dist/tools/shell-session.js +174 -6
  94. package/dist/tools/tool-output-spill.js +1 -1
  95. package/dist/tools/wave-tools.js +609 -0
  96. package/dist/tools/wave2-tools.js +411 -0
  97. package/dist/ui/App.js +15 -4
  98. package/dist/ui/BgPanel.js +30 -6
  99. package/dist/ui/Composer.js +15 -2
  100. package/dist/ui/QuestionPrompt.js +32 -12
  101. package/dist/ui/SessionPicker.js +86 -0
  102. package/dist/ui/StatusRule.js +5 -5
  103. package/dist/ui/ToolStep.js +17 -1
  104. package/dist/ui/Transcript.js +17 -1
  105. package/dist/ui/index.js +1 -1
  106. package/dist/ui/liveTools.js +21 -3
  107. package/dist/ui/slashCommands.js +2 -0
  108. package/dist/util/mentions.js +1 -1
  109. package/dist/util/screenshots.js +74 -8
  110. package/dist/util/slash.js +2 -2
  111. package/dist/vault/store.js +1 -1
  112. package/mcp/README.md +88 -0
  113. package/mcp/ocr-macos.swift +45 -0
  114. package/mcp/powertools-media.mjs +464 -0
  115. package/mcp/powertools-toolbox.mjs +1114 -0
  116. package/mcp/powertools.md +210 -0
  117. package/mcp/powertools.mjs +861 -0
  118. package/package.json +9 -2
@@ -0,0 +1,343 @@
1
+ import { acquireEndpoint, releaseEndpoint, isDegenerate, trimLoop } from "./aurora.js";
2
+ import { anthropicKey } from "./anthropic.js";
3
+ import { classifyFailure, backoffMs, sleep } from "./selfheal.js";
4
+ const ANTHROPIC_VERSION = "2023-06-01";
5
+ const FETCH_TRIES = 3; // same pre-response transient retry budget as aurora.fetchChat (no bytes streamed yet → safe)
6
+ /** OpenAI tool-call `arguments` is a JSON STRING; Anthropic `input` is an OBJECT. Parse defensively — a
7
+ * malformed/empty string becomes `{}` (messages.ts already sanitizes history, but a live round may not). */
8
+ function parseInput(args) {
9
+ if (!args || !args.trim())
10
+ return {};
11
+ try {
12
+ return JSON.parse(args);
13
+ }
14
+ catch {
15
+ return {};
16
+ }
17
+ }
18
+ function toBlocks(content) {
19
+ if (Array.isArray(content))
20
+ return content;
21
+ return content.trim() ? [{ type: "text", text: content }] : [];
22
+ }
23
+ /** Anthropic requires messages to alternate user/assistant; a dangling same-role pair (defensive — the agent
24
+ * loop's conversations alternate, but a restored/edited transcript might not) is merged into one turn. */
25
+ function mergeAdjacent(msgs) {
26
+ const out = [];
27
+ for (const m of msgs) {
28
+ const prev = out[out.length - 1];
29
+ if (prev && prev.role === m.role)
30
+ prev.content = [...toBlocks(prev.content), ...toBlocks(m.content)];
31
+ else
32
+ out.push({ ...m });
33
+ }
34
+ return out;
35
+ }
36
+ /** Split the OpenAI-shaped conversation into Anthropic's top-level `system` + alternating `messages[]`. */
37
+ export function toAnthropicConversation(messages) {
38
+ let system;
39
+ const out = [];
40
+ for (let i = 0; i < messages.length; i++) {
41
+ const m = messages[i];
42
+ if (m.role === "system") {
43
+ system = m.content;
44
+ continue;
45
+ }
46
+ if (m.role === "user") {
47
+ out.push({ role: "user", content: m.content });
48
+ continue;
49
+ }
50
+ if (m.role === "assistant") {
51
+ const blocks = [];
52
+ if (m.content && m.content.trim())
53
+ blocks.push({ type: "text", text: m.content });
54
+ for (const tc of m.tool_calls ?? [])
55
+ blocks.push({ type: "tool_use", id: tc.id, name: tc.function.name, input: parseInput(tc.function.arguments) });
56
+ // An assistant turn with neither text nor a tool call is an empty content[] — Anthropic 400s on it, so drop it.
57
+ if (blocks.length)
58
+ out.push({ role: "assistant", content: blocks.length === 1 && blocks[0].type === "text" ? m.content : blocks });
59
+ continue;
60
+ }
61
+ // A run of `tool` results → ONE user turn of tool_result blocks (Anthropic requires results in a user turn,
62
+ // and batched so the turn still alternates assistant(tool_use) → user(tool_result)).
63
+ const results = [];
64
+ let j = i;
65
+ while (j < messages.length && messages[j].role === "tool") {
66
+ results.push({ type: "tool_result", tool_use_id: messages[j].tool_call_id ?? "", content: messages[j].content ?? "" });
67
+ j++;
68
+ }
69
+ out.push({ role: "user", content: results });
70
+ i = j - 1;
71
+ }
72
+ return { system, messages: mergeAdjacent(out) };
73
+ }
74
+ /** OpenAI `[{type:"function",function:{name,description,parameters}}]` → Anthropic `[{name,description,input_schema}]`. */
75
+ export function toAnthropicTools(tools) {
76
+ if (!tools?.length)
77
+ return undefined;
78
+ const out = [];
79
+ for (const t of tools) {
80
+ const fn = (t.function) ?? t;
81
+ if (!fn?.name)
82
+ continue;
83
+ out.push({ name: fn.name, description: fn.description, input_schema: fn.parameters ?? { type: "object", properties: {} } });
84
+ }
85
+ return out.length ? out : undefined;
86
+ }
87
+ /** Build the Anthropic /v1/messages request body from AuroraOpts. temperature is clamped to Anthropic's
88
+ * [0,1] (the engine's 0.7 default is already in range; a caller passing an OpenAI-style >1 would 400). */
89
+ export function anthropicRequestBody(messages, o, stream) {
90
+ const { system, messages: amsgs } = toAnthropicConversation(messages);
91
+ const tools = toAnthropicTools(o.tools);
92
+ return JSON.stringify({
93
+ model: o.model,
94
+ max_tokens: o.maxTokens ?? 8192,
95
+ temperature: Math.max(0, Math.min(1, o.temperature ?? 0.7)),
96
+ ...(system ? { system } : {}),
97
+ messages: amsgs,
98
+ ...(tools ? { tools } : {}),
99
+ stream,
100
+ });
101
+ }
102
+ // ── Transport ───────────────────────────────────────────────────────────────────────────────────────
103
+ /** x-api-key = the BYO vendor key (AuroraOpts.token), else the env fallback. NEVER the Operator bearer. */
104
+ function anthropicAuthKey(o) {
105
+ return o.token || anthropicKey();
106
+ }
107
+ /** POST the request, retrying ONLY a pre-response transport failure (nothing has streamed yet, so a resend
108
+ * can't duplicate output); an HTTP response (even 4xx/5xx) is returned for the caller to classify. */
109
+ async function fetchMessages(o, key, body) {
110
+ let lastErr;
111
+ for (let attempt = 0; attempt < FETCH_TRIES; attempt++) {
112
+ try {
113
+ return await fetch(`${o.base}/v1/messages`, {
114
+ method: "POST",
115
+ headers: {
116
+ "Content-Type": "application/json",
117
+ "x-api-key": key,
118
+ "anthropic-version": ANTHROPIC_VERSION,
119
+ "User-Agent": "operator/kode-tsi",
120
+ },
121
+ body,
122
+ signal: o.signal,
123
+ });
124
+ }
125
+ catch (e) {
126
+ if (o.signal?.aborted || (e instanceof Error && (e.name === "AbortError" || e.name === "TimeoutError")))
127
+ throw e;
128
+ if (classifyFailure(e) !== "transient" || attempt >= FETCH_TRIES - 1) {
129
+ lastErr = e;
130
+ break;
131
+ }
132
+ lastErr = e;
133
+ await sleep(backoffMs(attempt, e), o.signal, () => (e instanceof Error ? e : new Error(String(e))));
134
+ }
135
+ }
136
+ throw lastErr;
137
+ }
138
+ /** Parse the Anthropic SSE event stream into normalized deltas. Events seen:
139
+ * message_start (usage.input_tokens), content_block_start (text | tool_use | thinking),
140
+ * content_block_delta (text_delta | input_json_delta | thinking_delta), message_delta (stop_reason +
141
+ * usage.output_tokens), error, message_stop. Idle-gap + wall-clock deadlines mirror aurora.streamDeltas
142
+ * so a wedged stream can't hold the slot forever. The endpoint slot is held for the whole stream. */
143
+ async function* anthropicDeltas(messages, o) {
144
+ const key = anthropicAuthKey(o);
145
+ // The env fallback var is documented in AGENTS.md / the comment on anthropicAuthKey — it stays OUT of this
146
+ // user-facing string (branding-boundary: no KODE_* name in prose a user reads).
147
+ if (!key)
148
+ throw new Error("anthropic: no API key — store it: operator auth byo-key anthropic");
149
+ await acquireEndpoint(o.base, o.background === true);
150
+ let released = false;
151
+ const release = () => { if (!released) {
152
+ released = true;
153
+ releaseEndpoint(o.base);
154
+ } };
155
+ try {
156
+ const res = await fetchMessages(o, key, anthropicRequestBody(messages, o, true));
157
+ if (!res.ok || !res.body) {
158
+ let detail = "";
159
+ try {
160
+ detail = (await res.text()).slice(0, 500);
161
+ }
162
+ catch { /* body consumed / unreadable */ }
163
+ const err = new Error(`anthropic /v1/messages ${res.status}${detail ? `: ${detail}` : ""}`);
164
+ err.status = res.status;
165
+ const ra = res.headers.get("retry-after");
166
+ if (ra)
167
+ err.retryAfterMs = /^\d+$/.test(ra.trim()) ? Number(ra) * 1000 : Math.max(0, Date.parse(ra) - Date.now());
168
+ throw err;
169
+ }
170
+ const reader = res.body.getReader();
171
+ const dec = new TextDecoder();
172
+ let buf = "";
173
+ const idleMs = Number(process.env.KODE_STREAM_IDLE_MS ?? 90_000);
174
+ const wallMs = Number(process.env.KODE_REQUEST_TIMEOUT_MS ?? 30 * 60_000);
175
+ const startedAt = Date.now();
176
+ let lastByteAt = Date.now();
177
+ try {
178
+ for (;;) {
179
+ const idleLeft = idleMs > 0 ? idleMs - (Date.now() - lastByteAt) : Infinity;
180
+ const wallLeft = wallMs > 0 ? wallMs - (Date.now() - startedAt) : Infinity;
181
+ const budget = Math.min(idleLeft, wallLeft);
182
+ if (budget <= 0)
183
+ throw new Error("anthropic stream stalled — deadline exceeded before read (decode wedged; transient)");
184
+ let timer;
185
+ let raced;
186
+ try {
187
+ raced = await Promise.race([
188
+ reader.read(),
189
+ new Promise((r) => { timer = setTimeout(() => r("timeout"), budget); }),
190
+ ]);
191
+ }
192
+ finally {
193
+ if (timer)
194
+ clearTimeout(timer);
195
+ }
196
+ if (raced === "timeout") {
197
+ void reader.cancel().catch(() => { });
198
+ throw new Error(`anthropic stream stalled — no bytes within ${Math.round(budget / 1000)}s (decode wedged; transient)`);
199
+ }
200
+ const { value, done } = raced;
201
+ lastByteAt = Date.now();
202
+ if (done)
203
+ break;
204
+ buf += dec.decode(value, { stream: true });
205
+ for (const line of buf.split("\n")) {
206
+ const t = line.trim();
207
+ if (!t.startsWith("data:"))
208
+ continue; // `event:` lines are redundant — the JSON carries its own `type`
209
+ const d = t.slice(5).trim();
210
+ if (!d)
211
+ continue;
212
+ let j;
213
+ try {
214
+ j = JSON.parse(d);
215
+ }
216
+ catch {
217
+ continue;
218
+ }
219
+ const type = j.type;
220
+ if (type === "message_start") {
221
+ const u = j.message?.usage;
222
+ if (u?.input_tokens != null)
223
+ yield { usage: { input: u.input_tokens } };
224
+ }
225
+ else if (type === "content_block_start") {
226
+ const cb = j.content_block;
227
+ if (cb?.type === "tool_use")
228
+ yield { tool: { index: Number(j.index) || 0, id: cb.id, name: cb.name } };
229
+ }
230
+ else if (type === "content_block_delta") {
231
+ const del = j.delta;
232
+ if (del?.type === "text_delta" && del.text)
233
+ yield { content: del.text };
234
+ else if (del?.type === "thinking_delta" && del.thinking)
235
+ yield { reasoning: del.thinking };
236
+ else if (del?.type === "input_json_delta")
237
+ yield { tool: { index: Number(j.index) || 0, partial: del.partial_json ?? "" } };
238
+ }
239
+ else if (type === "message_delta") {
240
+ const del = j.delta;
241
+ const u = j.usage;
242
+ yield { finishReason: del?.stop_reason, usage: u?.output_tokens != null ? { output: u.output_tokens } : undefined };
243
+ }
244
+ else if (type === "error") {
245
+ const e = j.error;
246
+ throw new Error(`anthropic stream error: ${e?.type ?? "error"}${e?.message ? ` — ${e.message}` : ""}`);
247
+ }
248
+ else if (type === "message_stop") {
249
+ return;
250
+ }
251
+ }
252
+ buf = buf.slice(buf.lastIndexOf("\n") + 1);
253
+ }
254
+ }
255
+ finally {
256
+ await reader.cancel().catch(() => { });
257
+ }
258
+ }
259
+ finally {
260
+ release();
261
+ }
262
+ }
263
+ /**
264
+ * Drive one Anthropic Messages turn and return the SAME ChatResult the OpenAI path returns, so the agent
265
+ * loop is transport-blind. Accumulates text (onDelta), extended-thinking (onReasoning) and tool_use blocks
266
+ * (→ OpenAI-shaped ToolCall[] with a JSON-string `arguments`), and applies the same degeneration guard the
267
+ * OpenAI path does on a tool-free reply.
268
+ */
269
+ export async function anthropicChat(messages, o) {
270
+ let content = "";
271
+ let reasoning = "";
272
+ let degenerate = false;
273
+ let sinceCheck = 0;
274
+ let finishReason;
275
+ let promptTokens;
276
+ let outputTokens;
277
+ const LOOP_CHECK_EVERY = 200;
278
+ const tools = new Map();
279
+ for await (const d of anthropicDeltas(messages, o)) {
280
+ if (d.content) {
281
+ content += d.content;
282
+ o.onDelta?.(d.content);
283
+ }
284
+ if (d.reasoning) {
285
+ reasoning += d.reasoning;
286
+ o.onReasoning?.(d.reasoning);
287
+ }
288
+ if (d.finishReason)
289
+ finishReason = d.finishReason;
290
+ if (d.usage?.input != null) {
291
+ promptTokens = d.usage.input;
292
+ o.onMeta?.({ promptTokens: d.usage.input });
293
+ }
294
+ if (d.usage?.output != null) {
295
+ outputTokens = d.usage.output;
296
+ o.onMeta?.({ tokens: d.usage.output });
297
+ }
298
+ if (d.tool) {
299
+ const idx = d.tool.index;
300
+ const e = tools.get(idx) ?? { id: d.tool.id, name: "", args: "" };
301
+ if (d.tool.id)
302
+ e.id = d.tool.id;
303
+ if (d.tool.name)
304
+ e.name += d.tool.name;
305
+ if (d.tool.partial)
306
+ e.args += d.tool.partial;
307
+ tools.set(idx, e);
308
+ }
309
+ // Loop breaker: only scan a tool-free reply (a tool-calling turn is legitimately terminal), amortized.
310
+ if (tools.size === 0) {
311
+ sinceCheck += (d.content?.length ?? 0) + (d.reasoning?.length ?? 0);
312
+ if (sinceCheck >= LOOP_CHECK_EVERY) {
313
+ sinceCheck = 0;
314
+ if (isDegenerate(content) || isDegenerate(reasoning)) {
315
+ degenerate = true;
316
+ break;
317
+ }
318
+ }
319
+ }
320
+ }
321
+ if (degenerate)
322
+ content = trimLoop(content);
323
+ const toolCalls = [...tools.entries()]
324
+ .sort(([a], [b]) => a - b)
325
+ .map(([idx, e]) => ({
326
+ id: e.id ?? `call_${idx}`,
327
+ type: "function",
328
+ function: { name: e.name, arguments: e.args || "{}" },
329
+ }));
330
+ // Anthropic stop_reason → the engine's stopReason. "max_tokens" = output cap hit; "refusal" = model
331
+ // declined. Only flag when NO tool calls were made (a tool-use turn ending on a cap isn't a truncated answer).
332
+ const apiStop = finishReason === "max_tokens" ? "length" : finishReason === "refusal" ? "content_filter" : undefined;
333
+ const stopReason = degenerate ? "repetition" : (tools.size === 0 ? apiStop : undefined);
334
+ return {
335
+ content,
336
+ toolCalls,
337
+ reasoningContent: reasoning || undefined,
338
+ stopReason,
339
+ tokens: outputTokens,
340
+ tokensExact: !!outputTokens && outputTokens > 0,
341
+ promptTokens,
342
+ };
343
+ }
@@ -99,8 +99,13 @@ export function getOperatorToken() { return _operatorToken; }
99
99
  * loopback exclusion: an ingest on a loopback AuthGate is exactly where the bearer is required). */
100
100
  export function operatorTrustedUrl(url) { return isOperatorTrustedHost(hostOf(url)); }
101
101
  export function authHeaders(o) {
102
- if (!isRemoteBase(o.base))
103
- return {}; // a local server never gets any bearer — vendor or operator
102
+ if (!isRemoteBase(o.base)) {
103
+ // A local llama-server normally gets no bearer. The one exception is the local gateway (server.json),
104
+ // which publishes an api_key for its loopback port: send that EXPLICIT, loopback-safe key (loopbackAuth)
105
+ // when present. A BYO vendor key never sets loopbackAuth, and the operator identity token is never the
106
+ // source here, so neither can leak to a local server.
107
+ return o.loopbackAuth && o.token ? { Authorization: `Bearer ${o.token}` } : {};
108
+ }
104
109
  const token = o.token ?? (isOperatorTrustedHost(hostOf(o.base)) ? _operatorToken : undefined);
105
110
  return token ? { Authorization: `Bearer ${token}` } : {};
106
111
  }
@@ -203,9 +208,11 @@ export function trimLoop(text) {
203
208
  * at the end of it). NO for third-party openai-dialect BYO (strict fields only — unknown keys may 400).
204
209
  * Exported so the scope is pinned by unit tests without needing a resolvable axe.onl echo server. */
205
210
  export function shipsLlamaCacheKnobs(base, transport) {
206
- return transport !== "openai" || requiresOperatorToken(base);
211
+ if (transport === "openai" || transport === "anthropic")
212
+ return requiresOperatorToken(base);
213
+ return true;
207
214
  }
208
- function requestBody(messages, o, stream) {
215
+ export function requestBody(messages, o, stream) {
209
216
  // Transport dialect: llama.cpp-only fields ship to Aurora/fleet (default "llama") AND to our OWN
210
217
  // vendor gateway (*.axe.onl — LiteLLM terminating at our llama.cpp, so the wire is OpenAI but the
211
218
  // BACKEND understands the knobs; measured live 2026-10-11: extras pass api.axe.onl with no 400 and
@@ -228,14 +235,25 @@ function requestBody(messages, o, stream) {
228
235
  // prefix each time — the "compaction takes 4-5 min at 80k ctx" and "long sessions crawl" symptom. With it,
229
236
  // the server prefix-matches and prefills only the new tail. llama dialect (and our own gateway).
230
237
  ...(cacheKnobs ? { cache_prompt: true } : {}),
231
- // GW-26 — ngram speculation is DEFAULT-ON in modern llama.cpp and a NET LOSS on the DeltaNet-hybrid
232
- // Aurora at untuned draft params: measured live on :8097 (b11146, ctx 307K), acceptance 3-17% and
233
- // 4-6 tok/s decode WITH it vs 20-25 tok/s WITHOUT — every rejected draft forces a multi-token
234
- // re-verify + recache on the hybrid. Shape verified live: {"speculative":{"ngram":{"enabled":false}}}
235
- // -> timings.draft_n drops to 0 and decode jumps 4x; a `{"type":"none"}` variant is silently IGNORED,
236
- // so keep this exact shape. llama dialect (and our own gateway). Escape hatch when a retuned/
237
- // high-acceptance bless lands: enableSpeculation: true.
238
- ...(cacheKnobs && !o.enableSpeculation ? { speculative: { ngram: { enabled: false } } } : {}),
238
+ // Prefill progress (llama.cpp return_progress): the server sends NOTHING while it reads the prompt, so a
239
+ // cold re-read of a long session (159K tokens after a restart: minutes) looked like a wedged decode to the
240
+ // idle-gap deadline below and was cancelled as "stalled" on every retry. Progress chunks keep the stream
241
+ // alive while the prompt is genuinely being read, and feed onPromptProgress for a "reading context N%" line.
242
+ // 2026-10-19: request progress for EVERY llama-dialect stream (was cacheKnobs-only). A loopback Aurora /
243
+ // fleet node that doesn't ship the full cache knobs still benefits — the progress chunks keep the idle-gap
244
+ // fed through a long cold prefill instead of looking wedged. A server that ignores the field is harmless.
245
+ ...(stream && llama ? { return_progress: true } : {}),
246
+ // GW-26 (UPDATED 2026-10-19, selective): spec-decode is a measured 3.3x on prose/code (16.7→54.5 tok/s)
247
+ // but FIGHTS the tool-call grammar (the reason aurora-op.conf sits at AURORA_SPEC_TYPE=none today). So
248
+ // steer it PER REQUEST: a tool-bearing request (any agent round) sends the ngram disable; a tool-free
249
+ // request (summarizer, delegate prose, MOA aggregation) leaves the server default on. With today's
250
+ // spec-none serving this whole knob is a no-op either way; it's the engine half that makes a future
251
+ // conf flip back to ngram-mod safe. ⚠ The fleet flip is GATED on verifying the per-request disable
252
+ // actually disables on the serving build — a 2026-10-16 A/B found it a NO-OP on the ngram-mod path
253
+ // (GW-26 correction #9); re-verify upstream before touching AURORA_SPEC_TYPE. Explicit
254
+ // enableSpeculation true/false always wins over the tool-presence default.
255
+ ...(cacheKnobs && (o.enableSpeculation === false || (o.enableSpeculation === undefined && (o.tools?.length ?? 0) > 0))
256
+ ? { speculative: { ngram: { enabled: false } } } : {}),
239
257
  max_tokens: o.maxTokens ?? 8192, temperature: o.temperature ?? 0.7,
240
258
  ...(o.tools?.length ? { tools: o.tools, tool_choice: "auto", parallel_tool_calls: true } : {}),
241
259
  // /think: re-enable the model's native reasoning for THIS request, overriding the server's
@@ -259,7 +277,7 @@ async function fetchChat(o, body) {
259
277
  method: "POST",
260
278
  headers: { "Content-Type": "application/json", ...authHeaders(o) },
261
279
  body,
262
- signal: o.signal, // SPEC §9 interrupt parity: tears down the in-flight stream on abort, not at the next loop boundary
280
+ signal: o.signal, // SPEC §9 interrupt handling: tears down the in-flight stream on abort, not at the next loop boundary
263
281
  });
264
282
  }
265
283
  catch (e) {
@@ -278,6 +296,53 @@ async function fetchChat(o, body) {
278
296
  }
279
297
  throw lastErr;
280
298
  }
299
+ // ── Degraded-decode detector (SPEC §4, GAP 2) ──────────────────────────────────────────────────────────────
300
+ // A wedged slot stops emitting bytes (the idle-gap deadline above catches that). But when Aurora's Metal
301
+ // backend faults it falls back to CPU: bytes STILL flow, just at ~5 tok/s instead of ~24-53 on GPU — no stall,
302
+ // no 5xx, so nothing failed over and the whole turn crawled on a dead-GPU box. This watches the SUSTAINED
303
+ // decode rate (tokens/sec, estimated chars/4 — the engine-wide heuristic) over consecutive token WINDOWS and,
304
+ // if a full window stays below a floor, aborts the stream as a TRANSIENT "endpoint degraded" error so the
305
+ // existing self-heal marks THIS endpoint unhealthy (router cooldown + /health climb-back) and fails over for
306
+ // the retry. Conservative by construction — the clock starts at the FIRST generated byte (prefill excluded),
307
+ // a reply shorter than one window never trips, and a legitimately slow-but-above-floor long decode never
308
+ // trips. NEVER kills a process. The floor cleanly separates CPU (~5) from healthy GPU (~24-53); 0 disables.
309
+ // 2026-10-19: DEFAULT OFF. The mid-stream slow-decode abort was tearing down live generations on a loaded /
310
+ // contended box (2 slots busy → ~14 tok/s, a 35B model slower) — i.e. exactly during the long autonomous
311
+ // sessions it was meant to protect. A torn-down stream surfaces as a cut-off tool call / mid-sentence answer,
312
+ // which made Operator unusable for long runs. Re-enable per-box with KODE_DECODE_FLOOR_TPS=12 only where a
313
+ // genuine Metal→CPU fault (steady ~5 tok/s) must be caught; the router/health path still handles 5xx/stalls.
314
+ export const DECODE_FLOOR_TPS = Number(process.env.KODE_DECODE_FLOOR_TPS ?? 0);
315
+ export const DECODE_WINDOW_TOKENS = Number(process.env.KODE_DECODE_WINDOW_TOKENS ?? 48);
316
+ const DECODE_CHARS_PER_TOKEN = 4; // chars/4 — the same decode-token estimate compaction.ts / router-adapter.ts use
317
+ /** A sliding-window decode-rate watcher. Pure + injectable-clock, so tests drive it with synthetic streams. */
318
+ export function createDecodeMonitor(floorTps = DECODE_FLOOR_TPS, windowTokens = DECODE_WINDOW_TOKENS) {
319
+ if (!(floorTps > 0) || !(windowTokens > 0))
320
+ return { observe: () => null }; // disabled (KODE_DECODE_FLOOR_TPS=0)
321
+ let tokens = 0; // estimated decode tokens since the first generated byte (prefill time is never counted)
322
+ let winStartAt = -1;
323
+ let winStartTokens = 0;
324
+ return {
325
+ observe(chars, nowMs) {
326
+ if (!(chars > 0))
327
+ return null;
328
+ if (winStartAt < 0) {
329
+ winStartAt = nowMs;
330
+ winStartTokens = 0;
331
+ } // first byte: start the decode clock AFTER prefill
332
+ tokens += chars / DECODE_CHARS_PER_TOKEN;
333
+ const winTokens = tokens - winStartTokens;
334
+ if (winTokens < windowTokens)
335
+ return null; // not a full window yet — a short reply never reaches this, so never trips
336
+ const secs = (nowMs - winStartAt) / 1000;
337
+ const rate = secs > 0 ? winTokens / secs : Infinity;
338
+ if (rate < floorTps)
339
+ return rate; // a whole window stayed below the floor → degraded (CPU fallback)
340
+ winStartAt = nowMs;
341
+ winStartTokens = tokens; // window healthy → slide forward and keep watching
342
+ return null;
343
+ },
344
+ };
345
+ }
281
346
  /** Shared SSE parse loop. Yields each `data:` line's `choices[0].delta`, raw. */
282
347
  async function* streamDeltas(messages, o) {
283
348
  // Hold this endpoint's slot for the WHOLE request+stream lifetime — the one decode slot is busy the entire
@@ -316,8 +381,14 @@ async function* streamDeltas(messages, o) {
316
381
  // waiter behind it. Idle-gap catches the wedge fast (no bytes for idleMs => transient cancel —
317
382
  // undefined status self-classifies as transient through the selfheal policy, so failover/backoff
318
383
  // already own recovery); the wall-clock is the paranoia ceiling. KODE_STREAM_IDLE_MS=0 disables.
319
- const idleMs = Number(process.env.KODE_STREAM_IDLE_MS ?? 90_000);
320
- const wallMs = Number(process.env.KODE_REQUEST_TIMEOUT_MS ?? 30 * 60_000);
384
+ // 2026-10-19: idle-gap raised 90s → 300s. A cold prefix-cache miss on a long session re-prefills the whole
385
+ // prompt with NO streamed bytes (observed live: 55,243 tokens ≈ 104.8s prefill) — well past the old 90s gap,
386
+ // so the "no bytes = wedged" deadline fired and aborted a perfectly healthy request mid-prefill, cutting the
387
+ // answer off. 300s clears a worst-case cold prefill on a loaded box while still catching a truly dead slot.
388
+ // return_progress keeps the gap fed when the server emits it; this covers the transports/paths that don't.
389
+ const idleMs = Number(process.env.KODE_STREAM_IDLE_MS ?? 300_000);
390
+ const wallMs = Number(process.env.KODE_REQUEST_TIMEOUT_MS ?? 60 * 60_000);
391
+ const decodeMon = createDecodeMonitor(); // GAP 2: abort a CPU-fallback-slow decode so self-heal fails over
321
392
  const startedAt = Date.now();
322
393
  let lastByteAt = Date.now();
323
394
  // finally: if a consumer breaks early (loop breaker, abort, first-answer), tear the socket down.
@@ -361,6 +432,11 @@ async function* streamDeltas(messages, o) {
361
432
  // llama.cpp sends a final chunk carrying `timings` (predicted_n/_ms); OpenAI servers send `usage`.
362
433
  // cache_n / prompt_tokens_details.cached_tokens = how much of the prompt the server SERVED FROM
363
434
  // ITS PREFIX CACHE this round (vs re-prefilled) — GW-05: parse it, don't throw away the truth.
435
+ if (j.prompt_progress) {
436
+ const pp = j.prompt_progress;
437
+ if (Number(pp.total) > 0)
438
+ o.onPromptProgress?.({ processed: Number(pp.processed) || 0, total: Number(pp.total), cached: Number(pp.cache) || 0 });
439
+ }
364
440
  if (j.timings || j.usage)
365
441
  o.onMeta?.({ tokens: j.timings?.predicted_n ?? j.usage?.completion_tokens, genMs: j.timings?.predicted_ms, promptTokens: j.timings?.prompt_n ?? j.usage?.prompt_tokens, promptMs: j.timings?.prompt_ms, cacheN: j.timings?.cache_n ?? j.usage?.prompt_tokens_details?.cached_tokens });
366
442
  const choice = j.choices?.[0];
@@ -371,6 +447,16 @@ async function* streamDeltas(messages, o) {
371
447
  if (delta) {
372
448
  if (choice?.finish_reason)
373
449
  delta.finish_reason = choice.finish_reason;
450
+ // Degraded-decode guard: count THIS chunk's generated chars (content + reasoning + tool-call args)
451
+ // and abort if the sustained decode rate falls under the floor (CPU fallback). Undefined-status
452
+ // throw ⇒ selfheal classifies it transient ⇒ router marks this endpoint unhealthy + fails over.
453
+ const gen = (delta.content?.length ?? 0) + (delta.reasoning_content?.length ?? 0)
454
+ + ((delta.tool_calls ?? []).reduce((n, tc) => n + (tc.function?.arguments?.length ?? 0), 0));
455
+ const slowRate = gen > 0 ? decodeMon.observe(gen, Date.now()) : null;
456
+ if (slowRate !== null) {
457
+ void reader.cancel().catch(() => { });
458
+ throw new Error(`aurora endpoint degraded — decode ${slowRate.toFixed(1)} tok/s under the ${DECODE_FLOOR_TPS} tok/s floor (CPU fallback; transient)`);
459
+ }
374
460
  yield delta;
375
461
  }
376
462
  }
@@ -409,6 +495,13 @@ export async function* streamChat(messages, o) {
409
495
  * delta.tool_calls[] by index (SPEC §1), and returns the finished message.
410
496
  */
411
497
  export async function chat(messages, o) {
498
+ // Anthropic speaks its own wire (x-api-key, /v1/messages, content[] blocks, tool_use/tool_result), not the
499
+ // OpenAI-shaped SSE the rest of this module parses. Hand the whole call off to the native Messages adapter.
500
+ // Dynamic import (not a static one) keeps the aurora <-> anthropic-chat module graph acyclic: anthropic-chat
501
+ // imports the gate + degeneracy helpers from here, and this path loads it only when a turn actually needs it.
502
+ if (o.transport === "anthropic") {
503
+ return (await import("./anthropic-chat.js")).anthropicChat(messages, o);
504
+ }
412
505
  let content = "";
413
506
  let reasoning = "";
414
507
  let degenerate = false;
@@ -488,7 +581,7 @@ export async function chat(messages, o) {
488
581
  const tokens = tokensExact ? meta.tokens
489
582
  : generatedChars > 0 ? globalTokenMeter.estimateCompletion(generatedChars) // SPEC §5: calibrated output ratio (cold = chars/4 prior)
490
583
  : meta.tokens;
491
- return { content, toolCalls, reasoningContent: reasoning || undefined, stopReason, tokens, tokensExact, genMs: meta.genMs, promptTokens: meta.promptTokens, promptMs: meta.promptMs, cacheN: meta.cacheN };
584
+ return { content, toolCalls, reasoningContent: reasoning || undefined, stopReason, finishReason, tokens, tokensExact, genMs: meta.genMs, promptTokens: meta.promptTokens, promptMs: meta.promptMs, cacheN: meta.cacheN };
492
585
  }
493
586
  /** GW-05 cache-bust notice: a PURE shape-checker — the CALLER decides what counts as a continuation
494
587
  * (the very first request of a process legitimately misses everything). Returns a human line when a
@@ -13,21 +13,33 @@
13
13
  // reads that named an overlapping resource (RAW, WAW and WAR) — so a batch is observably equivalent to
14
14
  // running it one call at a time in input order, on every resource it shares. A read that named no
15
15
  // resource (web_search, memory_search…) never holds a writer back.
16
- // • Barrier tools (bash/shell_exec/git_command/checkpoint/computer_*/browser*/browser_vault/…) can
17
- // touch ANYTHING and share one persistent shell — they run alone, in input order.
16
+ // • Barrier tools (git_command/checkpoint/computer_*/browser*/delegate_*/…) can touch ANYTHING and
17
+ // share a device — they run alone, in input order.
18
+ // • Shell tools (bash/shell_exec) can also touch anything, but INDEPENDENT shells in one round run
19
+ // concurrently (matches Cursor). A shell waits for every prior non-shell; later non-shells wait for
20
+ // the whole shell wave. Shells do NOT wait for each other. (Ephemeral one-shot processes when a
21
+ // round has ≥2 shells — see shellExecMode; lone bash still uses the persistent session.)
18
22
  // • A rejected/denied run resolves as a string (executor contract: resolve-not-reject); one call's
19
23
  // failure never strands its dependents — the chain advances regardless.
20
24
  // Pure JS: no node builtins, no asyncLocalStorage — safe for the neutral engine bundle (run-jsc).
21
25
  export const cancelledResult = (name) => `cancelled: ${name} did not start — the turn was interrupted before it ran`;
26
+ /** Foreground shells that may run concurrently within one model round (matches Cursor). */
27
+ const SHELL_EXACT = new Set(["bash", "shell_exec"]);
22
28
  const BARRIER_EXACT = new Set([
23
- "bash", "shell_exec", "shell_background", "bash_kill",
29
+ "shell_background", "bash_kill",
24
30
  "git_command", "checkpoint", "tool_call",
25
- "delegate_task", // a whole sub-agent session with the full tool set: it can touch anything, so it runs alone like bash
31
+ "delegate_task", // a whole sub-agent session with the full tool set: it can touch anything, so it runs alone
32
+ "delegate_to_agent", // spawns an external autonomous CLI agent with write + shell access: runs alone
33
+ "spawn_cloud_agent", // launches a whole autonomous agent in a remote container (clone→run→PR): runs alone
26
34
  "app_open", "app_activate", "computer_applescript", "computer_type", "computer_key", "computer_click", "computer_screenshot",
27
35
  ]);
28
36
  const BARRIER_PREFIX = ["computer_", "browser", "shell", "mcp__"]; // browser_vault included: it drives the same browser device
29
- export function defaultClassify(name, isSafe) {
37
+ // NOTE: "shell" prefix still matches shell_background / shell_*; SHELL_EXACT is checked FIRST so
38
+ // bash/shell_exec become "shell" (parallelizable) instead of falling through to barrier.
39
+ export function defaultClassify(_unused, isSafe) {
30
40
  return (n) => {
41
+ if (SHELL_EXACT.has(n))
42
+ return "shell";
31
43
  if (BARRIER_EXACT.has(n))
32
44
  return "barrier";
33
45
  for (const p of BARRIER_PREFIX)
@@ -84,7 +96,8 @@ export function runBatch(calls, opts) {
84
96
  const writeTails = new Map(); // resource key -> last WRITE on it
85
97
  const keyedReads = []; // prior reads that named a resource (a later conflicting write waits for them)
86
98
  const inflight = new Set(); // everything not yet settled (barrier gate)
87
- let afterBarrier = Promise.resolve(); // every op must clear the last barrier
99
+ const shellInflight = new Set(); // shells currently running — other shells skip these
100
+ let afterBarrier = Promise.resolve(); // every op must clear the last hard barrier / shell wave
88
101
  // Cancellation: `aborted` settles when the turn is interrupted so queued calls stop waiting on their
89
102
  // predecessors and are cancelled, not run late. The listener is removed when the batch ends — a long turn
90
103
  // runs hundreds of batches on ONE signal and an unremoved listener per batch trips the EventTarget leak warning.
@@ -99,10 +112,19 @@ export function runBatch(calls, opts) {
99
112
  signal.addEventListener("abort", onAbort, { once: true });
100
113
  detach = () => signal.removeEventListener("abort", onAbort);
101
114
  });
115
+ /** Fold any open shell wave into afterBarrier so a later non-shell waits for ALL concurrent shells. */
116
+ const flushShellWave = () => {
117
+ if (!shellInflight.size)
118
+ return;
119
+ afterBarrier = Promise.all([...shellInflight, afterBarrier]).then(() => { });
120
+ };
102
121
  for (let i = 0; i < calls.length; i++) {
103
122
  const c = calls[i];
104
123
  const kind = opts.classify(c.name);
105
- let keys = kind === "barrier" ? [] : opts.keys(c.name, c.args);
124
+ // Flush before scheduling a non-shell so it observes the whole prior shell wave.
125
+ if (kind !== "shell")
126
+ flushShellWave();
127
+ let keys = (kind === "barrier" || kind === "shell") ? [] : opts.keys(c.name, c.args);
106
128
  // no-path MUTATIONS (memory_store, task_add, cron create…): serialize per tool-name lock.
107
129
  // Reads never take the lock — a path-less read pairs with nothing and is safe to overlap.
108
130
  if (kind === "write" && keys.length === 0)
@@ -113,8 +135,16 @@ export function runBatch(calls, opts) {
113
135
  for (const p of inflight)
114
136
  gate.push(p); // a barrier runs ALONE: waits for everything prior
115
137
  }
138
+ else if (kind === "shell") {
139
+ // Matching Cursor: independent shells overlap. Wait for prior barriers + prior NON-shell work;
140
+ // do NOT wait for other shells in this wave.
141
+ gate.push(afterBarrier);
142
+ for (const p of inflight)
143
+ if (!shellInflight.has(p))
144
+ gate.push(p);
145
+ }
116
146
  else if (kind === "read") {
117
- gate.push(afterBarrier); // barriers can change anything a read observes
147
+ gate.push(afterBarrier); // barriers/shells can change anything a read observes
118
148
  if (!keys.length) {
119
149
  for (const t2 of writeTails.values())
120
150
  gate.push(t2); // path-less read: any prior write may target it
@@ -162,13 +192,15 @@ export function runBatch(calls, opts) {
162
192
  });
163
193
  if (kind === "barrier")
164
194
  afterBarrier = run; // everything later waits behind this barrier
195
+ else if (kind === "shell")
196
+ shellInflight.add(run);
165
197
  else if (kind === "write")
166
198
  for (const k of keys)
167
199
  writeTails.set(k, run);
168
200
  else if (keys.length)
169
201
  keyedReads.push({ keys, run });
170
202
  inflight.add(run);
171
- run.then(() => inflight.delete(run));
203
+ run.then(() => { inflight.delete(run); shellInflight.delete(run); });
172
204
  done.push(run);
173
205
  }
174
206
  return Promise.all(done).then(() => { detach(); return results; });