@0perator/operator 0.1.331 → 0.1.333

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 (44) hide show
  1. package/dist/acp/config-options.js +10 -1
  2. package/dist/auth/byo.js +90 -9
  3. package/dist/auth/commands.js +1 -1
  4. package/dist/autonomy/delegate.js +3 -2
  5. package/dist/autonomy/session-factory.js +1 -0
  6. package/dist/cli.js +210 -62
  7. package/dist/config/persona.js +3 -1
  8. package/dist/config/settings.js +38 -4
  9. package/dist/engine/agent.js +8 -4
  10. package/dist/engine/anthropic-chat.js +28 -6
  11. package/dist/engine/anthropic.js +1 -1
  12. package/dist/engine/aurora.js +5 -1
  13. package/dist/engine/continuation.js +1 -1
  14. package/dist/engine/router-adapter.js +6 -5
  15. package/dist/engine/verify-gate.js +30 -3
  16. package/dist/remote/safe-commands.js +1 -1
  17. package/dist/router/discovery.js +23 -4
  18. package/dist/router/free-models.js +191 -0
  19. package/dist/router/models.js +142 -60
  20. package/dist/services/preflight.js +17 -2
  21. package/dist/session.js +94 -23
  22. package/dist/tools/sandbox.js +1 -1
  23. package/dist/ui/App.js +4 -3
  24. package/dist/ui/Composer.js +16 -1
  25. package/dist/ui/QuestionPrompt.js +22 -4
  26. package/dist/ui/SecretPrompt.js +77 -0
  27. package/dist/ui/StatusRule.js +6 -6
  28. package/dist/ui/modelPicker.js +110 -0
  29. package/dist/ui/slashCommands.js +3 -1
  30. package/dist/util/slash.js +3 -2
  31. package/package.json +1 -1
  32. package/dist/engine/cli.js +0 -1171
  33. package/dist/router/models.js.bak +0 -78
  34. package/dist/router/models.js.bak-1791259923 +0 -78
  35. package/dist/router/models.js.bak-pre-gateway +0 -78
  36. package/dist/router/models.js.bak-pre-patch2 +0 -78
  37. package/dist/router/models.js.bak2 +0 -78
  38. package/dist/services/model-autodetect.js +0 -240
  39. package/dist/tools/native-redirect.js +0 -140
  40. package/dist/tools/power-tools.js +0 -627
  41. package/dist/tools/registry.js.bak-1791259948 +0 -1914
  42. package/dist/tools/registry.js.bak-pre-plugins +0 -1914
  43. package/dist/ui/BusTray.js +0 -70
  44. package/dist/ui/resize.js +0 -160
package/dist/cli.js CHANGED
@@ -9,6 +9,7 @@ import { render, Box, Text, useApp } from "ink";
9
9
  import { App } from "./ui/index.js";
10
10
  import { mastheadLines } from "./ui/Masthead.js";
11
11
  import { shouldPromptPlanExit, resolvePlanExit, PLAN_EXIT_OPTIONS } from "./ui/planExit.js";
12
+ import { FREE_ROW_PRESETS, connectedAccounts, looksLikeSecret, contextLine, contextPickerView, keyStoredLine, markModelRows, modelLine, modelPickerView, onceEach, pickerAnswer, providerPickerView, wantsContextStep } from "./ui/modelPicker.js";
12
13
  import { RemoteHost } from "./remote/host.js";
13
14
  import { REMOTE_SAFE_COMMANDS, REMOTE_SAFE_COMMAND_NAMES } from "./remote/safe-commands.js";
14
15
  import { newCode, pairURL } from "./remote/pairing.js";
@@ -22,7 +23,7 @@ import { cacheBustNotice } from "./engine/aurora.js";
22
23
  import { seedCalibration } from "./engine/calibration-seed.js";
23
24
  import { AuroraRouter } from "./router/router.js";
24
25
  import { BackgroundAgents } from "./background/index.js";
25
- import { loadSettings, saveSettings, compactionThreshold, compactionCeilingTokens, rcAutostart, applySeat, setActiveSeat, buildEndpointChain } from "./config/settings.js";
26
+ import { loadSettings, saveSettings, compactionThreshold, compactionCeilingTokens, rcAutostart, applySeat, setActiveSeat, buildEndpointChain, parseContextArg, nextContextPin } from "./config/settings.js";
26
27
  import { resolveSeat } from "./auth/identity.js";
27
28
  import { PermissionPolicy } from "./permissions/index.js";
28
29
  import { caps } from "./ui/capabilities.js";
@@ -30,10 +31,11 @@ import { composeSystemPrompt, appendMemory } from "./config/persona.js";
30
31
  import { applyToolsBinPath, operatorPath } from "./config/home.js";
31
32
  import { ensureOperatorHome } from "./config/scaffold.js";
32
33
  import { listLocalSkills } from "./config/skills-index.js";
33
- import { modelCtxFor, leanHarnessFor, selectModel, modelRegistry, DEFAULT_MODEL_ID } from "./router/models.js";
34
- import { fetchPortalModels, markPickerOptions, offlineNote, portalIdFor } from "./router/portal.js";
34
+ import { modelCtxFor, leanHarnessFor, selectModel, modelRegistry, fmtCtx, shortName, BYO_PRESETS, DEFAULT_MODEL_ID } from "./router/models.js";
35
+ import { fetchPortalModels, offlineNote, portalIdFor } from "./router/portal.js";
36
+ import { fetchFreeModels } from "./router/free-models.js";
35
37
  import { describeTurnError } from "./engine/net-error.js";
36
- import { hasByoToken } from "./auth/byo.js";
38
+ import { hasByoToken, setByoToken } from "./auth/byo.js";
37
39
  import { getDiscoveredModels } from "./router/discovery.js";
38
40
  import { disposeShellSession, getAgentTasks, registry } from "./tools/registry.js";
