@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
@@ -0,0 +1,260 @@
1
+ // Autonomy CLI dispatch — the entry the shell (cli.tsx) calls BEFORE mounting Ink, alongside the existing
2
+ // `operator auth` / `operator update` barewords. It owns the unattended subcommands:
3
+ //
4
+ // operator run "<task>" [--keep-awake] [--json] [--log F] [--loop] [--max-turns N] [--max-seconds S]
5
+ // operator loop "<objective>" (alias for `run --loop`)
6
+ // operator board <list|add "<task>"|run|status> [--json] [--max N] [--keep-awake]
7
+ // operator routine <list|run <id>|install <id> [--crontab]|watch> [--keep-awake]
8
+ // operator dream [--keep-awake]
9
+ //
10
+ // Returns an exit code when it handled the argv, or null when the first arg isn't an autonomy command
11
+ // (so cli.tsx falls through to the interactive REPL). Keep-awake is applied centrally here and torn down
12
+ // in a finally, so every long mode is covered and nothing leaks a caffeinate/inhibitor.
13
+ import { startKeepAwake } from "./keepawake.js";
14
+ import { runHeadless } from "./headless.js";
15
+ import { runBoard } from "./board-run.js";
16
+ import { runDream } from "./dream.js";
17
+ import { runAcp } from "../acp/run.js";
18
+ import { boardPath, addTask, readBoard } from "./board.js";
19
+ import { routinesPath, readRoutines } from "./routines.js";
20
+ import { readableRoutine, nextFire, runRoutine, launchdPlist, launchdLabel, crontabLine } from "./routine-run.js";
21
+ const AUTONOMY_COMMANDS = new Set(["run", "loop", "board", "routine", "dream", "acp"]);
22
+ /** Split argv (after the subcommand) into --bool flags, --key value pairs, and positionals. `--` ends
23
+ * flag parsing so a task string starting with a dash is preserved. */
24
+ function parseFlags(args, valued) {
25
+ const bool = new Set();
26
+ const val = new Map();
27
+ const positional = [];
28
+ let raw = false;
29
+ for (let i = 0; i < args.length; i++) {
30
+ const a = args[i];
31
+ if (raw) {
32
+ positional.push(a);
33
+ continue;
34
+ }
35
+ if (a === "--") {
36
+ raw = true;
37
+ continue;
38
+ }
39
+ if (a.startsWith("--")) {
40
+ const key = a.slice(2);
41
+ if (valued.has(key)) {
42
+ val.set(key, args[++i] ?? "");
43
+ }
44
+ else {
45
+ bool.add(key);
46
+ }
47
+ }
48
+ else {
49
+ positional.push(a);
50
+ }
51
+ }
52
+ return { bool, val, positional };
53
+ }
54
+ const VALUED = new Set(["log", "max-turns", "max-seconds", "max"]);
55
+ function intFlag(f, key) {
56
+ const v = f.val.get(key);
57
+ if (v === undefined)
58
+ return undefined;
59
+ const n = parseInt(v, 10);
60
+ return Number.isFinite(n) ? n : undefined;
61
+ }
62
+ /** Whether to hold the machine awake: the persisted setting OR an explicit --keep-awake on this run. */
63
+ function wantKeepAwake(settings, f) {
64
+ return !!settings.autonomy?.keepAwake || f.bool.has("keep-awake");
65
+ }
66
+ /** Run `fn` with keep-awake held for its duration when requested; always released afterward. */
67
+ async function withKeepAwake(on, reason, fn) {
68
+ const ka = on ? startKeepAwake(reason) : null;
69
+ if (ka?.active)
70
+ process.stderr.write(`[keep-awake: ${ka.method}]\n`);
71
+ try {
72
+ return await fn();
73
+ }
74
+ finally {
75
+ ka?.stop();
76
+ }
77
+ }
78
+ /** Absolute path to the running operator executable, for generated scheduler entries. */
79
+ function operatorBin() {
80
+ return process.argv[1] || "operator";
81
+ }
82
+ async function dispatchBoard(settings, f) {
83
+ const sub = f.positional[0] ?? "list";
84
+ const file = boardPath(settings);
85
+ if (sub === "add") {
86
+ const task = f.positional.slice(1).join(" ").trim();
87
+ if (!task) {
88
+ process.stderr.write('usage: operator board add "<task>"\n');
89
+ return 1;
90
+ }
91
+ const item = addTask(file, task);
92
+ process.stdout.write(`added ${item.id}: ${item.task}\n`);
93
+ return 0;
94
+ }
95
+ if (sub === "list" || sub === "status") {
96
+ const items = readBoard(file);
97
+ if (!items.length) {
98
+ process.stdout.write(`board empty (${file})\n`);
99
+ return 0;
100
+ }
101
+ if (f.bool.has("json")) {
102
+ process.stdout.write(JSON.stringify(items, null, 2) + "\n");
103
+ return 0;
104
+ }
105
+ const counts = items.reduce((m, i) => ((m[i.status] = (m[i.status] ?? 0) + 1), m), {});
106
+ for (const i of items)
107
+ process.stdout.write(`${i.status.padEnd(11)} ${i.id} ${i.task.slice(0, 72)}\n`);
108
+ process.stdout.write(`— ${items.length} items: ${Object.entries(counts).map(([k, v]) => `${v} ${k}`).join(", ")}\n`);
109
+ return 0;
110
+ }
111
+ if (sub === "run") {
112
+ const on = wantKeepAwake(settings, f);
113
+ return withKeepAwake(on, "Operator board run", async () => {
114
+ const res = await runBoard(settings, { json: f.bool.has("json"), logFile: f.val.get("log"), maxItems: intFlag(f, "max") });
115
+ return res.failed > 0 ? 1 : 0;
116
+ });
117
+ }
118
+ process.stderr.write(`unknown: operator board ${sub} (try list|add|run|status)\n`);
119
+ return 1;
120
+ }
121
+ async function dispatchRoutine(settings, f) {
122
+ const sub = f.positional[0] ?? "list";
123
+ const file = routinesPath(settings);
124
+ const routines = readRoutines(file);
125
+ if (sub === "list") {
126
+ if (!routines.length) {
127
+ process.stdout.write(`no routines (${file})\n`);
128
+ return 0;
129
+ }
130
+ for (const r of routines)
131
+ process.stdout.write(readableRoutine(r) + "\n");
132
+ return 0;
133
+ }
134
+ if (sub === "run") {
135
+ const id = f.positional[1];
136
+ const r = routines.find((x) => x.id === id);
137
+ if (!r) {
138
+ process.stderr.write(`no routine "${id}" in ${file}\n`);
139
+ return 1;
140
+ }
141
+ return withKeepAwake(wantKeepAwake(settings, f), `Operator routine ${id}`, () => runRoutine(settings, r, { json: f.bool.has("json"), logFile: f.val.get("log") }));
142
+ }
143
+ if (sub === "install") {
144
+ const id = f.positional[1];
145
+ const r = routines.find((x) => x.id === id);
146
+ if (!r) {
147
+ process.stderr.write(`no routine "${id}" in ${file}\n`);
148
+ return 1;
149
+ }
150
+ if (f.bool.has("crontab")) {
151
+ process.stdout.write(crontabLine(r, operatorBin(), process.cwd()) + "\n");
152
+ process.stderr.write(`# add the line above to your crontab (crontab -e)\n`);
153
+ return 0;
154
+ }
155
+ process.stdout.write(launchdPlist(r, operatorBin(), process.cwd()));
156
+ process.stderr.write(`# save as ~/Library/LaunchAgents/${launchdLabel(r.id)}.plist then: launchctl load -w that path\n`);
157
+ return 0;
158
+ }
159
+ if (sub === "watch") {
160
+ return withKeepAwake(wantKeepAwake(settings, f), "Operator routine watch", () => watchRoutines(settings));
161
+ }
162
+ process.stderr.write(`unknown: operator routine ${sub} (try list|run|install|watch)\n`);
163
+ return 1;
164
+ }
165
+ /** Internal scheduler: sleep until the soonest routine's next fire, run it, repeat. The durable path is
166
+ * `routine install` (launchd/cron); this is the lightweight fallback for hosts without them + testing. */
167
+ async function watchRoutines(settings) {
168
+ const file = routinesPath(settings);
169
+ process.stdout.write(`watching routines in ${file} (Ctrl-C to stop)\n`);
170
+ let stop = false;
171
+ const onSig = () => { stop = true; };
172
+ process.on("SIGINT", onSig);
173
+ process.on("SIGTERM", onSig);
174
+ try {
175
+ while (!stop) {
176
+ const routines = readRoutines(file).filter((r) => r.enabled !== false);
177
+ const upcoming = routines
178
+ .map((r) => ({ r, at: nextFire(r.schedule) }))
179
+ .filter((x) => !!x.at)
180
+ .sort((a, b) => a.at.getTime() - b.at.getTime());
181
+ if (!upcoming.length) {
182
+ process.stdout.write("no schedulable routines — exiting watch\n");
183
+ break;
184
+ }
185
+ const { r, at } = upcoming[0];
186
+ const waitMs = Math.max(0, at.getTime() - Date.now());
187
+ process.stdout.write(`next: ${r.id} at ${at.toISOString()} (${Math.round(waitMs / 1000)}s)\n`);
188
+ const slept = await interruptibleSleep(waitMs, () => stop);
189
+ if (stop || !slept)
190
+ break;
191
+ process.stdout.write(`firing routine ${r.id}\n`);
192
+ try {
193
+ await runRoutine(settings, r, {});
194
+ }
195
+ catch (e) {
196
+ process.stderr.write(`routine ${r.id} error: ${e instanceof Error ? e.message : String(e)}\n`);
197
+ }
198
+ }
199
+ }
200
+ finally {
201
+ process.off("SIGINT", onSig);
202
+ process.off("SIGTERM", onSig);
203
+ }
204
+ return 0;
205
+ }
206
+ /** Sleep up to `ms`, waking early (returns false) if `abort()` goes true. Polls on a bounded interval so
207
+ * a Ctrl-C is honored within ~1s even for a far-future fire. */
208
+ function interruptibleSleep(ms, abort) {
209
+ return new Promise((resolve) => {
210
+ const deadline = Date.now() + ms;
211
+ const tick = () => {
212
+ if (abort())
213
+ return resolve(false);
214
+ const left = deadline - Date.now();
215
+ if (left <= 0)
216
+ return resolve(true);
217
+ // NOT unref'd: this timer is the only thing keeping the event loop alive while
218
+ // `operator routine watch` waits for the next fire. Unref'ing it makes Node exit
219
+ // immediately (unsettled top-level await). On abort/SIGINT, tick() resolves and
220
+ // stops rescheduling, so the loop drains and the process still exits cleanly.
221
+ setTimeout(tick, Math.min(left, 1000));
222
+ };
223
+ tick();
224
+ });
225
+ }
226
+ /**
227
+ * Handle an autonomy subcommand. `argv` is the full process.argv. Returns the exit code, or null if this
228
+ * isn't an autonomy command (the caller then continues to the interactive shell).
229
+ */
230
+ export async function dispatchAutonomy(argv, settings) {
231
+ const cmd = argv[2];
232
+ if (!cmd || !AUTONOMY_COMMANDS.has(cmd))
233
+ return null;
234
+ const f = parseFlags(argv.slice(3), VALUED);
235
+ if (cmd === "run" || cmd === "loop") {
236
+ const prompt = f.positional.join(" ").trim();
237
+ if (!prompt) {
238
+ process.stderr.write(`usage: operator ${cmd} "<task>"\n`);
239
+ return 1;
240
+ }
241
+ const loop = cmd === "loop" || f.bool.has("loop");
242
+ return withKeepAwake(wantKeepAwake(settings, f), "Operator run", () => runHeadless(settings, prompt, {
243
+ json: f.bool.has("json"),
244
+ logFile: f.val.get("log"),
245
+ loop,
246
+ maxTurns: intFlag(f, "max-turns"),
247
+ maxWallClockSec: intFlag(f, "max-seconds"),
248
+ }));
249
+ }
250
+ if (cmd === "acp")
251
+ return runAcp(settings); // editor-embeddable ACP agent over stdio (Zed, VS Code bridge)
252
+ if (cmd === "board")
253
+ return dispatchBoard(settings, f);
254
+ if (cmd === "routine")
255
+ return dispatchRoutine(settings, f);
256
+ if (cmd === "dream") {
257
+ return withKeepAwake(wantKeepAwake(settings, f), "Operator dream", () => runDream(settings, { json: f.bool.has("json"), logFile: f.val.get("log") }));
258
+ }
259
+ return null;
260
+ }
@@ -0,0 +1,84 @@
1
+ // Keep-awake — hold the machine awake for the duration of an unattended run, then release cleanly.
2
+ // macOS: `caffeinate -dimsu -w <our pid>` (prevents display+idle+system sleep; auto-exits when WE exit,
3
+ // so even a hard crash can't leak it). Linux: `systemd-inhibit ... sleep infinity` when available. Any
4
+ // other platform: a no-op that still returns a working (inert) handle, so callers never branch on OS.
5
+ //
6
+ // Leak-free + interruptible by construction: the child is unref'd (never keeps the event loop alive on
7
+ // its own), stop() is idempotent and kills it, and we reap it on process 'exit' + SIGINT/SIGTERM so an
8
+ // interrupt never leaves a caffeinate/systemd-inhibit behind.
9
+ import { spawn, spawnSync } from "node:child_process";
10
+ function linuxHasSystemdInhibit() {
11
+ try {
12
+ return spawnSync("sh", ["-c", "command -v systemd-inhibit"], { stdio: "ignore" }).status === 0;
13
+ }
14
+ catch {
15
+ return false;
16
+ }
17
+ }
18
+ /**
19
+ * Start keeping the machine awake. Returns a handle whose stop() releases the hold. On an unsupported
20
+ * platform (or if the inhibitor binary is missing / fails to spawn) it returns an inert handle
21
+ * (active:false, method:"noop") rather than throwing — keep-awake is best-effort, never fatal to a run.
22
+ */
23
+ export function startKeepAwake(reason = "Operator autonomous run") {
24
+ let child;
25
+ let method = "noop";
26
+ try {
27
+ if (process.platform === "darwin") {
28
+ // -d display, -i idle, -m disk, -s system; -u declares user activity; -w waits on our pid so the
29
+ // OS tears caffeinate down if we die without calling stop().
30
+ child = spawn("caffeinate", ["-dimsu", "-w", String(process.pid)], { stdio: "ignore" });
31
+ method = "caffeinate";
32
+ }
33
+ else if (process.platform === "linux" && linuxHasSystemdInhibit()) {
34
+ child = spawn("systemd-inhibit", ["--what=idle:sleep", `--why=${reason}`, "--mode=block", "sleep", "infinity"], { stdio: "ignore" });
35
+ method = "systemd-inhibit";
36
+ }
37
+ }
38
+ catch {
39
+ child = undefined;
40
+ method = "noop";
41
+ }
42
+ // A spawn that errored asynchronously (ENOENT) must degrade to inert, not crash the process.
43
+ child?.on("error", () => { child = undefined; });
44
+ // Never let the inhibitor keep Node alive on its own — the run's own work owns the lifetime.
45
+ child?.unref();
46
+ let stopped = false;
47
+ const stop = () => {
48
+ if (stopped)
49
+ return;
50
+ stopped = true;
51
+ process.off("exit", onExit);
52
+ process.off("SIGINT", onSignal);
53
+ process.off("SIGTERM", onSignal);
54
+ if (child && child.exitCode === null && !child.killed) {
55
+ try {
56
+ child.kill("SIGTERM");
57
+ }
58
+ catch { /* already gone */ }
59
+ }
60
+ child = undefined;
61
+ };
62
+ const onExit = () => stop();
63
+ // On a signal, release the hold then let the default disposition proceed (re-raise once our listener
64
+ // is off, so we don't swallow Ctrl-C). Other listeners the runner installs still run.
65
+ const onSignal = (sig) => {
66
+ stop();
67
+ if (process.listenerCount(sig) === 0) {
68
+ try {
69
+ process.kill(process.pid, sig);
70
+ }
71
+ catch { /* exiting */ }
72
+ }
73
+ };
74
+ if (child) {
75
+ process.once("exit", onExit);
76
+ process.on("SIGINT", onSignal);
77
+ process.on("SIGTERM", onSignal);
78
+ }
79
+ return {
80
+ stop,
81
+ get active() { return !!child; },
82
+ method,
83
+ };
84
+ }
@@ -0,0 +1,82 @@
1
+ export const DONE_MARK = "<<OPERATOR_DONE>>";
2
+ export const CONTINUE_MARK = "<<OPERATOR_CONTINUE>>";
3
+ /** The instruction appended to the FIRST send so the model knows it's in an autonomous loop and how to
4
+ * signal completion. It must end each reply with exactly one marker so the outer loop can act on it. */
5
+ function loopPreamble(objective) {
6
+ return (`${objective}\n\n---\n` +
7
+ `You are running in AUTONOMOUS LOOP mode: you will be re-prompted to continue until this objective ` +
8
+ `is fully complete. Work in concrete steps using your tools. At the END of every reply, on its own ` +
9
+ `line, output exactly one marker:\n` +
10
+ ` ${DONE_MARK} — the objective is fully complete and verified; include a short summary above it.\n` +
11
+ ` ${CONTINUE_MARK} — more work remains; state the single next step above it.\n` +
12
+ `Do not claim ${DONE_MARK} until you have verified the work (e.g. the build passes, the file exists). ` +
13
+ `Never stop early with unfinished work marked done.`);
14
+ }
15
+ const CONTINUE_PROMPT = `Continue the objective. If it is now fully complete AND verified, reply with a short summary then ` +
16
+ `${DONE_MARK} on its own line; otherwise do the next step and end with ${CONTINUE_MARK}.`;
17
+ function declaredDone(content) {
18
+ // The marker wins; but a reply that emits BOTH (a confused model) is treated as "continue" — safer to
19
+ // do another turn than to stop with work unfinished.
20
+ return content.includes(DONE_MARK) && !content.includes(CONTINUE_MARK);
21
+ }
22
+ /**
23
+ * Run `objective` to completion on `worker`. Resolves with why it stopped — it never throws for a turn
24
+ * error (that resolves as reason:"error"); only misuse would reject. `signal` aborts between turns and
25
+ * interrupts the in-flight turn.
26
+ */
27
+ export async function runLoop(worker, objective, opts = {}, signal) {
28
+ const maxTurns = opts.maxTurns ?? 25;
29
+ const maxWallMs = (opts.maxWallClockSec ?? 3600) * 1000;
30
+ const stallAfter = Math.max(1, opts.stallAfter ?? 3);
31
+ const now = opts.now ?? (() => Date.now());
32
+ const started = now();
33
+ let turns = 0;
34
+ let toolCalls = 0;
35
+ let noActionStreak = 0;
36
+ let lastContent = "";
37
+ // Interrupt the in-flight turn the moment the caller aborts.
38
+ const onAbort = () => { try {
39
+ worker.interrupt();
40
+ }
41
+ catch { /* idle */ } };
42
+ signal?.addEventListener("abort", onAbort, { once: true });
43
+ try {
44
+ for (turns = 1; turns <= maxTurns; turns++) {
45
+ if (signal?.aborted)
46
+ return { reason: "interrupted", turns: turns - 1, toolCalls, lastContent };
47
+ if (now() - started > maxWallMs)
48
+ return { reason: "timeout", turns: turns - 1, toolCalls, lastContent };
49
+ const prompt = turns === 1 ? loopPreamble(objective) : CONTINUE_PROMPT;
50
+ let outcome;
51
+ try {
52
+ outcome = await worker.send(prompt, opts.handlers);
53
+ }
54
+ catch (e) {
55
+ return { reason: "error", turns, toolCalls, lastContent, error: e instanceof Error ? e.message : String(e) };
56
+ }
57
+ toolCalls += outcome.toolCalls;
58
+ lastContent = outcome.content;
59
+ opts.onTurn?.({
60
+ turn: turns,
61
+ toolCalls: outcome.toolCalls,
62
+ rounds: outcome.rounds,
63
+ durationMs: outcome.durationMs ?? 0,
64
+ content: outcome.content,
65
+ interrupted: outcome.interrupted,
66
+ });
67
+ if (outcome.interrupted)
68
+ return { reason: "interrupted", turns, toolCalls, lastContent };
69
+ if (declaredDone(outcome.content))
70
+ return { reason: "done", turns, toolCalls, lastContent };
71
+ // Outer stall guard: a turn that took no real action makes no progress on the objective. Enough of
72
+ // those in a row (and no "done") means the model is spinning — stop instead of burning the budget.
73
+ noActionStreak = outcome.toolCalls > 0 ? 0 : noActionStreak + 1;
74
+ if (noActionStreak >= stallAfter)
75
+ return { reason: "stall", turns, toolCalls, lastContent };
76
+ }
77
+ return { reason: "max_turns", turns: maxTurns, toolCalls, lastContent };
78
+ }
79
+ finally {
80
+ signal?.removeEventListener("abort", onAbort);
81
+ }
82
+ }
@@ -0,0 +1,54 @@
1
+ // Structured progress reporter for the headless autonomy runners. An unattended run has no TUI, so it
2
+ // streams machine-readable progress to stdout (and, optionally, appends the same to a log file) and exits
3
+ // with a status code. `--json` emits one JSON object per line (for a supervisor to parse); otherwise it
4
+ // prints compact human lines. Best-effort file writes — a bad --log path degrades to stdout-only.
5
+ import { appendFileSync, mkdirSync } from "node:fs";
6
+ import { dirname } from "node:path";
7
+ export function makeReporter(opts = {}) {
8
+ const out = opts.out ?? ((s) => process.stdout.write(s));
9
+ let logOk = false;
10
+ if (opts.logFile) {
11
+ try {
12
+ mkdirSync(dirname(opts.logFile), { recursive: true });
13
+ logOk = true;
14
+ }
15
+ catch {
16
+ logOk = false;
17
+ }
18
+ }
19
+ const toLog = (s) => {
20
+ if (logOk && opts.logFile) {
21
+ try {
22
+ appendFileSync(opts.logFile, s, "utf8");
23
+ }
24
+ catch { /* best-effort */ }
25
+ }
26
+ };
27
+ const emit = (rendered) => { out(rendered); toLog(rendered); };
28
+ return {
29
+ event(kind, data = {}) {
30
+ const rec = { ts: new Date().toISOString(), kind, ...data };
31
+ if (opts.json) {
32
+ emit(JSON.stringify(rec) + "\n");
33
+ }
34
+ else {
35
+ const extra = Object.entries(data)
36
+ .filter(([, v]) => v !== undefined && v !== "")
37
+ .map(([k, v]) => `${k}=${typeof v === "string" ? v : JSON.stringify(v)}`)
38
+ .join(" ");
39
+ emit(`[${kind}]${extra ? " " + extra : ""}\n`);
40
+ }
41
+ },
42
+ line(text) {
43
+ if (!text)
44
+ return;
45
+ if (opts.json) {
46
+ emit(JSON.stringify({ ts: new Date().toISOString(), kind: "text", text }) + "\n");
47
+ }
48
+ else {
49
+ emit(text.endsWith("\n") ? text : text + "\n");
50
+ }
51
+ },
52
+ close() { },
53
+ };
54
+ }
@@ -0,0 +1,25 @@
1
+ // Routine execution — map a declared Routine to a real run (headless / loop / board) and render a routine
2
+ // for `routine list`. Kept separate from routines.ts (the pure data + cron/launchd layer) so that module
3
+ // stays dependency-light and unit-testable without pulling in the Session/engine stack.
4
+ import { runHeadless } from "./headless.js";
5
+ import { runBoard } from "./board-run.js";
6
+ import { nextFire } from "./routines.js";
7
+ export { nextFire, launchdPlist, launchdLabel, crontabLine } from "./routines.js";
8
+ /** Run a routine once, now. board-mode ignores the prompt; headless/loop use it. Returns an exit code. */
9
+ export async function runRoutine(settings, r, opts = {}) {
10
+ const mode = r.mode ?? "headless";
11
+ if (mode === "board") {
12
+ const res = await runBoard(settings, { json: opts.json, logFile: opts.logFile });
13
+ return res.failed > 0 ? 1 : 0;
14
+ }
15
+ return runHeadless(settings, r.prompt, { json: opts.json, logFile: opts.logFile, loop: mode === "loop" });
16
+ }
17
+ /** One-line summary for `routine list`: id, schedule, mode, next fire, and the (truncated) prompt. */
18
+ export function readableRoutine(r) {
19
+ const next = nextFire(r.schedule);
20
+ const nextStr = next ? next.toISOString() : "never";
21
+ const state = r.enabled === false ? " (disabled)" : "";
22
+ const mode = r.mode ?? "headless";
23
+ const body = mode === "board" ? "[board queue]" : `"${r.prompt.slice(0, 60)}"`;
24
+ return `${r.id}${state} ${r.schedule} ${mode} next=${nextStr} ${body}`;
25
+ }