@0perator/operator 0.1.329 → 0.1.331

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.
@@ -91,7 +91,7 @@ function briefFor(task) {
91
91
  * flywheel-prefix contract, _ai-docs/conventions) and the two parenthesized empty-reply notes in engine/agent.ts.
92
92
  * Returned verbatim they would reach the planner AS the sub-agent's answer — seen live: Scout on a tool task
93
93
  * emitted whitespace twice and the planner would have been told "(the model returned an empty response…)". */
94
- const NO_ANSWER = /^\s*(\[(stopped|paused)\b|\((the model returned an empty response|hit the output limit before an answer landed))/;
94
+ const NO_ANSWER = /^\s*(\[(stopped|paused|no reply came back from the model)\b|\((the model returned an empty response|hit the output limit before an answer landed))/;
95
95
  let _seq = 0;
96
96
  const TIMED_OUT = Symbol("delegate-timeout");
97
97
  /** Race a send against the wall-clock bound. On timeout the session is interrupted (so a cooperative turn
@@ -6,18 +6,29 @@
6
6
  import { createAutonomySession } from "./session-factory.js";
7
7
  import { runLoop } from "./loop.js";
8
8
  import { makeReporter } from "./reporter.js";
9
+ import { recordLiveProgress, roundProgressed, touchedPaths } from "../memory/live-progress.js";
10
+ import { getAgentTasks } from "../tools/registry.js";
9
11
  /** Streaming handlers that render a turn's activity through the reporter. Text deltas stream only in
10
12
  * human mode (JSON mode reports the settled content as one event, to stay line-parseable). */
11
- function handlersFor(reporter, json) {
13
+ function handlersFor(reporter, json, prompt = "") {
14
+ const touched = [];
15
+ const session = `headless-${process.pid}`;
12
16
  return {
13
17
  onRoute: (label, ctxPct) => reporter.event("route", { route: label, ctxPct }),
14
18
  onAutoContinue: (round) => reporter.event("auto_continue", { round }),
15
19
  onSelfHeal: (kind, attempt) => reporter.event("self_heal", { kind, attempt }),
16
- onToolBatch: (events, durationMs) => reporter.event("tools", {
17
- count: events.length,
18
- names: events.map((e) => e.name).join(","),
19
- durationMs: Math.round(durationMs),
20
- }),
20
+ onToolBatch: (events, durationMs) => {
21
+ reporter.event("tools", {
22
+ count: events.length,
23
+ names: events.map((e) => e.name).join(","),
24
+ durationMs: Math.round(durationMs),
25
+ });
26
+ // Live progress journal, same contract as the TUI: a cut-off unattended run leaves its state in the handoff.
27
+ if (roundProgressed(events)) {
28
+ touched.push(...touchedPaths(events));
29
+ recordLiveProgress(process.env.KODE_HANDOFF_FILE, { session, cwd: process.cwd(), request: prompt, tasks: getAgentTasks(), touched });
30
+ }
31
+ },
21
32
  onDelta: json ? undefined : (chunk) => process.stdout.write(chunk),
22
33
  };
23
34
  }
@@ -28,7 +39,7 @@ function handlersFor(reporter, json) {
28
39
  export async function runHeadless(settings, prompt, opts = {}) {
29
40
  const reporter = opts.reporter ?? makeReporter({ json: opts.json, logFile: opts.logFile });
30
41
  const session = createAutonomySession(settings);
31
- const handlers = handlersFor(reporter, !!opts.json);
42
+ const handlers = handlersFor(reporter, !!opts.json, prompt);
32
43
  const controller = new AbortController();
33
44
  const onSig = () => { controller.abort(); try {
34
45
  session.interrupt();
@@ -7,6 +7,7 @@ import { Session } from "../session.js";
7
7
  import { AuroraRouter } from "../router/router.js";
8
8
  import { buildMemory } from "../memory/providers.js";
9
9
  import { composeSystemPrompt } from "../config/persona.js";
10
+ import { ensureScratchDir } from "../config/scratch.js";
10
11
  import { modelCtxFor, leanHarnessFor, DEFAULT_MODEL_ID } from "../router/models.js";
11
12
  import { compactionThreshold, compactionCeilingTokens, turnWallClockMs, buildEndpointChain } from "../config/settings.js";
12
13
  /** Build the Aurora router from settings — the headless twin of cli.tsx's buildRouter(). Both share the one
@@ -18,6 +19,7 @@ export function buildRouterFromSettings(settings) {
18
19
  /** The full headless system prompt: the SAME composeSystemPrompt the TUI calls (persona + project context +
19
20
  * memory + handoff + catalogue), non-interactive — minus the TUI-only Sub-agents + embodiment sections. */
20
21
  export function buildHeadlessSystemPrompt(settings, cwd = process.cwd()) {
22
+ ensureScratchDir(cwd); // `<cwd>/.operator/.op-writes` + OPERATOR_SCRATCH for the tools — same contract as the TUI
21
23
  const ctxTokens = modelCtxFor(settings.activeModel, settings.models);
22
24
  const lean = leanHarnessFor(settings.activeModel, settings.models); // small-ctx OR a weak big-ctx model (leanPersona) → trim persona + drop heavy memory/handoff
23
25
  return composeSystemPrompt({ settings, cwd, ctxTokens, lean, interactive: false });
package/dist/bus/inbox.js CHANGED
@@ -68,7 +68,21 @@ export function buildMentorWake(incoming, allow) {
68
68
  if (!toWake.length)
69
69
  return null;
70
70
  return (`[mentor-wake] ${toWake.length} new bus message(s) arrived — review and act on them now:\n\n` +
71
- toWake.map((m) => `--- from ${m.from}${m.subject ? ` · ${m.subject}` : ""} (${m.ts}) ---\n${m.body}`).join("\n\n"));
71
+ toWake.map((m) => `--- from ${m.from}${m.subject ? ` · ${m.subject}` : ""} (${m.ts}) ---\n${m.body}`).join("\n\n") +
72
+ `\n\n${replyProtocol([...new Set(toWake.map((m) => m.from))])}`);
73
+ }
74
+ /** The reply contract a woken turn owes its sender, spelled out in the frame itself. The sender is another agent
75
+ * on the bus and cannot see this screen: a turn that works in silence is invisible to the teacher, and the plan
76
+ * message BEFORE the work is what lets the teacher stop a wrong plan early. It lived only in memories.md until
77
+ * 2026-10-28, when a lesson wake went straight to the fix round and never posted — the model treated "post your
78
+ * plan first" in the lesson body as optional; the frame is the one place every wake passes through. */
79
+ export function replyProtocol(senders) {
80
+ const send = senders.map((s) => `\`switch send ${s} "…"\``).join(" / ");
81
+ return (`Reply protocol — the sender cannot see this screen. Read what the message points you at, then, BEFORE any other ` +
82
+ `action (no edit, build, search or spawn first), send ONE plan message back with ${send}: what you understood, the ` +
83
+ `steps you will take, what you will verify. Then do the work. When it is done, send ONE report the same way: what ` +
84
+ `changed (files, commit), what you verified and HOW, what is still open. A woken turn that acts without the plan ` +
85
+ `message or ends without the report has broken the protocol.`);
72
86
  }
73
87
  /** Per-source cooldown selection for wake-on-mentor (ping-pong guard). From a buffer of pending wake messages,
74
88
  * return the subset whose source last woke the session at least `cooldownMs` ago — a source's FIRST message is
package/dist/cli.js CHANGED
@@ -38,6 +38,9 @@ import { getDiscoveredModels } from "./router/discovery.js";
38
38
  import { disposeShellSession, getAgentTasks, registry } from "./tools/registry.js";
39
39
  import { drainJobNotices, getJobNoticeMode, listShellJobs, onJobEvent, parseJobsArgs, pendingJobNotices, renderJobsList, runningJobCount, setJobNoticeMode, stopShellJob } from "./tools/shell-jobs.js";
40
40
  import { drainAgentReports, onAgentReport, pendingAgentReports, queueAgentReport } from "./background/notices.js";
41
+ import { ensureScratchDir } from "./config/scratch.js";
42
+ import { caffeinateEnabled, startCaffeinate } from "./util/caffeinate.js";
43
+ import { recordLiveProgress, roundProgressed, settleLiveProgress, touchedPaths } from "./memory/live-progress.js";
41
44
  import { lastActiveAt as idleLastActiveAt, resolveIdlePolicy, startIdleMonitor, touchWork } from "./idle/index.js";
42
45
  import { disposeBrowserNow } from "./browser/session.js";
43
46
  import { EventSink, defaultEventsFile } from "./telemetry/events.js";
@@ -475,6 +478,10 @@ const chauffeurReady = !!chauffeurServer || settings.mcp;
475
478
  // section) so the model stays uncensored.
476
479
  const LEAN_HARNESS = leanHarnessFor(settings.activeModel, settings.models);
477
480
  // TODO(R1b): built once at startup — a mid-session /model does not rebuild it (ctxTokens + lean follow the startup model).
481
+ // Scratch dir for this project (`<cwd>/.operator/.op-writes`): created here so every tool subprocess inherits
482
+ // OPERATOR_SCRATCH and the persona can point the model at a real path. Skipped for auth/version/help (SKIP_SEAT).
483
+ if (!SKIP_SEAT)
484
+ ensureScratchDir(process.cwd());
478
485
  const SYSTEM_PROMPT = composeSystemPrompt({ settings, cwd: process.cwd(), ctxTokens: modelCtxFor(settings.activeModel, settings.models), lean: LEAN_HARNESS, interactive: true, chauffeurReady });
479
486
  const HELP = [
480
487
  "commands:",
@@ -759,6 +766,8 @@ function Root() {
759
766
  const tokHist = useRef([]); // per-turn decode tok/s, for the /stats throughput sparkline
760
767
  const toolTotal = useRef(0); // cumulative tool calls this session, for /stats
761
768
  const liveText = useRef("");
769
+ const touchedThisTurn = useRef([]); // files written/edited this turn, for the live progress journal
770
+ const lastNarrationRef = useRef(""); // the narration that preceded the current tool batch (liveText is cleared when the batch starts)
762
771
  const liveReasoning = useRef(""); // current completion's reasoning ("thinking"), shown dim + above the answer
763
772
  const liveTokRef = useRef(0); // per-token count accumulated by the stream; flushed to liveTok on the throttled tick
764
773
  // Coalesced live-frame update: applies the accumulated stream refs in ONE render, rate-limited to ~15fps,
@@ -974,6 +983,7 @@ function Root() {
974
983
  setLive(null);
975
984
  setLiveTok(0); // reset the live counter at the start of the turn
976
985
  turnStartRef.current = Date.now();
986
+ touchedThisTurn.current = [];
977
987
  turnCachedRef.current = 0;
978
988
  setElapsed(0);
979
989
  setStat("thinking");
@@ -1078,6 +1088,8 @@ function Root() {
1078
1088
  const preThought = liveReasoning.current.trim();
1079
1089
  if (preThought)
1080
1090
  push({ kind: "message", message: { id: nextId(), role: "assistant", content: "", reasoning: preThought } });
1091
+ if (liveText.current.trim())
1092
+ lastNarrationRef.current = liveText.current; // keep it for the live progress journal
1081
1093
  liveText.current = "";
1082
1094
  liveReasoning.current = "";
1083
1095
  setLive(null);
@@ -1089,6 +1101,13 @@ function Root() {
1089
1101
  setLiveTools((rows) => settleLiveTool(rows, id, result));
1090
1102
  },
1091
1103
  onToolBatch: (events, durationMs) => {
1104
+ // Live progress journal: after every round that changed something, the request, the task list, the files
1105
+ // touched and the last narration are rewritten at the end of this directory's handoff file — a cutoff
1106
+ // (killed session, wedged model, empty reply) loses nothing the next session cannot resume from.
1107
+ if (roundProgressed(events)) {
1108
+ touchedThisTurn.current.push(...touchedPaths(events));
1109
+ recordLiveProgress(process.env.KODE_HANDOFF_FILE, { session: SESSION_ID, cwd: process.cwd(), request: text, tasks: getAgentTasks(), touched: touchedThisTurn.current, narration: lastNarrationRef.current });
1110
+ }
1092
1111
  const steps = [];
1093
1112
  for (const ev of events) {
1094
1113
  const step = {
@@ -1132,6 +1151,9 @@ function Root() {
1132
1151
  }, turnDirective, { wake: opts?.wake === true });
1133
1152
  // A completed (not interrupted) turn while still in plan mode counts as "a plan was proposed" —
1134
1153
  // arms the exit-time Approve & run picker (see applyMode).
1154
+ // The turn ended normally: settle the live progress block so the next session is not told to resume a finished turn.
1155
+ if (!outcome.interrupted && touchedThisTurn.current.length)
1156
+ settleLiveProgress(process.env.KODE_HANDOFF_FILE, { session: SESSION_ID, cwd: process.cwd(), request: text, tasks: getAgentTasks(), touched: touchedThisTurn.current, narration: lastNarrationRef.current });
1135
1157
  if (!outcome.interrupted && session.inPlanMode())
1136
1158
  planProposedRef.current = true;
1137
1159
  if (outcome.interrupted) {
@@ -1265,6 +1287,31 @@ function Root() {
1265
1287
  teardown.add("idle-monitor", () => mon.stop(), { order: 20 });
1266
1288
  return () => mon.stop();
1267
1289
  }, []);
1290
+ // Keep the Mac awake for the life of the session (settings.caffeinate, default on; KODE_CAFFEINATE=0 off; /caffeinate
1291
+ // toggles). `caffeinate -w <pid>` dies with this process, so it can never outlive the session.
1292
+ const caffeineRef = useRef(null);
1293
+ const [caffeinated, setCaffeinated] = useState(false);
1294
+ const setCaffeine = useCallback((on) => {
1295
+ if (on && !caffeineRef.current?.active) {
1296
+ caffeineRef.current = startCaffeinate();
1297
+ setCaffeinated(caffeineRef.current.active);
1298
+ return caffeineRef.current.active;
1299
+ }
1300
+ if (!on && caffeineRef.current) {
1301
+ caffeineRef.current.stop();
1302
+ caffeineRef.current = null;
1303
+ setCaffeinated(false);
1304
+ }
1305
+ return caffeineRef.current?.active ?? false;
1306
+ }, []);
1307
+ useEffect(() => {
1308
+ if (boot !== "ready")
1309
+ return;
1310
+ if (caffeinateEnabled(settings.caffeinate))
1311
+ setCaffeine(true);
1312
+ teardown.add("caffeinate", () => { setCaffeine(false); }, { order: 25 });
1313
+ return () => { setCaffeine(false); };
1314
+ }, [boot, setCaffeine]);
1268
1315
  // Say so when this launch cleaned up after a previous one — silently killing processes would be worse than the orphans.
1269
1316
  useEffect(() => {
1270
1317
  const n = REAPED.killed.length;
@@ -2108,6 +2155,14 @@ function Root() {
2108
2155
  sys(id ? `spawned ${id} in the background — /bg to list · /bg stop ${id} to cancel` : bg.capacityLine());
2109
2156
  }
2110
2157
  break;
2158
+ case "caffeinate":
2159
+ case "caffeine": {
2160
+ const want = arg === "off" ? false : arg === "on" ? true : !caffeineRef.current?.active;
2161
+ const active = setCaffeine(want);
2162
+ sys(active ? "☕ caffeinate on — this Mac stays awake while the session runs (/caffeinate off to allow sleep)"
2163
+ : want ? "caffeinate unavailable here (macOS only, needs /usr/bin/caffeinate)" : "caffeinate off — the Mac may sleep while idle");
2164
+ break;
2165
+ }
2111
2166
  case "remotecontrol":
2112
2167
  case "remote":
2113
2168
  case "rc": {
@@ -2387,7 +2442,7 @@ function Root() {
2387
2442
  ? `${spin} reading your prompt… (${fmtDuration(elapsed)})`
2388
2443
  : `${spin} ${fmtMeta(elapsed, liveTok)}`
2389
2444
  : metrics;
2390
- 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, approval: approval, question: question, modelPicker: modelPicker, planExitPicker: planExitPicker, artifactsPicker: artifactsPicker, sessionsPicker: sessionsPicker, onApprovalDecide: (allow, always) => {
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) => {
2391
2446
  const cur = approval;
2392
2447
  if (cur)
2393
2448
  settleApproval(cur.id, allow, always); // first-wins with any remote follower answer
@@ -5,6 +5,7 @@
5
5
  import { readFileSync, appendFileSync, mkdirSync } from "node:fs";
6
6
  import { join, dirname } from "node:path";
7
7
  import { operatorPath } from "./home.js";
8
+ import { scratchDirFor } from "./scratch.js";
8
9
  import { renderHarnessContext } from "./operator-harness.js";
9
10
  import { renderToolCatalogue } from "../tools/registry.js";
10
11
  import { renderSkillsIndex } from "./skills-index.js";
@@ -201,6 +202,9 @@ export function basePersona(cwd = process.cwd(), opts = {}) {
201
202
  `a conventional \`type(scope): subject\` with explicit paths (never a blanket add in a shared checkout) ` +
202
203
  `and no AI / Co-Authored-By / Claude-Session trailers.` +
203
204
  `\n## This machine\nWorking dir: ${cwd}` +
205
+ `\nScratch dir: ${scratchDirFor(cwd)} (also \`$OPERATOR_SCRATCH\` in every shell) — temporary scripts, probe ` +
206
+ `output, downloads to inspect, intermediate files: ALWAYS here, never /tmp and never the repo root. It is ` +
207
+ `git-ignored and swept after a week, so nothing you keep belongs in it; name files \`<subject>-<thing>\`.` +
204
208
  ctxLine +
205
209
  `\n## Talking about yourself\nYou are Operator, whichever model is serving you — the model underneath can change between sessions (or mid-session with /model) and you are still Operator. When asked what you are or which model you run on, ` +
206
210
  `say you are Operator (AXE's agent) and give the context window above. Never name, guess or compare backend models (do not say ` +
@@ -280,7 +284,7 @@ export function basePersona(cwd = process.cwd(), opts = {}) {
280
284
  // shipped as "...rather than guessing.the script to a file…" — no heading, no space (the persona
281
285
  // regression test's red on main was the witness). Restored as its own section; do not re-splice.
282
286
  `\n## Running scripts — never inline a multi-line script\nFor anything more than a ONE-LINE snippet, write ` +
283
- `the script to a file with file_write and run the file (\`python3 /tmp/probe.py\`). Do NOT embed a ` +
287
+ `the script to a file in the scratch dir with file_write and run the file (\`python3 "$OPERATOR_SCRATCH/probe.py"\`). Do NOT embed a ` +
284
288
  `multi-line program inside \`python3 -c "…"\` or \`bash -c "…"\`: the newlines, \`#\` comments and quotes ` +
285
289
  `have to be escaped inside the tool-call JSON, and a slip there breaks the whole call (\`500: missing ` +
286
290
  `closing quote\`) and wastes the turn. A short one-liner inline is fine; a real script goes to a file first.` +
@@ -295,6 +299,12 @@ export function basePersona(cwd = process.cwd(), opts = {}) {
295
299
  `Keep it to ONE short line and put your tool calls in the SAME message right after it — narration must ` +
296
300
  `NEVER delay, crowd out, or replace the actual tool call, and never grow long enough to push a big ` +
297
301
  `tool-call argument late in your output where it can get cut off.` +
302
+ `\n## Talking to the owner — never to yourself\nThe owner speaks only in user messages. Anything that starts with ` +
303
+ `"[engine note" is the engine, not the owner: act on it silently or with one line of status, never reply to it ` +
304
+ `("you're right", "good point") and never narrate "the user said". Never write a line for the owner and then ` +
305
+ `answer it. When you have something to say, say it TO the owner as a status: what is done, what you are doing, ` +
306
+ `what you need. Never end a turn on nothing: if you cannot finish, close with one line per open task and ONE ` +
307
+ `question whose answer steers the next step.` +
298
308
  (opts.lean ? "" : (`\n## Explain your thinking — tables, diagrams, status (Explanatory default)\nThe owner follows a long ` +
299
309
  `session by reading YOUR words, not your tool output — so make your reasoning legible, not just your ` +
300
310
  `actions. The one-line what-and-why before each batch (above) is the floor; on top of it: for anything ` +
@@ -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
+ }
@@ -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 } 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 {
@@ -847,7 +853,7 @@ export async function runTurn(userInput, conversation, opts) {
847
853
  }
848
854
  truncRetries += 1;
849
855
  opts.onSelfHeal?.("server_error", truncRetries); // footer ↻ — a recovery is in flight
850
- conversation.user(truncatedToolNudge(err instanceof Error ? err.message : String(err)));
856
+ engineUser(truncatedToolNudge(err instanceof Error ? err.message : String(err)));
851
857
  continue;
852
858
  }
853
859
  // Endpoint (re)starting: a 503 whose body says it's loading/warming (seen live 09-26 when a JL2
@@ -901,7 +907,7 @@ export async function runTurn(userInput, conversation, opts) {
901
907
  if (chars(shrunk) >= chars(before))
902
908
  throw err; // nothing left to shed — surface honestly rather than spin
903
909
  if (shrunk.length < before.length)
904
- conversation.user(rehydrationNote(touchedFiles)); // rehydrate after a forced compaction
910
+ engineUser(rehydrationNote(touchedFiles)); // rehydrate after a forced compaction
905
911
  continue;
906
912
  }
907
913
  // transient (429 / 5xx / network drop): a busy or unhealthy backend, NOT a context problem.
@@ -983,7 +989,7 @@ export async function runTurn(userInput, conversation, opts) {
983
989
  finishReason: response.finishReason, maxTokensSent: lastMaxTokens, promptTokens: response.promptTokens,
984
990
  genTokens: response.tokens, endpoint: endpoint.base, model: endpoint.model,
985
991
  });
986
- conversation.user(truncatedToolNudge(cut.function?.arguments ?? ""));
992
+ engineUser(truncatedToolNudge(cut.function?.arguments ?? ""));
987
993
  continue;
988
994
  }
989
995
  // Budget spent. A truncated call bypasses the (name,args) loop guard — it's never dispatched with a
@@ -1035,8 +1041,8 @@ export async function runTurn(userInput, conversation, opts) {
1035
1041
  // 09-27). NUDGE it to try something different and CONTINUE; keep counting so a model that ignores
1036
1042
  // the nudge escalates. A bare user-role nudge is safe here (no leak).
1037
1043
  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 ` +
1044
+ engineUser(`You've repeated the same step ${seen}× with the same result — that approach is not working. Do NOT ` +
1045
+ `end the turn or ask the owner how to proceed. STOP repeating it and try a genuinely DIFFERENT approach: a ` +
1040
1046
  `different command, tool, path, or angle; if a tool seems broken, work around it. If you already ` +
1041
1047
  `know the fix (you often do — you just described one), do it now.`);
1042
1048
  continue;
@@ -1052,7 +1058,7 @@ export async function runTurn(userInput, conversation, opts) {
1052
1058
  forcedRedirects += 1;
1053
1059
  contentSigs.set(rsig, 0); // fresh runway for this signature after the forced redirect
1054
1060
  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 ` +
1061
+ engineUser(`You have repeated the SAME step ${seen}× and it is STILL not working — repeating it again will not ` +
1056
1062
  `help. Stop and do this explicitly, in order:\n` +
1057
1063
  `1. In ONE line, state exactly WHAT you keep doing and WHY it isn't making progress (what you ` +
1058
1064
  `expected vs what actually happened).\n` +
@@ -1070,8 +1076,7 @@ export async function runTurn(userInput, conversation, opts) {
1070
1076
  const stuck = `[stopped — I repeated the same step ${seen}× and self-correction (${forcedRedirects} ` +
1071
1077
  `forced redirects) didn't break it, which usually means a tool isn't doing what I expect. Where I'm ` +
1072
1078
  `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 };
1079
+ return stopTurn(stuck, rounds + 1);
1075
1080
  }
1076
1081
  }
1077
1082
  }
@@ -1090,7 +1095,7 @@ export async function runTurn(userInput, conversation, opts) {
1090
1095
  if (thinkSpiralStreak >= THINK_SPIRAL_ROUNDS) {
1091
1096
  thinkLatched = true;
1092
1097
  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 ` +
1098
+ engineUser(`You've spent ${thinkSpiralStreak} rounds thinking at length while only polling/reading — no file ` +
1094
1099
  `changed and no answer given. That is a reasoning loop. Stop deliberating: if you know the next ` +
1095
1100
  `concrete action, take it now with a tool; if you have enough to answer, answer directly and ` +
1096
1101
  `concisely. Extended thinking is now off for the rest of this turn.`);
@@ -1114,14 +1119,13 @@ export async function runTurn(userInput, conversation, opts) {
1114
1119
  const stuck = `[stopped — I said I was going in circles ${selfLoopStreak}× without making a change that broke ` +
1115
1120
  `the loop, so I'm handing back rather than burning more time. Where I am: ${gist}\nTell me how you'd like ` +
1116
1121
  `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 };
1122
+ return stopTurn(stuck, rounds + 1);
1119
1123
  }
1120
1124
  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 ` +
1125
+ engineUser(`You just said you're stuck or looping — that is the moment to CHANGE something concrete, not run the ` +
1122
1126
  `same investigation again. If you understand the root cause, apply the fix NOW with file_edit/file_write ` +
1123
1127
  `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.`);
1128
+ `are truly blocked, STOP and give the owner one line naming exactly what is blocking you and what you would try next.`);
1125
1129
  continue; // let the model act on the nudge; don't dispatch this round's repeated calls
1126
1130
  }
1127
1131
  selfLoopStreak = 0; // a round that fixes, doesn't act, or doesn't admit looping clears the streak
@@ -1150,12 +1154,25 @@ export async function runTurn(userInput, conversation, opts) {
1150
1154
  noProgressStreak = progressed ? 0 : noProgressStreak + 1; // reset the stall counter on any real progress
1151
1155
  noEditStreak = response.toolCalls.some((c) => MUTATING_TOOLS.has(c.function?.name ?? "")) ? 0 : noEditStreak + 1;
1152
1156
  trackTouchedFiles(response.toolCalls, touchedFiles);
1157
+ if (response.toolCalls.some((c) => c.function?.name === "ask_user"))
1158
+ repliesSinceOwner = -1; // the answer lands as a tool result: the next reply answers the OWNER
1159
+ // Owner-facing: narration that answers a speaker who did not speak ("You're right — …" to an engine note) is
1160
+ // redirected into a status for the owner. The round's calls already ran; the note rides into the next round.
1161
+ if (selfDialogueNudges < SELF_DIALOGUE_NUDGE_MAX && detectSelfDialogue(response.content, repliesSinceOwner)) {
1162
+ selfDialogueNudges++;
1163
+ engineUser(SELF_DIALOGUE_NUDGE);
1164
+ }
1165
+ if (response.content.trim())
1166
+ repliesSinceOwner++;
1167
+ lastReasoning = "";
1168
+ emptyRetries = 0;
1169
+ emptyNudged = false; // a productive round: the empty streak and its stale reasoning are over
1153
1170
  // Delegation-by-prose guard: the round's narration said "spawn sub-agents / delegate" but none of its calls
1154
1171
  // delegated. Nudge ONCE per turn to make the call (tasks[] for parallel work) or stop announcing it — a
1155
1172
  // nudge, never a stop; the model may legitimately decide the work is sequential after all.
1156
1173
  if (!delegationNudged && hasSpawnTool && detectAnnouncedDelegation(response.content, response.toolCalls.map((c) => c.function?.name ?? ""))) {
1157
1174
  delegationNudged = true;
1158
- conversation.user(DELEGATION_NUDGE);
1175
+ engineUser(DELEGATION_NUDGE);
1159
1176
  }
1160
1177
  // Poll-spin guard: an agent_status spin (auto-post pending, no other work, no status change) wastes the
1161
1178
  // turn — pollers are exempt from the loop guard above, so this catches them. Nudge once, then end the
@@ -1165,7 +1182,7 @@ export async function runTurn(userInput, conversation, opts) {
1165
1182
  if (ps.action === "halt")
1166
1183
  return stopTurn(ps.message, rounds + 1);
1167
1184
  if (ps.action === "nudge") {
1168
- conversation.user(ps.message);
1185
+ engineUser(ps.message);
1169
1186
  continue;
1170
1187
  }
1171
1188
  }
@@ -1174,7 +1191,7 @@ export async function runTurn(userInput, conversation, opts) {
1174
1191
  if (yg.action === "halt")
1175
1192
  return stopTurn(yg.message, rounds + 1);
1176
1193
  if (yg.action === "nudge") {
1177
- conversation.user(yg.message);
1194
+ engineUser(yg.message);
1178
1195
  continue;
1179
1196
  }
1180
1197
  }
@@ -1217,12 +1234,23 @@ export async function runTurn(userInput, conversation, opts) {
1217
1234
  noProgressStreak = progressed ? 0 : noProgressStreak + 1; // reset the stall counter on any real progress
1218
1235
  noEditStreak = recovered.calls.some((c) => MUTATING_TOOLS.has(c.function?.name ?? "")) ? 0 : noEditStreak + 1;
1219
1236
  trackTouchedFiles(recovered.calls, touchedFiles);
1237
+ if (recovered.calls.some((c) => c.function?.name === "ask_user"))
1238
+ repliesSinceOwner = -1;
1239
+ if (selfDialogueNudges < SELF_DIALOGUE_NUDGE_MAX && detectSelfDialogue(recovered.cleanedContent, repliesSinceOwner)) {
1240
+ selfDialogueNudges++;
1241
+ engineUser(SELF_DIALOGUE_NUDGE);
1242
+ }
1243
+ if (recovered.cleanedContent.trim())
1244
+ repliesSinceOwner++;
1245
+ lastReasoning = "";
1246
+ emptyRetries = 0;
1247
+ emptyNudged = false;
1220
1248
  if (pollSpin) {
1221
1249
  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
1250
  if (ps.action === "halt")
1223
1251
  return stopTurn(ps.message, rounds + 1);
1224
1252
  if (ps.action === "nudge") {
1225
- conversation.user(ps.message);
1253
+ engineUser(ps.message);
1226
1254
  continue;
1227
1255
  }
1228
1256
  }
@@ -1231,7 +1259,7 @@ export async function runTurn(userInput, conversation, opts) {
1231
1259
  if (yg.action === "halt")
1232
1260
  return stopTurn(yg.message, rounds + 1);
1233
1261
  if (yg.action === "nudge") {
1234
- conversation.user(yg.message);
1262
+ engineUser(yg.message);
1235
1263
  continue;
1236
1264
  }
1237
1265
  }
@@ -1240,7 +1268,7 @@ export async function runTurn(userInput, conversation, opts) {
1240
1268
  if (nwp.action === "halt")
1241
1269
  return stopTurn(nwp.message, rounds + 1);
1242
1270
  if (nwp.action === "warn") {
1243
- conversation.user(nwp.message);
1271
+ engineUser(nwp.message);
1244
1272
  continue;
1245
1273
  }
1246
1274
  }
@@ -1248,13 +1276,13 @@ export async function runTurn(userInput, conversation, opts) {
1248
1276
  return stopTurn(notConvergingNote(recovered.calls), rounds + 1);
1249
1277
  continue;
1250
1278
  }
1251
- const final = stripScratchpad(recovered.cleanedContent);
1279
+ const final = stripEngineEcho(stripScratchpad(recovered.cleanedContent)); // a model that echoes the marker must not show it to the owner
1252
1280
  // A tool call that could not be parsed (stray tags, cut off) must not end the turn silently: the model said it
1253
1281
  // would act and nothing ran. Tell it, once or twice, to re-emit the call as a proper tool call.
1254
1282
  if (recovered.malformed && malformedCallNudges < 2 && response.stopReason !== "length") {
1255
1283
  malformedCallNudges++;
1256
1284
  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.");
1285
+ 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
1286
  continue;
1259
1287
  }
1260
1288
  // Empty round — two very different causes, handled differently so we never (a) inject a user-role
@@ -1279,6 +1307,12 @@ export async function runTurn(userInput, conversation, opts) {
1279
1307
  // (the leak). Instead we PERTURB SAMPLING: the operator decodes greedily (temp 0), so a bit-identical
1280
1308
  // re-request reproduces the same deterministic argmax-EOS empty forever; raising the retry's temperature
1281
1309
  // is the one change that can actually escape it, and it touches nothing in the conversation.
1310
+ if (response.reasoningContent)
1311
+ lastReasoning = response.reasoningContent; // an answer that went to the reasoning channel
1312
+ if (!emptyNudged) {
1313
+ emptyNudged = true;
1314
+ engineUser(EMPTY_REPLY_NUDGE);
1315
+ } // marked as an engine note, so it cannot be read as the owner speaking
1282
1316
  retryTempOverride = emptyRetryTemp(emptyRetries); // escalate: retry 1 → 0.7, retry 2 → 1.0
1283
1317
  continue;
1284
1318
  }
@@ -1298,13 +1332,24 @@ export async function runTurn(userInput, conversation, opts) {
1298
1332
  if (response.stopReason === "length" && final && final.trim().length > 0 && truncationContinues < TRUNCATION_CONTINUE_MAX) {
1299
1333
  truncationContinues++;
1300
1334
  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.");
1335
+ 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.");
1336
+ continue;
1337
+ }
1338
+ // Owner-facing: a text-only reply that reacts to a speaker who did not speak (a stale greeting answered an hour
1339
+ // later, "you're right" to an engine note) must not end the turn as the answer — redirect it to a status.
1340
+ if (final && response.stopReason !== "length" && selfDialogueNudges < SELF_DIALOGUE_NUDGE_MAX && detectSelfDialogue(final, repliesSinceOwner)) {
1341
+ selfDialogueNudges++;
1342
+ repliesSinceOwner++;
1343
+ conversation.assistant(final);
1344
+ engineUser(SELF_DIALOGUE_NUDGE);
1302
1345
  continue;
1303
1346
  }
1347
+ if (final)
1348
+ repliesSinceOwner++;
1304
1349
  if (continuationEnabled && final && response.stopReason !== "length" && announceNudges < continuationMax && detectUnfinishedAction(final)) {
1305
1350
  announceNudges++;
1306
1351
  conversation.assistant(final);
1307
- conversation.user(ANNOUNCE_NUDGE);
1352
+ engineUser(ANNOUNCE_NUDGE);
1308
1353
  continue;
1309
1354
  }
1310
1355
  // Verify-before-done gate: the model is finalizing (no more tool calls). If this turn CHANGED files
@@ -1316,19 +1361,26 @@ export async function runTurn(userInput, conversation, opts) {
1316
1361
  if (verifyEnabled && final && verify.gate() && verifyNudges < verifyMaxNudges) {
1317
1362
  verifyNudges++;
1318
1363
  conversation.assistant(final);
1319
- conversation.user(VERIFY_REMINDER);
1364
+ engineUser(VERIFY_REMINDER);
1365
+ continue;
1366
+ }
1367
+ // Owner-facing: a final that leaves open task-list items with neither a question nor a status is a bare stop —
1368
+ // 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?.())) {
1370
+ closingNudged = true;
1371
+ conversation.assistant(final);
1372
+ engineUser(opts.unattended ? CLOSING_NUDGE_UNATTENDED : CLOSING_NUDGE);
1320
1373
  continue;
1321
1374
  }
1322
1375
  const unverified = verifyEnabled && verify.gate(); // changed files, still no passing check after the nudge
1323
1376
  const answer = (unverified ? NOT_VERIFIED_BANNER : "") +
1324
- (final || stripScratchpad(response.reasoningContent ?? "") ||
1377
+ (final || stripScratchpad(response.reasoningContent ?? "") || stripScratchpad(lastReasoning) ||
1325
1378
  (response.stopReason === "length"
1326
1379
  ? "(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.)"));
1380
+ : emptyReplyStatus(opts.preservedState?.(), emptyRetries + 1)));
1328
1381
  conversation.assistant(answer);
1329
1382
  return { content: answer, rounds: rounds + 1, toolCalls: toolCallTotal, stopReason: response.stopReason, tokens: tokensTotal, genMs: genMsTotal, promptTokens: promptTokensTotal, promptMs: promptMsTotal, unverified: unverified || undefined };
1330
1383
  }
1331
1384
  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 };
1385
+ return stopTurn(timeoutMsg, rounds);
1334
1386
  }
@@ -183,10 +183,13 @@ export function pickSummaryContent(content, reasoning) {
183
183
  return (reasoning ?? "").trim();
184
184
  }
185
185
  /** A "turn" starts at a user message. Returns the index of each turn start, in order. */
186
+ /** An engine-injected user-role message (nudges, reminders, notes — continuation.ts::engineNote) is not a turn the
187
+ * owner started and not the owner's voice: compaction must neither count it as a turn boundary nor quote it back. */
188
+ const isEngineNote = (m) => typeof m.content === "string" && m.content.startsWith("[engine note");
186
189
  export function turnStarts(conversation) {
187
190
  const idxs = [];
188
191
  conversation.forEach((m, i) => {
189
- if (m.role === "user")
192
+ if (m.role === "user" && !isEngineNote(m))
190
193
  idxs.push(i);
191
194
  });
192
195
  return idxs;
@@ -316,7 +319,7 @@ export function applyAnchorVerification(summaryMsg, evicted, outAll) {
316
319
  * exactly the shape frontier compaction uses (objective pinned at head, recency at tail) and keeps the
317
320
  * block bounded regardless of span depth. */
318
321
  export function verbatimUserTail(span, k = 3, capPerMsg = 400) {
319
- const users = span.filter((m) => m.role === "user" && typeof m.content === "string" && m.content.trim().length > 0);
322
+ const users = span.filter((m) => m.role === "user" && typeof m.content === "string" && m.content.trim().length > 0 && !isEngineNote(m));
320
323
  if (!users.length)
321
324
  return "";
322
325
  const head = users[0];
@@ -69,3 +69,101 @@ export function detectAnnouncedDelegation(content, calledTools) {
69
69
  const text = (content ?? "").trim();
70
70
  return !!text && DELEGATION_RE.test(text);
71
71
  }
72
+ // ── Owner-facing turns (0.1.331) ─────────────────────────────────────────────────────────────────────────────
73
+ // Every mid-turn nudge the engine injects rides in the USER role (the only role a chat template lets a second voice
74
+ // use), so a model read them as the owner speaking and answered them in conversation — "You're right — I wrote
75
+ // compose blocks without validating them" to a verify-gate reminder, and a stale "hello operator" answered an hour
76
+ // later with "Hey. What's the play?". The owner saw a model talking to itself. Three rules fix the shape:
77
+ // 1. an engine note is MARKED as such, so the model can tell it from the owner;
78
+ // 2. a reply that reacts to a speaker who did not speak (after round 0 nothing but tool results and engine notes
79
+ // arrive) is redirected into a one-line status for the owner;
80
+ // 3. a turn never ends on nothing: an empty reply gets one reframed retry and then an engine-composed status, and
81
+ // a final with open tasks and no question or report gets one nudge to close with a status plus a steering
82
+ // question — the owner is always left with something to answer, never a silent stop.
83
+ /** Prefix every engine-injected user-role message so the model never mistakes it for the owner. */
84
+ export const ENGINE_NOTE_PREFIX = "[engine note — automatic, not from the owner] ";
85
+ export function engineNote(text) {
86
+ return text.startsWith(ENGINE_NOTE_PREFIX) ? text : ENGINE_NOTE_PREFIX + text;
87
+ }
88
+ export const SELF_DIALOGUE_NUDGE_MAX = 2;
89
+ export const SELF_DIALOGUE_NUDGE = "Nobody spoke: the owner has sent nothing new since they last wrote, and engine notes are not the owner. Do not " +
90
+ "answer an imagined message, do not write a line for the owner and reply to it, and do not quote or paraphrase an " +
91
+ "owner message that is not in the conversation. Give the owner ONE line of status addressed to them (what is done, " +
92
+ "what you are doing now), then continue the task.";
93
+ // Concessions and acknowledgements that only make sense as a reply to a NEW message — not references to the original
94
+ // request ("as you asked, here it is" is a normal closing line).
95
+ const REACTION_RE = /\b(?:you['’]re (?:right|correct)|you are (?:right|correct)|good (?:question|point|catch)|fair (?:point|enough)|you are (?:calling|asking) me|the user (?:just )?(?:said|says|is (?:calling|asking|pointing)|called|asked|wants|pointed)|thanks for (?:pointing|the (?:reminder|nudge|catch)))\b/i;
96
+ // A fabricated exchange inside one reply: a greeting/question line written FOR the owner and then answered below it
97
+ // (a greeting-question that IS the whole reply is a real question to the owner).
98
+ const FABRICATED_LINE_RE = /^(?:hey|hi|hello|yo)\b[^\n]{0,60}\?[ \t]*\n+\s*\S/im;
99
+ // A speaker-labelled line the model wrote for someone else: "User: …", "Owner: …", "> continue".
100
+ const SPEAKER_LABEL_RE = /^(?:user|owner|human|james|you)\s*:\s*\S/im;
101
+ // A reply that is NOTHING but a greeting, after the owner has already been answered in this turn: the model is
102
+ // replying to a stale "hello" from the start of the conversation ("Hey. What's the play?" an hour into a fix round).
103
+ const GREETING_ONLY_RE = /^(?:hey|hi|hello|yo)\b[^\n]{0,80}$/i;
104
+ /** True when a model reply reacts to a speaker who did not speak. `repliesSinceOwner` is 0 for the first model
105
+ * reply after the owner wrote — the turn's first real reply, or the one right after an ask_user answer landed —
106
+ * where acknowledging (or greeting) is fine. */
107
+ export function detectSelfDialogue(content, repliesSinceOwner) {
108
+ if (repliesSinceOwner < 1)
109
+ return false;
110
+ const text = (content ?? "").trim();
111
+ if (!text)
112
+ return false;
113
+ return REACTION_RE.test(text) || FABRICATED_LINE_RE.test(text) || SPEAKER_LABEL_RE.test(text) || GREETING_ONLY_RE.test(text);
114
+ }
115
+ /** A model that was just told what the marker means may echo it back; the owner must never see it. */
116
+ export function stripEngineEcho(content) {
117
+ return (content ?? "").replace(/^\s*\[engine note[^\]]*\]\s*/i, "").replace(/^\s*engine note:\s*/i, "");
118
+ }
119
+ export const CLOSING_NUDGE = "You are about to end this turn with work still open and no question for the owner. Either continue the open " +
120
+ "items now, or close properly: one line of status per open item (done / in progress / blocked and why) and " +
121
+ "ONE question whose answer steers the next step. Never end on a bare stop.";
122
+ /** Unattended runs have nobody to answer a question: close with the status and the next step instead. */
123
+ export const CLOSING_NUDGE_UNATTENDED = "You are about to end this turn with work still open. Either continue the open items now, or close properly: one " +
124
+ "line of status per open item (done / in progress / blocked and why) and the next step you will take when resumed. " +
125
+ "Never end on a bare stop.";
126
+ const QUESTION_RE = /[??]\s*(?:\*\*|_)?\s*$/m;
127
+ // A labelled status report ("Status: …", "## Progress", "Open items —"), not a sentence that merely starts with "done".
128
+ const STATUS_RE = /^(?:#{1,4}\s*|\*\*)?(?:status|where (?:things|we) (?:stand|are)|progress|open items?|next steps?|blocked(?: on)?)\b\s*(?:\*\*)?\s*[:—–-]/im;
129
+ // A final that names remaining work without a task list ("cameras and lights are still to do").
130
+ const REMAINING_RE = /\b(?:still to do|still (?:need|needs|remain)|remaining|left to do|to do next|not (?:yet )?done|haven['’]t (?:done|finished|started)|next up)\b/i;
131
+ /** True when a text-only final should not end the turn as is: work remains (open task-list items, or — with no task
132
+ * list — the text itself names remaining work) and the text neither asks the owner anything, hands back, nor
133
+ * reports status. A hand-back ("let me know…") or a report already leaves the owner with something to act on. */
134
+ export function needsClosingSteer(content, hasOpenTasks) {
135
+ const text = (content ?? "").trim();
136
+ if (!hasOpenTasks && !(text && REMAINING_RE.test(text)))
137
+ return false;
138
+ if (!text)
139
+ return true;
140
+ if (QUESTION_RE.test(text))
141
+ return false;
142
+ if (HANDBACK_RE.test(text) || SUMMARY_RE.test(text) || STATUS_RE.test(text))
143
+ return false;
144
+ return true;
145
+ }
146
+ /** True for a final the ENGINE wrote (a stop/pause/yield note or the no-reply status) rather than the model — the
147
+ * flywheel must not grade it as the model's answer and a planner must not accept it as a sub-agent's result. */
148
+ export function isEngineFinal(content) {
149
+ return /^\s*(?:\[(?:stopped|paused|turn ended|no reply came back from the model)\b|\((?:the model returned an empty response|hit the output limit before an answer landed))/i.test(content ?? "");
150
+ }
151
+ export const EMPTY_REPLY_NUDGE = "Your reply was empty. Answer the owner now in plain text: what is done, what you are doing or about to do, and " +
152
+ "one question if you are blocked. If a tool call is needed, make the call — but never return nothing.";
153
+ /** The active task list as the owner should read it — without the compaction header renderActiveTasks() carries. */
154
+ function tasksBlock(activeTasks) {
155
+ const t = (activeTasks ?? "").replace(/^\[Your active task list[^\n]*\]\n?/, "").trim();
156
+ return t ? `\n\nOpen items:\n${t}` : "";
157
+ }
158
+ /** The engine's own closing status when the model gives nothing: the active task list (when any) and a steer. */
159
+ export function emptyReplyStatus(activeTasks, tries) {
160
+ const tasks = tasksBlock(activeTasks) || "\n\nNo open items on the task list.";
161
+ return `[no reply came back from the model after ${tries} tries. Where things stand:${tasks}\n\nTell me which step to take next, or say "continue" to resume from here.]`;
162
+ }
163
+ /** Append the active task list and a steer to an engine stop note. A yield note (sub-agents will resume the turn)
164
+ * gets the list only — asking the owner to steer there would contradict "nothing needed from you". */
165
+ export function closeStopNote(note, activeTasks) {
166
+ const yielded = /sub-agents? (?:are running|dispatched)|waiting on sub-agents/i.test(note);
167
+ const steer = yielded ? "" : `\n\nTo steer: tell me which step to take next, or say "continue" to resume from here.`;
168
+ return note + tasksBlock(activeTasks) + steer;
169
+ }
@@ -0,0 +1,83 @@
1
+ // Live progress journal: progress is saved WHILE a turn runs, not only when the model remembers to call
2
+ // session_handoff or when compaction fires. After every tool round that changed something (a landed file write/edit
3
+ // or a task_* call) the shell rewrites one marker-delimited block at the END of the per-working-directory handoff
4
+ // file — the file the next session in this directory auto-loads ("continue from where it leaves off"). A mid-flight
5
+ // cutoff (a killed session, a wedged model, an empty reply) therefore loses nothing the owner would have to ask for:
6
+ // the request, the task list with its states, the files touched and the last thing the model said are already on
7
+ // disk. The block is keyed by session (two tabs in one directory keep their own), rewritten atomically (tmp +
8
+ // rename, so ENOSPC or a kill mid-write never truncates the owner's handoff), budgeted to fit the 6000-char tail the
9
+ // persona loads, and settled ("turn completed") when the turn ends normally so a finished turn is never offered as
10
+ // something to resume.
11
+ import { existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from "node:fs";
12
+ import { dirname, relative, isAbsolute } from "node:path";
13
+ export const LIVE_START = "<!-- live-progress:start";
14
+ export const LIVE_END = "<!-- live-progress:end -->";
15
+ const MUTATING = new Set(["file_write", "file_edit", "task_add", "task_update", "task_clear"]);
16
+ const MAX_FILES = 12;
17
+ const MAX_TASK_CHARS = 80;
18
+ const MAX_BLOCK_CHARS = 1500;
19
+ const ERROR_RESULT = /^\s*(?:error\b|loop guard|permission denied)/i;
20
+ const landed = (e) => !ERROR_RESULT.test(e.result ?? "");
21
+ /** True when a tool round changed state worth journaling (a failed write is not progress). */
22
+ export function roundProgressed(events) {
23
+ return events.some((e) => MUTATING.has(e.name) && landed(e));
24
+ }
25
+ /** The file paths a round actually touched (file_write / file_edit `path` whose result was not an error). */
26
+ export function touchedPaths(events) {
27
+ return events.filter((e) => (e.name === "file_write" || e.name === "file_edit") && landed(e)).map((e) => String(e.args?.path ?? "")).filter(Boolean);
28
+ }
29
+ const MARK = { pending: "[ ]", in_progress: "[>]", done: "[x]", cancelled: "[~]" };
30
+ const openTag = (session) => `${LIVE_START} ${session} -->`;
31
+ const clip = (s, n) => (s.length <= n ? s : s.slice(0, n - 1) + "…");
32
+ const rel = (p, cwd) => (cwd && isAbsolute(p) && p.startsWith(cwd) ? relative(cwd, p) || "." : p);
33
+ /** Pure: the block as it lands in the handoff file (budgeted to stay inside the tail the next session reads). */
34
+ export function liveProgressBlock(p) {
35
+ const at = (p.at ?? new Date()).toISOString();
36
+ const head = p.completed
37
+ ? `## Live progress — turn completed ${at} (nothing to resume from here)`
38
+ : `## Live progress (auto-saved ${at}) — the turn may have been cut off here; resume from this`;
39
+ const tasks = p.tasks.length
40
+ ? p.tasks.map((t) => `${MARK[t.status] ?? "[ ]"} #${t.id} ${clip(t.text.replace(/\s+/g, " "), MAX_TASK_CHARS)} (${t.status})`).join("\n")
41
+ : "(no task list this turn)";
42
+ const files = [...new Set(p.touched.map((f) => rel(f, p.cwd)))];
43
+ const shown = files.slice(-MAX_FILES);
44
+ const fileList = shown.length ? shown.join("\n") + (files.length > shown.length ? `\n(+${files.length - shown.length} earlier)` : "") : "(none yet)";
45
+ const body = [
46
+ head,
47
+ `REQUEST: ${clip(p.request.replace(/\s+/g, " ").trim(), 400)}`,
48
+ `TASKS:\n${tasks}`,
49
+ `FILES TOUCHED THIS TURN:\n${fileList}`,
50
+ p.narration?.trim() ? `LAST SAID: ${clip(p.narration.replace(/\s+/g, " ").trim(), 300)}` : "",
51
+ ].filter(Boolean).join("\n");
52
+ return `${openTag(p.session)}\n${clip(body, MAX_BLOCK_CHARS)}\n${LIVE_END}\n`;
53
+ }
54
+ /** Remove THIS session's block (complete, or half-written after a crash) from the handoff text. */
55
+ function withoutOwnBlock(text, session) {
56
+ const tag = openTag(session).replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
57
+ const end = LIVE_END.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
58
+ return text
59
+ .replace(new RegExp(`\\n?${tag}[\\s\\S]*?${end}\\n?`, "g"), "")
60
+ .replace(new RegExp(`\\n?${tag}[\\s\\S]*$`), "") // an unterminated block = the previous write died mid-way
61
+ .replace(/\s+$/, "");
62
+ }
63
+ /** Rewrite this session's live block at the end of `file`, atomically (tmp + rename). Best-effort; never throws. */
64
+ export function recordLiveProgress(file, p) {
65
+ if (!file)
66
+ return false;
67
+ try {
68
+ mkdirSync(dirname(file), { recursive: true });
69
+ const cur = existsSync(file) ? readFileSync(file, "utf8") : "";
70
+ const kept = withoutOwnBlock(cur, p.session);
71
+ const tmp = `${file}.${p.session}.tmp`;
72
+ writeFileSync(tmp, (kept ? kept + "\n\n" : "") + liveProgressBlock(p), { encoding: "utf8", mode: 0o600 });
73
+ renameSync(tmp, file);
74
+ return true;
75
+ }
76
+ catch {
77
+ return false;
78
+ }
79
+ }
80
+ /** The turn ended normally: mark the block completed so the next session is not told to resume a finished turn. */
81
+ export function settleLiveProgress(file, p) {
82
+ return recordLiveProgress(file, { ...p, completed: true });
83
+ }
@@ -5,6 +5,7 @@
5
5
  // (same mobile/JSCore-bundle discipline as services/preflight.ts) so the neutral bundle carries none of it.
6
6
  import { operatorPath } from "../config/home.js";
7
7
  import { redactSecrets } from "../engine/redact.js";
8
+ import { isEngineFinal } from "../engine/continuation.js"; // a stop/pause/no-reply note is the engine's text, never a promotable answer
8
9
  const nodeImport = (m) => import(/* @vite-ignore */ m);
9
10
  // GW-18 (flywheel gate): markers of a STRUCTURED tool call that leaked into the assistant's plain text instead
10
11
  // of being parsed into tool_calls — the documented Qwen3 failure when the server runs without `--jinja` (the
@@ -36,7 +37,7 @@ async function captureFlywheel(r) {
36
37
  // prose (self-poisoning) — exclude it from promotable rows AND tag it so the pipeline can audit leak rate
37
38
  // and the serving side (GW-01/GW-18 `--jinja`) can be verified by the trend going to ~0.
38
39
  const parseFallback = hasLeakedToolCall(r.content);
39
- const graded = !!r.content.trim() && r.stopReason !== "repetition" && r.rounds > 0 && !r.unverified && !parseFallback;
40
+ const graded = !!r.content.trim() && r.stopReason !== "repetition" && r.rounds > 0 && !r.unverified && !parseFallback && !isEngineFinal(r.content);
40
41
  // The row carries the user's PROMPT and the full answer, and the corpus is read by the training pipeline —
41
42
  // mask known secret shapes before they reach disk (the same boundary events.jsonl enforces) and keep the
42
43
  // file owner-only; this used to be a 0644 file in a 0755 dir with raw prompts in it.
@@ -6,7 +6,7 @@
6
6
  //
7
7
  // TWO tiers, and the split is the whole point:
8
8
  // • Aurora (:8097) is SHARED, always-on infrastructure owned by launchd — the mobile app (via
9
- // com.imi.aurora-tunnel), api.axe.onl / aurora.axe.onl, and LAN web clients all read it. Operator
9
+ // ai.operator.tunnel), api.axe.onl / aurora.axe.onl, and LAN web clients all read it. Operator
10
10
  // only ever brings it UP (kickstart, else bootstrap, the launchd job); it NEVER stops Aurora on exit,
11
11
  // because that would break every other client. launchd's KeepAlive is the real supervisor — the
12
12
  // lever just makes sure the job is loaded and the port is live before the REPL opens.
package/dist/session.js CHANGED
@@ -1184,7 +1184,7 @@ export class Session {
1184
1184
  spill: spillToolOutput, // GW-10-COMPLETE: runTurn's fitToWindow offloads (node host)
1185
1185
  systemPrompt: sys,
1186
1186
  summarize: this.summarize,
1187
- preservedState: () => renderActiveTasks() ?? undefined, // a mid-turn compaction keeps the active task list
1187
+ preservedState: this.background ? undefined : () => renderActiveTasks() ?? undefined, // a mid-turn compaction keeps the active task list — the FOREGROUND's; the list is one module store, so a sub-agent must not see (or close on) the owner's items
1188
1188
  background: this.background, // endpoint gate: a sub-agent's rounds yield the shared slot to the main turn
1189
1189
  liveSubAgents: this.wakeTurn ? this.liveAgents : undefined, // a wake turn with sub-agents live yields from its first idle round
1190
1190
  maxTokens: this.maxTokens,
@@ -15,6 +15,7 @@
15
15
  // node-only; imported lazily from the tool layer so the neutral (mobile) bundle never pulls it.
16
16
  import { wrapInteractiveShell } from "./sandbox.js";
17
17
  import { ownChild } from "../util/owned-children.js";
18
+ import { scratchDirFor } from "../config/scratch.js";
18
19
  // Variable-specifier dynamic import: esbuild --platform=neutral (the mobile/JSCore purity gate)
19
20
  // STATICALLY resolves a string-literal `import("node:...")` and errors on it, but cannot resolve a
20
21
  // variable specifier, so the Node builtin stays out of the neutral bundle. Same idiom as
@@ -69,7 +70,7 @@ export class ShellSession {
69
70
  const { file, args } = await wrapInteractiveShell();
70
71
  const p = spawn(file, args, {
71
72
  cwd: this.cwd,
72
- env: { ...process.env, PS1: "", PROMPT_COMMAND: "", TERM: "dumb" },
73
+ env: { ...process.env, OPERATOR_SCRATCH: scratchDirFor(this.cwd ?? process.cwd()), PS1: "", PROMPT_COMMAND: "", TERM: "dumb" }, // per-session scratch: an ACP process hosts many cwds
73
74
  stdio: ["pipe", "pipe", "pipe"],
74
75
  detached: true, // own process group, so killShell() can reap grandchildren (`&` jobs), not just bash
75
76
  });
@@ -365,7 +366,7 @@ export async function runEphemeralShell(command, timeoutMs = 120_000, cwd) {
365
366
  return new Promise((resolve) => {
366
367
  const p = spawn(file, args, {
367
368
  cwd,
368
- env: { ...process.env, PS1: "", PROMPT_COMMAND: "", TERM: "dumb" },
369
+ env: { ...process.env, OPERATOR_SCRATCH: scratchDirFor(cwd ?? process.cwd()), PS1: "", PROMPT_COMMAND: "", TERM: "dumb" },
369
370
  stdio: ["ignore", "pipe", "pipe"],
370
371
  detached: true,
371
372
  });
package/dist/ui/App.js CHANGED
@@ -36,7 +36,7 @@ function BackgroundHint({ rows }) {
36
36
  return hint ? _jsx(Text, { dimColor: true, children: ` · ${hint}` }) : null;
37
37
  }
38
38
  export function App(props) {
39
- const { messages, live = null, status, thinkingVerb, verbs, stepLabel, prefill = "", liveTools = [], route, ctxPct, version, build, fullscreen = false, metrics, sessionTokens, authUser, tier, planMode, thinkMode, bgAgents, shellJobs = [], onBackground, tasks = [], onSubmit, onQueue, queuedPreview = "", onInterrupt, onCycleMode, opMode, rcConnected = false, rcActive = false, approval = null, onApprovalDecide, question = null, modelPicker = null, planExitPicker = null, artifactsPicker = null, sessionsPicker = null } = props;
39
+ const { messages, live = null, status, thinkingVerb, verbs, stepLabel, prefill = "", liveTools = [], route, ctxPct, version, build, fullscreen = false, metrics, sessionTokens, authUser, tier, planMode, thinkMode, bgAgents, shellJobs = [], onBackground, tasks = [], onSubmit, onQueue, queuedPreview = "", onInterrupt, onCycleMode, opMode, rcConnected = false, rcActive = false, caffeinated = false, approval = null, onApprovalDecide, question = null, modelPicker = null, planExitPicker = null, artifactsPicker = null, sessionsPicker = null } = props;
40
40
  useTerminalSize(); // subscribe so the inline pinned UI (status rule, composer, footer) reflows the instant the terminal resizes
41
41
  const thinking = status === "thinking" || status === "streaming";
42
42
  // A parallel batch (2+ live rows) gets its own per-call view instead of the single-line StepSpinner —
@@ -51,7 +51,7 @@ export function App(props) {
51
51
  // be scrolled off. The Composer is `suspended` (keystrokes route to the decision, not the draft).
52
52
  const prompts = (_jsxs(_Fragment, { children: [_jsx(ApprovalPrompt, { approval: approval, onDecide: onApprovalDecide ?? (() => { }) }), _jsx(QuestionPrompt, { pending: question }), _jsx(QuestionPrompt, { pending: modelPicker }), _jsx(QuestionPrompt, { pending: planExitPicker }), _jsx(ArtifactPicker, { pending: artifactsPicker }), _jsx(SessionPicker, { pending: sessionsPicker })] }));
53
53
  // The pinned bottom band: status rule, composer, bottom rule, then the mode/cycle FOOTER below the rule.
54
- const bottom = (_jsxs(_Fragment, { children: [_jsx(StatusRule, { route: route, ctxPct: ctxPct, version: version, build: build, user: authUser, tier: tier, planMode: planMode, thinkMode: thinkMode, sessionTokens: sessionTokens }), queuedPreview ? (_jsx(Text, { color: "yellow", children: `⏎ queued · sends when this turn ends (Esc to send now): ${queuedPreview.replace(/\n/g, " / ").slice(0, 120)}${queuedPreview.length > 120 ? "…" : ""}` })) : null, _jsx(Composer, { onSubmit: onSubmit, onQueue: onQueue, onInterrupt: onInterrupt, onBackground: onBackground, onCycleMode: onCycleMode, disabled: status !== "idle", suspended: !!approval || !!question || !!modelPicker || !!planExitPicker || !!artifactsPicker || !!sessionsPicker }), _jsx(InputRule, {}), opMode && (_jsxs(Box, { justifyContent: "space-between", children: [_jsx(Text, { dimColor: true, children: ` ${opMode === "auto" ? "⎈ Autonomous" : opMode === "manual" ? "⊙ Manual" : "◑ Plan"} · shift+tab to cycle` }), _jsx(Text, { color: rcConnected ? "green" : rcActive ? "yellow" : "gray", bold: rcConnected || rcActive, dimColor: !rcConnected && !rcActive, children: `${rcConnected ? "▮ rc live" : rcActive ? "▮ rc on" : "▯ rc"} ` })] }))] }));
54
+ const bottom = (_jsxs(_Fragment, { children: [_jsx(StatusRule, { route: route, ctxPct: ctxPct, version: version, build: build, user: authUser, tier: tier, planMode: planMode, thinkMode: thinkMode, sessionTokens: sessionTokens }), queuedPreview ? (_jsx(Text, { color: "yellow", children: `⏎ queued · sends when this turn ends (Esc to send now): ${queuedPreview.replace(/\n/g, " / ").slice(0, 120)}${queuedPreview.length > 120 ? "…" : ""}` })) : null, _jsx(Composer, { onSubmit: onSubmit, onQueue: onQueue, onInterrupt: onInterrupt, onBackground: onBackground, onCycleMode: onCycleMode, disabled: status !== "idle", suspended: !!approval || !!question || !!modelPicker || !!planExitPicker || !!artifactsPicker || !!sessionsPicker }), _jsx(InputRule, {}), opMode && (_jsxs(Box, { justifyContent: "space-between", children: [_jsx(Text, { dimColor: true, children: ` ${opMode === "auto" ? "⎈ Autonomous" : opMode === "manual" ? "⊙ Manual" : "◑ Plan"} · shift+tab to cycle` }), _jsx(Text, { color: rcConnected ? "green" : rcActive ? "yellow" : "gray", bold: rcConnected || rcActive, dimColor: !rcConnected && !rcActive, children: `${caffeinated ? "☕ " : ""}${rcConnected ? "▮ rc live" : rcActive ? "▮ rc on" : "▯ rc"} ` })] }))] }));
55
55
  // Fullscreen (opt-in): a full-terminal-height column. The transcript fills a clipped, bottom-anchored
56
56
  // region (non-Static tail) so the newest output sits just above a composer pinned to the very bottom —
57
57
  // no dead space. Off by default: inline keeps the terminal's native scrollback (mouse-scroll + copy).
@@ -0,0 +1,52 @@
1
+ // Keep the Mac awake while Operator runs. A long autonomous turn on a laptop dies with the lid's idle timer; the owner
2
+ // has been running `caffeinate` by hand in every terminal tab. macOS ships `caffeinate`; `-w <pid>` ties the
3
+ // assertion to THIS process so it can never outlive the session; `-i -m -s` keep the system, disk and (on AC) sleep
4
+ // assertions up without holding the DISPLAY awake — the screen may still dim and lock while the model works, which
5
+ // is the right default for a machine left in an office overnight (`-d` is a deliberate non-default). No-op anywhere
6
+ // else (platform gate) or when the binary is missing.
7
+ import { spawn } from "node:child_process";
8
+ import { existsSync } from "node:fs";
9
+ import { ownChild } from "./owned-children.js";
10
+ export const CAFFEINATE_BIN = "/usr/bin/caffeinate";
11
+ /** Pure: the argv for the given pid. `-w` makes caffeinate exit when that pid exits. */
12
+ export function caffeinateArgs(pid) {
13
+ return ["-ims", "-w", String(pid)];
14
+ }
15
+ /** Settings then env (env wins): `KODE_CAFFEINATE=0` or `settings.caffeinate === false` turns it off. Default ON. */
16
+ export function caffeinateEnabled(setting, env = process.env) {
17
+ if (env.KODE_CAFFEINATE === "0" || env.KODE_CAFFEINATE === "false")
18
+ return false;
19
+ if (env.KODE_CAFFEINATE === "1" || env.KODE_CAFFEINATE === "true")
20
+ return true;
21
+ return setting !== false;
22
+ }
23
+ const INERT = { active: false, stop: () => { } };
24
+ /** Start the assertion for `pid` (default: this process). Returns an inert handle when unsupported. */
25
+ export function startCaffeinate(pid = process.pid, platformName = process.platform, bin = CAFFEINATE_BIN) {
26
+ if (platformName !== "darwin" || !existsSync(bin))
27
+ return INERT;
28
+ let child;
29
+ try {
30
+ child = spawn(bin, caffeinateArgs(pid), { stdio: "ignore", detached: false });
31
+ }
32
+ catch {
33
+ return INERT;
34
+ }
35
+ if (!child.pid)
36
+ return INERT;
37
+ ownChild(child, "caffeinate", { cmd: `${bin} ${caffeinateArgs(pid).join(" ")}` }); // killed at exit, reaped if we crash (-w ties it to this pid as well)
38
+ let alive = true;
39
+ child.once("exit", () => { alive = false; });
40
+ child.once("error", () => { alive = false; });
41
+ const started = child;
42
+ return {
43
+ get active() { return alive; },
44
+ get pid() { return started.pid; },
45
+ stop: () => { if (alive) {
46
+ try {
47
+ started.kill("SIGTERM");
48
+ }
49
+ catch { /* already gone */ }
50
+ } alive = false; },
51
+ };
52
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@0perator/operator",
3
- "version": "0.1.329",
3
+ "version": "0.1.331",
4
4
  "type": "module",
5
5
  "bin": {
6
6
  "operator": "dist/cli.js",