39
41
  import { drainJobNotices, getJobNoticeMode, listShellJobs, onJobEvent, parseJobsArgs, pendingJobNotices, renderJobsList, runningJobCount, setJobNoticeMode, stopShellJob } from "./tools/shell-jobs.js";
@@ -486,7 +488,8 @@ const SYSTEM_PROMPT = composeSystemPrompt({ settings, cwd: process.cwd(), ctxTok
486
488
  const HELP = [
487
489
  "commands:",
488
490
  " /help this list",
489
- " /model [id] pick a model: operator-1m · operator-128k · qwen connectors (auth byo qwen) · moa",
491
+ " /model [id] pick a model — fleet, connected providers, free rows; + connect a key",
492
+ " /context [300k|600k|1m|auto] context window for this session (alias /ctx); also Ctrl+X to cycle",
490
493
  " /endpoints show the Operator endpoint + live health",
491
494
  " /services ensure/inspect the service lever (Operator+autopilot+searxng); /services stop",
492
495
  " /audit [n] recent tool + control-plane events from the audit trail (default 15)",
@@ -584,8 +587,10 @@ function Root() {
584
587
  remoteRef.current?.askUser(id, q, options); // mirror to followers (owner-scoped; follower prompt is single-select)
585
588
  }), [settleQuestion]);
586
589
  // /model picker: same QuestionPrompt UI pattern as ask_user, but purely local (never relayed) —
587
- // it's a session setting, not something the model is asking.
590
+ // it's a session setting, not something the model is asking. Its context step, /context and the provider
591
+ // step share the slot; the provider key itself goes into the masked SecretPrompt, never a QuestionPrompt.
588
592
  const [modelPicker, setModelPicker] = useState(null);
593
+ const [secretPrompt, setSecretPrompt] = useState(null);
589
594
  // Plan-mode "Approve & run": true once an assistant turn has completed while still in plan mode
590
595
  // (i.e. the model actually proposed something), reset whenever a fresh plan-mode session starts.
591
596
  // Gates the exit-time picker below — plan mode toggled on/off with no proposal stays silent.
@@ -625,6 +630,10 @@ function Root() {
625
630
  remoteRef.current?.approvalRequest(id, name, args); // mirror to followers (owner-scoped)
626
631
  });
627
632
  }, [settleApproval]);
633
+ // The free vendor rows (router/free-models.ts), fetched when /model opens with that gateway's key connected; the
634
+ // Session reads them on every registry access (dynamicModels), so a fetched row is pickable the moment it lands.
635
+ const freeRowsRef = useRef([]);
636
+ const freeStaleRef = useRef(false); // served from the disk cache after a failed read → the rows say " · cached"
628
637
  const sessionRef = useRef(null); // lazy — never reconstruct on re-render
629
638
  // MCP opts the foreground session into the fleet MCP tool surface (off by default: local tools
630
639
  // only, no network fan-out at session start). Background agents stay local-only + lean.
@@ -647,10 +656,12 @@ function Root() {
647
656
  temperature: settings.temperature,
648
657
  recall: settings.memory.recall,
649
658
  models: MERGED_MODELS, // discovered fleet nodes + settings.models overrides (built-ins in router/models.ts)
659
+ dynamicModels: () => freeRowsRef.current, // the free vendor rows /model fetched this session
650
660
  moa: settings.moa, // MOA proposers/aggregator config (MOA-DESIGN.md); absent = "/model moa" explains
651
661
  fastStart: settings.fastStart, // fast-model-vs-real-turn race (feature: fastStart, default OFF)
652
662
  features: settings.features, // feature flags — registers flag-gated tools (e.g. cloudAgents) only when on
653
663
  activeModel: settings.activeModel, // persisted /model choice, applied at startup
664
+ contextPin: settings.contextPin, // persisted /context · ctrl+x choice (KODE_CONTEXT wins); unset = the served window
654
665
  permissions: fgPermissions, // owner's policy + computer tools forced to "ask" when enabled (else bypass)
655
666
  approve: approveFn, // renders the in-TUI approval prompt for any "ask" decision
656
667
  askUser, // registers the ask_user tool so the model can put a clarifying question to the owner
@@ -734,6 +745,7 @@ function Root() {
734
745
  });
735
746
  }
736
747
  const session = sessionRef.current;
748
+ const [ctxPin, setCtxPin] = useState(() => session.contextPin()); // the footer's "ctx 600K" — the pin the engine took, undefined = auto
737
749
  // Background sub-agents run on their own Session against the same single Aurora 1M endpoint as the
738
750
  // foreground — one model, one context tier.
739
751
  const bgRef = useRef(null);
