@0perator/operator 0.1.332 → 0.1.334

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 (37) hide show
  1. package/dist/auth/byo.js +5 -0
  2. package/dist/auth/commands.js +1 -1
  3. package/dist/cli.js +2 -1
  4. package/dist/config/persona.js +42 -7
  5. package/dist/config/settings.js +29 -5
  6. package/dist/engine/agent.js +57 -4
  7. package/dist/engine/anthropic-chat.js +4 -4
  8. package/dist/engine/aurora.js +8 -1
  9. package/dist/engine/compaction.js +4 -2
  10. package/dist/engine/decision-points.js +78 -0
  11. package/dist/engine/moa.js +4 -1
  12. package/dist/engine/router-adapter.js +2 -0
  13. package/dist/engine/selfheal.js +41 -0
  14. package/dist/router/free-models.js +3 -2
  15. package/dist/router/models.js +15 -6
  16. package/dist/services/preflight.js +17 -2
  17. package/dist/session.js +25 -13
  18. package/dist/tools/doc-text.js +129 -0
  19. package/dist/tools/paths.js +13 -1
  20. package/dist/tools/registry.js +117 -44
  21. package/dist/tools/vision-gateway.js +55 -0
  22. package/dist/ui/QuestionPrompt.js +4 -3
  23. package/dist/ui/modelPicker.js +2 -2
  24. package/package.json +1 -1
  25. package/dist/engine/cli.js +0 -1171
  26. package/dist/router/models.js.bak +0 -78
  27. package/dist/router/models.js.bak-1791259923 +0 -78
  28. package/dist/router/models.js.bak-pre-gateway +0 -78
  29. package/dist/router/models.js.bak-pre-patch2 +0 -78
  30. package/dist/router/models.js.bak2 +0 -78
  31. package/dist/services/model-autodetect.js +0 -240
  32. package/dist/tools/native-redirect.js +0 -140
  33. package/dist/tools/power-tools.js +0 -627
  34. package/dist/tools/registry.js.bak-1791259948 +0 -1914
  35. package/dist/tools/registry.js.bak-pre-plugins +0 -1914
  36. package/dist/ui/BusTray.js +0 -70
  37. package/dist/ui/resize.js +0 -160
package/dist/auth/byo.js CHANGED
@@ -14,6 +14,7 @@ import { platform } from "node:os";
14
14
  import { dirname } from "node:path";
15
15
  import { operatorPath } from "../config/home.js";
16
16
  import { BYO_PRESETS } from "../router/models.js"; // leaf registry (no imports of its own) — no cycle
17
+ import { getOperatorToken } from "../engine/aurora.js";
17
18
  const SERVICE = "axe-operator-byo";
18
19
  // Resolved per call, not at import: the file follows $KODE_HOME / $KODE_PROFILE, so a profile's vendor keys
19
20
  // never land in (or get read from) another identity's file.
