@0perator/operator 0.1.330 → 0.1.332

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.
@@ -0,0 +1,90 @@
1
+ // The session's scratch directory: `<cwd>/.operator/.op-writes`, created where the shell is sitting when Operator
2
+ // starts. Temporary scripts, probe outputs and intermediate files go here instead of /tmp (lost, shared, outside the
3
+ // project) or the repo root (pollutes the tree). The directory ignores itself in git, is handed to every tool
4
+ // subprocess as OPERATOR_SCRATCH, is named in the persona, and is swept of stale files so it never grows unbounded.
5
+ // A cwd that cannot take the directory (root-owned checkout, read-only mount, `/`) falls back to a per-project dir
6
+ // under the Operator home, which is always writable — the persona then names THAT path, never one that errors.
7
+ import { existsSync, mkdirSync, readdirSync, rmSync, statSync, writeFileSync } from "node:fs";
8
+ import { createHash } from "node:crypto";
9
+ import { join } from "node:path";
10
+ import { operatorPath } from "./home.js";
11
+ export const SCRATCH_ENV = "OPERATOR_SCRATCH";
12
+ export const SCRATCH_RETENTION_MS = 7 * 24 * 60 * 60 * 1000; // a scratch entry untouched for a week is forgotten
13
+ export const SCRATCH_MAX_BYTES = 250 * 1024 * 1024; // past this, the least recently touched entries go first
14
+ const WALK_DEPTH = 3; // how deep "last touched" and "size" look inside a top-level entry
15
+ /** Pure: where the scratch dir lives for a working directory. The persona names it without creating it. */
16
+ export function scratchDirFor(cwd) {
17
+ return join(cwd, ".operator", ".op-writes");
18
+ }
19
+ /** Pure: the fallback when the cwd cannot hold the dir — per project, under the Operator home. */
20
+ export function scratchFallbackFor(cwd) {
21
+ return operatorPath("scratch", createHash("sha1").update(cwd).digest("hex").slice(0, 16));
22
+ }
23
+ function prepare(dir) {
24
+ try {
25
+ mkdirSync(dir, { recursive: true, mode: 0o700 });
26
+ const ignore = join(dir, ".gitignore");
27
+ if (!existsSync(ignore))
28
+ writeFileSync(ignore, "*\n", { mode: 0o600 });
29
+ return true;
30
+ }
31
+ catch {
32
+ return false;
33
+ }
34
+ }
35
+ /** Create the scratch dir (0700) with a self-ignoring .gitignore — or the fallback when the cwd refuses — export it as
36
+ * OPERATOR_SCRATCH, sweep stale entries, and return the path that actually exists. Idempotent; never throws. */
37
+ export function ensureScratchDir(cwd, env = process.env) {
38
+ const preferred = scratchDirFor(cwd);
39
+ const dir = prepare(preferred) ? preferred : (prepare(scratchFallbackFor(cwd)) ? scratchFallbackFor(cwd) : preferred);
40
+ env[SCRATCH_ENV] = dir;
41
+ sweepScratch(dir);
42
+ return dir;
43
+ }
44
+ /** Newest mtime and total size under an entry (a directory's own mtime only changes on add/remove; a file edited
45
+ * inside it yesterday still counts as "touched yesterday"). Bounded depth; errors count as nothing. */
46
+ function measure(path, depth) {
47
+ try {
48
+ const st = statSync(path);
49
+ if (!st.isDirectory() || depth <= 0)
50
+ return { touched: st.mtimeMs, size: st.isDirectory() ? 0 : st.size };
51
+ let touched = st.mtimeMs, size = 0;
52
+ for (const child of readdirSync(path)) {
53
+ const m = measure(join(path, child), depth - 1);
54
+ touched = Math.max(touched, m.touched);
55
+ size += m.size;
56
+ }
57
+ return { touched, size };
58
+ }
59
+ catch {
60
+ return { touched: 0, size: 0 };
61
+ }
62
+ }
63
+ /** Drop top-level entries untouched for the retention window, then the least recently touched until the dir is under
64
+ * the byte cap. `.gitignore` is kept; an entry touched recently is never removed by age. Silent on any error. */
65
+ export function sweepScratch(dir, now = Date.now(), maxBytes = SCRATCH_MAX_BYTES, retentionMs = SCRATCH_RETENTION_MS) {
66
+ const removed = [];
67
+ let entries;
68
+ try {
69
+ entries = readdirSync(dir).filter((f) => f !== ".gitignore").map((f) => ({ f, ...measure(join(dir, f), WALK_DEPTH) }));
70
+ }
71
+ catch {
72
+ return { removed };
73
+ }
74
+ const drop = (e) => { try {
75
+ rmSync(join(dir, e.f), { recursive: true, force: true });
76
+ removed.push(e.f);
77
+ }
78
+ catch { /* raced; fine */ } };
79
+ for (const e of entries)
80
+ if (now - e.touched > retentionMs)
81
+ drop(e);
82
+ const alive = entries.filter((e) => now - e.touched <= retentionMs).sort((a, b) => a.touched - b.touched);
83
+ let total = alive.reduce((n, e) => n + e.size, 0);
84
+ while (total > maxBytes && alive.length) {
85
+ const e = alive.shift();
86
+ drop(e);
87
+ total -= e.size;
88
+ }
89
+ return { removed };
90
+ }
@@ -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. */
@@ -129,6 +129,11 @@ function applyEnv(s) {
129
129
  const base = process.env.KODE_AURORA ?? process.env.KODE_1M; // KODE_1M kept as a back-compat alias for the base override
130
130
  if (base)
131
131
  out.endpoints = { ...out.endpoints, aurora: { ...out.endpoints.aurora, base } };
132
+ const pin = parseContextArg(process.env.KODE_CONTEXT); // context cap: 300k|600k|1m sets it, "auto" clears the file's pin
133
+ if (pin === null)
134
+ out.contextPin = undefined;
135
+ else if (pin !== undefined)
136
+ out.contextPin = pin;
132
137
  if (process.env.KODE_TSI_MCP !== undefined)
133
138
  out.mcp = process.env.KODE_TSI_MCP === "1";
134
139
  if (process.env.KODE_SYSTEM_PROMPT)
@@ -268,6 +273,32 @@ export function turnWallClockMs(s) {
268
273
  return undefined;
269
274
  return Math.floor(sec * 1000);
270
275
  }
276
+ /** The context pins /context, Ctrl+X and the /model picker step offer, ascending. "auto" (no pin) is the fourth
277
+ * state of the cycle, not a preset. */
278
+ export const CONTEXT_PRESETS = [300000, 600000, 1000000];
279
+ /** Parse a context-pin argument the way /context and KODE_CONTEXT take it: "600k" | "600K" | "600000" | "1m" |
280
+ * "1.5m" → tokens; "auto" → null (clear the pin); anything else (unset, empty, "abc", "0", "-5k") → undefined. */
281
+ export function parseContextArg(raw) {
282
+ const s = raw?.trim().toLowerCase();
283
+ if (!s)
284
+ return undefined;
285
+ if (s === "auto")
286
+ return null;
287
+ const m = /^(\d+(?:\.\d+)?)\s*([km])?$/.exec(s);
288
+ if (!m)
289
+ return undefined;
290
+ // A bare number under 1000 means thousands: `/context 300` is 300K — nobody pins a 300-token window.
291
+ const unit = m[2] === "m" ? 1_000_000 : m[2] === "k" || Number(m[1]) < 1000 ? 1000 : 1;
292
+ const n = Math.round(Number(m[1]) * unit);
293
+ return n >= MIN_CONTEXT_PIN ? n : undefined;
294
+ }
295
+ /** The next stop of the Ctrl+X cycle: auto → 300K → 600K → 1M → auto. A pin between presets moves up to the next
296
+ * preset; one past the largest wraps to auto (undefined). */
297
+ export function nextContextPin(current) {
298
+ if (current === undefined)
299
+ return CONTEXT_PRESETS[0];
300
+ return CONTEXT_PRESETS.find((p) => p > current);
301
+ }
271
302
  /** Whether to auto-start a Remote Control host on session boot. An explicit setting/env wins
272
303
  * (settings.remote.autostart / KODE_RC_AUTOSTART=1/0). Otherwise it is FEATURE-FLAGGED to the admin/VIP
273
304
  * 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 } 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"]);
@@ -587,6 +587,11 @@ export async function runTurn(userInput, conversation, opts) {
587
587
  // sub-agent has no spawn tool and must not be told to call one).
588
588
  const hasSpawnTool = (opts.toolSchemas ?? []).some((s) => s?.function?.name === "spawn_agent");
589
589
  let announceNudges = 0;
590
+ let selfDialogueNudges = 0; // owner-facing: replies that react to a speaker who did not speak (continuation.ts)
591
+ let closingNudged = false; // owner-facing: one nudge to close with status + a steering question instead of a bare stop
592
+ let lastReasoning = ""; // the reasoning channel of an empty round — a model that answers there still answered
593
+ 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
+ let emptyNudged = false; // the reframe nudge goes in on the FIRST genuine empty, whatever the retry counter says
590
595
  let malformedCallNudges = 0; // bounded re-prompts for an unparseable text tool call
591
596
  // Spectre fix (b): bounded auto-continue after a LENGTH truncation (see gate at finalize).
592
597
  let truncationContinues = 0;
@@ -607,8 +612,9 @@ export async function runTurn(userInput, conversation, opts) {
607
612
  let convergeStreak = 0;
608
613
  const narratedSigs = new Set(); // prose fingerprints already spoken this turn — repeating one is not "new" text
609
614
  const stopTurn = (note, roundsRun, stopReason) => {
610
- conversation.assistant(note);
611
- return { content: note, rounds: roundsRun, toolCalls: toolCallTotal, stopReason, tokens: tokensTotal, genMs: genMsTotal, promptTokens: promptTokensTotal, promptMs: promptMsTotal };
615
+ const text = closeStopNote(note, opts.preservedState?.()); // never a bare stop: the open items + how to steer
616
+ conversation.assistant(text);
617
+ return { content: text, rounds: roundsRun, toolCalls: toolCallTotal, stopReason, tokens: tokensTotal, genMs: genMsTotal, promptTokens: promptTokensTotal, promptMs: promptMsTotal };
612
618
  };
613
619
  /** Feed one settled tool batch to the converge guard; true ⇒ the turn has stalled and must stop. */
614
620
  const stalledNotConverging = (calls, toolMsgs, content) => {
@@ -629,6 +635,9 @@ export async function runTurn(userInput, conversation, opts) {
629
635
  `tell me how you'd like to proceed, or ask me to continue and I'll pick up from here with a different approach.]`;
630
636
  };
631
637
  conversation.user(userInput);
638
+ /** Every mid-turn message the engine injects rides in the user role; the marker is what lets the model tell it from
639
+ * the owner (continuation.ts, owner-facing turns). */
640
+ const engineUser = (text) => conversation.user(engineNote(text));
632
641
  let rounds = 0;
633
642
  let toolCallTotal = 0;
634
643
  let tokensTotal = 0; // output tokens summed across rounds (from llama.cpp timings)
@@ -650,8 +659,7 @@ export async function runTurn(userInput, conversation, opts) {
650
659
  const note = `[paused — this turn reached its token budget (${spent} ≥ ${opts.maxTurnTokens} tokens). ` +
651
660
  `The work so far is above; continue with a fresh, focused request, or raise the budget ` +
652
661
  `(settings.maxTurnTokens).]`;
653
- conversation.assistant(note);
654
- return { content: note, rounds, toolCalls: toolCallTotal, tokens: tokensTotal, genMs: genMsTotal, promptTokens: promptTokensTotal, promptMs: promptMsTotal };
662
+ return stopTurn(note, rounds);
655
663
  }
656
664
  // Opt-in per-turn WALL-CLOCK ceiling: the only bound on TIME. Round/token budgets don't stop a turn whose
657
665
  // decode has crawled (RAM pressure from a big model on the serving box, or very high context) to ~1 tok/s —
@@ -663,7 +671,7 @@ export async function runTurn(userInput, conversation, opts) {
663
671
  if (opts.maxTurnWallClockMs && rounds > 0 && !budgetWarned && Date.now() - turnStart >= opts.maxTurnWallClockMs * 0.75) {
664
672
  budgetWarned = true;
665
673
  const leftSec = Math.max(1, Math.round((opts.maxTurnWallClockMs - (Date.now() - turnStart)) / 1000));
666
- conversation.user(`You are ~75% through this turn's wall-clock budget (~${leftSec}s left) — converge NOW: finish the ` +
674
+ engineUser(`You are ~75% through this turn's wall-clock budget (~${leftSec}s left) — converge NOW: finish the ` +
667
675
  `current objective with what you have, stop opening new threads or exploring, keep any remaining tool ` +
668
676
  `calls minimal. If you can answer, answer concisely; if not, summarize progress and the one blocker. ` +
669
677
  `The turn will be wrapped at the hard limit either way.`);
@@ -677,8 +685,7 @@ export async function runTurn(userInput, conversation, opts) {
677
685
  const crawl = tps > 0 && tps < 3 ? ` Decode was crawling (~${tps.toFixed(1)} tok/s) — likely RAM pressure (a large model loaded on the serving box) or very high context; avoid co-locating heavy model loads with the serving model.` : "";
678
686
  const note = `[paused — this turn hit its ${capMin}-min wall-clock budget (ran ${ranMin} min, ${spent} tokens).${crawl} ` +
679
687
  `The work so far is above; continue with a fresh, focused request (or raise it via settings.autonomy.maxTurnWallClockSec).]`;
680
- conversation.assistant(note);
681
- return { content: note, rounds, toolCalls: toolCallTotal, tokens: tokensTotal, genMs: genMsTotal, promptTokens: promptTokensTotal, promptMs: promptMsTotal };
688
+ return stopTurn(note, rounds);
682
689
  }
683
690
  if (rounds === softRounds)
684
691
  opts.onAutoContinue?.(rounds); // crossed the soft budget, still working — keep going while progressing
@@ -690,7 +697,7 @@ export async function runTurn(userInput, conversation, opts) {
690
697
  // stop; a legitimate long read-only task is valid) to convert insight into action or surface a blocker.
691
698
  if (!noEditNudged && noEditStreak >= NO_EDIT_NUDGE) {
692
699
  noEditNudged = true;
693
- conversation.user(`You've run ${noEditStreak} rounds of tools without changing a file. If you've found the root cause, ` +
700
+ engineUser(`You've run ${noEditStreak} rounds of tools without changing a file. If you've found the root cause, ` +
694
701
  `make the change now and verify it. If you're still gathering context that's fine — but if you're ` +
695
702
  `going in circles, say so and switch to a genuinely different approach.`);
696
703
  }
@@ -730,7 +737,7 @@ export async function runTurn(userInput, conversation, opts) {
730
737
  // Rehydrate: if compaction actually evicted turns, re-surface the plan + recently-touched files so the
731
738
  // model re-reads current state instead of acting on the now-summarized (stale) earlier reads.
732
739
  if (conversation.all.length < beforeLen)
733
- conversation.user(rehydrationNote(touchedFiles));
740
+ engineUser(rehydrationNote(touchedFiles));
734
741
  }
735
742
  // Intra-turn output-headroom guard (task #14's third leg — _ai-docs 2026-10-19): the proactive gate
736
743
  // above keeps the PROMPT under threshold, but near the window (or on a small endpoint) the leftover
@@ -752,8 +759,7 @@ export async function runTurn(userInput, conversation, opts) {
752
759
  const stuck = `[stopped — the context is over this model's window and compaction can't free enough space ` +
753
760
  `(${compactionFailStreak} rounds running; the summarizer may be failing). Start a fresh session, or ask me ` +
754
761
  `again with a shorter request — nothing was lost.]`;
755
- conversation.assistant(stuck);
756
- return { content: stuck, rounds: rounds + 1, toolCalls: toolCallTotal, tokens: tokensTotal, genMs: genMsTotal, promptTokens: promptTokensTotal, promptMs: promptMsTotal };
762
+ return stopTurn(stuck, rounds + 1);
757
763
  }
758
764
  }
759
765
  else {
@@ -772,6 +778,7 @@ export async function runTurn(userInput, conversation, opts) {
772
778
  token: endpoint.token,
773
779
  loopbackAuth: endpoint.loopbackAuth,
774
780
  transport: endpoint.transport,
781
+ chatPath: endpoint.chatPath,
775
782
  maxTokens,
776
783
  // Empty-retry perturbation: a greedy (temp 0) empty is deterministic, so the retry must change the
777
784
  // sampling to escape it. One-shot — consumed right after this call so the normal path stays greedy.
@@ -847,7 +854,7 @@ export async function runTurn(userInput, conversation, opts) {
847
854
  }
848
855
  truncRetries += 1;
849
856
  opts.onSelfHeal?.("server_error", truncRetries); // footer ↻ — a recovery is in flight
850
- conversation.user(truncatedToolNudge(err instanceof Error ? err.message : String(err)));
857
+ engineUser(truncatedToolNudge(err instanceof Error ? err.message : String(err)));
851
858
  continue;
852
859
  }
853
860
  // Endpoint (re)starting: a 503 whose body says it's loading/warming (seen live 09-26 when a JL2
@@ -901,7 +908,7 @@ export async function runTurn(userInput, conversation, opts) {
901
908
  if (chars(shrunk) >= chars(before))
902
909
  throw err; // nothing left to shed — surface honestly rather than spin
903
910
  if (shrunk.length < before.length)
904
- conversation.user(rehydrationNote(touchedFiles)); // rehydrate after a forced compaction
911
+ engineUser(rehydrationNote(touchedFiles)); // rehydrate after a forced compaction
905
912
  continue;
906
913
  }
907
914
  // transient (429 / 5xx / network drop): a busy or unhealthy backend, NOT a context problem.
@@ -925,7 +932,9 @@ export async function runTurn(userInput, conversation, opts) {
925
932
  // original (unchanged) content and falls through to the normal round handling below. This never touches
926
933
  // a tool-permission denial or the deniedReadAsync credential-path guard (tools/registry.ts) — those
927
934
  // aren't chat() output, so detectRefusal never sees them; the two hard floors are untouched.
928
- 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") {
929
938
  let unrestrictedRetries = 0;
930
939
  while (unrestrictedRetries < UNRESTRICTED_MAX_RETRIES &&
931
940
  response.toolCalls.length === 0 &&
@@ -939,6 +948,7 @@ export async function runTurn(userInput, conversation, opts) {
939
948
  token: endpoint.token,
940
949
  loopbackAuth: endpoint.loopbackAuth,
941
950
  transport: endpoint.transport,
951
+ chatPath: endpoint.chatPath,
942
952
  maxTokens: clampMaxTokens(retryMessages, compactionOptsFor(endpoint), opts.maxTokens ?? 8192),
943
953
  temperature: opts.temperature,
944
954
  tools: opts.toolSchemas,
@@ -983,7 +993,7 @@ export async function runTurn(userInput, conversation, opts) {
983
993
  finishReason: response.finishReason, maxTokensSent: lastMaxTokens, promptTokens: response.promptTokens,
984
994
  genTokens: response.tokens, endpoint: endpoint.base, model: endpoint.model,
985
995
  });
986
- conversation.user(truncatedToolNudge(cut.function?.arguments ?? ""));
996
+ engineUser(truncatedToolNudge(cut.function?.arguments ?? ""));
987
997
  continue;
988
998
  }
989
999
  // Budget spent. A truncated call bypasses the (name,args) loop guard — it's never dispatched with a
@@ -1035,8 +1045,8 @@ export async function runTurn(userInput, conversation, opts) {
1035
1045
  // 09-27). NUDGE it to try something different and CONTINUE; keep counting so a model that ignores
1036
1046
  // the nudge escalates. A bare user-role nudge is safe here (no leak).
1037
1047
  opts.onSelfHeal?.("server_error", seen - CONTENT_LOOP_LIMIT + 1); // footer ↻ — breaking a stall
1038
- conversation.user(`You've repeated the same step ${seen}× with the same result — that approach is not working. Do NOT ` +
1039
- `end the turn or ask me how to proceed. STOP repeating it and try a genuinely DIFFERENT approach: a ` +
1048
+ engineUser(`You've repeated the same step ${seen}× with the same result — that approach is not working. Do NOT ` +
1049
+ `end the turn or ask the owner how to proceed. STOP repeating it and try a genuinely DIFFERENT approach: a ` +
1040
1050
  `different command, tool, path, or angle; if a tool seems broken, work around it. If you already ` +
1041
1051
  `know the fix (you often do — you just described one), do it now.`);
1042
1052
  continue;
@@ -1052,7 +1062,7 @@ export async function runTurn(userInput, conversation, opts) {
1052
1062
  forcedRedirects += 1;
1053
1063
  contentSigs.set(rsig, 0); // fresh runway for this signature after the forced redirect
1054
1064
  opts.onSelfHeal?.("server_error", forcedRedirects); // footer ↻ — a forced self-correction
1055
- conversation.user(`You have repeated the SAME step ${seen}× and it is STILL not working — repeating it again will not ` +
1065
+ engineUser(`You have repeated the SAME step ${seen}× and it is STILL not working — repeating it again will not ` +
1056
1066
  `help. Stop and do this explicitly, in order:\n` +
1057
1067
  `1. In ONE line, state exactly WHAT you keep doing and WHY it isn't making progress (what you ` +
1058
1068
  `expected vs what actually happened).\n` +
@@ -1070,8 +1080,7 @@ export async function runTurn(userInput, conversation, opts) {
1070
1080
  const stuck = `[stopped — I repeated the same step ${seen}× and self-correction (${forcedRedirects} ` +
1071
1081
  `forced redirects) didn't break it, which usually means a tool isn't doing what I expect. Where I'm ` +
1072
1082
  `stuck: ${gist}\nTell me how you'd like to proceed.]`;
1073
- conversation.assistant(stuck);
1074
- return { content: stuck, rounds: rounds + 1, toolCalls: toolCallTotal, tokens: tokensTotal, genMs: genMsTotal, promptTokens: promptTokensTotal, promptMs: promptMsTotal };
1083
+ return stopTurn(stuck, rounds + 1);
1075
1084
  }
1076
1085
  }
1077
1086
  }
@@ -1090,7 +1099,7 @@ export async function runTurn(userInput, conversation, opts) {
1090
1099
  if (thinkSpiralStreak >= THINK_SPIRAL_ROUNDS) {
1091
1100
  thinkLatched = true;
1092
1101
  opts.onSelfHeal?.("server_error", thinkSpiralStreak); // footer ↻ — breaking a reasoning spiral
1093
- conversation.user(`You've spent ${thinkSpiralStreak} rounds thinking at length while only polling/reading — no file ` +
1102
+ engineUser(`You've spent ${thinkSpiralStreak} rounds thinking at length while only polling/reading — no file ` +
1094
1103
  `changed and no answer given. That is a reasoning loop. Stop deliberating: if you know the next ` +
1095
1104
  `concrete action, take it now with a tool; if you have enough to answer, answer directly and ` +
1096
1105
  `concisely. Extended thinking is now off for the rest of this turn.`);
@@ -1114,14 +1123,13 @@ export async function runTurn(userInput, conversation, opts) {
1114
1123
  const stuck = `[stopped — I said I was going in circles ${selfLoopStreak}× without making a change that broke ` +
1115
1124
  `the loop, so I'm handing back rather than burning more time. Where I am: ${gist}\nTell me how you'd like ` +
1116
1125
  `to proceed — a different angle, or I can apply the fix I've been circling if you confirm it.]`;
1117
- conversation.assistant(stuck);
1118
- return { content: stuck, rounds: rounds + 1, toolCalls: toolCallTotal, tokens: tokensTotal, genMs: genMsTotal, promptTokens: promptTokensTotal, promptMs: promptMsTotal };
1126
+ return stopTurn(stuck, rounds + 1);
1119
1127
  }
1120
1128
  opts.onSelfHeal?.("server_error", selfLoopStreak); // footer ↻ — breaking a self-declared loop
1121
- conversation.user(`You just said you're stuck or looping — that is the moment to CHANGE something concrete, not run the ` +
1129
+ engineUser(`You just said you're stuck or looping — that is the moment to CHANGE something concrete, not run the ` +
1122
1130
  `same investigation again. If you understand the root cause, apply the fix NOW with file_edit/file_write ` +
1123
1131
  `and verify it. If a tool, path, or approach isn't working, switch to a genuinely different one. If you ` +
1124
- `are truly blocked, STOP and tell me exactly what is blocking you and what you would try next.`);
1132
+ `are truly blocked, STOP and give the owner one line naming exactly what is blocking you and what you would try next.`);
1125
1133
  continue; // let the model act on the nudge; don't dispatch this round's repeated calls
1126
1134
  }
1127
1135
  selfLoopStreak = 0; // a round that fixes, doesn't act, or doesn't admit looping clears the streak
@@ -1150,12 +1158,25 @@ export async function runTurn(userInput, conversation, opts) {
1150
1158
  noProgressStreak = progressed ? 0 : noProgressStreak + 1; // reset the stall counter on any real progress
1151
1159
  noEditStreak = response.toolCalls.some((c) => MUTATING_TOOLS.has(c.function?.name ?? "")) ? 0 : noEditStreak + 1;
1152
1160
  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
1163
+ // Owner-facing: narration that answers a speaker who did not speak ("You're right — …" to an engine note) is
1164
+ // redirected into a status for the owner. The round's calls already ran; the note rides into the next round.
1165
+ if (selfDialogueNudges < SELF_DIALOGUE_NUDGE_MAX && detectSelfDialogue(response.content, repliesSinceOwner)) {
1166
+ selfDialogueNudges++;
1167
+ engineUser(SELF_DIALOGUE_NUDGE);
1168
+ }
1169
+ if (response.content.trim())
1170
+ repliesSinceOwner++;
1171
+ lastReasoning = "";
1172
+ emptyRetries = 0;
1173
+ emptyNudged = false; // a productive round: the empty streak and its stale reasoning are over
1153
1174
  // Delegation-by-prose guard: the round's narration said "spawn sub-agents / delegate" but none of its calls
1154
1175
  // delegated. Nudge ONCE per turn to make the call (tasks[] for parallel work) or stop announcing it — a
1155
1176
  // nudge, never a stop; the model may legitimately decide the work is sequential after all.
1156
1177
  if (!delegationNudged && hasSpawnTool && detectAnnouncedDelegation(response.content, response.toolCalls.map((c) => c.function?.name ?? ""))) {
1157
1178
  delegationNudged = true;
1158
- conversation.user(DELEGATION_NUDGE);
1179
+ engineUser(DELEGATION_NUDGE);
1159
1180
  }
1160
1181
  // Poll-spin guard: an agent_status spin (auto-post pending, no other work, no status change) wastes the
1161
1182
  // turn — pollers are exempt from the loop guard above, so this catches them. Nudge once, then end the
@@ -1165,7 +1186,7 @@ export async function runTurn(userInput, conversation, opts) {
1165
1186
  if (ps.action === "halt")
1166
1187
  return stopTurn(ps.message, rounds + 1);
1167
1188
  if (ps.action === "nudge") {
1168
- conversation.user(ps.message);
1189
+ engineUser(ps.message);
1169
1190
  continue;
1170
1191
  }
1171
1192
  }
@@ -1174,7 +1195,7 @@ export async function runTurn(userInput, conversation, opts) {
1174
1195
  if (yg.action === "halt")
1175
1196
  return stopTurn(yg.message, rounds + 1);
1176
1197
  if (yg.action === "nudge") {
1177
- conversation.user(yg.message);
1198
+ engineUser(yg.message);
1178
1199
  continue;
1179
1200
  }
1180
1201
  }
@@ -1217,12 +1238,23 @@ export async function runTurn(userInput, conversation, opts) {
1217
1238
  noProgressStreak = progressed ? 0 : noProgressStreak + 1; // reset the stall counter on any real progress
1218
1239
  noEditStreak = recovered.calls.some((c) => MUTATING_TOOLS.has(c.function?.name ?? "")) ? 0 : noEditStreak + 1;
1219
1240
  trackTouchedFiles(recovered.calls, touchedFiles);
1241
+ if (recovered.calls.some((c) => c.function?.name === "ask_user"))
1242
+ repliesSinceOwner = -1;
1243
+ if (selfDialogueNudges < SELF_DIALOGUE_NUDGE_MAX && detectSelfDialogue(recovered.cleanedContent, repliesSinceOwner)) {
1244
+ selfDialogueNudges++;
1245
+ engineUser(SELF_DIALOGUE_NUDGE);
1246
+ }
1247
+ if (recovered.cleanedContent.trim())
1248
+ repliesSinceOwner++;
1249
+ lastReasoning = "";
1250
+ emptyRetries = 0;
1251
+ emptyNudged = false;
1220
1252
  if (pollSpin) {
1221
1253
  const ps = pollSpin.observe(recovered.calls.map((c) => c.function.name), toolMsgs.map((m) => m.content ?? ""), recovered.calls.some((c) => MUTATING_TOOLS.has(c.function?.name ?? "")));
1222
1254
  if (ps.action === "halt")
1223
1255
  return stopTurn(ps.message, rounds + 1);
1224
1256
  if (ps.action === "nudge") {
1225
- conversation.user(ps.message);
1257
+ engineUser(ps.message);
1226
1258
  continue;
1227
1259
  }
1228
1260
  }
@@ -1231,7 +1263,7 @@ export async function runTurn(userInput, conversation, opts) {
1231
1263
  if (yg.action === "halt")
1232
1264
  return stopTurn(yg.message, rounds + 1);
1233
1265
  if (yg.action === "nudge") {
1234
- conversation.user(yg.message);
1266
+ engineUser(yg.message);
1235
1267
  continue;
1236
1268
  }
1237
1269
  }
@@ -1240,7 +1272,7 @@ export async function runTurn(userInput, conversation, opts) {
1240
1272
  if (nwp.action === "halt")
1241
1273
  return stopTurn(nwp.message, rounds + 1);
1242
1274
  if (nwp.action === "warn") {
1243
- conversation.user(nwp.message);
1275
+ engineUser(nwp.message);
1244
1276
  continue;
1245
1277
  }
1246
1278
  }
@@ -1248,13 +1280,13 @@ export async function runTurn(userInput, conversation, opts) {
1248
1280
  return stopTurn(notConvergingNote(recovered.calls), rounds + 1);
1249
1281
  continue;
1250
1282
  }
1251
- const final = stripScratchpad(recovered.cleanedContent);
1283
+ const final = stripEngineEcho(stripScratchpad(recovered.cleanedContent)); // a model that echoes the marker must not show it to the owner
1252
1284
  // A tool call that could not be parsed (stray tags, cut off) must not end the turn silently: the model said it
1253
1285
  // would act and nothing ran. Tell it, once or twice, to re-emit the call as a proper tool call.
1254
1286
  if (recovered.malformed && malformedCallNudges < 2 && response.stopReason !== "length") {
1255
1287
  malformedCallNudges++;
1256
1288
  conversation.assistant(final);
1257
- conversation.user("Your last tool call was malformed (a tag was missing or the call was cut off), so NOTHING ran. Call the tool again now as a proper tool call, with the complete arguments. If the content is long, split it into smaller calls.");
1289
+ engineUser("Your last tool call was malformed (a tag was missing or the call was cut off), so NOTHING ran. Call the tool again now as a proper tool call, with the complete arguments. If the content is long, split it into smaller calls.");
1258
1290
  continue;
1259
1291
  }
1260
1292
  // Empty round — two very different causes, handled differently so we never (a) inject a user-role
@@ -1279,6 +1311,12 @@ export async function runTurn(userInput, conversation, opts) {
1279
1311
  // (the leak). Instead we PERTURB SAMPLING: the operator decodes greedily (temp 0), so a bit-identical
1280
1312
  // re-request reproduces the same deterministic argmax-EOS empty forever; raising the retry's temperature
1281
1313
  // is the one change that can actually escape it, and it touches nothing in the conversation.
1314
+ if (response.reasoningContent)
1315
+ lastReasoning = response.reasoningContent; // an answer that went to the reasoning channel
1316
+ if (!emptyNudged) {
1317
+ emptyNudged = true;
1318
+ engineUser(EMPTY_REPLY_NUDGE);
1319
+ } // marked as an engine note, so it cannot be read as the owner speaking
1282
1320
  retryTempOverride = emptyRetryTemp(emptyRetries); // escalate: retry 1 → 0.7, retry 2 → 1.0
1283
1321
  continue;
1284
1322
  }
@@ -1298,13 +1336,24 @@ export async function runTurn(userInput, conversation, opts) {
1298
1336
  if (response.stopReason === "length" && final && final.trim().length > 0 && truncationContinues < TRUNCATION_CONTINUE_MAX) {
1299
1337
  truncationContinues++;
1300
1338
  conversation.assistant(final);
1301
- conversation.user("Your output hit the token limit and was CUT OFF mid-stream. Continue EXACTLY from where you stopped — no preamble, no re-analysis. If you were emitting a tool call, re-emit it complete and keep arguments short: for long scripts, file_write the script then bash the file.");
1339
+ engineUser("Your output hit the token limit and was CUT OFF mid-stream. Continue EXACTLY from where you stopped — no preamble, no re-analysis. If you were emitting a tool call, re-emit it complete and keep arguments short: for long scripts, file_write the script then bash the file.");
1340
+ continue;
1341
+ }
1342
+ // Owner-facing: a text-only reply that reacts to a speaker who did not speak (a stale greeting answered an hour
1343
+ // later, "you're right" to an engine note) must not end the turn as the answer — redirect it to a status.
1344
+ if (final && response.stopReason !== "length" && selfDialogueNudges < SELF_DIALOGUE_NUDGE_MAX && detectSelfDialogue(final, repliesSinceOwner)) {
1345
+ selfDialogueNudges++;
1346
+ repliesSinceOwner++;
1347
+ conversation.assistant(final);
1348
+ engineUser(SELF_DIALOGUE_NUDGE);
1302
1349
  continue;
1303
1350
  }
1351
+ if (final)
1352
+ repliesSinceOwner++;
1304
1353
  if (continuationEnabled && final && response.stopReason !== "length" && announceNudges < continuationMax && detectUnfinishedAction(final)) {
1305
1354
  announceNudges++;
1306
1355
  conversation.assistant(final);
1307
- conversation.user(ANNOUNCE_NUDGE);
1356
+ engineUser(ANNOUNCE_NUDGE);
1308
1357
  continue;
1309
1358
  }
1310
1359
  // Verify-before-done gate: the model is finalizing (no more tool calls). If this turn CHANGED files
@@ -1313,22 +1362,29 @@ export async function runTurn(userInput, conversation, opts) {
1313
1362
  // warning above applies only to an EMPTY round; here real content + tool results exist, so the reminder
1314
1363
  // is answered as the intended verify step, not mistaken for the request. Capped (verifyMaxNudges) →
1315
1364
  // ≤1 extra round, the main-loop mirror of grandmaster's single repair round.
1316
- if (verifyEnabled && final && verify.gate() && verifyNudges < verifyMaxNudges) {
1365
+ if (verifyEnabled && final && !isEngineFinal(final) && verify.gate() && verifyNudges < verifyMaxNudges) {
1317
1366
  verifyNudges++;
1318
1367
  conversation.assistant(final);
1319
- conversation.user(VERIFY_REMINDER);
1368
+ engineUser(VERIFY_REMINDER);
1369
+ continue;
1370
+ }
1371
+ // Owner-facing: a final that leaves open task-list items with neither a question nor a status is a bare stop —
1372
+ // one nudge to continue or to close with a status line per item and ONE steering question.
1373
+ if (final && response.stopReason !== "length" && !closingNudged && !opts.background && !isEngineFinal(final) && needsClosingSteer(final, !!opts.preservedState?.())) {
1374
+ closingNudged = true;
1375
+ conversation.assistant(final);
1376
+ engineUser(opts.unattended ? CLOSING_NUDGE_UNATTENDED : CLOSING_NUDGE);
1320
1377
  continue;
1321
1378
  }
1322
1379
  const unverified = verifyEnabled && verify.gate(); // changed files, still no passing check after the nudge
1323
1380
  const answer = (unverified ? NOT_VERIFIED_BANNER : "") +
1324
- (final || stripScratchpad(response.reasoningContent ?? "") ||
1381
+ (final || stripScratchpad(response.reasoningContent ?? "") || stripScratchpad(lastReasoning) ||
1325
1382
  (response.stopReason === "length"
1326
1383
  ? "(hit the output limit before an answer landed — ask me to continue and I'll pick up where I left off.)"
1327
- : "(the model returned an empty response — try rephrasing.)"));
1384
+ : emptyReplyStatus(opts.preservedState?.(), emptyRetries + 1)));
1328
1385
  conversation.assistant(answer);
1329
1386
  return { content: answer, rounds: rounds + 1, toolCalls: toolCallTotal, stopReason: response.stopReason, tokens: tokensTotal, genMs: genMsTotal, promptTokens: promptTokensTotal, promptMs: promptMsTotal, unverified: unverified || undefined };
1330
1387
  }
1331
1388
  const timeoutMsg = `[stopped after ${rounds} tool rounds — the task may be unfinished; ask me to continue and I'll pick up where I left off]`;
1332
- conversation.assistant(timeoutMsg);
1333
- return { content: timeoutMsg, rounds, toolCalls: toolCallTotal, tokens: tokensTotal, genMs: genMsTotal, promptTokens: promptTokensTotal, promptMs: promptMsTotal };
1389
+ return stopTurn(timeoutMsg, rounds);
1334
1390
  }
@@ -2,6 +2,7 @@ import { acquireEndpoint, releaseEndpoint, isDegenerate, trimLoop } from "./auro
2
2
  import { anthropicKey } from "./anthropic.js";
3
3
  import { classifyFailure, backoffMs, sleep } from "./selfheal.js";
4
4
  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
5
6
  const FETCH_TRIES = 3; // same pre-response transient retry budget as aurora.fetchChat (no bytes streamed yet → safe)
6
7
  /** OpenAI tool-call `arguments` is a JSON STRING; Anthropic `input` is an OBJECT. Parse defensively — a
7
8
  * malformed/empty string becomes `{}` (messages.ts already sanitizes history, but a live round may not). */
@@ -84,15 +85,16 @@ export function toAnthropicTools(tools) {
84
85
  }
85
86
  return out.length ? out : undefined;
86
87
  }
87
- /** Build the Anthropic /v1/messages request body from AuroraOpts. temperature is clamped to Anthropic's
88
- * [0,1] (the engine's 0.7 default is already in range; a caller passing an OpenAI-style >1 would 400). */
88
+ /** Build the Anthropic /v1/messages request body from AuroraOpts. No sampling knobs: the current Claude family
89
+ * rejects `temperature`/`top_p`/`top_k` (400), so the engine's temperature is dropped here rather than clamped.
90
+ * `thinking` is omitted on purpose — omitted means the model's adaptive default, while a token budget or
91
+ * `{type:"disabled"}` is a 400 — and max_tokens is capped at the vendor's output ceiling. */
89
92
  export function anthropicRequestBody(messages, o, stream) {
90
93
  const { system, messages: amsgs } = toAnthropicConversation(messages);
91
94
  const tools = toAnthropicTools(o.tools);
92
95
  return JSON.stringify({
93
96
  model: o.model,
94
- max_tokens: o.maxTokens ?? 8192,
95
- temperature: Math.max(0, Math.min(1, o.temperature ?? 0.7)),
97
+ max_tokens: Math.min(o.maxTokens ?? 8192, MAX_OUTPUT_TOKENS),
96
98
  ...(system ? { system } : {}),
97
99
  messages: amsgs,
98
100
  ...(tools ? { tools } : {}),
@@ -135,6 +137,11 @@ async function fetchMessages(o, key, body) {
135
137
  }
136
138
  throw lastErr;
137
139
  }
140
+ /** What the owner sees when the provider's safety classifier declines a reply. The partial output is discarded
141
+ * and no tool call from it runs — the vendor's rule for a refusal stop is "discard, then branch on stop_reason". */
142
+ export function refusalNote(category) {
143
+ return `[declined by the provider's safety classifier${category ? ` (${category})` : ""} — nothing from that reply was run]`;
144
+ }
138
145
  /** Parse the Anthropic SSE event stream into normalized deltas. Events seen:
139
146
  * message_start (usage.input_tokens), content_block_start (text | tool_use | thinking),
140
147
  * content_block_delta (text_delta | input_json_delta | thinking_delta), message_delta (stop_reason +
@@ -239,7 +246,7 @@ async function* anthropicDeltas(messages, o) {
239
246
  else if (type === "message_delta") {
240
247
  const del = j.delta;
241
248
  const u = j.usage;
242
- yield { finishReason: del?.stop_reason, usage: u?.output_tokens != null ? { output: u.output_tokens } : undefined };
249
+ yield { finishReason: del?.stop_reason, refusalCategory: del?.stop_details?.category ?? null, usage: u?.output_tokens != null ? { output: u.output_tokens } : undefined };
243
250
  }
244
251
  else if (type === "error") {
245
252
  const e = j.error;
@@ -272,6 +279,7 @@ export async function anthropicChat(messages, o) {
272
279
  let degenerate = false;
273
280
  let sinceCheck = 0;
274
281
  let finishReason;
282
+ let refusalCategory = null;
275
283
  let promptTokens;
276
284
  let outputTokens;
277
285
  const LOOP_CHECK_EVERY = 200;
@@ -285,8 +293,10 @@ export async function anthropicChat(messages, o) {
285
293
  reasoning += d.reasoning;
286
294
  o.onReasoning?.(d.reasoning);
287
295
  }
288
- if (d.finishReason)
296
+ if (d.finishReason) {
289
297
  finishReason = d.finishReason;
298
+ refusalCategory = d.refusalCategory ?? null;
299
+ }
290
300
  if (d.usage?.input != null) {
291
301
  promptTokens = d.usage.input;
292
302
  o.onMeta?.({ promptTokens: d.usage.input });
@@ -320,6 +330,18 @@ export async function anthropicChat(messages, o) {
320
330
  }
321
331
  if (degenerate)
322
332
  content = trimLoop(content);
333
+ // A refusal can land mid-stream after a complete tool_use block: nothing from a declined reply may run.
334
+ if (finishReason === "refusal") {
335
+ return {
336
+ content: refusalNote(refusalCategory),
337
+ toolCalls: [],
338
+ reasoningContent: reasoning || undefined,
339
+ stopReason: "content_filter",
340
+ tokens: outputTokens,
341
+ tokensExact: !!outputTokens && outputTokens > 0,
342
+ promptTokens,
343
+ };
344
+ }
323
345
  const toolCalls = [...tools.entries()]
324
346
  .sort(([a], [b]) => a - b)
325
347
  .map(([idx, e]) => ({
@@ -27,7 +27,7 @@ export async function anthropicComplete(system, user, opts = {}) {
27
27
  body: JSON.stringify({
28
28
  model: opts.model || DEFAULT_MODEL,
29
29
  max_tokens: opts.maxTokens ?? 4096,
30
- temperature: opts.temperature ?? 0.3,
30
+ ...(/^claude-haiku-4-5/.test(opts.model || DEFAULT_MODEL) ? { temperature: opts.temperature ?? 0.3 } : {}), // the 5.x family rejects sampling fields
31
31
  system,
32
32
  messages: [{ role: "user", content: user }],
33
33
  }),