@0perator/operator 0.1.62 → 0.1.153

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (75) hide show
  1. package/CHANGELOG.md +1023 -0
  2. package/LICENSE +19 -0
  3. package/dist/acp/agent.js +103 -0
  4. package/dist/acp/run.js +23 -0
  5. package/dist/auth/client.js +4 -1
  6. package/dist/auth/login-intent.js +12 -0
  7. package/dist/autonomy/board-run.js +65 -0
  8. package/dist/autonomy/board.js +83 -0
  9. package/dist/autonomy/dream.js +71 -0
  10. package/dist/autonomy/headless.js +70 -0
  11. package/dist/autonomy/index.js +260 -0
  12. package/dist/autonomy/keepawake.js +84 -0
  13. package/dist/autonomy/loop.js +82 -0
  14. package/dist/autonomy/reporter.js +54 -0
  15. package/dist/autonomy/routine-run.js +25 -0
  16. package/dist/autonomy/routines.js +173 -0
  17. package/dist/autonomy/session-factory.js +61 -0
  18. package/dist/background/index.js +269 -20
  19. package/dist/background/worktree.js +62 -0
  20. package/dist/cli.js +518 -95
  21. package/dist/config/brand.js +81 -0
  22. package/dist/config/operator-harness.js +86 -0
  23. package/dist/config/persona.js +174 -0
  24. package/dist/config/settings.js +98 -9
  25. package/dist/engine/agent.js +447 -51
  26. package/dist/engine/aurora.js +180 -64
  27. package/dist/engine/compaction.js +97 -5
  28. package/dist/engine/grandmaster.js +69 -10
  29. package/dist/engine/router-adapter.js +3 -0
  30. package/dist/engine/selfheal.js +35 -0
  31. package/dist/engine/verify-gate.js +81 -0
  32. package/dist/mcp/index.js +1 -1
  33. package/dist/permissions/index.js +13 -7
  34. package/dist/router/models.js +1 -1
  35. package/dist/router/router.js +46 -7
  36. package/dist/selfimprove/index.js +88 -0
  37. package/dist/services/preflight.js +42 -1
  38. package/dist/session.js +227 -20
  39. package/dist/telemetry/events.js +9 -0
  40. package/dist/tools/executor.js +48 -24
  41. package/dist/tools/git-status.js +71 -0
  42. package/dist/tools/mutating.js +9 -0
  43. package/dist/tools/registry.js +214 -11
  44. package/dist/tools/result-cap.js +23 -0
  45. package/dist/tools/searxng.js +42 -2
  46. package/dist/ui/ActivitySpinner.js +6 -5
  47. package/dist/ui/App.js +23 -5
  48. package/dist/ui/AuthScreen.js +1 -1
  49. package/dist/ui/BgPanel.js +60 -5
  50. package/dist/ui/Composer.js +135 -13
  51. package/dist/ui/Header.js +6 -4
  52. package/dist/ui/InputRule.js +2 -1
  53. package/dist/ui/Markdown.js +69 -10
  54. package/dist/ui/Masthead.js +6 -4
  55. package/dist/ui/PlanPane.js +23 -0
  56. package/dist/ui/QuestionPrompt.js +22 -8
  57. package/dist/ui/StatsCard.js +15 -0
  58. package/dist/ui/StatusRule.js +13 -4
  59. package/dist/ui/SummaryCard.js +18 -0
  60. package/dist/ui/Table.js +114 -0
  61. package/dist/ui/ThinkingSpinner.js +6 -4
  62. package/dist/ui/ToolBatch.js +12 -0
  63. package/dist/ui/ToolStep.js +12 -4
  64. package/dist/ui/Transcript.js +30 -6
  65. package/dist/ui/chart.js +34 -0
  66. package/dist/ui/editdiff.js +84 -0
  67. package/dist/ui/highlight.js +89 -0
  68. package/dist/ui/osc.js +32 -0
  69. package/dist/ui/planExit.js +26 -0
  70. package/dist/ui/term.js +16 -0
  71. package/dist/ui/theme.js +60 -0
  72. package/dist/ui/tree.js +71 -0
  73. package/dist/util/slash.js +15 -0
  74. package/dist/util/throttle.js +28 -0
  75. package/package.json +11 -2