@@ -747,6 +759,7 @@ function Root() {
747
759
  loopGuard: settings.loopGuard,
748
760
  hooks: settings.hooks, // sub-agents are gated by the same hooks (e.g. git-safety)
749
761
  maxRoundsHard: 50, // a focused delegated sub-agent that hits 50 rounds isn't converging — cap it well below the foreground's 200 so a review/fix agent can't run away to round 40+ burning the shared Aurora (seen live 09-26)
762
+ contextPin: sessionRef.current?.contextPin() ?? settings.contextPin, // a sub-agent runs on the owner's current window choice, not the full served one
750
763
  background: true, // endpoint gate: this is a sub-agent — its Aurora requests yield the shared single slot to the interactive main turn (fixes the sub-agent-contention crawl + "4 min for a prompt")
751
764
  cwd, // isolation: a code-editing bg agent gets its own worktree dir here so it can't touch the foreground tree
752
765
  temperature: settings.temperature,
@@ -814,7 +827,7 @@ function Root() {
814
827
  commands: REMOTE_SAFE_COMMANDS,
815
828
  skills: [...skillsRef.current.entries()].map(([name, description]) => ({ name, description })),
816
829
  mcpServers: session.mcpServers().map((s) => ({ name: s.name, toolCount: s.tools.length, tools: s.tools })),
817
- models: session.modelRegistry().map((m) => ({ id: m.id, label: m.label, ctx: m.ctx ?? 0, kind: m.kind })),
830
+ models: session.modelRegistry().map((m) => ({ id: m.id, label: shortName(m), ctx: m.ctx ?? 0, kind: m.kind })),
818
831
  mode: opModeRef.current, // live operating mode (Plan/Manual/Autonomous) — a follower can read + drive it via /mode
819
832
  cwd: process.cwd(),
820
833
  model: session.currentModel(),
@@ -878,6 +891,13 @@ function Root() {
878
891
  setBootDetail(a?.detail ?? `no response from ${settings.endpoints.aurora.base}`);
879
892
  return;
880
893
  }
894
+ // The primary's served window, learned now rather than after the first overflow — AFTER the lever, so the gateway's
895
+ // dynamic port is the base probed (Session probes loopback/LAN only, ≤1.5 s, never a cloud leg). Never blocks boot;
896
+ // a pin above the served window gets its one clamp line.
897
+ void session.probeServedContext().then((r) => {
898
+ if (r.note)
899
+ push({ kind: "message", message: { id: nextId(), role: "system", content: r.note } });
900
+ }).catch(() => { });
881
901
  if (RESUME) {
882
902
  try {
883
903
  const saved = JSON.parse(readFileSync(SESSION_FILE, "utf8"));
@@ -1002,9 +1022,12 @@ function Root() {
1002
1022
  }
1003
1023
  const outcome = await session.send(expandFileMentions(snapshotEphemeralImages(toSend)), {
1004
1024
  onRoute: (label, pct) => {
1005
- setRoute(label);
1025
+ // The owner reads the model, not the leg that answered ("cortana", never "cortana@192.168.1.103:8112");
1026
+ // /endpoints still lists the legs and their health.
1027
+ const model = session.currentModel();
1028
+ setRoute(model);
1006
1029
  setCtxPct(pct);
1007
- remoteRef.current?.setStatus(pct, label, session.sessionTokens());
1030
+ remoteRef.current?.setStatus(pct, model, session.sessionTokens());
1008
1031
  // GW-06 oracle seed (once, fire-and-forget): a fresh meter cold-starts at chars/4 (4.0) — measured
1009
1032
  // truth on agent traffic is ~2.15 (aurora-tier0/calibrate-token-meter.py), i.e. the gate fires LATE
1010
1033
  // for the first rounds. Seed ONE weight-1 observation from the endpoint's own tokenizer
@@ -1202,8 +1225,8 @@ function Root() {
1202
1225
  }
1203
1226
  }
1204
1227
  catch (e) {
1205
- const activeLabel = session.modelRegistry().find((m) => m.id === session.currentModel())?.label;
1206
- push({ kind: "message", message: { id: nextId(), role: "assistant", content: describeTurnError(e.message, { label: activeLabel, bases: session.endpoints().map((x) => x.base) }) } });
1228
+ const activeModel = session.modelRegistry().find((m) => m.id === session.currentModel());
1229
+ push({ kind: "message", message: { id: nextId(), role: "assistant", content: describeTurnError(e.message, { label: activeModel && shortName(activeModel), bases: session.endpoints().map((x) => x.base) }) } });
1207
1230
  }
1208
1231
  finally {
1209
1232
  tracker.noteTurn();
@@ -1266,6 +1289,28 @@ function Root() {
1266
1289
  push({ kind: "message", message: { id: nextId(), role: "system", content: text } });
1267
1290
  remoteRef.current?.system(text);
1268
1291
  }, []);
1292
+ // A follower drove a slash command. Reuse the EXACT same path a local `/name args` line takes (submitRef → onSubmit →
1293
+ // handleSlash) — never a second implementation of the switch — but only for names on the remote-safe allowlist;
1294
+ // anything else is refused locally-visibly (sys + an audit event) rather than silently dropped or silently run.
1295
+ const remoteCommand = useCallback((name, args) => {
1296
+ if (!REMOTE_SAFE_COMMAND_NAMES.has(name)) {
1297
+ sys(`remote control: blocked "/${name}" from a follower — not exposed for remote dispatch`);
1298
+ eventSink.emit({ kind: "control", session: SESSION_ID, actor: EVENT_ACTOR, control: { event: "rc_command_blocked", detail: name } });
1299
+ return;
1300
+ }
1301
+ eventSink.emit({ kind: "control", session: SESSION_ID, actor: EVENT_ACTOR, control: { event: "rc_command", detail: args ? `${name} ${args}` : name } });
1302
+ submitRef.current(`/${name}${args ? " " + args : ""}`);
1303
+ }, [sys]);
1304
+ // A follower's prompt that reads as a slash command takes the command path, allowlist included: the prompt frame must
1305
+ // not be a side door around it (/allow, /mode, /context typed on the phone would otherwise run host-side).
1306
+ const remotePrompt = useCallback((text) => {
1307
+ if (isSlashCommand(text)) {
1308
+ const [name, ...rest] = text.trim().slice(1).split(/\s+/);
1309
+ remoteCommand(name, rest.join(" "));
1310
+ return;
1311
+ }
1312
+ submitRef.current(text);
1313
+ }, [remoteCommand]);
1269
1314
  // Idle-session policy (idle/): end a session nobody has touched for a while, never one that is working. This is the one entry that
1270
1315
  // mounts an interactive TUI, so headless/ACP/serve sessions are never subject to it. Ends through the SAME Teardown as /exit.
1271
1316
  useEffect(() => {
@@ -1371,6 +1416,68 @@ function Root() {
1371
1416
  }
1372
1417
  performModeSwitch(next, quiet);
1373
1418
  }, [performModeSwitch, sys]);
1419
+ // One path for every context change — /context, ctrl+x and the /model step: pin the engine (it runs on min(served,
1420
+ // pin) from the next round), persist the choice, light the footer badge, and say what it runs on now.
1421
+ const applyContext = useCallback((pin) => {
1422
+ session.setContextPin(pin);
1423
+ saveSettings({ contextPin: session.contextPin() });
1424
+ setCtxPin(session.contextPin());
1425
+ setCtxPct(session.ctxPct());
1426
+ sys(contextLine(session.contextPin(), session.servedContext(), session.ctxPct()));
1427
+ }, [sys]);
1428
+ // The /model, context and provider pickers share the one local QuestionPrompt slot. A row resolves by INDEX into the
1429
+ // entries it was drawn from (row text can repeat); the empty reply / ctrl+c (DISCUSS) closes the picker without
1430
+ // applying anything. The returned redraw re-renders the SAME picker while it is still the one on screen (portal
1431
+ // markers, late free rows) and is a no-op once it closed or another took its place.
1432
+ const pickerSeqRef = useRef(0);
1433
+ const openPicker = useCallback((question, rows, entries, onAnswer) => {
1434
+ const seq = ++pickerSeqRef.current;
1435
+ const pending = (shown, from) => ({
1436
+ question,
1437
+ options: shown,
1438
+ key: seq, // a redraw of this open keeps the owner's place (QuestionPrompt.redrawState)
1439
+ resolve: (answer, index) => {
1440
+ pickerSeqRef.current++;
1441
+ setModelPicker(null);
1442
+ const a = pickerAnswer(from, answer, index);
1443
+ if (a)
1444
+ onAnswer(a);
1445
+ },
1446
+ });
1447
+ setModelPicker(pending(rows, entries));
1448
+ return (shown, from) => { if (pickerSeqRef.current === seq)
1449
+ setModelPicker(pending(shown, from)); };
1450
+ }, []);
1451
+ // "Context for this session": bare /context, and the step after a /model pick whose window beats the smallest pin.
1452
+ const openContextPicker = useCallback(() => {
1453
+ const { rows, pins } = contextPickerView(session.contextPin(), session.servedContext());
1454
+ openPicker("Context for this session", rows, pins, (a) => {
1455
+ if ("entry" in a) {
1456
+ applyContext(a.entry);
1457
+ return;
1458
+ }
1459
+ const pin = parseContextArg(a.typed); // a typed reply takes the /context argument grammar
1460
+ if (pin === undefined)
1461
+ sys(`"${a.typed}" is not a context size — 300k · 600k · 1m · auto`);
1462
+ else
1463
+ applyContext(pin ?? undefined);
1464
+ });
1465
+ }, [openPicker, applyContext, sys]);
1466
+ // ctrl+x: the next stop of auto → 300K → 600K → 1M → auto, through the same path /context takes.
1467
+ const onCycleContext = useCallback(() => { applyContext(nextContextPin(session.contextPin())); }, [applyContext]);
1468
+ // The free rows behind a connected free-tier key (FREE_ROW_PRESETS): ≤4 s, then the 10-min disk cache, so a picker
1469
+ // never waits on them. Resolves true when the rows changed — an open picker redraws only for news.
1470
+ const refreshFreeRows = useCallback(async (isConnected) => {
1471
+ const presets = FREE_ROW_PRESETS.map((k) => BYO_PRESETS[k]).filter((p) => p && isConnected(p.account, p.endpoint));
1472
+ const lists = await Promise.all(presets.map((p) => fetchFreeModels(p)));
1473
+ const models = lists.flatMap((l) => l.models);
1474
+ const stale = lists.some((l) => l.stale);
1475
+ const sig = (ms, st) => `${st}|${ms.map((m) => m.id).join(",")}`;
1476
+ const changed = sig(models, stale) !== sig(freeRowsRef.current, freeStaleRef.current);
1477
+ freeRowsRef.current = models;
1478
+ freeStaleRef.current = stale;
1479
+ return changed;
1480
+ }, []);
1374
1481
  const handleSlash = useCallback(async (cmd) => {
1375
1482
  const [name, ...rest] = cmd.slice(1).split(/\s+/);
1376
1483
  const arg = rest.join(" ").trim();
@@ -1404,51 +1511,112 @@ function Root() {
1404
1511
  // status rule right away — the router only updates its label mid-turn (onRoute), and MOA has
1405
1512
  // no router of its own at all, so this is the one place that's always accurate immediately.
1406
1513
  const apply = (id) => {
1514
+ if (looksLikeSecret(id)) {
1515
+ sys("that looks like an API key — use “+ Connect a provider key” in /model; nothing was stored or shown");
1516
+ return undefined;
1517
+ }
1407
1518
  const r = s.setModel(id);
1408
1519
  if (!r.ok) {
1409
1520
  sys(`${r.error} — run /model for the list`);
1410
- return;
1521
+ return undefined;
1411
1522
  }
1412
1523
  setRoute(s.currentModel());
1413
1524
  saveSettings({ activeModel: s.currentModel() });
1414
- sys(`model → ${s.currentModel()} · ctx ${s.ctxPct()}% · turns ${s.turnCount()}`);
1525
+ const chosen = s.modelRegistry().find((m) => m.id === s.currentModel());
1526
+ sys(modelLine(s.currentModel(), chosen, s.ctxPct(), s.turnCount())); // a free row repeats its caveat here
1415
1527
  remoteRef.current?.setCapabilities(buildCapabilities()); // active model changed — re-sync attached followers
1416
1528
  // One honest line when the portal reports the chosen model down. Non-blocking (cache or ≤3s), silent when
1417
1529
  // the portal is unreachable or doesn't know the model — selection is never refused on portal state.
1418
- const chosen = s.modelRegistry().find((m) => m.id === s.currentModel());
1419
1530
  if (chosen)
1420
- void fetchPortalModels().then((cat) => { const note = offlineNote(chosen.label, cat?.get(portalIdFor(chosen))); if (note)
1531
+ void fetchPortalModels().then((cat) => { const note = offlineNote(shortName(chosen), cat?.get(portalIdFor(chosen))); if (note)
1421
1532
  sys(note); });
1533
+ return chosen;
1422
1534
  };
1423
1535
  if (arg) {
1424
1536
  apply(arg);
1425
1537
  break;
1426
1538
  }
1427
- const active = s.currentModel();
1428
- const models = s.modelRegistry();
1429
- const plain = models.map((m) => `${m.label}${m.id === active ? " (active)" : ""}`);
1430
- let shown = plain; // what the picker currently displays — resolve() maps the chosen text back through THIS
1431
- setModelPicker({
1432
- question: "Select a model",
1433
- options: shown,
1434
- resolve: (answer) => {
1435
- setModelPicker(null);
1436
- const idx = shown.indexOf(answer);
1437
- apply(idx >= 0 ? models[idx].id : answer.trim());
1539
+ // Each account is looked up at most once for this open, and only when a row needs it (a keychain miss spawns
1540
+ // `security`): the free-row check now, the full preset list only if the provider step opens.
1541
+ const isConnected = onceEach(hasByoToken);
1542
+ // The masked prompt (ui/SecretPrompt.tsx) hands the key straight to setByoToken (keychain via `security -i` on
1543
+ // STDIN, else the 0600 file); what comes back is the outcome, never the value. Then /model re-opens with the rows
1544
+ // the key unlocked — through submitRef, the same path a typed /model takes.
1545
+ const askKey = ({ preset, p }) => setSecretPrompt({
1546
+ title: `Paste your ${p.label} API key`,
1547
+ store: (value) => setByoToken(p.account, value),
1548
+ resolve: (outcome) => {
1549
+ setSecretPrompt(null);
1550
+ if (outcome === "cancelled")
1551
+ return;
1552
+ if (outcome === "failed") {
1553
+ sys(`${p.account} key not stored — the keychain refused it, or it is not one printable token (no spaces or quotes)`);
1554
+ return;
1555
+ }
1556
+ eventSink.emit({ kind: "control", session: SESSION_ID, actor: EVENT_ACTOR, control: { event: "credential_stored", detail: `byo account=${p.account} via /model` } });
1557
+ const free = FREE_ROW_PRESETS.includes(preset);
1558
+ void (free ? refreshFreeRows((a, e) => a === p.account || isConnected(a, e)) : Promise.resolve(false)).then(() => {
1559
+ sys(keyStoredLine(p.account, s.modelRegistry().filter((m) => m.byo === p.account), preset, free));
1560
+ remoteRef.current?.setCapabilities(buildCapabilities()); // the new rows reach attached followers too
1561
+ submitRef.current("/model");
1562
+ });
1438
1563
  },
1439
1564
  });
1440
- // Live state markers from the portal: the picker opens instantly as before; if the catalog arrives it
1441
- // re-renders the SAME rows (same order, same count) with a leading marker where the portal knows the model.
1442
- // Any failure leaves the picker exactly as it was.
1443
- void fetchPortalModels().then((cat) => {
1444
- if (!cat)
1565
+ const connectProvider = () => {
1566
+ const { rows, choices } = providerPickerView(connectedAccounts(isConnected));
1567
+ openPicker("Connect a provider — then paste its API key", rows, choices, (a) => { if ("entry" in a)
1568
+ askKey(a.entry); });
1569
+ };
1570
+ const active = s.currentModel();
1571
+ const view = () => modelPickerView(s.modelRegistry(), { active, servedCtx: s.servedContext(), staleFree: freeStaleRef.current });
1572
+ const first = view();
1573
+ let onScreen = first.rows;
1574
+ let cat;
1575
+ const redraw = openPicker("Select a model", first.rows, first.entries, (a) => {
1576
+ if ("typed" in a) {
1577
+ apply(a.typed);
1445
1578
  return;
1446
- const marked = markPickerOptions(plain, models.map(portalIdFor), cat);
1447
- if (marked.every((t, i) => t === plain[i]))
1579
+ } // the typed-id escape: an explicit id skips the context step
1580
+ if (a.entry.kind === "connect") {
1581
+ connectProvider();
1448
1582
  return;
1449
- shown = marked;
1450
- setModelPicker((cur) => (cur && cur.question === "Select a model" ? { ...cur, options: marked } : cur));
1583
+ }
1584
+ const chosen = apply(a.entry.profile.id);
1585
+ if (chosen && wantsContextStep(chosen, s.servedContext()))
1586
+ openContextPicker();
1451
1587
  });
1588
+ // Live state markers from the portal and the free rows: the picker opens instantly; whichever lands re-renders
1589
+ // the SAME picker (markers on the same rows, free rows in their place before MOA) — only when something changed.
1590
+ const refresh = () => {
1591
+ const v = view();
1592
+ const rows = markModelRows(v, cat);
1593
+ if (rows.length === onScreen.length && rows.every((t, i) => t === onScreen[i]))
1594
+ return;
1595
+ onScreen = rows;
1596
+ redraw(rows, v.entries);
1597
+ };
1598
+ void fetchPortalModels().then((c) => { if (c) {
1599
+ cat = c;
1600
+ refresh();
1601
+ } });
1602
+ void refreshFreeRows(isConnected).then((changed) => { if (changed)
1603
+ refresh(); });
1604
+ break;
1605
+ }
1606
+ case "context":
1607
+ case "ctx": {
1608
+ // The engine's window under the served one: `/context 600k | 600000 | 1m | auto` applies at once; bare opens the
1609
+ // picker with the current choice first. Persisted (settings.contextPin); ctrl+x cycles the same stops.
1610
+ if (!arg) {
1611
+ openContextPicker();
1612
+ break;
1613
+ }
1614
+ const pin = parseContextArg(arg);
1615
+ if (pin === undefined) {
1616
+ sys(`usage: /context [300k|600k|1m|auto] — "${arg}" is not a context size`);
1617
+ break;
1618
+ }
1619
+ applyContext(pin ?? undefined);
1452
1620
  break;
1453
1621
  }
1454
1622
  case "artifacts": {
@@ -2195,7 +2363,7 @@ function Root() {
2195
2363
  const { relayUrls, hostOf } = await import("./config/product-hosts.js");
2196
2364
  const urls = relayUrls(); // api.0perator.co first, api.axe.onl as fallback (KODE_RELAY_URL overrides, comma-separated)
2197
2365
  const rh = new RemoteHost(urls, token, { title: `Operator · ${process.cwd().split("/").pop() || "session"}`, cwd: process.cwd(), host: hostname(), surface: "cli" }, {
2198
- onPrompt: (text) => submitRef.current(text), // follower drives a turn
2366
+ onPrompt: remotePrompt, // follower drives a turn (slash-shaped → the allowlisted command path)
2199
2367
  onApprovalResponse: (id, approve) => settleApproval(id, approve), // first-wins with local
2200
2368
  onAskUserResponse: (id, answer) => settleQuestion(id, answer), // first-wins with local
2201
2369
  onInterrupt: () => s.interrupt(), // follower cancels the turn
@@ -2204,19 +2372,7 @@ function Root() {
2204
2372
  // Both return a boolean the host turns into an agent_ack so the row shows ✓ / couldn't.
2205
2373
  onAgentStop: (id) => bgRef.current?.requestStop(id) ?? false,
2206
2374
  onAgentSteer: (id, text) => bgRef.current?.sendToAgent(id, text) ?? false,
2207
- // A follower drove a slash command. Reuse the EXACT same path a local `/name args` line
2208
- // takes (submitRef → onSubmit → handleSlash) — never a second implementation of the
2209
- // switch — but only for names on the remote-safe allowlist; anything else is refused
2210
- // locally-visibly (sys + an audit event) rather than silently dropped or silently run.
2211
- onCommand: (name, args) => {
2212
- if (!REMOTE_SAFE_COMMAND_NAMES.has(name)) {
2213
- sys(`remote control: blocked "/${name}" from a follower — not exposed for remote dispatch`);
2214
- eventSink.emit({ kind: "control", session: SESSION_ID, actor: EVENT_ACTOR, control: { event: "rc_command_blocked", detail: name } });
2215
- return;
2216
- }
2217
- eventSink.emit({ kind: "control", session: SESSION_ID, actor: EVENT_ACTOR, control: { event: "rc_command", detail: args ? `${name} ${args}` : name } });
2218
- submitRef.current(`/${name}${args ? " " + args : ""}`);
2219
- },
2375
+ onCommand: remoteCommand,
2220
2376
  onState: (st, detail) => {
2221
2377
  setRcConnected(st === "live"); // footer controller icon: green when live, gray otherwise
2222
2378
  if (st === "live")
@@ -2270,21 +2426,13 @@ function Root() {
2270
2426
  const urls = relayUrls(); // api.0perator.co first, api.axe.onl as fallback (KODE_RELAY_URL overrides, comma-separated)
2271
2427
  const code = newCode();
2272
2428
  const rh = new RemoteHost(urls, token, { title: `Operator · ${process.cwd().split("/").pop() || "session"}`, cwd: process.cwd(), host: hostname(), surface: "cli" }, {
2273
- onPrompt: (text) => submitRef.current(text),
2429
+ onPrompt: remotePrompt,
2274
2430
  onApprovalResponse: (id, approve) => settleApproval(id, approve),
2275
2431
  onAskUserResponse: (id, answer) => settleQuestion(id, answer),
2276
2432
  onInterrupt: () => s.interrupt(),
2277
2433
  onAgentStop: (id) => bgRef.current?.requestStop(id) ?? false, // RC v2 B1 (paired mode)
2278
2434
  onAgentSteer: (id, text) => bgRef.current?.sendToAgent(id, text) ?? false,
2279
- onCommand: (cmdName, cmdArgs) => {
2280
- if (!REMOTE_SAFE_COMMAND_NAMES.has(cmdName)) {
2281
- sys(`remote control: blocked "/${cmdName}" from a follower — not exposed for remote dispatch`);
2282
- eventSink.emit({ kind: "control", session: SESSION_ID, actor: EVENT_ACTOR, control: { event: "rc_command_blocked", detail: cmdName } });
2283
- return;
2284
- }
2285
- eventSink.emit({ kind: "control", session: SESSION_ID, actor: EVENT_ACTOR, control: { event: "rc_command", detail: cmdArgs ? `${cmdName} ${cmdArgs}` : cmdName } });
2286
- submitRef.current(`/${cmdName}${cmdArgs ? " " + cmdArgs : ""}`);
2287
- },
2435
+ onCommand: remoteCommand,
2288
2436
  onState: (st, detail) => {
2289
2437
  setRcConnected(st === "live");
2290
2438
  if (st === "connecting" && detail === "reconnecting")
@@ -2310,7 +2458,7 @@ function Root() {
2310
2458
  }
2311
2459
  default: sys(`unknown command /${name} — try /help`);
2312
2460
  }
2313
- }, [exit, sys, bg, authUser, approval, settleApproval, settleQuestion, applyMode]);
2461
+ }, [exit, sys, bg, authUser, approval, settleApproval, settleQuestion, applyMode, applyContext, openPicker, openContextPicker, refreshFreeRows, remoteCommand, remotePrompt]);
2314
2462
  const onSubmit = useCallback((text) => {
2315
2463
  if (isSlashCommand(text)) {
2316
2464
  void handleSlash(text.trim());
@@ -2426,7 +2574,7 @@ function Root() {
2426
2574
  if (boot === "checking")
2427
2575
  return _jsx(Text, { dimColor: true, children: bootDetail || "connecting to Operator…" });
2428
2576
  if (boot === "down") {
2429
- 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" })] }));
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, _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"] })] }));
2430
2578
  }
2431
2579
  // While a turn runs, show a LIVE line: braille spinner + climbing token count + live tok/s + elapsed
2432
2580
  // seconds. When idle, show the last turn's final "N tok · X tok/s · Ys". Never freeze on the previous
@@ -2442,7 +2590,7 @@ function Root() {
2442
2590
  ? `${spin} reading your prompt… (${fmtDuration(elapsed)})`
2443
2591
  : `${spin} ${fmtMeta(elapsed, liveTok)}`
2444
2592
  : metrics;
2445
- return (_jsx(App, { messages: entries, live: live, status: status, stepLabel: stepLabel, prefill: prefill, liveTools: liveTools, route: route, ctxPct: ctxPct, version: VERSION, fullscreen: FULLSCREEN, metrics: liveMetrics, sessionTokens: session.sessionTokens() + liveTok, authUser: authUser, tier: EVENT_ACTOR.tier, planMode: planMode, thinkMode: thinkMode, verbs: settings.verbs, bgAgents: bgAgents, shellJobs: shellJobs, onBackground: onBackground, tasks: tasks, onSubmit: onSubmit, onQueue: onQueue, queuedPreview: queuedPreview, onInterrupt: onInterrupt, onCycleMode: onCycleMode, opMode: opMode, rcConnected: rcConnected, rcActive: rcActive, caffeinated: caffeinated, approval: approval, question: question, modelPicker: modelPicker, planExitPicker: planExitPicker, artifactsPicker: artifactsPicker, sessionsPicker: sessionsPicker, onApprovalDecide: (allow, always) => {
2593
+ return (_jsx(App, { messages: entries, live: live, status: status, stepLabel: stepLabel, prefill: prefill, liveTools: liveTools, route: route, ctxPct: ctxPct, ctxPin: ctxPin ? fmtCtx(ctxPin) : undefined, version: VERSION, fullscreen: FULLSCREEN, metrics: liveMetrics, sessionTokens: session.sessionTokens() + liveTok, authUser: authUser, tier: EVENT_ACTOR.tier, planMode: planMode, thinkMode: thinkMode, verbs: settings.verbs, bgAgents: bgAgents, shellJobs: shellJobs, onBackground: onBackground, tasks: tasks, onSubmit: onSubmit, onQueue: onQueue, queuedPreview: queuedPreview, onInterrupt: onInterrupt, onCycleMode: onCycleMode, onCycleContext: onCycleContext, opMode: opMode, rcConnected: rcConnected, rcActive: rcActive, caffeinated: caffeinated, approval: approval, question: question, modelPicker: modelPicker, secretPrompt: secretPrompt, planExitPicker: planExitPicker, artifactsPicker: artifactsPicker, sessionsPicker: sessionsPicker, onApprovalDecide: (allow, always) => {
2446
2594
  const cur = approval;
2447
2595
  if (cur)
2448
2596
  settleApproval(cur.id, allow, always); // first-wins with any remote follower answer
@@ -192,7 +192,9 @@ export function basePersona(cwd = process.cwd(), opts = {}) {
192
192
  `has passed in front of you. Tests must assert BEHAVIOR (the CLI runs, a dependency resolves, the ` +
193
193
  `output is correct), not merely that files exist — green tests that assert nothing are not proof, and ` +
194
194
  `"all tests pass" while the program is broken is the worst possible report. If you did not run it, say ` +
195
- `so plainly instead of calling it done.` +
195
+ `so plainly instead of calling it done. A document deliverable has runnable checks too — a link check, ` +
196
+ `\`docker compose config\` on an embedded compose block, a script that sums the tables, a linter — run ` +
197
+ `them; and a "checked <date>" stamp on a product row is written only in the turn that opened that page.` +
196
198
  `\n## How I work — the AXE self-check\nBefore acting: for a bug I state the ROOT CAUSE in one line ` +
197
199
  `(not the symptom) and how I confirmed it; I reuse the nearest existing pattern (a new pattern needs a ` +
198
200
  `reason); I stay scoped to exactly what was asked and don't touch the data layer or infra unless asked. ` +
@@ -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 { DEFAULT_MODEL_ID } from "../router/models.js";
10
+ import { MIN_CONTEXT_PIN, DEFAULT_MODEL_ID } 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,15 +63,16 @@ 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
  },
77
78
  activeModel: DEFAULT_MODEL_ID, // /model default — the 1M endpoint, unchanged from before /model existed
@@ -129,6 +130,11 @@ function applyEnv(s) {
129
130
  const base = process.env.KODE_AURORA ?? process.env.KODE_1M; // KODE_1M kept as a back-compat alias for the base override
130
131
  if (base)
131
132
  out.endpoints = { ...out.endpoints, aurora: { ...out.endpoints.aurora, base } };
133
+ const pin = parseContextArg(process.env.KODE_CONTEXT); // context cap: 300k|600k|1m sets it, "auto" clears the file's pin
134
+ if (pin === null)
135
+ out.contextPin = undefined;
136
+ else if (pin !== undefined)
137
+ out.contextPin = pin;
132
138
  if (process.env.KODE_TSI_MCP !== undefined)
133
139
  out.mcp = process.env.KODE_TSI_MCP === "1";
134
140
  if (process.env.KODE_SYSTEM_PROMPT)
@@ -175,6 +181,8 @@ function applyEnv(s) {
175
181
  out.sandbox = { mode: sb };
176
182
  if (process.env.KODE_COMPUTER === "1")
177
183
  out.computer = { enabled: true };
184
+ else if (process.env.KODE_COMPUTER === "0")
185
+ out.computer = { enabled: false };
178
186
  // Service lever: KODE_SERVICES_AUTOSTART=0 disables autostart of ALL launchd services (Operator then
179
187
  // only probes + reports); KODE_STOP_SEARXNG_ON_EXIT=0 keeps the SearXNG container running after exit.
180
188
  if (out.services) {
@@ -268,6 +276,32 @@ export function turnWallClockMs(s) {
268
276
  return undefined;
269
277
  return Math.floor(sec * 1000);
270
278
  }
279
+ /** The context pins /context, Ctrl+X and the /model picker step offer, ascending. "auto" (no pin) is the fourth
280
+ * state of the cycle, not a preset. */
281
+ export const CONTEXT_PRESETS = [300000, 600000, 1000000];
282
+ /** Parse a context-pin argument the way /context and KODE_CONTEXT take it: "600k" | "600K" | "600000" | "1m" |
283
+ * "1.5m" → tokens; "auto" → null (clear the pin); anything else (unset, empty, "abc", "0", "-5k") → undefined. */
284
+ export function parseContextArg(raw) {
285
+ const s = raw?.trim().toLowerCase();
286
+ if (!s)
287
+ return undefined;
288
+ if (s === "auto")
289
+ return null;
290
+ const m = /^(\d+(?:\.\d+)?)\s*([km])?$/.exec(s);
291
+ if (!m)
292
+ return undefined;
293
+ // A bare number under 1000 means thousands: `/context 300` is 300K — nobody pins a 300-token window.
294
+ const unit = m[2] === "m" ? 1_000_000 : m[2] === "k" || Number(m[1]) < 1000 ? 1000 : 1;
295
+ const n = Math.round(Number(m[1]) * unit);
296
+ return n >= MIN_CONTEXT_PIN ? n : undefined;
297
+ }
298
+ /** The next stop of the Ctrl+X cycle: auto → 300K → 600K → 1M → auto. A pin between presets moves up to the next
299
+ * preset; one past the largest wraps to auto (undefined). */
300
+ export function nextContextPin(current) {
301
+ if (current === undefined)
302
+ return CONTEXT_PRESETS[0];
303
+ return CONTEXT_PRESETS.find((p) => p > current);
304
+ }
271
305
  /** Whether to auto-start a Remote Control host on session boot. An explicit setting/env wins
272
306
  * (settings.remote.autostart / KODE_RC_AUTOSTART=1/0). Otherwise it is FEATURE-FLAGGED to the admin/VIP
273
307
  * tier only (owner decision, James 2026-09-28): auto-RC ships ON for admin accounts and OFF for everyone
@@ -26,7 +26,7 @@ const LOOP_GUARD_LIMIT = 5; // identical (name+args) calls in a turn before shor
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
28
  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
- 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 } from "./continuation.js";
29
+ 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
30
  // Poll/status tools are meant to be called repeatedly while waiting on async work — NEVER a spin, so the
31
31
  // loop guard skips them entirely (agent_status polls sub-agents, bash_output polls a background job).
32
32
  const LOOP_GUARD_EXEMPT = new Set(["agent_status", "bash_output"]);
@@ -778,6 +778,7 @@ export async function runTurn(userInput, conversation, opts) {
778
778
  token: endpoint.token,
779
779
  loopbackAuth: endpoint.loopbackAuth,
780
780
  transport: endpoint.transport,
781
+ chatPath: endpoint.chatPath,
781
782
  maxTokens,
782
783
  // Empty-retry perturbation: a greedy (temp 0) empty is deterministic, so the retry must change the
783
784
  // sampling to escape it. One-shot — consumed right after this call so the normal path stays greedy.
@@ -931,7 +932,9 @@ export async function runTurn(userInput, conversation, opts) {
931
932
  // original (unchanged) content and falls through to the normal round handling below. This never touches
932
933
  // a tool-permission denial or the deniedReadAsync credential-path guard (tools/registry.ts) — those
933
934
  // aren't chat() output, so detectRefusal never sees them; the two hard floors are untouched.
934
- if (unrestrictedEnabled) {
935
+ // Not on the Anthropic wire: the retry is an assistant prefill, which the current Claude family rejects (400), and a
936
+ // classifier decline there is final — anthropic-chat surfaces it as a refusal note instead.
937
+ if (unrestrictedEnabled && endpoint.transport !== "anthropic") {
935
938
  let unrestrictedRetries = 0;
936
939
  while (unrestrictedRetries < UNRESTRICTED_MAX_RETRIES &&
937
940
  response.toolCalls.length === 0 &&
@@ -945,6 +948,7 @@ export async function runTurn(userInput, conversation, opts) {
945
948
  token: endpoint.token,
946
949
  loopbackAuth: endpoint.loopbackAuth,
947
950
  transport: endpoint.transport,
951
+ chatPath: endpoint.chatPath,
948
952
  maxTokens: clampMaxTokens(retryMessages, compactionOptsFor(endpoint), opts.maxTokens ?? 8192),
949
953
  temperature: opts.temperature,
950
954
  tools: opts.toolSchemas,
@@ -1358,7 +1362,7 @@ export async function runTurn(userInput, conversation, opts) {
1358
1362
  // warning above applies only to an EMPTY round; here real content + tool results exist, so the reminder
1359
1363
  // is answered as the intended verify step, not mistaken for the request. Capped (verifyMaxNudges) →
1360
1364
  // ≤1 extra round, the main-loop mirror of grandmaster's single repair round.
1361
- if (verifyEnabled && final && verify.gate() && verifyNudges < verifyMaxNudges) {
1365
+ if (verifyEnabled && final && !isEngineFinal(final) && verify.gate() && verifyNudges < verifyMaxNudges) {
1362
1366
  verifyNudges++;
1363
1367
  conversation.assistant(final);
1364
1368
  engineUser(VERIFY_REMINDER);
@@ -1366,7 +1370,7 @@ export async function runTurn(userInput, conversation, opts) {
1366
1370
  }
1367
1371
  // Owner-facing: a final that leaves open task-list items with neither a question nor a status is a bare stop —
1368
1372
  // one nudge to continue or to close with a status line per item and ONE steering question.
1369
- if (final && response.stopReason !== "length" && !closingNudged && !opts.background && needsClosingSteer(final, !!opts.preservedState?.())) {
1373
+ if (final && response.stopReason !== "length" && !closingNudged && !opts.background && !isEngineFinal(final) && needsClosingSteer(final, !!opts.preservedState?.())) {
1370
1374
  closingNudged = true;
1371
1375
  conversation.assistant(final);
1372
1376
  engineUser(opts.unattended ? CLOSING_NUDGE_UNATTENDED : CLOSING_NUDGE);