@@ -72,7 +73,11 @@ export function getByoToken(account, endpoint) {
72
73
  export function hasStoredByoToken(account) {
73
74
  return !!storedByoToken(account);
74
75
  }
76
+ /** A sign-in preset's account (0perator Free) is the Operator sign-in itself: no key is ever stored for it. */
77
+ const signInAccount = (account) => Object.values(BYO_PRESETS).some((p) => p.signIn && p.account === account);
75
78
  function storedByoToken(account) {
79
+ if (signInAccount(account))
80
+ return process.env.KODE_OPERATOR_TOKEN?.trim() || getOperatorToken();
76
81
  const env = process.env[envName(account)];
77
82
  if (env)
78
83
  return env.trim() || undefined;
@@ -269,7 +269,7 @@ async function byoModel(rest) {
269
269
  console.error(` presets: ${Object.keys(BYO_PRESETS).join(", ")}`);
270
270
  return 1;
271
271
  }
272
- const profile = { id, label: label ?? id, kind: "single", desc: `BYO ${label ?? id} — your key`, endpoint: base, model, ctx, byo: account, transport: dialect, ...(preset?.chatPath && base === preset.endpoint ? { chatPath: preset.chatPath } : {}) };
272
+ const profile = { id, label: label ?? id, kind: "single", desc: `BYO ${label ?? id} — your key`, endpoint: base, model, ctx, byo: account, transport: dialect, ...(preset?.chatPath && base === preset.endpoint ? { chatPath: preset.chatPath } : {}), ...(preset?.maxOutput && model === preset.model ? { maxOutput: preset.maxOutput } : {}) };
273
273
  const existing = loadSettings().models ?? [];
274
274
  const models = [...existing.filter((m) => m.id !== id), profile];
275
275
  saveSettings({ models });
package/dist/cli.js CHANGED
@@ -665,6 +665,7 @@ function Root() {
665
665
  permissions: fgPermissions, // owner's policy + computer tools forced to "ask" when enabled (else bypass)
666
666
  approve: approveFn, // renders the in-TUI approval prompt for any "ask" decision
667
667
  askUser, // registers the ask_user tool so the model can put a clarifying question to the owner
668
+ decisionPoints: settings.decisionPoints, // a build turn's first change waits for the owner's choice (ask_user); false / KODE_DECISION_POINTS=0 = off
668
669
  telemetry: settings.telemetry, // local-only metrics by default
669
670
  eventSink, eventActor: EVENT_ACTOR, sessionId: SESSION_ID, // frozen event stream (tool/control audit)
670
671
  // Foreground only: lets Aurora delegate via spawn_agent. The bg factory below OMITS this, so a
@@ -2574,7 +2575,7 @@ function Root() {
2574
2575
  if (boot === "checking")
2575
2576
  return _jsx(Text, { dimColor: true, children: bootDetail || "connecting to Operator…" });
2576
2577
  if (boot === "down") {
2577
- return (_jsxs(Box, { flexDirection: "column", children: [_jsx(Text, { color: "red", children: "Can't reach Operator on the configured endpoint." }), bootDetail ? _jsx(Text, { dimColor: true, children: bootDetail }) : null, _jsx(Text, { dimColor: true, children: "The Operator model is launchd-owned. Recover it with: launchctl kickstart -k gui/$(id -u)/ai.operator.gateway" })] }));
2578
+ return (_jsxs(Box, { flexDirection: "column", children: [_jsx(Text, { color: "red", children: "Can't reach Operator on the configured endpoint." }), bootDetail ? _jsx(Text, { dimColor: true, children: bootDetail }) : null, _jsxs(Text, { dimColor: true, children: ["The Operator model is launchd-owned. Recover it with: launchctl kickstart -k gui/$(id -u)/", settings.services?.aurora?.launchdLabel ?? "co.0perator.gateway"] })] }));
2578
2579
  }
2579
2580
  // While a turn runs, show a LIVE line: braille spinner + climbing token count + live tok/s + elapsed
2580
2581
  // seconds. When idle, show the last turn's final "N tok · X tok/s · Ys". Never freeze on the previous
@@ -9,6 +9,7 @@ import { scratchDirFor } from "./scratch.js";
9
9
  import { renderHarnessContext } from "./operator-harness.js";
10
10
  import { renderToolCatalogue } from "../tools/registry.js";
11
11
  import { renderSkillsIndex } from "./skills-index.js";
12
+ import { decisionPointsEnabled } from "../engine/decision-points.js";
12
13
  // Project context: auto-load a per-repo instructions file from `cwd` and append it to the system prompt, so
13
14
  // Operator picks up house rules, conventions and build commands the way modern coding agents do. First match
14
15
  // wins, so the ORDER is the brand precedence: our own `.operator/AGENTS.md`, then the vendor-neutral open
@@ -170,8 +171,9 @@ export function basePersona(cwd = process.cwd(), opts = {}) {
170
171
  ? `. But not every message is a task, and not every turn needs a tool: when the owner asks a question, or ` +
171
172
  `the request is conversational, meta ("what can you do?"), or genuinely under-specified, just ANSWER in ` +
172
173
  `prose — or ask ONE short clarifying question — instead of reaching for a tool to avoid answering`
173
- : ` — bias to doing over asking: when you can do the work and verify it yourself, do it rather than asking ` +
174
- `the owner to confirm. Answer a question, or a conversational or meta ("what can you do?") turn, in prose ` +
174
+ : ` — bias to doing over asking for ROUTINE work: when you can do the work and verify it yourself, do it ` +
175
+ `rather than asking the owner to confirm (the direction of a new build is the exception — see Decision ` +
176
+ `points). Answer a question, or a conversational or meta ("what can you do?") turn, in prose ` +
175
177
  `without reaching for a tool`) +
176
178
  `. Never call self_status, list a directory, or run any tool merely to fill a turn or to decide what to do ` +
177
179
  `next; if you already know the answer, give it. The ONLY floor is fleet integrity — never leak secrets into ` +
@@ -186,6 +188,7 @@ export function basePersona(cwd = process.cwd(), opts = {}) {
186
188
  `unfixed — that risks leaving them unfixed forever. Bring back to the user ONLY genuine judgment calls: ` +
187
189
  `design decisions, real tradeoffs, or destructive/irreversible actions — never routine fixes. When in ` +
188
190
  `doubt on a low-risk fix, make it and note what you did.` +
191
+ decisionPointsSection(opts) +
189
192
  `\n## Verify by running before you claim done\nNever report that something works, passes, or is ` +
190
193
  `complete on the strength of your own reasoning — RUN it and read the result first. Execute the actual ` +
191
194
  `command, CLI, or code path you are claiming works; a task is done only when the check that proves it ` +
@@ -263,10 +266,10 @@ export function basePersona(cwd = process.cwd(), opts = {}) {
263
266
  `model you don't have. It also accepts \`reference\`+\`strength\`, passed through to the broker. (b) VIDEO ` +
264
267
  `— \`video_generate\` → LTX-Video-0.9.5 on the video broker, with \`expand\` and \`reference_image\` ` +
265
268
  `(IMAGE-TO-VIDEO): pass an image and LTX conditions on it as the FIRST FRAME, so the subject in the clip ` +
266
- `IS that image, in motion. (c) VISION — \`image_analyze\` / \`video_analyze\` → a Qwen2-VL worker on the ` +
267
- `fleet (REAL vision, not guessing from a filename). It walks an ordered endpoint chain with per-endpoint ` +
268
- `health-cooldown + an optional cloud fallback, so a cold/busy worker never hard-fails; large images are ` +
269
- `auto-downscaled before the model sees them. To match a reference, \`image_analyze\` it FIRST, then write ` +
269
+ `IS that image, in motion. (c) VISION — \`image_analyze\` / \`video_analyze\` → the 0perator gateway's \`vision\` ` +
270
+ `route (REAL vision, not guessing from a filename); the gateway owns failover across the fleet's VL workers. ` +
271
+ `A DOCUMENT (PDF, DOCX, XLSX, PPTX, RTF, HTML) is read as TEXT, every page (also via \`file_read\`) — only a ` +
272
+ `scanned page with no text is rendered for vision. Large images are auto-downscaled before the model sees them. To match a reference, \`image_analyze\` it FIRST, then write ` +
270
273
  `your generate prompt from what you actually SAW.` +
271
274
  `\n**Likeness is LIVE — this is how you "generate HER".** To make a SPECIFIC person, pass their FACE photo ` +
272
275
  `as \`reference\` to \`image_generate\`: it routes to the identity broker (RealVisXL + IP-Adapter-FaceID) ` +
@@ -430,6 +433,33 @@ export function basePersona(cwd = process.cwd(), opts = {}) {
430
433
  : ""));
431
434
  }
432
435
  const LEAN_NOTE = "\n\n(Lean harness: long-term memory + handoff omitted to fit this model's smaller context — answer from the live conversation; do not recite stored notes.)";
436
+ // Decision points (0.1.334): 0 ask_user calls in 96 recorded sessions — the persona only ever said "don't ask",
437
+ // never WHEN options are wanted. Routine fixes still never ask (Fix what you find); the direction of a build does.
438
+ // Interactive sessions have ask_user; a headless run / sub-agent has no approver, so it states its assumption.
439
+ function decisionPointsSection(opts) {
440
+ if (!decisionPointsEnabled(opts.decisionPoints))
441
+ return "";
442
+ if (!opts.interactive) {
443
+ return `\n## Decision points\nNo one is here to choose for you: where a build has genuinely different approaches, ` +
444
+ `pick the most conventional one, state that assumption in one line, and proceed.`;
445
+ }
446
+ if (opts.lean) {
447
+ return `\n## Decision points — give the owner options\nAt the START of a new build, feature or refactor, or when ` +
448
+ `there are 2+ genuinely different approaches or an irreversible step: before your first change, give a short ` +
449
+ `plan and call ask_user with 2-4 options, the recommended one FIRST marked "(recommended)". Then do what they ` +
450
+ `chose. Routine fixes, small edits, questions and checks: never ask.`;
451
+ }
452
+ return `\n## Decision points — give the owner options\nThe owner wants to steer direction, not approve chores. ` +
453
+ `Call ask_user BEFORE your first change when: (1) the request is a new build, feature, integration or refactor ` +
454
+ `spanning several steps or files — reply with a short numbered plan, then ask "Go with this plan ` +
455
+ `(recommended)" / "Adjust scope: …" / "Different approach: …"; (2) there are 2+ genuinely different ` +
456
+ `approaches, scopes or tradeoffs (library A vs B, quick patch vs proper fix); or (3) the next step is ` +
457
+ `destructive or irreversible. Give 2-4 concrete options, the recommended one FIRST labelled "(recommended)", ` +
458
+ `each a short line saying what happens. Read what you need first (read-only), then ask; once the owner ` +
459
+ `answers, proceed with their choice without asking again this turn. Do NOT ask for routine work — a typo, a ` +
460
+ `small clear edit, a rename, a bug you found, running tests, or a question you can answer. In plan mode, the ` +
461
+ `plan you present IS the decision point.`;
462
+ }
433
463
  // Embodiment guidance, appended only to an interactive session with computer control on. It steers the
434
464
  // model to READ the screen with chauffeur's textual accessibility tree instead of hand-rolling osascript —
435
465
  // the exact loop that failed on Slack (AppleScript can't read Electron UIs). `chauffeurReady` = chauffeur is
@@ -472,7 +502,12 @@ export function composeSystemPrompt(o) {
472
502
  const cwd = o.cwd ?? process.cwd();
473
503
  const lean = o.lean === true;
474
504
  const interactive = o.interactive === true;
475
- const identity = o.settings.systemPrompt ?? loadSoul() ?? basePersona(cwd, { ctxTokens: o.ctxTokens, interactive, lean });
505
+ const custom = o.settings.systemPrompt ?? loadSoul();
506
+ // A SOUL.md / settings.systemPrompt REPLACES basePersona (JL2 runs one), so the decision-points rule — harness
507
+ // behavior, not identity — is appended to it here; basePersona already carries it inline.
508
+ const identity = custom
509
+ ? custom + decisionPointsSection({ interactive, lean, decisionPoints: o.settings.decisionPoints })
510
+ : basePersona(cwd, { ctxTokens: o.ctxTokens, interactive, lean, decisionPoints: o.settings.decisionPoints });
476
511
  // Local-skills index (name: trigger, 4k cap) — the model must KNOW skills exist without spending a
477
512
  // skill_list call; bodies stay pull-on-demand via skill_fetch. Skipped in lean (small-ctx) mode like
478
513
  // the other heavy sections. Appended exactly like renderToolCatalogue, right before it.
@@ -7,7 +7,7 @@ import { totalmem } from "node:os";
7
7
  import { dirname } from "node:path";
8
8
  import { operatorPath } from "./home.js";
9
9
  import { applyManagedPolicy, loadManagedPolicy } from "./managed.js";
10
- import { MIN_CONTEXT_PIN, DEFAULT_MODEL_ID } from "../router/models.js";
10
+ import { MIN_CONTEXT_PIN, DEFAULT_MODEL_ID, GATEWAY_BASE } from "../router/models.js";
11
11
  import { LEGACY_API_HOST, PRODUCT_API_HOST } from "./product-hosts.js";
12
12
  /** Resolve an endpoint's bearer from config/env/secret-file (first hit wins); undefined when none set
13
13
  * (a local/un-gated endpoint). Keeps the raw key out of settings when `apiKeyEnv`/`apiKeyFile` are used. */
@@ -63,17 +63,27 @@ const DEFAULTS = {
63
63
  permissions: { mode: "gated" }, // ask-by-default: the user decides Allow/Deny; bypass is the opt-out
64
64
  telemetry: { enabled: true }, // local-only metrics (silent JSONL); remote sink opt-in via KODE_TELEMETRY_URL
65
65
  sandbox: { mode: "off" }, // no isolation by default — enterprise turns it on (KODE_SANDBOX / settings)
66
- computer: { enabled: false }, // computer control OFF by default; enable with KODE_COMPUTER=1 or settings.json
66
+ computer: { enabled: true }, // computer control ON (every action asks; bg agents denied; macOS TCC on top). Off: KODE_COMPUTER=0, settings.json or managed policy
67
67
  sessionSearch: { enabled: true }, // /sessions + session_search over Operator's and agents.md providers' sessions; per-provider switches in sources; KODE_SESSION_SEARCH=0 to disable
68
68
  search: {}, // web_search backend unset by default; set search.searxngUrl / search.autopilotUrl or the env vars
69
69
  // Service lever — JL1 defaults. On a machine without these launchd agents every start step just fails
70
70
  // harmlessly and the boot screen falls back to the manual hint (autostart is best-effort by design).
71
71
  services: {
72
- aurora: { autostart: true, launchdLabel: "ai.operator.gateway", plistPath: "~/Library/LaunchAgents/ai.operator.gateway.plist", waitSec: 90 },
72
+ // co.0perator.* since 2026-10-28; legacyLabels keeps a box that still runs the old job self-healing.
73
+ aurora: { autostart: true, launchdLabel: "co.0perator.gateway", plistPath: "~/Library/LaunchAgents/co.0perator.gateway.plist", legacyLabels: ["ai.operator.gateway"], waitSec: 90 },
73
74
  autopilot: { autostart: true, launchdLabel: "com.axe.autopilot", plistPath: "~/Library/LaunchAgents/com.axe.autopilot.plist", url: "http://127.0.0.1:9333" },
74
- vision: { autostart: false, launchdLabel: "axe.vision-bot", plistPath: "~/Library/LaunchAgents/axe.vision-bot.plist", url: "http://127.0.0.1:7788", remoteUrl: "http://192.168.1.103:8095" },
75
+ vision: { autostart: false, launchdLabel: "co.0perator.vision", plistPath: "~/Library/LaunchAgents/co.0perator.vision.plist", legacyLabels: ["axe.vision-bot"], url: "http://127.0.0.1:7788", remoteUrl: "http://192.168.1.103:8095" },
75
76
  stopOnExit: { searxng: true }, // aurora/autopilot are shared + never stopped; only the SearXNG container is
76
77
  },
78
+ // MOA (2026-10-28, James): Dolphin 7B + Cortana propose, Cortana aggregates — both on JL1, reached through the
79
+ // 0perator gateway so every signed-in Operator has the same team. settings.moa replaces it wholesale.
80
+ moa: {
81
+ proposers: [
82
+ { id: "cortana", endpoint: GATEWAY_BASE, model: "cortana" },
83
+ { id: "dolphin-7b", endpoint: GATEWAY_BASE, model: "dolphin-7b" },
84
+ ],
85
+ aggregator: { id: "cortana", endpoint: GATEWAY_BASE, model: "cortana" },
86
+ },
77
87
  activeModel: DEFAULT_MODEL_ID, // /model default — the 1M endpoint, unchanged from before /model existed
78
88
  // Autonomy: everything conservative. keepAwake off; dream OFF and read-mostly with a board-only
79
89
  // allowlist. An interactive owner never touches any of this until they run an autonomy subcommand.
@@ -180,6 +190,8 @@ function applyEnv(s) {
180
190
  out.sandbox = { mode: sb };
181
191
  if (process.env.KODE_COMPUTER === "1")
182
192
  out.computer = { enabled: true };
193
+ else if (process.env.KODE_COMPUTER === "0")
194
+ out.computer = { enabled: false };
183
195
  // Service lever: KODE_SERVICES_AUTOSTART=0 disables autostart of ALL launchd services (Operator then
184
196
  // only probes + reports); KODE_STOP_SEARXNG_ON_EXIT=0 keeps the SearXNG container running after exit.
185
197
  if (out.services) {
@@ -191,6 +203,16 @@ function applyEnv(s) {
191
203
  vision: { ...out.services.vision, autostart: false },
192
204
  };
193
205
  }
206
+ if (process.env.KODE_VISION_GATEWAY || process.env.KODE_VISION_MODEL) {
207
+ out.services = {
208
+ ...out.services,
209
+ vision: {
210
+ ...out.services.vision,
211
+ ...(process.env.KODE_VISION_GATEWAY ? { gateway: process.env.KODE_VISION_GATEWAY } : {}),
212
+ ...(process.env.KODE_VISION_MODEL ? { model: process.env.KODE_VISION_MODEL } : {}),
213
+ },
214
+ };
215
+ }
194
216
  if (process.env.KODE_STOP_SEARXNG_ON_EXIT === "0") {
195
217
  out.services = { ...out.services, stopOnExit: { ...out.services.stopOnExit, searxng: false } };
196
218
  }
@@ -417,7 +439,9 @@ export function loadSettings() {
417
439
  const flywheelPinned = (isPlainObject(file) && isPlainObject(file.selfImprove) && typeof file.selfImprove.flywheel === "boolean") ||
418
440
  process.env.KODE_SELFIMPROVE !== undefined ||
419
441
  typeof managed.policy?.selfImprove?.flywheel === "boolean";
420
- let out = applyManagedPolicy({ ...merged, explicit: { flywheel: flywheelPinned } }, managed);
442
+ const fv = isPlainObject(file) && isPlainObject(file.services) && isPlainObject(file.services.vision) ? file.services.vision : undefined;
443
+ const visionUrlPinned = !!fv && (typeof fv.url === "string" || typeof fv.remoteUrl === "string");
444
+ let out = applyManagedPolicy({ ...merged, explicit: { flywheel: flywheelPinned, visionUrl: visionUrlPinned } }, managed);
421
445
  if (managed.info.status === "invalid" && !warnedManaged) {
422
446
  warnedManaged = true;
423
447
  process.stderr.write(`[operator] managed policy ${managed.info.path} is not usable (${managed.info.errors.join("; ")}) — running locked down (read-only) until it is fixed\n`);
@@ -8,7 +8,7 @@ import { buildMessages } from "./messages.js";
8
8
  import { recoverToolCalls, cleanAssistantProse } from "./toolcalls.js";
9
9
  import { compact, needsCompaction, shouldProactivelyCompact, fitToWindow, clampMaxTokens, outputRoom, headroomTargetRatio, TOOL_CALL_HEADROOM_TOKENS } from "./compaction.js";
10
10
  import { globalTokenMeter, endpointKey, requestChars } from "./token-meter.js";
11
- import { classifyFailure, servedContextLimit, backoffMs, sleep } from "./selfheal.js";
11
+ import { classifyFailure, servedContextLimit, outputCeilingLimit, learnOutputCeiling, learnedOutputCeiling, backoffMs, sleep } from "./selfheal.js";
12
12
  import { TaskVerification, VERIFY_REMINDER, NOT_VERIFIED_BANNER } from "./verify-gate.js";
13
13
  import { detectRefusal, buildAffirmativeRetry, UNRESTRICTED_MAX_RETRIES } from "./unrestricted.js";
14
14
  import { ComputerEventStream, ComputerEventTracker } from "./computer-event.js";
@@ -25,6 +25,7 @@ const LOOP_GUARD_LIMIT = 5; // identical (name+args) calls in a turn before shor
25
25
  // file is verify-after-fix iteration, not a spin, so it must be unbounded. Only a genuinely repeated call
26
26
  // with NO intervening edit (a true no-progress loop) trips this. Raised 3→5 so even a no-edit re-run has
27
27
  // headroom before the guard fires. The narration/no-progress stalls below are the separate progress-gated stops.
28
+ import { DECISION_POINT_NUDGE, isBuildRequest, shouldHoldForDecision } from "./decision-points.js";
28
29
  import { MUTATING_TOOLS, mutationLanded } from "../tools/mutating.js"; // single source of truth (see tools/mutating.ts) — a LANDED workspace edit ⇒ prior identical-call counts are stale
29
30
  import { ANNOUNCE_NUDGE, ANNOUNCE_NUDGE_MAX, DELEGATION_NUDGE, detectAnnouncedDelegation, detectUnfinishedAction, engineNote, detectSelfDialogue, SELF_DIALOGUE_NUDGE, SELF_DIALOGUE_NUDGE_MAX, needsClosingSteer, CLOSING_NUDGE, CLOSING_NUDGE_UNATTENDED, EMPTY_REPLY_NUDGE, emptyReplyStatus, closeStopNote, stripEngineEcho, isEngineFinal } from "./continuation.js";
30
31
  // Poll/status tools are meant to be called repeatedly while waiting on async work — NEVER a spin, so the
@@ -139,6 +140,14 @@ const MAX_TRUNC_RETRIES = 3; // chunk-write nudges before a repeatedly-truncated
139
140
  // standing directive. A user role (not a 2nd system message, which 400s the endpoint — SPEC §1).
140
141
  const TRUNC_POS_RE = /at (?:column|position) (\d+)/i;
141
142
  const TRUNC_LARGE_BODY_CHARS = 300; // past this, "cut off at column/position N" means a big body, not a quoted command
143
+ /** The endpoint's output ceiling: the tighter of its profile's maxOutput and any ceiling a vendor 400 stated this
144
+ * process (selfheal.learnOutputCeiling). Undefined = no cap — the local llama-server fleet, unknown vendors. */
145
+ export function outputCeilingFor(ep) {
146
+ const learned = learnedOutputCeiling(endpointKey(ep.base, ep.model));
147
+ if (ep.maxOutput === undefined)
148
+ return learned;
149
+ return learned === undefined ? ep.maxOutput : Math.min(ep.maxOutput, learned);
150
+ }
142
151
  function truncatedToolPos(message) {
143
152
  const m = TRUNC_POS_RE.exec(message);
144
153
  return m ? Number(m[1]) : undefined;
@@ -590,6 +599,11 @@ export async function runTurn(userInput, conversation, opts) {
590
599
  let selfDialogueNudges = 0; // owner-facing: replies that react to a speaker who did not speak (continuation.ts)
591
600
  let closingNudged = false; // owner-facing: one nudge to close with status + a steering question instead of a bare stop
592
601
  let lastReasoning = ""; // the reasoning channel of an empty round — a model that answers there still answered
602
+ const hasAskTool = (opts.toolSchemas ?? []).some((s) => s?.function?.name === "ask_user");
603
+ const decisionGate = opts.decisionPoints?.enabled === true && hasAskTool;
604
+ const buildTurn = decisionGate && isBuildRequest(userInput);
605
+ let askedThisTurn = false; // ask_user ran this turn — the owner already chose a direction
606
+ let decisionNudged = false; // the decision-point hold fires at most once per turn
593
607
  let repliesSinceOwner = 0; // non-empty model replies since the owner last spoke (turn start, or an ask_user answer) — the first is never self-dialogue
594
608
  let emptyNudged = false; // the reframe nudge goes in on the FIRST genuine empty, whatever the retry counter says
595
609
  let malformedCallNudges = 0; // bounded re-prompts for an unparseable text tool call
@@ -707,6 +721,7 @@ export async function runTurn(userInput, conversation, opts) {
707
721
  // failover below can swap endpoints mid-round and each has its own ctx_window.
708
722
  const compactionOptsFor = (ep) => ({
709
723
  ctxWindow: ep.ctxWindow,
724
+ outputCeiling: outputCeilingFor(ep),
710
725
  systemPrompt: opts.systemPrompt,
711
726
  tools: opts.toolSchemas,
712
727
  summarize: opts.summarize,
@@ -720,6 +735,7 @@ export async function runTurn(userInput, conversation, opts) {
720
735
  });
721
736
  let response;
722
737
  let lastMaxTokens; // the clamp actually sent this round — black-box evidence
738
+ let ceilingRetried = false; // one output-ceiling retry per round — never a loop
723
739
  for (;;) {
724
740
  // Harness-layer compaction gate — the single choke point every request passes through, on the
725
741
  // INITIAL attempt AND after any self-heal failover/route switch below (which `continue`s back
@@ -775,6 +791,8 @@ export async function runTurn(userInput, conversation, opts) {
775
791
  response = await chat(messages, {
776
792
  base: endpoint.base,
777
793
  model: endpoint.model,
794
+ label: endpoint.label,
795
+ provider: endpoint.provider,
778
796
  token: endpoint.token,
779
797
  loopbackAuth: endpoint.loopbackAuth,
780
798
  transport: endpoint.transport,
@@ -871,6 +889,19 @@ export async function runTurn(userInput, conversation, opts) {
871
889
  await sleep(opts.loadingBackoffMs ?? DEFAULT_LOADING_BACKOFF_MS, opts.signal, () => new TurnAbortedError());
872
890
  continue;
873
891
  }
892
+ // The vendor's 400 stated its OUTPUT ceiling (max_tokens over what it accepts — QwenCloud's "Range of
893
+ // max_tokens should be [1, 131072]"): learn it for this endpoint, so every later clamp honours it, and
894
+ // retry this round ONCE. Not a context problem (compaction/failover can't help) and no self-heal
895
+ // budget spent. A ceiling no lower than what we sent, or a second hit this round, is surfaced as-is.
896
+ if (recovery === "output_ceiling") {
897
+ const cap = outputCeilingLimit(err);
898
+ if (ceilingRetried || cap === undefined || (lastMaxTokens !== undefined && cap >= lastMaxTokens))
899
+ throw err;
900
+ ceilingRetried = true;
901
+ learnOutputCeiling(endpointKey(endpoint.base, endpoint.model), cap);
902
+ opts.onSelfHeal?.("server_error", 1); // footer ↻ — a recovery is in flight
903
+ continue;
904
+ }
874
905
  // Non-retryable: a malformed request (a bad tool call) or bad credentials won't be fixed by
875
906
  // resending — fail fast rather than spin (that futile-retry storm is what burned minutes).
876
907
  if (recovery === "bad_request" || recovery === "auth" || selfHealBudget <= 0)
@@ -945,6 +976,8 @@ export async function runTurn(userInput, conversation, opts) {
945
976
  response = await chat(retryMessages, {
946
977
  base: endpoint.base,
947
978
  model: endpoint.model,
979
+ label: endpoint.label,
980
+ provider: endpoint.provider,
948
981
  token: endpoint.token,
949
982
  loopbackAuth: endpoint.loopbackAuth,
950
983
  transport: endpoint.transport,
@@ -1134,6 +1167,15 @@ export async function runTurn(userInput, conversation, opts) {
1134
1167
  }
1135
1168
  selfLoopStreak = 0; // a round that fixes, doesn't act, or doesn't admit looping clears the streak
1136
1169
  }
1170
+ // Decision points: a build turn's first change, with no direction chosen yet, is held back once so the owner
1171
+ // gets a plan + options (ask_user) instead of a silently picked approach. This round's calls are not dispatched.
1172
+ if (response.toolCalls.length > 0 && shouldHoldForDecision({ enabled: decisionGate, buildTurn, askedThisTurn, nudged: decisionNudged, calls: response.toolCalls.map((c) => ({ name: c.function?.name, args: c.function?.arguments })) })) {
1173
+ decisionNudged = true;
1174
+ if (response.content.trim())
1175
+ conversation.assistant(cleanAssistantProse(response.content));
1176
+ engineUser(DECISION_POINT_NUDGE);
1177
+ continue;
1178
+ }
1137
1179
  if (response.toolCalls.length > 0) {
1138
1180
  throwIfAborted(opts.signal); // don't dispatch a tool batch for a turn the user already cancelled
1139
1181
  // Strip any leaked tool-call/thinking delimiter tags the model emitted into content ALONGSIDE the
@@ -1158,8 +1200,10 @@ export async function runTurn(userInput, conversation, opts) {
1158
1200
  noProgressStreak = progressed ? 0 : noProgressStreak + 1; // reset the stall counter on any real progress
1159
1201
  noEditStreak = response.toolCalls.some((c) => MUTATING_TOOLS.has(c.function?.name ?? "")) ? 0 : noEditStreak + 1;
1160
1202
  trackTouchedFiles(response.toolCalls, touchedFiles);
1161
- if (response.toolCalls.some((c) => c.function?.name === "ask_user"))
1162
- repliesSinceOwner = -1; // the answer lands as a tool result: the next reply answers the OWNER
1203
+ if (response.toolCalls.some((c) => c.function?.name === "ask_user")) {
1204
+ repliesSinceOwner = -1;
1205
+ askedThisTurn = true;
1206
+ } // the answer lands as a tool result: the next reply answers the OWNER
1163
1207
  // Owner-facing: narration that answers a speaker who did not speak ("You're right — …" to an engine note) is
1164
1208
  // redirected into a status for the owner. The round's calls already ran; the note rides into the next round.
1165
1209
  if (selfDialogueNudges < SELF_DIALOGUE_NUDGE_MAX && detectSelfDialogue(response.content, repliesSinceOwner)) {
@@ -1224,6 +1268,13 @@ export async function runTurn(userInput, conversation, opts) {
1224
1268
  if (fromReasoning.calls.length > 0)
1225
1269
  recovered = { ...recovered, calls: fromReasoning.calls };
1226
1270
  }
1271
+ if (recovered.calls.length > 0 && shouldHoldForDecision({ enabled: decisionGate, buildTurn, askedThisTurn, nudged: decisionNudged, calls: recovered.calls.map((c) => ({ name: c.function?.name, args: c.function?.arguments })) })) {
1272
+ decisionNudged = true;
1273
+ if (recovered.cleanedContent.trim())
1274
+ conversation.assistant(recovered.cleanedContent);
1275
+ engineUser(DECISION_POINT_NUDGE);
1276
+ continue;
1277
+ }
1227
1278
  if (recovered.calls.length > 0) {
1228
1279
  throwIfAborted(opts.signal);
1229
1280
  conversation.assistant(recovered.cleanedContent, recovered.calls);
@@ -1238,8 +1289,10 @@ export async function runTurn(userInput, conversation, opts) {
1238
1289
  noProgressStreak = progressed ? 0 : noProgressStreak + 1; // reset the stall counter on any real progress
1239
1290
  noEditStreak = recovered.calls.some((c) => MUTATING_TOOLS.has(c.function?.name ?? "")) ? 0 : noEditStreak + 1;
1240
1291
  trackTouchedFiles(recovered.calls, touchedFiles);
1241
- if (recovered.calls.some((c) => c.function?.name === "ask_user"))
1292
+ if (recovered.calls.some((c) => c.function?.name === "ask_user")) {
1242
1293
  repliesSinceOwner = -1;
1294
+ askedThisTurn = true;
1295
+ }
1243
1296
  if (selfDialogueNudges < SELF_DIALOGUE_NUDGE_MAX && detectSelfDialogue(recovered.cleanedContent, repliesSinceOwner)) {
1244
1297
  selfDialogueNudges++;
1245
1298
  engineUser(SELF_DIALOGUE_NUDGE);
@@ -1,8 +1,8 @@
1
- import { acquireEndpoint, releaseEndpoint, isDegenerate, trimLoop } from "./aurora.js";
1
+ import { acquireEndpoint, releaseEndpoint, isDegenerate, trimLoop, httpErrorLabel } from "./aurora.js";
2
2
  import { anthropicKey } from "./anthropic.js";
3
3
  import { classifyFailure, backoffMs, sleep } from "./selfheal.js";
4
+ import { ANTHROPIC_MAX_OUTPUT } from "../router/models.js"; // the same ceiling the Claude rows' maxOutput carries — the wire keeps it for callers that skip the turn-loop clamp
4
5
  const ANTHROPIC_VERSION = "2023-06-01";
5
- const MAX_OUTPUT_TOKENS = 128_000; // the vendor's output ceiling for the current Claude family — a larger max_tokens is a 400
6
6
  const FETCH_TRIES = 3; // same pre-response transient retry budget as aurora.fetchChat (no bytes streamed yet → safe)
7
7
  /** OpenAI tool-call `arguments` is a JSON STRING; Anthropic `input` is an OBJECT. Parse defensively — a
8
8
  * malformed/empty string becomes `{}` (messages.ts already sanitizes history, but a live round may not). */
@@ -94,7 +94,7 @@ export function anthropicRequestBody(messages, o, stream) {
94
94
  const tools = toAnthropicTools(o.tools);
95
95
  return JSON.stringify({
96
96
  model: o.model,
97
- max_tokens: Math.min(o.maxTokens ?? 8192, MAX_OUTPUT_TOKENS),
97
+ max_tokens: Math.min(o.maxTokens ?? 8192, ANTHROPIC_MAX_OUTPUT),
98
98
  ...(system ? { system } : {}),
99
99
  messages: amsgs,
100
100
  ...(tools ? { tools } : {}),
@@ -167,7 +167,7 @@ async function* anthropicDeltas(messages, o) {
167
167
  detail = (await res.text()).slice(0, 500);
168
168
  }
169
169
  catch { /* body consumed / unreadable */ }
170
- const err = new Error(`anthropic /v1/messages ${res.status}${detail ? `: ${detail}` : ""}`);
170
+ const err = new Error(`${o.label ? httpErrorLabel(o) : "anthropic /v1/messages"} ${res.status}${detail ? `: ${detail}` : ""}`);
171
171
  err.status = res.status;
172
172
  const ra = res.headers.get("retry-after");
173
173
  if (ra)
@@ -278,6 +278,13 @@ const FETCH_TRIES = 3; // a transient network drop ("fetch failed") gets a coupl
278
278
  export function chatUrl(base, chatPath) {
279
279
  return `${base}${chatPath ?? "/v1/chat/completions"}`;
280
280
  }
281
+ /** Who answered an HTTP error, for the owner: the profile id + provider box when the turn loop passed them
282
+ * ("qwen3.8-flash (QwenCloud)"), else the legacy "aurora /v1" — every OpenAI-dialect call used to read as Aurora. */
283
+ export function httpErrorLabel(o) {
284
+ if (!o.label)
285
+ return "aurora /v1";
286
+ return o.provider ? `${o.label} (${o.provider})` : o.label;
287
+ }
281
288
  async function fetchChat(o, body) {
282
289
  let lastErr;
283
290
  for (let attempt = 0; attempt < FETCH_TRIES; attempt++) {
@@ -374,7 +381,7 @@ async function* streamDeltas(messages, o) {
374
381
  catch { /* body already consumed / unreadable */ }
375
382
  // Carry the status + body so the self-heal policy can classify WHY (context vs shape vs busy),
376
383
  // not just guess from the number. `retryAfterMs` honors a Retry-After header on 429/503.
377
- const err = new Error(`aurora /v1 ${res.status}${detail ? `: ${detail}` : ""}`);
384
+ const err = new Error(`${httpErrorLabel(o)} ${res.status}${detail ? `: ${detail}` : ""}`);
378
385
  err.status = res.status;
379
386
  const ra = res.headers.get("retry-after");
380
387
  if (ra)
@@ -141,7 +141,8 @@ export function fitToWindow(conversation, opts, targetRatio) {
141
141
  }
142
142
  return out;
143
143
  }
144
- /** Clamp generation length so prompt + output never exceeds the window. A static max_tokens plus a
144
+ /** Clamp generation length so prompt + output never exceeds the window, nor the endpoint's output ceiling
145
+ * (opts.outputCeiling — a vendor 400s on a larger max_tokens). A static max_tokens plus a
145
146
  * deep-session prompt otherwise gets the model squeezed to a truncated reply (matching the Python
146
147
  * core's _predict_budget). `built` already includes the system message, so pass systemPrompt:undefined
147
148
  * to avoid double-counting it; tool-schema tokens still come from opts.tools. Floored (≥1024) so a
@@ -149,7 +150,8 @@ export function fitToWindow(conversation, opts, targetRatio) {
149
150
  * cut-off call is unparseable (see selfheal's truncated_tool_call). If even the floor won't fit, the
150
151
  * prompt is over budget and the caller's compaction handles it. */
151
152
  export function clampMaxTokens(built, opts, want, min = 1024) {
152
- return Math.max(min, Math.min(want, outputRoom(built, opts)));
153
+ const clamped = Math.max(min, Math.min(want, outputRoom(built, opts)));
154
+ return opts.outputCeiling && opts.outputCeiling > 0 ? Math.min(clamped, opts.outputCeiling) : clamped;
153
155
  }
154
156
  /** The generation room a request leaves: window − prompt estimate − the 256-token chat-template/role margin.
155
157
  * The SAME basis clampMaxTokens clamps to (factored out so the turn loop's headroom guard and the clamp can
@@ -0,0 +1,78 @@
1
+ // Decision points (0.1.334): the owner gets a short list of options at the start of a real build instead of the
2
+ // model silently picking a direction. Across 96 recorded sessions the local model called ask_user ZERO times
3
+ // (vs 3,132 bash calls) — the persona told it to bias to doing, and nothing said WHEN options are wanted. The
4
+ // persona + ask_user description now say when; this module is the small engine backstop: on a build-shaped
5
+ // owner turn, the FIRST mutating call before any ask_user is held back once and the model is told to offer a
6
+ // plan + options first. Pure and dependency-free so the gate's trigger logic is unit-testable.
7
+ import { isMutatingTool } from "../tools/mutating.js";
8
+ const SHELL_TOOLS = new Set(["bash", "shell_exec", "shell_background", "shell_task_start"]);
9
+ // Shell commands that change the workspace or the machine. Read-only probes (ls, cat, grep, git status, a test
10
+ // run) are NOT here — the gate must never hold back investigation, only the first change.
11
+ const MUTATING_SHELL_RE = new RegExp([
12
+ String.raw `(?:^|[;&|]\s*|\s)(?:mkdir|touch|rm|rmdir|mv|cp|ln|chmod|tee|install|truncate)\s`,
13
+ String.raw `\bsed\s+-i`,
14
+ String.raw `\b(?:npm|pnpm|yarn|bun)\s+(?:init|install|i|add|create|remove|uninstall)\b`,
15
+ String.raw `\bnpx\s+(?:create-|degit|tsc\s+--init)`,
16
+ String.raw `\b(?:cargo\s+(?:new|init|add)|pip3?\s+install|uv\s+(?:init|add|pip\s+install)|poetry\s+(?:new|init|add)|go\s+mod\s+init)\b`,
17
+ String.raw `\bgit\s+(?:init|add|commit|checkout|switch|apply|reset|merge|rebase|stash|mv|rm)\b`,
18
+ String.raw `(?:^|[^<>&0-9])>{1,2}\s*(?!&|/dev/null)[^\s>]`,
19
+ ].join("|"));
20
+ /** True when a tool call changes the workspace: a file write/edit, a mutating shell command, or a git write. */
21
+ export function isMutatingCall(name, rawArgs) {
22
+ if (isMutatingTool(name))
23
+ return true;
24
+ if (name === "checkpoint")
25
+ return true;
26
+ let args = {};
27
+ try {
28
+ args = JSON.parse(rawArgs || "{}");
29
+ }
30
+ catch { /* partial args: treat as text */ }
31
+ if (name === "git_command") {
32
+ const cmd = String(args.command ?? args.args ?? rawArgs ?? "");
33
+ return !/^\s*(?:git\s+)?(?:status|log|diff|show|branch|remote|rev-parse|blame|ls-files)\b/.test(cmd);
34
+ }
35
+ if (!SHELL_TOOLS.has(name ?? ""))
36
+ return false;
37
+ const cmd = String(args.command ?? args.cmd ?? rawArgs ?? "");
38
+ return MUTATING_SHELL_RE.test(cmd);
39
+ }
40
+ // A build-shaped owner turn: a construction verb aimed at something bigger than a one-line edit. Routine asks
41
+ // ("fix the typo", "what does X do", "run the tests", "rename tmp to result") deliberately do not match.
42
+ const BUILD_VERB_RE = /\b(?:build|create|implement|scaffold|set\s*up|setup|make|write|add|introduce|design|refactor|restructure|rewrite|redesign|migrate|port|convert|overhaul|integrate)\b/i;
43
+ const BUILD_OBJECT_RE = /\b(?:app|application|cli|tool|service|server|api|endpoint|feature|auth\w*|login|sign[- ]?in|oauth|cach\w*|database|db|schema|module|package|library|lib|plugin|extension|dashboard|page|site|website|ui|frontend|backend|pipeline|workflow|system|integration|bot|agent|engine|layer|architecture|structure|framework|tests?|test suite|project|component|support)\b/i;
44
+ const ROUTINE_RE = /\b(?:typo|spelling|whitespace|indent\w*|lint|format(?:ting)?|comment|docstring|rename|bump|version|log line|print)\b/i;
45
+ /** True when the owner's message reads like a multi-step build/feature/refactor request. */
46
+ export function isBuildRequest(text) {
47
+ const t = text.trim();
48
+ if (!t || t.length > 4000)
49
+ return false; // a pasted spec/log is not a fresh build brief to re-scope
50
+ if (/^\s*(?:what|why|how|where|when|who|which|explain|describe|summari[sz]e|show|tell|is|are|does|do|can|could)\b/i.test(t) && /\?\s*$/.test(t))
51
+ return false;
52
+ if (ROUTINE_RE.test(t) && t.length < 160)
53
+ return false;
54
+ return BUILD_VERB_RE.test(t) && BUILD_OBJECT_RE.test(t);
55
+ }
56
+ /** Engine note when the model reached for its first change on a build turn without offering a direction. */
57
+ export const DECISION_POINT_NUDGE = "Before changing anything: this is a multi-step build, and the owner wants to choose its direction. Do NOT make " +
58
+ "the change yet. Reply with a short numbered plan (3-6 steps), then call ask_user with 2-4 concrete options — " +
59
+ "the recommended one FIRST and labelled \"(recommended)\", each a short line saying what happens (e.g. \"Go with " +
60
+ "this plan (recommended)\", \"Smaller scope: …\", \"Different approach: …\"). After the owner answers, proceed " +
61
+ "with their choice without asking again.";
62
+ /** Resolve whether decision points are on: settings.decisionPoints (default true), overridden off by
63
+ * KODE_DECISION_POINTS=0. */
64
+ export function decisionPointsEnabled(setting, env = process.env) {
65
+ if (env.KODE_DECISION_POINTS === "0" || env.KODE_DECISION_POINTS === "false")
66
+ return false;
67
+ if (env.KODE_DECISION_POINTS === "1")
68
+ return true;
69
+ return setting !== false;
70
+ }
71
+ /** The gate's per-turn decision: hold back this round's calls once and nudge, or let them run. */
72
+ export function shouldHoldForDecision(s) {
73
+ if (!s.enabled || !s.buildTurn || s.askedThisTurn || s.nudged)
74
+ return false;
75
+ if (s.calls.some((c) => c.name === "ask_user"))
76
+ return false;
77
+ return s.calls.some((c) => isMutatingCall(c.name, c.args));
78
+ }
@@ -1,3 +1,4 @@
1
+ import { authHeaders } from "./aurora.js";
1
2
  // Fan-out budget per proposer. 60s default: generous for a draft, hard enough that a contended
2
3
  // JL1 slot times out gracefully instead of stalling the aggregator (measured 2026-10-12: same
3
4
  // task 1.1s local vs 60s+ timeout on the shared lane). Env-overridable — heavy offline drafts on
@@ -14,7 +15,9 @@ async function callProposer(p, messages) {
14
15
  try {
15
16
  const res = await fetch(`${p.endpoint.replace(/\/$/, "")}/chat/completions`, {
16
17
  method: "POST",
17
- headers: { "content-type": "application/json" },
18
+ // The same bearer scoping as every model call: the signed-in Operator token on the 0perator gateway (proposers
19
+ // default to it), nothing for a local server or a foreign host.
20
+ headers: { "content-type": "application/json", ...authHeaders({ base: p.endpoint, model: p.model }) },
18
21
  body: JSON.stringify({ model: p.model, messages, stream: false }),
19
22
  signal: ctrl.signal,
20
23
  });
@@ -13,6 +13,8 @@ const toRE = (e, pin) => ({
13
13
  loopbackAuth: e.loopbackAuth,
14
14
  transport: e.transport,
15
15
  chatPath: e.chatPath,
16
+ maxOutput: e.maxOutput,
17
+ provider: e.provider,
16
18
  });
17
19
  function estimateTokens(messages, tools) {
18
20
  const chars = JSON.stringify(messages).length + (tools ? JSON.stringify(tools).length : 0);
@@ -36,6 +36,45 @@ export function servedContextLimit(err) {
36
36
  const n = Number(m[1] ?? m[2]);
37
37
  return Number.isFinite(n) && n > 0 ? n : undefined;
38
38
  }
39
+ // A 400 whose body states the endpoint's OUTPUT ceiling: the request's max_tokens is larger than the vendor
40
+ // accepts (JL2 2026-10-28, QwenCloud qwen3.8-flash: "Range of max_tokens should be [1, 131072]" while we sent
41
+ // ~220K). Not a context problem — compacting or failing over can't help — so it gets its own class: retry the
42
+ // round ONCE at the stated ceiling and remember it for the endpoint. Each pattern captures the ceiling; they
43
+ // all name max_tokens or output/completion tokens, so a context-length 400 ("maximum context length is N
44
+ // tokens") never reads as one.
45
+ const OUTPUT_CEILING_RES = [
46
+ /max_(?:completion_)?tokens\b[^[\]]{0,60}?\[\s*\d+\s*,\s*(\d+)\s*\]/i, // "Range of max_tokens should be [1, N]" / "valid range of max_tokens is [1, N]"
47
+ /max_(?:completion_)?tokens`?\s*(?:must|should)\s+be\s+(?:<=|less than or equal to|at most|no (?:more|greater|larger) than)\s*`?(\d+)/i, // "max_tokens must be <= N"
48
+ /max_tokens:\s*\d+\s*>\s*(\d+)/i, // Anthropic: "max_tokens: 200000 > 128000, which is the maximum allowed…"
49
+ /supports at most (\d+) (?:completion|output) tokens/i, // OpenAI: "This model supports at most N completion tokens"
50
+ /maximum (?:allowed |supported )?(?:number of )?(?:output|completion|generated|generation) tokens?(?: is| of|:|\s*\()?\s*(\d+)/i, // "the maximum output tokens is N"
51
+ /max_(?:completion_)?tokens\b[^.]{0,60}?\bmaximum(?: allowed| value)?(?: of| is|:)?\s*`?(\d+)/i, // "max_tokens (N') exceeds the maximum of N"
52
+ ];
53
+ export function outputCeilingLimit(err) {
54
+ const msg = err instanceof Error ? err.message : String(err);
55
+ for (const re of OUTPUT_CEILING_RES) {
56
+ const m = re.exec(msg);
57
+ const n = m ? Number(m[1]) : NaN;
58
+ if (Number.isFinite(n) && n > 0)
59
+ return n;
60
+ }
61
+ return undefined;
62
+ }
63
+ // Output ceilings learned from those 400s, keyed by endpointKey(base, model). Process-lifetime (a vendor's
64
+ // ceiling is a fact of the model, not of one turn), so later rounds and turns clamp up front instead of
65
+ // re-hitting the 400. Monotonic down, like AuroraRouter.observeContextLimit.
66
+ const learnedCeilings = new Map();
67
+ export function learnOutputCeiling(key, n) {
68
+ const prev = learnedCeilings.get(key);
69
+ if (n > 0 && (prev === undefined || n < prev))
70
+ learnedCeilings.set(key, n);
71
+ }
72
+ export function learnedOutputCeiling(key) {
73
+ return learnedCeilings.get(key);
74
+ }
75
+ export function _resetLearnedOutputCeilings() {
76
+ learnedCeilings.clear();
77
+ }
39
78
  function statusOf(err) {
40
79
  const s = err?.status;
41
80
  if (typeof s === "number" && Number.isFinite(s))
@@ -58,6 +97,8 @@ export function classifyFailure(err) {
58
97
  return "truncated_tool_call";
59
98
  if (s === 413)
60
99
  return "context"; // payload too large == context pressure
100
+ if ((s === 400 || s === 422) && outputCeilingLimit(msg) !== undefined)
101
+ return "output_ceiling"; // before CTX_RE: Groq's wording also says "context_window"
61
102
  if (s === 400)
62
103
  return CTX_RE.test(msg) ? "context" : "bad_request"; // the 400 body decides
63
104
  if (s !== undefined && s >= 500 && LOADING_RE.test(msg))