package/LICENSE ADDED
@@ -0,0 +1,19 @@
1
+ Copyright (c) 2026 AXE Technology. All rights reserved.
2
+
3
+ This software and its source code ("Operator", npm package `@0perator/operator`,
4
+ directory `kode-tsi`) are proprietary and confidential to AXE Technology. The
5
+ package manifest declares `"license": "UNLICENSED"` — no license, express or
6
+ implied, is granted to any party to use, copy, modify, merge, publish,
7
+ distribute, sublicense, or create derivative works of this software, except as
8
+ explicitly authorized in writing by AXE Technology.
9
+
10
+ The package is published to a PRIVATE registry (pkg.axe.onl) for internal fleet
11
+ distribution only. Publication to that registry does not grant any public
12
+ license, and mirroring the source to public git remotes for backup or
13
+ collaboration does not place it in the public domain or under any open-source
14
+ license.
15
+
16
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17
+ IMPLIED. IN NO EVENT SHALL AXE TECHNOLOGY BE LIABLE FOR ANY CLAIM, DAMAGES, OR
18
+ OTHER LIABILITY ARISING FROM, OUT OF, OR IN CONNECTION WITH THE SOFTWARE OR ITS
19
+ USE.
@@ -0,0 +1,103 @@
1
+ // ACP (Agent Client Protocol) agent — the editor-embeddable surface. Zed and any ACP client (VS Code via a
2
+ // bridge, etc.) spawn `operator acp` and drive turns over JSON-RPC/stdio. This class is a pure TRANSLATION
3
+ // layer: an ACP `session/prompt` becomes `Session.send()`, and the session's streaming callbacks become ACP
4
+ // `session/update` notifications. Nothing re-implements the agent loop — like the remote-control host, ACP
5
+ // funnels into the one `runTurn` (via Session), so compaction, loop-guard, and the verify gate come for free.
6
+ import { randomUUID } from "node:crypto";
7
+ import { PROTOCOL_VERSION } from "@zed-industries/agent-client-protocol";
8
+ import { createAutonomySession } from "../autonomy/session-factory.js";
9
+ export class OperatorAcpAgent {
10
+ conn;
11
+ settings;
12
+ sessions = new Map();
13
+ constructor(conn, settings) {
14
+ this.conn = conn;
15
+ this.settings = settings;
16
+ }
17
+ async initialize(_params) {
18
+ // We negotiate the version we build against and advertise a text-prompt agent. loadSession is not yet
19
+ // supported (each `session/new` is a fresh context); embeddedContext lets the editor inline file refs.
20
+ return {
21
+ protocolVersion: PROTOCOL_VERSION,
22
+ agentCapabilities: {
23
+ loadSession: false,
24
+ promptCapabilities: { image: false, audio: false, embeddedContext: true },
25
+ },
26
+ authMethods: [], // Operator's own auth (AuthGate) is orthogonal; the local ACP link needs none.
27
+ };
28
+ }
29
+ async newSession(params) {
30
+ // Same building blocks as headless (router, MCP tools, permissions, telemetry) — no TUI, no ask_user.
31
+ const session = createAutonomySession(this.settings);
32
+ const sessionId = randomUUID();
33
+ this.sessions.set(sessionId, { session, cwd: params.cwd || process.cwd() });
34
+ return { sessionId };
35
+ }
36
+ // Required by the interface; the local editor link is unauthenticated (authMethods is empty above).
37
+ async authenticate(_params) {
38
+ return {};
39
+ }
40
+ async prompt(params) {
41
+ const live = this.sessions.get(params.sessionId);
42
+ if (!live)
43
+ throw new Error(`ACP: unknown session ${params.sessionId}`);
44
+ // Operator's tools default to process.cwd(); honor the editor's project root for this turn.
45
+ try {
46
+ if (live.cwd)
47
+ process.chdir(live.cwd);
48
+ }
49
+ catch { /* dir gone — keep current cwd */ }
50
+ const sid = params.sessionId;
51
+ const handlers = acpHandlers((update) => void this.conn.sessionUpdate({ sessionId: sid, update: update }).catch(() => { }));
52
+ const outcome = await live.session.send(promptToText(params.prompt), handlers);
53
+ return { stopReason: outcome.interrupted ? "cancelled" : "end_turn" };
54
+ }
55
+ async cancel(params) {
56
+ this.sessions.get(params.sessionId)?.session.interrupt();
57
+ }
58
+ }
59
+ /** Map Operator's turn callbacks to ACP session/update payloads. `emit` sends one update. Exported so the
60
+ * mapping can be unit-tested without a live connection or model. */
61
+ export function acpHandlers(emit) {
62
+ return {
63
+ onDelta: (chunk) => emit({ sessionUpdate: "agent_message_chunk", content: { type: "text", text: chunk } }),
64
+ onReasoning: (chunk) => emit({ sessionUpdate: "agent_thought_chunk", content: { type: "text", text: chunk } }),
65
+ onToolStart: (calls) => {
66
+ for (const c of calls) {
67
+ emit({ sessionUpdate: "tool_call", toolCallId: c.id, title: toolTitle(c), status: "in_progress", rawInput: c.args });
68
+ }
69
+ },
70
+ onToolResult: (id, result) => {
71
+ emit({
72
+ sessionUpdate: "tool_call_update",
73
+ toolCallId: id,
74
+ status: "completed",
75
+ content: [{ type: "content", content: { type: "text", text: result } }],
76
+ });
77
+ },
78
+ };
79
+ }
80
+ /** Flatten ACP prompt content blocks to the plain text Operator's Session.send expects. Text blocks pass
81
+ * through; a resource_link / embedded resource becomes an `@path` mention the agent can act on. */
82
+ function promptToText(blocks) {
83
+ return blocks
84
+ .map((b) => {
85
+ if (b.type === "text")
86
+ return b.text;
87
+ if (b.type === "resource_link")
88
+ return `@${b.uri}`;
89
+ if (b.type === "resource") {
90
+ const r = b.resource;
91
+ return r.text ?? (r.uri ? `@${r.uri}` : "");
92
+ }
93
+ return "";
94
+ })
95
+ .filter(Boolean)
96
+ .join("\n");
97
+ }
98
+ /** A human-readable tool_call title for the editor's tool timeline: "file_edit: src/x.ts", "bash: npm test". */
99
+ function toolTitle(c) {
100
+ const a = (c.args ?? {});
101
+ const hint = a.path ?? a.file_path ?? a.command ?? a.query ?? a.url ?? a.pattern;
102
+ return hint ? `${c.name}: ${String(hint).slice(0, 80)}` : c.name;
103
+ }
@@ -0,0 +1,23 @@
1
+ // `operator acp` — run Operator as an ACP agent over stdio. An ACP client (Zed, or VS Code via a bridge)
2
+ // spawns this process and speaks JSON-RPC on stdin/stdout. stdout is therefore the PROTOCOL channel and must
3
+ // carry nothing else, so we route console.* to stderr up front (a stray log would corrupt the framing).
4
+ import { AgentSideConnection, ndJsonStream } from "@zed-industries/agent-client-protocol";
5
+ import { Readable, Writable } from "node:stream";
6
+ import { OperatorAcpAgent } from "./agent.js";
7
+ export async function runAcp(settings) {
8
+ // Safety net: anything that reaches for stdout (an MCP server, a dependency) would break the JSON-RPC
9
+ // stream. Send every console channel to stderr; the ACP connection owns stdout exclusively.
10
+ for (const k of ["log", "info", "debug", "warn"]) {
11
+ console[k] = (...args) => process.stderr.write(args.map(String).join(" ") + "\n");
12
+ }
13
+ const output = Writable.toWeb(process.stdout);
14
+ const input = Readable.toWeb(process.stdin);
15
+ const stream = ndJsonStream(output, input);
16
+ // The connection lives until the client closes stdin (the editor detached / quit).
17
+ new AgentSideConnection((conn) => new OperatorAcpAgent(conn, settings), stream);
18
+ await new Promise((resolve) => {
19
+ process.stdin.once("end", resolve);
20
+ process.stdin.once("close", resolve);
21
+ });
22
+ return 0;
23
+ }
@@ -2,7 +2,10 @@
2
2
  // verify). The base URL is configurable (AXE_AUTH_URL) so it works against staging/prod/local without
