@0perator/operator 0.1.277 → 0.1.282

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.
package/dist/acp/agent.js CHANGED
@@ -19,6 +19,7 @@ import { hasByoToken } from "../auth/byo.js";
19
19
  import { operatorPath } from "../config/home.js";
20
20
  import { redactSecrets } from "../engine/redact.js";
21
21
  import { EventSink } from "../telemetry/events.js";
22
+ import { centralRecording } from "../telemetry/ingest.js";
22
23
  import { PermissionPolicy } from "../permissions/index.js";
23
24
  import { signatureLine } from "../permissions/signature.js";
24
25
  import { allowSandboxWriteRoot } from "../tools/sandbox.js";
@@ -107,7 +108,8 @@ export class OperatorAcpAgent {
107
108
  get actor() {
108
109
  return { tier: this.settings.permissions?.tier ?? "admin", surface: "acp", sub: this.subject ?? this.settings.seat?.sub, ...this.actorOverride };
109
110
  }
110
- get audits() { return new PermissionPolicy(this.settings.permissions ?? {}).audits; }
111
+ // Audited seat, or signed in / events URL configured (the central ledger records an unenforced owner too).
112
+ get audits() { return new PermissionPolicy(this.settings.permissions ?? {}).audits || centralRecording(); }
111
113
  async initialize(params) {
112
114
  // Spec: answer the client's version when we speak it, else our latest. We speak exactly PROTOCOL_VERSION.
113
115
  void params;
@@ -168,7 +170,10 @@ export class OperatorAcpAgent {
168
170
  throw e;
169
171
  }
170
172
  this.sessions.set(sid, live);
171
- this.audit(auditId, { event: "session_start", detail: `surface=acp tier=${this.actor.tier} mode=${this.settings.permissions?.mode ?? "bypass"} cwd=${cwd}` });
173
+ // model + version make this a tracked session for the central ledger (telemetry/ingest.ts); a factory whose session
174
+ // exposes no model (a test fake) stays local-only.
175
+ const model = live.session.currentModel?.();
176
+ this.audit(auditId, { event: "session_start", detail: `surface=acp tier=${this.actor.tier} mode=${this.settings.permissions?.mode ?? "bypass"} cwd=${cwd}`, ...(model ? { model, version: agentVersion() } : {}) });
172
177
  // GW-40: the stabilized configOptions surface (Zed dropdown for new clients; the SDK-0.4.5 legacy
173
178
  // set_model below for current ones). Extra field on the response — the SDK validates REQUESTS only.
174
179
  return { sessionId: sid, configOptions: [this.modelOption(sid)] };
@@ -283,7 +288,7 @@ export class OperatorAcpAgent {
283
288
  rmSync(live.summaryPath, { force: true });
284
289
  }
285
290
  catch { /* derived artifact; nothing to keep */ }
286
- this.audit(live.auditId, { event: "session_end", detail: reason });
291
+ this.audit(live.auditId, { event: "session_end", detail: reason, outcome: reason === "client_closed" ? "ok" : "interrupted" });
287
292
  }
288
293
  settleApprovals(live, allow) {
289
294
  for (const settle of [...live.pending])
@@ -48,6 +48,7 @@ export function openBrowser(url) {
48
48
  const cmd = os === "darwin" ? "open" : os === "win32" ? "cmd" : "xdg-open";
49
49
  const args = os === "win32" ? ["/c", "start", "", url] : [url];
50
50
  try {
51
+ // owned-exempt: opens the sign-in page in the user's browser, then is gone; it must outlive this command
51
52
  const child = spawn(cmd, args, { stdio: "ignore", detached: true });
52
53
  child.on("error", () => { });
53
54
  child.unref();
@@ -11,6 +11,7 @@
11
11
  // builtins and the node-bound session factory load lazily via the nodeImport idiom (same as autonomy/cron.ts).
12
12
  import { modelRegistry, selectModel, endpointBase } from "../router/models.js";
13
13
  import { MemoryStore } from "../memory/index.js";
14
+ import { delegateBrief } from "../engine/grandmaster.js";
14
15
  const nodeImport = (m) => import(/* @vite-ignore */ m);
15
16
  /** Model a delegation lands on when the planner names none — the fast local tier. */
16
17
  export const DEFAULT_DELEGATE_MODEL = "scout";
@@ -65,18 +66,12 @@ export function deriveDelegateSettings(base, profile) {
65
66
  mcp: false,
66
67
  };
67
68
  }
68
- /** The user message the sub-agent receives: the planner's task, framed so a model with no conversation
69
- * history knows its last message is what comes back, and that it can't ask or delegate. */
69
+ /** The user message the sub-agent receives: the planner's task, framed with the SAME enterprise brief
70
+ * structure spawn_agent uses (Role → Objective → Context → Deliverable → Definition of done), closing with
71
+ * delegate's verbatim-result convention. One shared standard (grandmaster.delegateBrief) keeps delegate_task
72
+ * and spawn_agent briefs consistent instead of this path emitting a thinner, free-form preamble. */
70
73
  function briefFor(task) {
71
- return [
72
- "You are a delegated sub-agent. A planner handed you ONE self-contained subtask; it cannot answer questions",
73
- "and cannot see your work — only your final message is returned to it, verbatim. Do the subtask with your",
74
- "tools, then reply with just the result (concise, no preamble). If you cannot finish, say exactly what blocked",
75
- "you. You cannot delegate further.",
76
- "",
77
- "## Subtask",
78
- task,
79
- ].join("\n");
74
+ return delegateBrief({ objective: task }, process.cwd());
80
75
  }
81
76
  /** The turn loop hands back its OWN "no answer" notes as ordinary `content`: `[stopped …]` / `[paused …]` (the
82
77
  * flywheel-prefix contract, _ai-docs/conventions) and the two parenthesized empty-reply notes in engine/agent.ts.
@@ -27,10 +27,12 @@ export function startKeepAwake(reason = "Operator autonomous run") {
27
27
  if (process.platform === "darwin") {
28
28
  // -d display, -i idle, -m disk, -s system; -u declares user activity; -w waits on our pid so the
29
29
  // OS tears caffeinate down if we die without calling stop().
30
+ // owned-exempt: `-w <our pid>` makes the OS stop caffeinate when we die, however we die; stop() + the exit hook below also kill it
30
31
  child = spawn("caffeinate", ["-dimsu", "-w", String(process.pid)], { stdio: "ignore" });
31
32
  method = "caffeinate";
32
33
  }
33
34
  else if (process.platform === "linux" && linuxHasSystemdInhibit()) {
35
+ // owned-exempt: reaped by stop() and the exit/SIGINT/SIGTERM hooks registered below (headless runs only)
34
36
  child = spawn("systemd-inhibit", ["--what=idle:sleep", `--why=${reason}`, "--mode=block", "sleep", "infinity"], { stdio: "ignore" });
35
37
  method = "systemd-inhibit";
36
38
  }
@@ -206,6 +206,11 @@ export async function launchChrome() {
206
206
  }
207
207
  catch { /* best-effort; e2e scan is the backstop */ }
208
208
  const proc = spawn(exe, chromeArgv(0, profileDir), { stdio: ["ignore", "ignore", "pipe"], detached: false });
209
+ try { // killed at exit, reaped if we crash (Chrome outlives a SIGKILLed parent). Lazy like every import here; never blocks the launch.
210
+ const { ownChild } = await nodeImport("../util/owned-children.js");
211
+ ownChild(proc, "chrome", { cmd: exe });
212
+ }
213
+ catch { /* tracking is best-effort */ }
209
214
  const wsUrl = await new Promise((res, rej) => {
210
215
  let buf = "";
211
216
  const to = setTimeout(() => rej(new Error(`browser: Chrome printed no DevTools URL within ${LAUNCH_TIMEOUT_MS / 1000}s${buf ? `; stderr tail: ${buf.slice(-300)}` : ""}`)), LAUNCH_TIMEOUT_MS);
package/dist/cli.js CHANGED
@@ -32,15 +32,21 @@ import { modelCtxFor, LEAN_HARNESS_CTX } from "./router/models.js";
32
32
  import { disposeShellSession, getAgentTasks } from "./tools/registry.js";
33
33
  import { disposeBrowserNow } from "./browser/session.js";
34
34
  import { EventSink, defaultEventsFile } from "./telemetry/events.js";
35
+ import { SessionTracker } from "./telemetry/lifecycle.js";
36
+ import { centralRecording, defaultIngest, setCentralEnabled } from "./telemetry/ingest.js";
37
+ import { Teardown } from "./util/teardown.js";
38
+ import { installProcessTeardown } from "./session-teardown.js";
39
+ import { reapStaleChildren } from "./util/owned-children.js";
35
40
  import { readFileSync, writeFileSync, mkdirSync } from "node:fs";
36
41
  import { expandFileMentions } from "./util/mentions.js";
42
+ import { snapshotEphemeralImages } from "./util/screenshots.js";
37
43
  import { throttle } from "./util/throttle.js";
38
44
  import { isSlashCommand } from "./util/slash.js";
39
45
  import * as compose from "./compose/client.js";
40
46
  import { execFile } from "node:child_process";
41
47
  import { join, dirname } from "node:path";
42
48
  import { homedir, hostname } from "node:os";
43
- import { createHash } from "node:crypto";
49
+ import { createHash, randomUUID } from "node:crypto";
44
50
  // RELEASE CHECKLIST (every bump): update this + package.json "version", ADD A CHANGELOG.md ENTRY
45
51
  // (improvements / fixes / tests), run the suite, then publish to npm + push both remotes.
46
52
  // Single source of truth = package.json, read at runtime — so the splash/statusline can never drift
@@ -219,7 +225,10 @@ const RESUME = process.argv.includes("--resume") || process.argv.includes("-r")
219
225
  // events emitted below. Writes local JSONL + POSTs to KODE_TELEMETRY_URL if set (the dashboard's feed).
220
226
  // The sink always exists so the audit trail works even with telemetry off; turn/service events are gated
221
227
  // on telemetry.enabled so the metrics stream honors the off switch.
222
- const SESSION_ID = createHash("sha1").update(`${process.cwd()}:${Date.now()}`).digest("hex").slice(0, 12);
228
+ // A real uuid, not a cwd hash: it is the one id every event of this session carries — local file, dashboard, and the
229
+ // central ledger (telemetry/ingest.ts) — and the remote-control pairing id. (The relay treats session ids as opaque
230
+ // strings and mints uuids itself, so the longer form is native there.)
231
+ const SESSION_ID = randomUUID();
223
232
  // Scratchpad (per session) + handoff (per working directory). Projected to env for the scratchpad /
224
233
  // session_handoff tools; the handoff is auto-loaded into the system prompt below so the next session in
225
234
  // this directory resumes from it. Kept under ~/.axe/operator, never in the workspace.
@@ -235,7 +244,8 @@ const EVENT_ACTOR = { tier: settings.permissions.tier ?? "admin", surface: proce
235
244
  const eventSink = new EventSink();
236
245
  // Startup audit — only for a seat that is audited at all (a narrowed tier / audit / gated mode); the inert owner
237
246
  // writes nothing. Names the managed policy in force (by content id), the resolved seat and why.
238
- if (new PermissionPolicy(settings.permissions).audits) {
247
+ const AUDITS = new PermissionPolicy(settings.permissions).audits;
248
+ if (AUDITS) {
239
249
  const m = settings.managed;
240
250
  if (m?.status === "invalid")
241
251
  eventSink.emit({ kind: "control", session: SESSION_ID, actor: EVENT_ACTOR, control: { event: "policy_invalid", detail: `${m.path}: ${m.errors.join("; ")}`.slice(0, 400) } });
@@ -246,6 +256,25 @@ if (new PermissionPolicy(settings.permissions).audits) {
246
256
  eventSink.emit({ kind: "control", session: SESSION_ID, actor: EVENT_ACTOR, control: { event: "session_start", detail: `entry=${process.argv[2] ?? "tui"} version=${VERSION} tier=${EVENT_ACTOR.tier} mode=${settings.permissions.mode} sandbox=${settings.sandbox.mode} policy=${m?.id ?? "none"} seat=${settings.seat?.source ?? "local-owner"} home=${HOME_SCAFFOLD.firstRun ? "created" : "existing"}` } });
247
257
  }
248
258
  const emitTelemetry = settings.telemetry.enabled !== false;
259
+ // The off switch also covers the central ledger: with metrics off, nothing is recorded or sent for tracking.
260
+ setCentralEnabled(emitTelemetry);
261
+ // Structured session lifecycle for the central ledger. Only a TUI session that actually mounts starts it (see <Root>),
262
+ // so `operator auth …` / `--version` mint nothing; `enabled` is the permission wrapper's gate — an audited seat, or
263
+ // signed in / events URL configured — so a signed-out owner writes nothing.
264
+ const tracker = new SessionTracker(eventSink, SESSION_ID, EVENT_ACTOR, VERSION, () => AUDITS || centralRecording());
265
+ // ONE idempotent teardown for everything this session owns (children, sockets, telemetry), shared by every way out: /exit, esc/ctrl-c
266
+ // at rest, SIGINT/SIGHUP/SIGTERM and a plain process exit all call into it (wired below, before render), so it runs exactly once.
267
+ // It stops SESSION-owned things only — never the launchd-owned Aurora/autopilot (preflight only ever brings those UP).
268
+ const teardown = new Teardown();
269
+ installProcessTeardown(teardown, {
270
+ recordEnd: (r) => tracker.end(r === "quit" ? "ok" : r),
271
+ flushTelemetry: () => defaultIngest().shutdown(2000),
272
+ flushTelemetrySync: () => defaultIngest().persistSync(),
273
+ disposeShells: disposeShellSession,
274
+ disposeBrowser: disposeBrowserNow,
275
+ });
276
+ // Children a previous Operator left behind (it crashed, or was killed -9; detached shells/jobs and Chrome outlive their parent).
277
+ let REAPED = { owners: 0, killed: [], skipped: 0 };
249
278
  // Build the endpoint router. ONE model now: Aurora at its native 1M context on :8097 — both `operator`
250
279
  // and `operator+` serve the same single tier (the air/1m/saddle roster collapsed once Aurora ran true
251
280
  // 1,048,576-token context at full speed). No size-based routing decision remains.
@@ -380,6 +409,7 @@ function Root() {
380
409
  const [ctxPct, setCtxPct] = useState(0);
381
410
  const seededRef = useRef(false); // GW-06: oracle cold-start seed fires once per process, on first route
382
411
  const cacheReqsRef = useRef(0); // GW-05: requests since process start — index 1 legitimately misses everything
412
+ const turnCachedRef = useRef(0); // prompt tokens the server served from its prefix cache THIS turn (summed over rounds) — the turn event's cachedTokens
383
413
  const [metrics, setMetrics] = useState(""); // last turn's "N tok · X tok/s · Ys" for the status rule
384
414
  const [liveTok, setLiveTok] = useState(0); // live output-token count for the CURRENT turn — animates the
385
415
  // status rule as tokens stream (each SSE delta ≈ 1 token). Zero extra renders: it rides the per-delta
@@ -579,6 +609,7 @@ function Root() {
579
609
  // Sub-agents may NOT drive the computer: they have no approval prompt, so any computer_* call is
580
610
  // denied outright. (No-op when computer control is off.) Everything else runs as normal.
581
611
  permissions: settings.computer.enabled ? { mode: "bypass", rules: computerDenyRules } : undefined,
612
+ eventSink, eventActor: EVENT_ACTOR, sessionId: SESSION_ID, // a sub-agent's tool calls belong to THIS session in the ledger
582
613
  }), throttle(() => setBgAgents(bgRef.current.list()), 90), // coalesce per-update churn: a 3+ agent swarm streaming at once would otherwise redraw the whole frame dozens×/s (flicker). Final state lands via the immediate setBgAgents on the done path below.
583
614
  (agent, result) => {
584
615
  setEntries((prev) => [...prev, { kind: "message", message: { id: nextId(), role: "system", content: `⤷ ${agent.id} (${agent.label}) done:\n${result.slice(0, 500)}` } }]);
@@ -608,6 +639,7 @@ function Root() {
608
639
  // state mutation below also mirrors to it so attached followers see identical transcript/tool/activity.
609
640
  const remoteRef = useRef(null);
610
641
  const [rcConnected, setRcConnected] = useState(false); // remote-control live? drives the footer controller icon
642
+ const [rcActive, setRcActive] = useState(false); // remote-control ENABLED/listening (host up) — distinct from rcConnected (a follower is attached); the footer shows OFF(gray) vs ON-waiting(amber) vs LIVE(green)
611
643
  const setStat = (s) => { statusRef.current = s; setStatus(s); remoteRef.current?.setActivity(s); };
612
644
  const push = (e) => setEntries((prev) => [...prev, e]);
613
645
  const submitRef = useRef(() => { });
@@ -637,15 +669,18 @@ function Root() {
637
669
  cwd: process.cwd(),
638
670
  model: session.currentModel(),
639
671
  });
640
- // Backstop the slash-/ESC-quit paths: an ordinary terminal close or `kill` must still tear down any
641
- // spawned stdio MCP subprocesses (session.shutdown), or they orphan. exit runs sync; SIGTERM exits after.
672
+ // The app-level teardown steps (they need these refs). Added once; the process-level ones (session end, shells, owned children,
673
+ // telemetry flush) are installed above. Order: stop sub-agents (aborts their in-flight requests — a child mid-send used to keep the
674
+ // event loop alive and freeze `operator` after /exit), drop the remote-control socket, then the Session (MCP servers, shell).
642
675
  useEffect(() => {
643
- const onExit = () => { bgRef.current?.dispose(); session.shutdown(); disposeShellSession(); disposeBrowserNow(); };
644
- const onTerm = () => { bgRef.current?.dispose(); session.shutdown(); disposeShellSession(); disposeBrowserNow(); process.exit(0); };
645
- process.once("exit", onExit);
646
- process.once("SIGTERM", onTerm);
647
- return () => { process.off("exit", onExit); process.off("SIGTERM", onTerm); };
676
+ if (teardown.names().includes("session"))
677
+ return;
678
+ teardown.add("background-agents", () => bgRef.current?.dispose(), { order: 30 });
679
+ teardown.add("remote-control", () => { remoteRef.current?.stop(); remoteRef.current = null; }, { order: 40 });
680
+ teardown.add("session", () => session.shutdown(), { order: 50 });
648
681
  }, [session]);
682
+ // Central session tracking: the session exists now, so its model is known. No-op unless signed in / audited.
683
+ useEffect(() => { tracker.start(session.currentModel()); }, [session]);
649
684
  useEffect(() => {
650
685
  void (async () => {
651
686
  // Service lever: bring Aurora (required) and autopilot (optional) up via launchd BEFORE gating on
@@ -744,10 +779,11 @@ function Root() {
744
779
  setLive(null);
745
780
  setLiveTok(0); // reset the live counter at the start of the turn
746
781
  turnStartRef.current = Date.now();
782
+ turnCachedRef.current = 0;
747
783
  setElapsed(0);
748
784
  setStat("thinking");
749
785
  try {
750
- const outcome = await session.send(expandFileMentions(text), {
786
+ const outcome = await session.send(expandFileMentions(snapshotEphemeralImages(text)), {
751
787
  onRoute: (label, pct) => {
752
788
  setRoute(label);
753
789
  setCtxPct(pct);
@@ -793,6 +829,7 @@ function Root() {
793
829
  // tokens with ZERO reuse is a cache bust — name it, with its measured cost, instead of letting
794
830
  // the user watch "0 tokens for N seconds" and guess (the v0.1.140-143 mystery, now answerable).
795
831
  cacheReqsRef.current += 1;
832
+ turnCachedRef.current += cached ?? 0; // gateway rounds report unknown (undefined) reuse — contribute 0, never NaN the turn tally
796
833
  const notice = cacheBustNotice({ requestIndex: cacheReqsRef.current, promptTokens, cached, promptMs });
797
834
  if (notice)
798
835
  sys("⚠ " + notice);
@@ -913,8 +950,10 @@ function Root() {
913
950
  }
914
951
  // Feed the same numbers to the frozen event stream (dashboard + mobile). Gated on telemetry.enabled.
915
952
  if (emitTelemetry) {
953
+ // tokens/completionTokens are the same number (the dashboard reads `tokens`); prompt/cached/model feed the ledger.
916
954
  eventSink.emit({ kind: "turn", session: SESSION_ID, actor: EVENT_ACTOR,
917
- turn: { tokens: tok, tokPerSec: secs > 0 ? Math.round(tok / secs) : undefined, ctxPct: session.ctxPct(), route: session.currentRoute(), durationMs } });
955
+ turn: { tokens: tok, tokPerSec: secs > 0 ? Math.round(tok / secs) : undefined, ctxPct: session.ctxPct(), route: session.currentRoute(), durationMs,
956
+ model: session.currentModel(), promptTokens: prefill, completionTokens: tok, ...(turnCachedRef.current > 0 ? { cachedTokens: turnCachedRef.current } : {}) } });
918
957
  }
919
958
  }
920
959
  }
@@ -922,6 +961,7 @@ function Root() {
922
961
  push({ kind: "message", message: { id: nextId(), role: "assistant", content: `[turn error: ${e.message}]` } });
923
962
  }
924
963
  finally {
964
+ tracker.noteTurn();
925
965
  liveText.current = "";
926
966
  setLive(null);
927
967
  setLiveTools([]); // an interrupt/error mid-batch must not leave stale "running" rows on screen
@@ -949,6 +989,12 @@ function Root() {
949
989
  push({ kind: "message", message: { id: nextId(), role: "system", content: text } });
950
990
  remoteRef.current?.system(text);
951
991
  }, []);
992
+ // Say so when this launch cleaned up after a previous one — silently killing processes would be worse than the orphans.
993
+ useEffect(() => {
994
+ const n = REAPED.killed.length;
995
+ if (n)
996
+ sys(`cleaned up ${n} leftover process${n === 1 ? "" : "es"} from a previous session that did not exit cleanly (${[...new Set(REAPED.killed.map((k) => k.label))].join(", ")}).`);
997
+ }, []);
952
998
  // The actual mode switch — policy, plan flag, status badge, and follower-facing capabilities, all in
953
999
  // lockstep. Factored out of applyMode so the plan-exit picker below can perform it from a resolve
954
1000
  // callback without re-entering (and re-gating) applyMode itself.
@@ -1012,8 +1058,7 @@ function Root() {
1012
1058
  break;
1013
1059
  case "exit":
1014
1060
  case "quit":
1015
- bg.dispose();
1016
- s.shutdown();
1061
+ void teardown.run("quit");
1017
1062
  exit();
1018
1063
  break;
1019
1064
  case "clear":
@@ -1479,6 +1524,7 @@ function Root() {
1479
1524
  const { fileURLToPath } = await import("node:url");
1480
1525
  const { dirname } = await import("node:path");
1481
1526
  const server = join(dirname(fileURLToPath(import.meta.url)), "..", "dashboard", "server.mjs");
1527
+ // owned-exempt: the swarm console is SHARED by every Operator session on the machine (the next /dashboard reuses it)
1482
1528
  const child = spawn(process.execPath, [server], { detached: true, stdio: "ignore", env: { ...process.env, PORT: String(port) } });
1483
1529
  child.unref();
1484
1530
  sys(`launched the swarm console → ${url} — live-tailing ${defaultEventsFile()} (every Operator session, zero config). Open it in a browser.`);
@@ -1548,6 +1594,8 @@ function Root() {
1548
1594
  if (remoteRef.current) {
1549
1595
  remoteRef.current.stop();
1550
1596
  remoteRef.current = null;
1597
+ setRcConnected(false);
1598
+ setRcActive(false);
1551
1599
  sys("remote control stopped — followers detached");
1552
1600
  break;
1553
1601
  }
@@ -1575,6 +1623,11 @@ function Root() {
1575
1623
  onApprovalResponse: (id, approve) => settleApproval(id, approve), // first-wins with local
1576
1624
  onAskUserResponse: (id, answer) => settleQuestion(id, answer), // first-wins with local
1577
1625
  onInterrupt: () => s.interrupt(), // follower cancels the turn
1626
+ // RC v2 B1: a follower tapped Stop/Steer on a sub-agent row → the SAME BackgroundAgents the local
1627
+ // owner drives. requestStop posts the "[stopped by user]" note; sendToAgent queues a steer turn.
1628
+ // Both return a boolean the host turns into an agent_ack so the row shows ✓ / couldn't.
1629
+ onAgentStop: (id) => bgRef.current?.requestStop(id) ?? false,
1630
+ onAgentSteer: (id, text) => bgRef.current?.sendToAgent(id, text) ?? false,
1578
1631
  // A follower drove a slash command. Reuse the EXACT same path a local `/name args` line
1579
1632
  // takes (submitRef → onSubmit → handleSlash) — never a second implementation of the
1580
1633
  // switch — but only for names on the remote-safe allowlist; anything else is refused
@@ -1592,8 +1645,12 @@ function Root() {
1592
1645
  setRcConnected(st === "live"); // footer controller icon: green when live, gray otherwise
1593
1646
  if (st === "live")
1594
1647
  sys(`✷ remote control LIVE — session ${rh.id}\n Continue on your phone or at https://0perator.co/session/${rh.id}\n /remotecontrol again to stop.`);
1648
+ // RC v2 A2: a drop is NOT a dead end — the host auto-reconnects to the SAME session id (no
1649
+ // re-mint). Show the quiet reconnecting state; only a genuine setup error is surfaced hard.
1650
+ else if (st === "connecting" && detail === "reconnecting")
1651
+ sys("remote control reconnecting… (same session resumes; followers stay attached)");
1595
1652
  else if (st === "error")
1596
- sys(`remote control error: ${detail ?? "connection lost"} — /remotecontrol to retry`);
1653
+ sys(`remote control error: ${detail ?? "connection lost"} — auto-reconnecting`);
1597
1654
  else if (st === "closed")
1598
1655
  sys("remote control disconnected");
1599
1656
  // Frozen event stream: the persistent RC indicator + dashboard read these control events.
@@ -1604,6 +1661,7 @@ function Root() {
1604
1661
  },
1605
1662
  });
1606
1663
  remoteRef.current = rh;
1664
+ setRcActive(true);
1607
1665
  rh.setCapabilities(buildCapabilities()); // cached now, so the very first attach's snapshot already carries it
1608
1666
  rh.connect();
1609
1667
  sys(`connecting remote control → ${url} …`);
@@ -1617,6 +1675,7 @@ function Root() {
1617
1675
  remoteRef.current.stop();
1618
1676
  remoteRef.current = null;
1619
1677
  setRcConnected(false);
1678
+ setRcActive(false);
1620
1679
  sys("pairing stopped — followers detached");
1621
1680
  break;
1622
1681
  }
@@ -1638,6 +1697,8 @@ function Root() {
1638
1697
  onApprovalResponse: (id, approve) => settleApproval(id, approve),
1639
1698
  onAskUserResponse: (id, answer) => settleQuestion(id, answer),
1640
1699
  onInterrupt: () => s.interrupt(),
1700
+ onAgentStop: (id) => bgRef.current?.requestStop(id) ?? false, // RC v2 B1 (paired mode)
1701
+ onAgentSteer: (id, text) => bgRef.current?.sendToAgent(id, text) ?? false,
1641
1702
  onCommand: (cmdName, cmdArgs) => {
1642
1703
  if (!REMOTE_SAFE_COMMAND_NAMES.has(cmdName)) {
1643
1704
  sys(`remote control: blocked "/${cmdName}" from a follower — not exposed for remote dispatch`);
@@ -1649,8 +1710,10 @@ function Root() {
1649
1710
  },
1650
1711
  onState: (st, detail) => {
1651
1712
  setRcConnected(st === "live");
1652
- if (st === "error")
1653
- sys(`pairing error: ${detail ?? "connection lost"} — /pair to retry`);
1713
+ if (st === "connecting" && detail === "reconnecting")
1714
+ sys("pairing reconnecting… (same session resumes)"); // RC v2 A2: auto-reconnect, no re-mint
1715
+ else if (st === "error")
1716
+ sys(`pairing error: ${detail ?? "connection lost"} — auto-reconnecting`);
1654
1717
  else if (st === "closed")
1655
1718
  sys("pairing disconnected");
1656
1719
  if (st === "live")
@@ -1660,6 +1723,7 @@ function Root() {
1660
1723
  },
1661
1724
  }, { sessionId: SESSION_ID, code });
1662
1725
  remoteRef.current = rh;
1726
+ setRcActive(true);
1663
1727
  rh.setCapabilities(buildCapabilities());
1664
1728
  rh.connect();
1665
1729
  const link = pairURL(code, SESSION_ID);
@@ -1688,8 +1752,7 @@ function Root() {
1688
1752
  }, [applyMode]);
1689
1753
  const onInterrupt = useCallback(() => {
1690
1754
  if (statusRef.current === "idle") {
1691
- bg.dispose();
1692
- session.shutdown();
1755
+ void teardown.run("quit");
1693
1756
  return exit();
1694
1757
  } // Ctrl-C / ESC at rest quits
1695
1758
  session.interrupt();
@@ -1745,7 +1808,7 @@ function Root() {
1745
1808
  ? `${spin} reading your prompt… (${fmtDuration(elapsed)})`
1746
1809
  : `${spin} ${fmtMeta(elapsed, liveTok)}`
1747
1810
  : metrics;
1748
- return (_jsx(App, { messages: entries, live: live, status: status, stepLabel: stepLabel, 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, tasks: tasks, onSubmit: onSubmit, onQueue: onQueue, queuedPreview: queuedPreview, onInterrupt: onInterrupt, onCycleMode: onCycleMode, opMode: opMode, rcConnected: rcConnected, approval: approval, question: question, modelPicker: modelPicker, planExitPicker: planExitPicker, artifactsPicker: artifactsPicker, onApprovalDecide: (allow, always) => {
1811
+ return (_jsx(App, { messages: entries, live: live, status: status, stepLabel: stepLabel, 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, 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, onApprovalDecide: (allow, always) => {
1749
1812
  const cur = approval;
1750
1813
  if (cur)
1751
1814
  settleApproval(cur.id, allow, always); // first-wins with any remote follower answer
@@ -1780,6 +1843,7 @@ if (process.argv[2] === "update" || process.argv.includes("--update")) {
1780
1843
  // code when it handled the argv, or null to fall through to the interactive REPL. Dynamic import so the
1781
1844
  // autonomy stack (Session, keep-awake, schedulers) is only loaded when actually invoked.
1782
1845
  {
1846
+ REAPED = reapStaleChildren(); // before anything of ours is spawned: a fresh `operator` (TUI or headless — both spawn shells/jobs/MCP servers) never stacks on a dead one's leftovers; the TUI reports it on mount
1783
1847
  const { dispatchAutonomy } = await import("./autonomy/index.js");
1784
1848
  const code = await dispatchAutonomy(process.argv, settings);
1785
1849
  if (code !== null)
@@ -1800,6 +1864,17 @@ const leaveAltScreen = () => { try {
1800
1864
  process.stdout.write("\x1b[?1049l");
1801
1865
  }
1802
1866
  catch { } };
1867
+ // Teardown wiring — this is the one entry that mounts an interactive session, so it owns the whole exit path (headless/ACP sessions end
1868
+ // themselves; their spawned children still die with the process via util/owned-children). A SIGINT/SIGHUP kills the process WITHOUT an
1869
+ // `exit` event (Ink's signal-exit and the keep-awake hook re-raise the signal; searxng/fullscreen call process.exit(0)), so the
1870
+ // synchronous half of the teardown must run right here: PREPENDED (before them) and `once` (it removes itself first, so those handlers
1871
+ // still see exactly the listener set they always did and behave as before — no added exit code, no delay, no suppressed default kill).
1872
+ // SIGTERM exits right after, as it always did. The `exit` event is the backstop for every other way out. All of them call the same
1873
+ // idempotent Teardown, so whichever fires first does the work and the rest are no-ops.
1874
+ for (const sig of ["SIGINT", "SIGHUP"])
1875
+ process.prependOnceListener(sig, () => teardown.runSync("interrupted"));
1876
+ process.prependOnceListener("SIGTERM", () => { teardown.runSync("interrupted"); process.exit(0); });
1877
+ process.once("exit", (code) => teardown.runSync(code === 0 ? "quit" : "error"));
1803
1878
  if (FULLSCREEN) {
1804
1879
  process.stdout.write("\x1b[?1049h\x1b[H"); // enter alt-screen + cursor home
1805
1880
  process.on("exit", leaveAltScreen);
@@ -1825,6 +1900,14 @@ else {
1825
1900
  const inkInstance = render(_jsx(Root, {}));
1826
1901
  if (FULLSCREEN)
1827
1902
  void inkInstance.waitUntilExit().then(leaveAltScreen);
1903
+ // Normal quit (/exit, esc/ctrl-c at rest): the TUI has unmounted — tear down everything the session owns and WAIT for it (children
1904
+ // stopped, telemetry delivered or parked in the outbox), then make sure the process really ends. Nothing session-owned is allowed to
1905
+ // keep Operator alive after the owner has left (that is how duplicate processes piled up); the unref'd timer only ever fires if
1906
+ // something still holds the event loop open.
1907
+ void inkInstance.waitUntilExit().then(() => "quit", () => "error").then(async (reason) => {
1908
+ await teardown.run(reason);
1909
+ setTimeout(() => process.exit(process.exitCode ?? 0), 1500).unref();
1910
+ });
1828
1911
  // Ink erases the previous frame by line COUNT, computed from the terminal width at draw time. When the
1829
1912
  // window is minimized or resized, a resize event with a changed/zero width desyncs that count, so every
1830
1913
  // later re-render (a keystroke, the 250ms clock) APPENDS the status rule instead of overwriting it — the
@@ -205,7 +205,13 @@ export function basePersona(cwd = process.cwd(), opts = {}) {
205
205
  `renderable URL, and the honest reference provenance — all of which the tool gives you for free. ` +
206
206
  `To SEE or understand an image (a reference, screenshot, or a generated output) ` +
207
207
  `use \`image_analyze\` (real vision via the fleet VL model) — NEVER infer an image's content from its ` +
208
- `file size, dimensions, or numpy/PIL brightness stats; that is guessing, not seeing. These all call ` +
208
+ `file size, dimensions, or numpy/PIL brightness stats; that is guessing, not seeing. ` +
209
+ `A screenshot the owner shares arrives EITHER as an ephemeral macOS temp path ` +
210
+ `(\`/var/folders/.../TemporaryItems/NSIRD_screencaptureui_*/…\`, which the OS deletes within seconds) ` +
211
+ `OR as a stable local file (Desktop/Downloads). The engine snapshots the ephemeral ones to a durable ` +
212
+ `attachments path the instant they enter the prompt, so just \`image_analyze\` the path exactly as given ` +
213
+ `— and when the owner shares several, pass the DISTINCT path of each to its own call, never the same one twice. ` +
214
+ `These all call ` +
209
215
  `scale-to-zero / dedicated workers (load, run, exit), so you NEVER hold ` +
210
216
  `diffusion/video/vision weights in your own ` +
211
217
  `process. If you notice your own output crawling, STOP and say so (likely memory pressure) rather than pushing ` +
@@ -322,6 +328,12 @@ export function basePersona(cwd = process.cwd(), opts = {}) {
322
328
  `skills catalogue: skill_list (or skill_list "<query>") searches 60k+ reusable playbooks (curated + ` +
323
329
  `community), and skill_fetch <name> returns one's full instructions to apply. Prefer an existing skill over ` +
324
330
  `reinventing it; skill_save keeps a new one for next time.` +
331
+ `\n## Documents & PDFs — a downloadable FILE vs a hosted page\nWhen the owner wants a PDF, report, brief, ` +
332
+ `client deliverable, or a presentation/deck as a FILE they can open or send (e.g. "make a PDF", "put ` +
333
+ `together a presentation pdf", "send it via telegram"), use \`document_generate\` — it renders markdown ` +
334
+ `to a real PDF with NO external tool (never shell out to pandoc/wkhtmltopdf/chrome, never "no PDF tools ` +
335
+ `installed"; it works on every box). When they want a shareable hosted PAGE/URL instead, use ` +
336
+ `\`artifact_create\` (compose.casa). PDF file → document_generate; hosted link → artifact_create.` +
325
337
  `\n## AXE surfaces — disambiguate "compose"\n"compose.casa", "composer", "a design/artifact canvas", or ` +
326
338
  `"build an artifact/design" mean the AXE **compose.casa** artifact + design surface (artifacts, design ` +
327
339
  `rooms, canvases). Act on it with the compose tools (\`compose_create\` / \`compose_canvas\` / ` +
@@ -344,10 +356,17 @@ export function basePersona(cwd = process.cwd(), opts = {}) {
344
356
  `next steps: your next session in this directory loads it automatically, so write it for your future self.` +
345
357
  (opts.interactive
346
358
  ? `\n## Sub-agents\nFor independent, parallelizable subtasks (search a large tree, draft a file, a long ` +
347
- `build) call spawn_agent with a fully self-contained instruction — it runs on another session ` +
348
- `in parallel and posts its result back here; keep working meanwhile. The user watches each sub-agent's ` +
349
- `live tokens + time in the background panel. Don't delegate trivial work you can do inline, and don't ` +
350
- `spawn many at once — they all share this one model.`
359
+ `build) call spawn_agent (or delegate_task) with a fully self-contained instruction — it runs on another ` +
360
+ `session in parallel and posts its result back here; keep working meanwhile. The user watches each ` +
361
+ `sub-agent's live tokens + time in the background panel. Don't delegate trivial work you can do inline, ` +
362
+ `and don't spawn many at once — they all share this one model.\n` +
363
+ `WRITE THE BRIEF LIKE A SPEC, not a run-on paragraph — the child has NO memory of this chat, so a wall ` +
364
+ `of prose makes it guess. Structure every brief: **Objective** (the one outcome), **Context** (the ` +
365
+ `exact paths/ids/facts it needs — it can't see anything you don't state), **Deliverable** (the precise ` +
366
+ `output/format you want back), **Constraints** (what NOT to touch; read-only? which dirs?), **Done** ` +
367
+ `(how it proves success — the command/check to run). Short labeled lines beat a dense sentence; one ` +
368
+ `clear objective per agent, never two. The engine wraps your brief in the standard sub-agent frame, so ` +
369
+ `give it clean, specific content to wrap.`
351
370
  : ""));
352
371
  }
353
372
  const LEAN_NOTE = "\n\n(Lean harness: long-term memory + handoff omitted to fit this model's smaller context — answer from the live conversation; do not recite stored notes.)";
@@ -12,7 +12,7 @@ import { chmodSync, existsSync, mkdirSync, readFileSync, statSync, writeFileSync
12
12
  import { join } from "node:path";
13
13
  import { get_operator_home } from "./home.js";
14
14
  export const HOME_SCHEMA = 1;
15
- const HOME_DIRS = ["sessions", "logs", "skills", "memories"];
15
+ const HOME_DIRS = ["sessions", "logs", "skills", "memories", "attachments"];
16
16
  const GITIGNORE = `# Operator home: credentials, transcripts, memory, the audit log. Never commit any of it.
17
17
  # Created once by Operator and never overwritten — narrow it deliberately if you version parts of the home.
18
18
  *
@@ -451,6 +451,7 @@ export async function runTurn(userInput, conversation, opts) {
451
451
  let thinkLatched = false; // once a think-spiral is detected, force thinking:false for the rest of the turn
452
452
  let noEditStreak = 0; // consecutive tool rounds that changed no file — investigating, not fixing
453
453
  let noEditNudged = false; // the soft no-edit nudge fires at most once per turn
454
+ let budgetWarned = false; // the one-time "near the time budget, converge" warning fires before the hard wall-clock stop
454
455
  const touchedFiles = []; // files read/edited this turn (LRU) — re-surfaced by rehydration after a compaction
455
456
  let compactionFailStreak = 0; // consecutive rounds still over budget after compaction fired — the circuit breaker
456
457
  let selfHealBudget = MAX_SELF_HEAL_PER_TURN;
@@ -548,6 +549,17 @@ export async function runTurn(userInput, conversation, opts) {
548
549
  // such a turn can run an hour generating almost nothing. Wrap up gracefully at the round boundary instead
549
550
  // (loop mode continues the objective next turn). "[paused —" (not "[stopped —") so the flywheel doesn't
550
551
  // read a time cap as a failure-lesson.
552
+ // Budget self-pacing: warn ONCE at 75% of the wall-clock budget so the model converges gracefully BEFORE
553
+ // the hard stop below, instead of getting cut off mid-thought. The hard stop stays as the backstop.
554
+ if (opts.maxTurnWallClockMs && rounds > 0 && !budgetWarned && Date.now() - turnStart >= opts.maxTurnWallClockMs * 0.75) {
555
+ budgetWarned = true;
556
+ const leftSec = Math.max(1, Math.round((opts.maxTurnWallClockMs - (Date.now() - turnStart)) / 1000));
557
+ conversation.user(`You are ~75% through this turn's wall-clock budget (~${leftSec}s left) — converge NOW: finish the ` +
558
+ `current objective with what you have, stop opening new threads or exploring, keep any remaining tool ` +
559
+ `calls minimal. If you can answer, answer concisely; if not, summarize progress and the one blocker. ` +
560
+ `The turn will be wrapped at the hard limit either way.`);
561
+ // fall through: the model is called THIS round with the warning in context, so it converges now
562
+ }
551
563
  if (opts.maxTurnWallClockMs && rounds > 0 && Date.now() - turnStart >= opts.maxTurnWallClockMs) {
552
564
  const ranMin = Math.round((Date.now() - turnStart) / 60000);
553
565
  const capMin = Math.round(opts.maxTurnWallClockMs / 60000);
@@ -92,6 +92,12 @@ function isOperatorTrustedHost(h) {
92
92
  // A local :8097 never receives it (isRemoteBase gate), so it is safe to set unconditionally.
93
93
  let _operatorToken;
94
94
  export function setOperatorToken(token) { _operatorToken = token || undefined; }
95
+ /** The signed-in operator token, or undefined when signed out. Read by the central event ingest (telemetry/ingest.ts),
96
+ * which is the second consumer of this identity after the model call. */
97
+ export function getOperatorToken() { return _operatorToken; }
98
+ /** Whether the operator bearer may be sent to `url` (same scope rule authHeaders applies to a model base, minus the
99
+ * loopback exclusion: an ingest on a loopback AuthGate is exactly where the bearer is required). */
100
+ export function operatorTrustedUrl(url) { return isOperatorTrustedHost(hostOf(url)); }
95
101
  export function authHeaders(o) {
96
102
  if (!isRemoteBase(o.base))
97
103
  return {}; // a local server never gets any bearer — vendor or operator
@@ -45,12 +45,16 @@ const REQUIRED = {
45
45
  plan: ["summary", "steps"],
46
46
  generic: ["summary"],
47
47
  };
48
- /** Build the self-contained brief prompt sent to the child (mechanism 1). */
49
- export function buildBrief(input, cwd) {
50
- const type = input.type ?? inferType(input.objective);
48
+ /** The shared, structured core of EVERY sub-agent brief — one enterprise standard used by both spawn_agent
49
+ * (buildBrief, which appends a typed JSON final_answer) and delegate_task (delegateBrief, which appends a
50
+ * verbatim-result instruction). Consolidating the structure here is what keeps the two paths consistent:
51
+ * Role → Objective → Context → Deliverable → Definition of done, so a child always gets a clean, bounded,
52
+ * self-contained brief instead of whatever free-form wall the planner happened to type. */
53
+ export function briefCore(input, cwd) {
51
54
  return [
52
55
  "# Sub-agent brief",
53
- "You are a focused sub-agent. You CANNOT see the parent conversation — everything you need is here.",
56
+ "You are a focused sub-agent. You CANNOT see the parent conversation and cannot ask it questions —",
57
+ "everything you need is in THIS brief. Work only toward the Objective; do not expand scope.",
54
58
  "",
55
59
  "## Objective",
56
60
  input.objective.trim(),
@@ -63,6 +67,14 @@ export function buildBrief(input, cwd) {
63
67
  "",
64
68
  "## Definition of done",
65
69
  input.done?.trim() || "The objective is achieved AND verified — the changed files exist and your verify_command (tests/build/grep) passes. Do not claim done on the strength of your own say-so; run the check. A test that only checks a file/path exists proves nothing about behavior — assert on the real output, value, or state, the way a skeptical reviewer would.",
70
+ ];
71
+ }
72
+ /** Build the self-contained brief prompt sent to a spawn_agent child (mechanism 1): the shared enterprise
73
+ * core + a typed JSON final_answer the parent validates (extractFinalAnswer) and repairs once. */
74
+ export function buildBrief(input, cwd) {
75
+ const type = input.type ?? inferType(input.objective);
76
+ return [
77
+ ...briefCore(input, cwd),
66
78
  "",
67
79
  "## Final answer (required)",
68
80
  "When finished, your LAST output must be ONLY a fenced ```json block matching this schema — no prose after it:",
@@ -75,6 +87,19 @@ export function buildBrief(input, cwd) {
75
87
  "its context and can force a compaction.",
76
88
  ].join("\n");
77
89
  }
90
+ /** Build the brief for a delegate_task child: the SAME enterprise core, but delegate returns the child's final
91
+ * message VERBATIM (no schema validation), so it closes with a concise-result instruction instead of a JSON
92
+ * block. This is what makes delegate_task's briefs as structured as spawn_agent's. */
93
+ export function delegateBrief(input, cwd) {
94
+ return [
95
+ ...briefCore(input, cwd),
96
+ "",
97
+ "## Final answer (required)",
98
+ "Reply with ONLY the result — concise, no preamble, no restating the task. Lead with the answer; add just the",
99
+ "specifics (paths, values, findings) the parent needs. If you cannot finish, say exactly what blocked you.",
100
+ "You cannot delegate further.",
101
+ ].join("\n");
102
+ }
78
103
  // Pull the last JSON object out of the child's output — prefer a fenced ```json block, else the last
79
104
  // balanced {...}. Reasoners often wrap the answer or trail whitespace; take the LAST candidate.
80
105
  function lastJsonBlock(text) {
package/dist/mcp/stdio.js CHANGED
@@ -1,4 +1,5 @@
1
1
  import { flattenResult } from "./client.js";
2
+ import { ownChild } from "../util/owned-children.js";
2
3
  // node:child_process is loaded LAZILY (variable-specifier import, never a literal) so this module is
3
4
  // node-free AT LOAD — safe in the browser/JSCore engine bundle. esbuild --platform=neutral can't resolve
4
5
  // a variable specifier, so it stays a runtime import on the node path. A stdio server is a node-only
@@ -39,6 +40,7 @@ export class McpStdioClient {
39
40
  return;
40
41
  }
41
42
  this.proc = proc;
43
+ ownChild(proc, `mcp ${this.command}`, { cmd: `${this.command} ${this.args.join(" ")}` }); // killed at exit, reaped if we crash
42
44
  proc.on("error", (e) => this.fail(e)); // e.g. ENOENT: binary not found
43
45
  proc.on("exit", () => this.fail(new Error("MCP server exited")));
44
46
  proc.stdout.setEncoding("utf8");