3
3
  // a code change. Pure transport + flow; the CLI commands (commands.ts) drive it and own the console.
4
4
  const AUTH_BASE = (process.env.AXE_AUTH_URL ?? "https://gate.authgate.cloud").replace(/\/$/, "");
5
- const CLIENT_ID = "operator-cli";
5
+ // Device-flow client_id — the canonical AuthGate app_id ("operator" in the Postgres apps table), so the
6
+ // gate/brand surfaces (gate/operator, 0perator.co/login, mobile) key on the same tenant. operator-tsi's
7
+ // device service records this as a free-text label (no registration/lookup), so it's a branding pointer.
8
+ const CLIENT_ID = "operator";
6
9
  async function post(path, body, timeoutMs = 15_000) {
7
10
  const ctrl = new AbortController();
8
11
  const t = setTimeout(() => ctrl.abort(), timeoutMs);
@@ -0,0 +1,12 @@
1
+ export function classifyLoginArg(arg) {
2
+ const a = arg.trim();
3
+ if (a === "--browser")
4
+ return "browser";
5
+ if (!a)
6
+ return "empty";
7
+ if (/^\d{6}$/.test(a))
8
+ return "code";
9
+ if (a.includes("@") && /\.[a-z]{2,}$/i.test(a))
10
+ return "email";
11
+ return "token";
12
+ }
@@ -0,0 +1,65 @@
1
+ // Board runner — work the durable JSONL queue (autonomy/board.ts) one item at a time. Each item is run
2
+ // as a bounded loop-mode objective (autonomy/loop.ts) on a FRESH session, so one task's context never
3
+ // bleeds into the next. Items are re-read from disk before every pick, so a task added (via `operator
4
+ // board add`) WHILE a run is in flight is picked up on the next iteration. Terminal outcome per item:
5
+ // done (marker) ⇒ status done+summary; anything else ⇒ status failed+reason. The attempt counter +
6
+ // maxAttempts guard stops a poison item from being retried forever across runs.
7
+ import { createAutonomySession } from "./session-factory.js";
8
+ import { runLoop } from "./loop.js";
9
+ import { boardPath, nextPending, setStatus, readBoard } from "./board.js";
10
+ import { makeReporter } from "./reporter.js";
11
+ export async function runBoard(settings, opts = {}) {
12
+ const file = boardPath(settings);
13
+ const reporter = opts.reporter ?? makeReporter({ json: opts.json, logFile: opts.logFile });
14
+ const maxItems = opts.maxItems ?? Infinity;
15
+ const maxAttempts = opts.maxAttempts ?? 3;
16
+ const perItemMaxTurns = opts.perItemMaxTurns ?? 12;
17
+ let worked = 0, done = 0, failed = 0;
18
+ reporter.event("board_start", { file, pending: readBoard(file).filter((i) => i.status === "pending").length });
19
+ while (worked < maxItems) {
20
+ if (opts.signal?.aborted) {
21
+ reporter.event("board_interrupted", {});
22
+ return { worked, done, failed, interrupted: true };
23
+ }
24
+ const item = nextPending(file, maxAttempts);
25
+ if (!item)
26
+ break;
27
+ setStatus(file, item.id, "in_progress", { attempt: true });
28
+ reporter.event("item_start", { id: item.id, task: item.task.slice(0, 80) });
29
+ worked++;
30
+ const session = createAutonomySession(settings, { permissions: opts.permissions });
31
+ try {
32
+ const res = await runLoop(session, item.task, {
33
+ maxTurns: perItemMaxTurns,
34
+ maxWallClockSec: settings.autonomy?.loop?.maxWallClockSec,
35
+ stallAfter: settings.autonomy?.loop?.stallAfter,
36
+ }, opts.signal);
37
+ if (res.reason === "done") {
38
+ done++;
39
+ setStatus(file, item.id, "done", { result: res.lastContent.slice(0, 2000) });
40
+ reporter.event("item_done", { id: item.id, turns: res.turns, toolCalls: res.toolCalls });
41
+ }
42
+ else if (res.reason === "interrupted") {
43
+ // Leave it pending (attempt already counted) so a later run resumes it; stop the batch.
44
+ setStatus(file, item.id, "pending", { note: "interrupted mid-run" });
45
+ reporter.event("board_interrupted", { id: item.id });
46
+ return { worked, done, failed, interrupted: true };
47
+ }
48
+ else {
49
+ failed++;
50
+ setStatus(file, item.id, "failed", { note: `${res.reason} after ${res.turns} turns`, result: res.lastContent.slice(0, 2000) });
51
+ reporter.event("item_failed", { id: item.id, reason: res.reason, turns: res.turns });
52
+ }
53
+ }
54
+ catch (e) {
55
+ failed++;
56
+ setStatus(file, item.id, "failed", { note: e instanceof Error ? e.message : String(e) });
57
+ reporter.event("item_failed", { id: item.id, reason: "error" });
58
+ }
59
+ finally {
60
+ session.shutdown();
61
+ }
62
+ }
63
+ reporter.event("board_done", { worked, done, failed });
64
+ return { worked, done, failed, interrupted: false };
65
+ }
@@ -0,0 +1,83 @@
1
+ // Board — a durable, append-only task queue Operator works through one item at a time (board mode) and
2
+ // dream mode pulls from. Stored as a JSONL EVENT LOG (not a mutable snapshot): every line is one event,
3
+ // state is the fold of all events. That makes writes atomic single-line appends that never clobber a
4
+ // concurrent `operator board add`, so tasks added WHILE a board run is in flight are picked up on the
5
+ // next re-read — the "continue on newly-added tasks" requirement, race-safe by construction.
6
+ import { appendFileSync, readFileSync, mkdirSync } from "node:fs";
7
+ import { homedir } from "node:os";
8
+ import { join, dirname } from "node:path";
9
+ /** Default board path — one JSONL under ~/.axe/operator, overridable via settings.autonomy.boardFile. */
10
+ export function boardPath(settings) {
11
+ const p = settings?.autonomy?.boardFile;
12
+ if (p)
13
+ return p.replace(/^~(?=\/|$)/, homedir());
14
+ return join(homedir(), ".axe", "operator", "board.jsonl");
15
+ }
16
+ function appendEvent(file, event) {
17
+ mkdirSync(dirname(file), { recursive: true });
18
+ appendFileSync(file, JSON.stringify(event) + "\n", "utf8");
19
+ }
20
+ /** Fold the event log into current item state, preserving first-seen (add) order. Malformed lines are
21
+ * skipped, not fatal — a partially-written tail never corrupts the read. */
22
+ export function readBoard(file) {
23
+ let raw;
24
+ try {
25
+ raw = readFileSync(file, "utf8");
26
+ }
27
+ catch {
28
+ return [];
29
+ }
30
+ const byId = new Map();
31
+ const order = [];
32
+ for (const line of raw.split("\n")) {
33
+ const s = line.trim();
34
+ if (!s)
35
+ continue;
36
+ let e;
37
+ try {
38
+ e = JSON.parse(s);
39
+ }
40
+ catch {
41
+ continue;
42
+ }
43
+ if (e.ev === "add") {
44
+ if (!byId.has(e.id))
45
+ order.push(e.id);
46
+ byId.set(e.id, { id: e.id, task: e.task, status: "pending", createdAt: e.t, updatedAt: e.t, attempts: 0 });
47
+ }
48
+ else if (e.ev === "status") {
49
+ const cur = byId.get(e.id);
50
+ if (!cur)
51
+ continue;
52
+ cur.status = e.status;
53
+ cur.updatedAt = e.t;
54
+ if (e.note !== undefined)
55
+ cur.note = e.note;
56
+ if (e.result !== undefined)
57
+ cur.result = e.result;
58
+ if (e.attempt)
59
+ cur.attempts += 1;
60
+ }
61
+ }
62
+ return order.map((id) => byId.get(id)).filter(Boolean);
63
+ }
64
+ function genId() {
65
+ return `t${Date.now().toString(36)}${Math.random().toString(36).slice(2, 6)}`;
66
+ }
67
+ /** Append a new pending task. Returns the created item. */
68
+ export function addTask(file, task) {
69
+ const t = Date.now();
70
+ const id = genId();
71
+ appendEvent(file, { ev: "add", t, id, task });
72
+ return { id, task, status: "pending", createdAt: t, updatedAt: t, attempts: 0 };
73
+ }
74
+ /** Record a status transition. `attempt:true` also increments the item's pickup counter (used when a
75
+ * runner claims a pending item as in_progress) so a repeatedly-failing task can be capped. */
76
+ export function setStatus(file, id, status, extra = {}) {
77
+ appendEvent(file, { ev: "status", t: Date.now(), id, status, ...extra });
78
+ }
79
+ /** The next actionable item: the first still-pending task (re-read fresh so items added mid-run appear).
80
+ * `maxAttempts` skips items already picked up that many times (a poison-pill guard). */
81
+ export function nextPending(file, maxAttempts = 3) {
82
+ return readBoard(file).find((i) => i.status === "pending" && i.attempts < maxAttempts);
83
+ }
@@ -0,0 +1,71 @@
1
+ // Dream mode — the low-priority, self-directed idle mode. When there's no active user task, Operator can
2
+ // pull the next board item or do safe maintenance/exploration on its own. This is the RISKIEST mode, so
3
+ // its defaults are deliberately conservative and its scope is explicit:
4
+ // • HARD OFF by default — settings.autonomy.dream.enabled must be true (or KODE_AUTONOMY_DREAM=1). With
5
+ // it off, dream refuses and does nothing.
6
+ // • READ-MOSTLY — the dream session runs under a gated policy with NO approver, so every mutating tool
7
+ // fails-safe to deny (see dreamPermissions). Set dream.permissions:"bypass" to opt into real changes.
8
+ // • ALLOWLISTED — dream only does what settings.autonomy.dream.allow lists ("board" | "maintenance" |
9
+ // "explore"); default ["board"]. Nothing outside the list runs.
10
+ // • BOUNDED — at most dream.maxTasks board items per cycle.
11
+ import { createAutonomySession, dreamPermissions } from "./session-factory.js";
12
+ import { runBoard } from "./board-run.js";
13
+ import { runLoop } from "./loop.js";
14
+ import { boardPath, nextPending } from "./board.js";
15
+ import { makeReporter } from "./reporter.js";
16
+ // Read-mostly maintenance/exploration objectives — phrased so the model INSPECTS and REPORTS. Even if a
17
+ // prompt tempted a mutation, the read-only permission posture denies it; the wording keeps intent aligned.
18
+ const MAINTENANCE_OBJECTIVE = "Idle maintenance sweep (READ-ONLY): scan the working tree for obvious problems — failing-looking " +
19
+ "TODO/FIXME hotspots, broken-looking config, stale lockfiles, uncommitted noise — and write a short " +
20
+ "prioritized summary of what a human should look at. Do NOT modify anything.";
21
+ const EXPLORE_OBJECTIVE = "Idle exploration (READ-ONLY): build a brief map of this repository — its entry points, main modules, " +
22
+ "and how they fit together — and summarize anything surprising or worth a human's attention. Do NOT " +
23
+ "modify anything.";
24
+ /**
25
+ * Run one dream cycle. Returns a process exit code: 0 (ran or cleanly did nothing), 2 (refused because
26
+ * dream is disabled). Never mutates unless the owner explicitly set dream.permissions:"bypass".
27
+ */
28
+ export async function runDream(settings, opts = {}) {
29
+ const reporter = opts.reporter ?? makeReporter({ json: opts.json, logFile: opts.logFile });
30
+ const dream = settings.autonomy?.dream;
31
+ if (!dream?.enabled) {
32
+ reporter.event("dream_disabled", { hint: "set autonomy.dream.enabled=true (or KODE_AUTONOMY_DREAM=1) to allow dream mode" });
33
+ return 2;
34
+ }
35
+ const allow = dream.allow ?? ["board"];
36
+ const maxTasks = dream.maxTasks ?? 3;
37
+ const perms = dreamPermissions(settings);
38
+ reporter.event("dream_start", { allow: allow.join(","), permissions: perms.mode, maxTasks });
39
+ // 1. Board work comes first (concrete, owner-queued intent) when allowed and something is pending.
40
+ if (allow.includes("board") && nextPending(boardPath(settings))) {
41
+ const res = await runBoard(settings, {
42
+ json: opts.json, logFile: opts.logFile, reporter,
43
+ maxItems: maxTasks, permissions: perms, signal: opts.signal,
44
+ });
45
+ reporter.event("dream_done", { via: "board", worked: res.worked, done: res.done, failed: res.failed });
46
+ return 0;
47
+ }
48
+ // 2. No board work — fall to a safe, read-mostly self-directed objective if the owner allowed it.
49
+ const objective = allow.includes("maintenance") ? MAINTENANCE_OBJECTIVE
50
+ : allow.includes("explore") ? EXPLORE_OBJECTIVE
51
+ : undefined;
52
+ if (!objective) {
53
+ reporter.event("dream_idle", { reason: "nothing pending on the board and no maintenance/explore in allowlist" });
54
+ return 0;
55
+ }
56
+ const session = createAutonomySession(settings, { permissions: perms });
57
+ try {
58
+ const res = await runLoop(session, objective, {
59
+ maxTurns: Math.min(maxTasks * 4, 12),
60
+ maxWallClockSec: settings.autonomy?.loop?.maxWallClockSec,
61
+ stallAfter: settings.autonomy?.loop?.stallAfter,
62
+ }, opts.signal);
63
+ reporter.event("dream_done", { via: allow.includes("maintenance") ? "maintenance" : "explore", reason: res.reason, turns: res.turns });
64
+ if (res.lastContent)
65
+ reporter.line(res.lastContent);
66
+ return 0;
67
+ }
68
+ finally {
69
+ session.shutdown();
70
+ }
71
+ }
@@ -0,0 +1,70 @@
1
+ // Headless mode — run ONE task without the Ink TUI: construct a real Session, stream structured progress
2
+ // to stdout (and optionally a log file), and exit with a status code. This is the non-interactive entry
3
+ // the CI/cron/board/dream paths build on. `--loop` promotes it to loop mode (autonomy/loop.ts) for a
4
+ // single objective worked across many turns; without it, one turn (the engine still auto-continues that
5
+ // turn while it makes progress).
6
+ import { createAutonomySession } from "./session-factory.js";
7
+ import { runLoop } from "./loop.js";
8
+ import { makeReporter } from "./reporter.js";
9
+ /** Streaming handlers that render a turn's activity through the reporter. Text deltas stream only in
10
+ * human mode (JSON mode reports the settled content as one event, to stay line-parseable). */
11
+ function handlersFor(reporter, json) {
12
+ return {
13
+ onRoute: (label, ctxPct) => reporter.event("route", { route: label, ctxPct }),
14
+ onAutoContinue: (round) => reporter.event("auto_continue", { round }),
15
+ 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
+ }),
21
+ onDelta: json ? undefined : (chunk) => process.stdout.write(chunk),
22
+ };
23
+ }
24
+ /**
25
+ * Run `prompt` headless. Returns a process exit code: 0 success, 1 error, 130 interrupted. Wires SIGINT
26
+ * to interrupt the in-flight turn so Ctrl-C stops cleanly (and the caller's keep-awake teardown runs).
27
+ */
28
+ export async function runHeadless(settings, prompt, opts = {}) {
29
+ const reporter = opts.reporter ?? makeReporter({ json: opts.json, logFile: opts.logFile });
30
+ const session = createAutonomySession(settings);
31
+ const handlers = handlersFor(reporter, !!opts.json);
32
+ const controller = new AbortController();
33
+ const onSig = () => { controller.abort(); try {
34
+ session.interrupt();
35
+ }
36
+ catch { /* idle */ } };
37
+ process.on("SIGINT", onSig);
38
+ process.on("SIGTERM", onSig);
39
+ reporter.event("start", { mode: opts.loop ? "loop" : "headless", model: settings.endpoints.aurora.model });
40
+ try {
41
+ if (opts.loop) {
42
+ const res = await runLoop(session, prompt, {
43
+ maxTurns: opts.maxTurns ?? settings.autonomy?.loop?.maxTurns,
44
+ maxWallClockSec: opts.maxWallClockSec ?? settings.autonomy?.loop?.maxWallClockSec,
45
+ stallAfter: settings.autonomy?.loop?.stallAfter,
46
+ handlers,
47
+ onTurn: (i) => reporter.event("turn", { turn: i.turn, tools: i.toolCalls, rounds: i.rounds, durationMs: Math.round(i.durationMs) }),
48
+ }, controller.signal);
49
+ reporter.event("done", { reason: res.reason, turns: res.turns, toolCalls: res.toolCalls });
50
+ if (res.lastContent)
51
+ reporter.line(res.lastContent);
52
+ return res.reason === "error" ? 1 : res.reason === "interrupted" ? 130 : 0;
53
+ }
54
+ const outcome = await session.send(prompt, handlers);
55
+ reporter.event("done", { rounds: outcome.rounds, toolCalls: outcome.toolCalls, interrupted: outcome.interrupted, durationMs: Math.round(outcome.durationMs ?? 0) });
56
+ if (outcome.content)
57
+ reporter.line(outcome.content);
58
+ return outcome.interrupted ? 130 : 0;
59
+ }
60
+ catch (e) {
61
+ reporter.event("error", { message: e instanceof Error ? e.message : String(e) });
62
+ return 1;
63
+ }
64
+ finally {
65
+ process.off("SIGINT", onSig);
66
+ process.off("SIGTERM", onSig);
67
+ session.shutdown();
68
+ reporter.close();
69
+ }
70
+ }