@0perator/operator 0.1.284 → 0.1.313

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 (99) hide show
  1. package/README.md +24 -2
  2. package/dist/acp/agent.js +3 -2
  3. package/dist/acp/config-options.js +15 -1
  4. package/dist/acp/tool-map.js +2 -1
  5. package/dist/auth/commands.js +69 -13
  6. package/dist/autonomy/agent-cli.js +304 -0
  7. package/dist/autonomy/cloud-agent.js +439 -0
  8. package/dist/autonomy/cron-lifecycle.js +78 -0
  9. package/dist/autonomy/cron-lock.js +121 -0
  10. package/dist/autonomy/cron.js +216 -43
  11. package/dist/autonomy/delegate.js +5 -1
  12. package/dist/autonomy/incidents.js +135 -0
  13. package/dist/autonomy/session-factory.js +25 -16
  14. package/dist/background/index.js +40 -0
  15. package/dist/bus/inbox.js +20 -0
  16. package/dist/classifier/config.js +47 -0
  17. package/dist/classifier/modes.js +41 -0
  18. package/dist/classifier/types.js +1 -0
  19. package/dist/cli.js +529 -53
  20. package/dist/config/features.js +69 -0
  21. package/dist/config/persona.js +118 -99
  22. package/dist/config/scaffold.js +15 -0
  23. package/dist/config/settings.js +96 -6
  24. package/dist/consolidation/sleep.js +73 -11
  25. package/dist/engine/agent.js +275 -18
  26. package/dist/engine/anthropic-chat.js +343 -0
  27. package/dist/engine/aurora.js +101 -13
  28. package/dist/engine/batch-scheduler.js +41 -9
  29. package/dist/engine/classifier.js +85 -0
  30. package/dist/engine/compaction.js +24 -5
  31. package/dist/engine/fast-start.js +25 -0
  32. package/dist/engine/loop-guard.js +448 -0
  33. package/dist/engine/moa.js +5 -1
  34. package/dist/engine/net-error.js +24 -0
  35. package/dist/engine/repetition-guard.js +180 -0
  36. package/dist/engine/selfheal.js +8 -0
  37. package/dist/engine/toolcalls.js +51 -1
  38. package/dist/engine/verify-gate.js +2 -0
  39. package/dist/flywheel/processor.js +78 -31
  40. package/dist/flywheel/srft.js +13 -0
  41. package/dist/hooks/index.js +196 -0
  42. package/dist/mcp/config.js +21 -1
  43. package/dist/memory/index.js +0 -0
  44. package/dist/memory/providers.js +210 -0
  45. package/dist/memory/session-catalog.js +422 -0
  46. package/dist/memory/session-providers.js +121 -0
  47. package/dist/memory/session-sources.js +335 -0
  48. package/dist/memory/skylark.js +131 -0
  49. package/dist/models/bench.js +103 -0
  50. package/dist/models/registry.js +144 -0
  51. package/dist/models/switch.js +69 -0
  52. package/dist/observability/blackbox.js +37 -0
  53. package/dist/permissions/policy.js +31 -6
  54. package/dist/router/discovery.js +127 -0
  55. package/dist/router/models.js +117 -24
  56. package/dist/router/portal.js +100 -0
  57. package/dist/router/router.js +1 -1
  58. package/dist/services/preflight.js +55 -7
  59. package/dist/session.js +316 -46
  60. package/dist/tools/chauffeur.js +12 -0
  61. package/dist/tools/executor.js +19 -9
  62. package/dist/tools/find-files.js +483 -0
  63. package/dist/tools/git-pr.js +94 -0
  64. package/dist/tools/incident-tools.js +82 -0
  65. package/dist/tools/memory.js +12 -2
  66. package/dist/tools/registry.js +281 -85
  67. package/dist/tools/semantic-compress.js +124 -0
  68. package/dist/tools/shell-context.js +1 -0
  69. package/dist/tools/shell-jobs.js +160 -0
  70. package/dist/tools/shell-session.js +170 -4
  71. package/dist/tools/wave-tools.js +609 -0
  72. package/dist/tools/wave2-tools.js +411 -0
  73. package/dist/ui/App.js +15 -4
  74. package/dist/ui/BgPanel.js +30 -6
  75. package/dist/ui/Composer.js +11 -1
  76. package/dist/ui/QuestionPrompt.js +31 -11
  77. package/dist/ui/SessionPicker.js +86 -0
  78. package/dist/ui/StatusRule.js +5 -5
  79. package/dist/ui/ToolStep.js +2 -1
  80. package/dist/ui/Transcript.js +17 -1
  81. package/dist/ui/index.js +1 -1
  82. package/dist/ui/liveTools.js +21 -3
  83. package/dist/ui/slashCommands.js +2 -0
  84. package/dist/util/screenshots.js +74 -8
  85. package/dist/util/slash.js +2 -2
  86. package/package.json +8 -2
  87. package/dist/engine/cli.js +0 -1171
  88. package/dist/router/models.js.bak +0 -78
  89. package/dist/router/models.js.bak-1791259923 +0 -78
  90. package/dist/router/models.js.bak-pre-gateway +0 -78
  91. package/dist/router/models.js.bak-pre-patch2 +0 -78
  92. package/dist/router/models.js.bak2 +0 -78
  93. package/dist/services/model-autodetect.js +0 -240
  94. package/dist/tools/native-redirect.js +0 -140
  95. package/dist/tools/power-tools.js +0 -627
  96. package/dist/tools/registry.js.bak-1791259948 +0 -1914
  97. package/dist/tools/registry.js.bak-pre-plugins +0 -1914
  98. package/dist/ui/BusTray.js +0 -70
  99. package/dist/ui/resize.js +0 -160
@@ -0,0 +1,439 @@
1
+ // Cloud agents — a sovereign "background/cloud agents" framework (Cursor-style), AXE's own. Operator spawns an
2
+ // autonomous agent inside an ISOLATED DOCKER CONTAINER on a configured fleet host (JL1, a Mac mini, …), which
3
+ // clones the repo, runs a chosen agent CLI (autonomy/agent-cli.ts presets: cursor-agent / claude / codex /
4
+ // operator) headless + autonomously on a task, commits to its own branch `cloud/<shortid>`, pushes, and opens a
5
+ // PR via `gh`. The run is TRACKED (status/logs/collect/stop), runs in PARALLEL with the owner's session, and is
6
+ // checkable anytime because its state is persisted to a small JSON file under the operator home (survives restarts).
7
+ //
8
+ // HOST-AGNOSTIC / CONFIG-DRIVEN — there is NO hardcoded host. A host is `{ id, ssh, image, workdir }` resolved
9
+ // from `settings.cloudAgents.hosts` (with `settings.cloudAgents.defaultHost`); the driver runs `docker …` on the
10
+ // remote host over SSH (`ssh user@host docker …`) or locally when `ssh === "local"`. The WHAT-runs-inside decision
11
+ // reuses the Path-B agent-CLI registry; the gate reuses config/features.ts; the config lives in config/settings.ts.
12
+ //
13
+ // INJECTABLE command runner: like autonomy/delegate.ts's createSession, the docker/ssh invocation goes through a
14
+ // `runner` dependency, so tests mock it and NO real docker/ssh/container/network is ever touched. Secrets (git
15
+ // creds, agent API keys) are passed via `-e NAME=VALUE` at RUNTIME only — never baked into the image, and masked
16
+ // out of everything we persist or return (state file, logTail, the loggable command).
17
+ //
18
+ // Browser-safe: this module is reachable from the tool registry (which rides in the engine bundle graph), so every
19
+ // node builtin loads LAZILY via the nodeImport idiom (same discipline as cron.ts / agent-cli.ts); the argv/host
20
+ // builders are pure.
21
+ import { operatorPath } from "../config/home.js";
22
+ const nodeImport = (m) => import(/* @vite-ignore */ m);
23
+ const msg = (e) => (e instanceof Error ? e.message : String(e));
24
+ // ── Defaults ────────────────────────────────────────────────────────────────────
25
+ export const DEFAULT_CLOUD_IMAGE = "operator-cloud-agent:latest";
26
+ export const DEFAULT_CLOUD_WORKDIR = "/tmp/cloud-agents";
27
+ /** Default cap on concurrent (running/provisioning) cloud agents — LOW by design: each clones the repo under the
28
+ * host workdir, and the default host (JL1) is disk-tight. Override with `settings.cloudAgents.maxConcurrent`. */
29
+ export const DEFAULT_CLOUD_MAX_CONCURRENT = 2;
30
+ /** Hard wall-clock bound on ONE docker/ssh CLIENT invocation (not the in-container run, which is detached). */
31
+ export const CLOUD_CMD_TIMEOUT_MS = 120_000;
32
+ const DEFAULT_LOG_TAIL_LINES = 80;
33
+ /** Env var names carrying SECRETS that the container needs at runtime (git push creds + agent API keys). Only the
34
+ * ones actually present in the environment are forwarded as `-e NAME=VALUE`; their values are masked everywhere we
35
+ * persist or return. Extendable by the owner via `settings.cloudAgents` is intentionally NOT done here — keeping
36
+ * the set code-pinned avoids a settings.json leak of which secrets exist. */
37
+ export const CLOUD_SECRET_ENV = [
38
+ "GH_TOKEN", "GITHUB_TOKEN", "GIT_TOKEN",
39
+ "ANTHROPIC_API_KEY", "KODE_ANTHROPIC_KEY",
40
+ "OPENAI_API_KEY", "CURSOR_API_KEY", "GEMINI_API_KEY",
41
+ ];
42
+ // Marker the entrypoint prints on stdout so collect/status can recover the PR URL from `docker logs` without
43
+ // reaching into the container. Kept in sync with docker/cloud-agent-entrypoint.sh.
44
+ const PR_MARKER = /::cloud-agent:pr::(\S+)/;
45
+ const CAPTURE_CAP = 1024 * 1024;
46
+ /** The real runner: spawn `file args`, capture stdout/stderr, enforce the timeout (kill the group on timeout). */
47
+ export const defaultRunner = async (file, args, opts) => {
48
+ const cp = (await nodeImport("node:child_process"));
49
+ return new Promise((resolve) => {
50
+ let stdout = "", stderr = "", timedOut = false, settled = false;
51
+ let child;
52
+ try {
53
+ child = cp.spawn(file, args, { detached: true, env: process.env, stdio: ["ignore", "pipe", "pipe"] });
54
+ }
55
+ catch (e) {
56
+ resolve({ code: null, stdout: "", stderr: "", error: msg(e) });
57
+ return;
58
+ }
59
+ const term = (sig) => { try {
60
+ if (child.pid)
61
+ process.kill(-child.pid, sig);
62
+ }
63
+ catch {
64
+ try {
65
+ child.kill(sig);
66
+ }
67
+ catch { /* gone */ }
68
+ } };
69
+ const finish = (extra) => {
70
+ if (settled)
71
+ return;
72
+ settled = true;
73
+ clearTimeout(timer);
74
+ resolve({ code: null, stdout, stderr, timedOut, ...extra });
75
+ };
76
+ const timer = setTimeout(() => { timedOut = true; term("SIGTERM"); setTimeout(() => term("SIGKILL"), 2000).unref?.(); }, opts.timeoutMs);
77
+ timer.unref?.();
78
+ child.stdout?.on("data", (d) => { if (stdout.length < CAPTURE_CAP)
79
+ stdout += d.toString("utf8"); });
80
+ child.stderr?.on("data", (d) => { if (stderr.length < CAPTURE_CAP)
81
+ stderr += d.toString("utf8"); });
82
+ child.on("error", (e) => finish({ error: msg(e) }));
83
+ child.on("close", (code) => finish({ code }));
84
+ });
85
+ };
86
+ // ── Pure host / argv builders (unit-testable, no I/O) ─────────────────────────────
87
+ /** Resolve the hosts + default from settings (never throws; returns an empty set when unconfigured). */
88
+ export function cloudHosts(settings) {
89
+ const c = settings?.cloudAgents;
90
+ const max = c?.maxConcurrent;
91
+ return {
92
+ hosts: (c?.hosts ?? []).filter((h) => !!h && !!h.id && !!h.ssh),
93
+ defaultHost: c?.defaultHost,
94
+ image: c?.image || DEFAULT_CLOUD_IMAGE,
95
+ timeout: c?.timeout,
96
+ maxConcurrent: typeof max === "number" && max > 0 ? Math.floor(max) : DEFAULT_CLOUD_MAX_CONCURRENT,
97
+ };
98
+ }
99
+ /** Pick the host for a spawn: the named `hostId`, else `defaultHost`, else the sole host. Throws an ACTIONABLE
100
+ * error when none is configured or the name is unknown — never spawns against a guessed host. */
101
+ export function resolveCloudHost(settings, hostId) {
102
+ const { hosts, defaultHost } = cloudHosts(settings);
103
+ if (!hosts.length) {
104
+ throw new Error('no cloud-agent hosts are configured — add one to settings.cloudAgents.hosts, e.g. {"id":"jl1","ssh":"home@192.168.1.103","image":"operator-cloud-agent:latest","workdir":"/tmp/cloud-agents"} and set settings.cloudAgents.defaultHost');
105
+ }
106
+ const ids = hosts.map((h) => h.id).join(", ");
107
+ const wanted = (hostId ?? "").trim() || defaultHost;
108
+ if (!wanted)
109
+ throw new Error(`no host given and no settings.cloudAgents.defaultHost set — pass host (one of: ${ids}) or set defaultHost`);
110
+ const host = hosts.find((h) => h.id === wanted);
111
+ if (!host)
112
+ throw new Error(`unknown cloud-agent host "${wanted}" — configured hosts: ${ids}`);
113
+ return host;
114
+ }
115
+ /** POSIX single-quote one token so a built command survives the remote shell intact over SSH. */
116
+ function shQuote(tok) { return `'${tok.replace(/'/g, `'\\''`)}'`; }
117
+ /** Join an argv into one shell-safe string (for `ssh target "<this>"`). */
118
+ function shJoin(argv) { return argv.map(shQuote).join(" "); }
119
+ /** Wrap a docker argv into the concrete `{ file, args }` to run on `host`: locally (`docker …`) when ssh==="local",
120
+ * else over SSH (`ssh -o BatchMode=yes user@host "docker …"`). Pure. */
121
+ export function invocationFor(host, dockerArgs) {
122
+ if (host.ssh === "local")
123
+ return { file: "docker", args: dockerArgs };
124
+ return { file: "ssh", args: ["-o", "BatchMode=yes", host.ssh, shJoin(["docker", ...dockerArgs])] };
125
+ }
126
+ /** The container name + branch derived from a short id. */
127
+ export function cloudContainerName(id) { return `op-cloud-${id}`; }
128
+ export function cloudBranchName(id) { return `cloud/${id}`; }
129
+ /** Build the `docker run` argv (without the leading "docker"). Non-secret config rides as `-e NAME=VALUE`; each
130
+ * secret rides as its own `-e NAME=VALUE` appended last. The image's baked entrypoint does the clone→run→PR. */
131
+ export function buildDockerRunArgs(spec) {
132
+ const container = cloudContainerName(spec.id);
133
+ const env = [];
134
+ const add = (k, v) => { if (v !== undefined && v !== "") {
135
+ env.push("-e", `${k}=${v}`);
136
+ } };
137
+ add("CLOUD_AGENT_ID", spec.id);
138
+ add("REPO", spec.repo);
139
+ add("BASE_BRANCH", spec.baseBranch);
140
+ add("BRANCH", spec.branch);
141
+ add("TASK", spec.task);
142
+ add("AGENT", spec.agent);
143
+ add("MODEL", spec.model);
144
+ if (spec.timeout && spec.timeout > 0)
145
+ add("AGENT_TIMEOUT", String(spec.timeout));
146
+ for (const [k, v] of Object.entries(spec.secrets))
147
+ add(k, v);
148
+ return [
149
+ "run", "-d",
150
+ "--name", container,
151
+ "--label", "op.cloud-agent=1",
152
+ "--label", `op.cloud-agent.id=${spec.id}`,
153
+ "-w", spec.workdir,
154
+ ...env,
155
+ spec.image,
156
+ ];
157
+ }
158
+ /** The SAME argv with secret VALUES masked — for state/logging/return. */
159
+ export function redactDockerArgs(args, secretValues) {
160
+ const vals = secretValues.filter(Boolean);
161
+ return args.map((a) => {
162
+ const eq = a.indexOf("=");
163
+ if (eq > 0) {
164
+ const name = a.slice(0, eq), val = a.slice(eq + 1);
165
+ if (vals.includes(val))
166
+ return `${name}=***`;
167
+ }
168
+ return a;
169
+ });
170
+ }
171
+ /** Mask any secret value appearing in free text (log tails, errors). */
172
+ function redactText(text, secretValues) {
173
+ let out = text;
174
+ for (const v of secretValues.filter((s) => s && s.length >= 4))
175
+ out = out.split(v).join("***");
176
+ return out;
177
+ }
178
+ function statePathFor(deps) {
179
+ return deps.statePath ?? globalThis.process?.env?.KODE_CLOUD_AGENTS_STATE ?? operatorPath("cloud-agents", "state.json");
180
+ }
181
+ async function readState(deps) {
182
+ try {
183
+ const fs = (await nodeImport("node:fs"));
184
+ const parsed = JSON.parse(fs.readFileSync(statePathFor(deps), "utf8"));
185
+ if (parsed && typeof parsed === "object" && parsed.agents && typeof parsed.agents === "object")
186
+ return parsed;
187
+ }
188
+ catch { /* missing/corrupt → empty */ }
189
+ return { agents: {} };
190
+ }
191
+ async function writeState(deps, state) {
192
+ const fs = (await nodeImport("node:fs"));
193
+ const path = (await nodeImport("node:path"));
194
+ const p = statePathFor(deps);
195
+ fs.mkdirSync(path.dirname(p), { recursive: true });
196
+ const tmp = `${p}.${process.pid}.tmp`;
197
+ fs.writeFileSync(tmp, JSON.stringify(state, null, 2) + "\n", "utf8");
198
+ fs.renameSync(tmp, p); // atomic replace
199
+ }
200
+ async function saveAgent(deps, agent) {
201
+ const state = await readState(deps);
202
+ state.agents[agent.id] = agent;
203
+ await writeState(deps, state);
204
+ }
205
+ // ── Shared helpers ────────────────────────────────────────────────────────────
206
+ async function resolveSettings(deps) {
207
+ if (deps.loadSettings)
208
+ return deps.loadSettings();
209
+ return (await nodeImport("../config/settings.js")).loadSettings();
210
+ }
211
+ function collectSecrets(env) {
212
+ const out = {};
213
+ for (const name of CLOUD_SECRET_ENV) {
214
+ const v = env[name];
215
+ if (v)
216
+ out[name] = v;
217
+ }
218
+ return out;
219
+ }
220
+ function shortId() {
221
+ // 8 lowercase-hex chars — enough entropy for a container/branch suffix, short enough to type.
222
+ let s = "";
223
+ for (let i = 0; i < 8; i++)
224
+ s += Math.floor(Math.random() * 16).toString(16);
225
+ return s;
226
+ }
227
+ /** Map `docker inspect` State → a CloudAgentStatus. running→running; exited code 0→done, non-zero→failed. */
228
+ export function statusFromInspect(stateJson) {
229
+ try {
230
+ const st = JSON.parse(stateJson);
231
+ if (st.Running || st.Status === "running" || st.Status === "created" || st.Status === "restarting")
232
+ return { status: "running" };
233
+ if (st.Status === "exited" || st.Status === "dead") {
234
+ const code = typeof st.ExitCode === "number" ? st.ExitCode : undefined;
235
+ return { status: code === 0 ? "done" : "failed", exitCode: code };
236
+ }
237
+ return { status: "running" };
238
+ }
239
+ catch {
240
+ return { status: "running" };
241
+ }
242
+ }
243
+ /**
244
+ * Spawn an autonomous agent in an isolated container on the chosen host. Builds + runs `docker run -d …` (via the
245
+ * injectable runner, over SSH or locally), returns a tracked CloudAgent handle, and persists it. Throws an
246
+ * ACTIONABLE error on bad config/input (no host, no repo, …) BEFORE anything runs; a docker/ssh FAILURE is not
247
+ * thrown — it is recorded as status "failed" on the returned handle.
248
+ */
249
+ export async function spawnCloudAgent(opts, deps = {}) {
250
+ const task = (opts.task ?? "").trim();
251
+ if (!task)
252
+ throw new Error("a cloud agent needs a non-empty `task` — it runs autonomously with only this");
253
+ const agent = (opts.agent ?? "").trim();
254
+ if (!agent)
255
+ throw new Error("a cloud agent needs an `agent` (the agent-CLI preset to run inside the container, e.g. cursor-agent / claude / codex)");
256
+ const repo = (opts.repo ?? "").trim();
257
+ if (!repo)
258
+ throw new Error("a cloud agent needs a `repo` to clone inside the container (an https or ssh git URL)");
259
+ const settings = await resolveSettings(deps);
260
+ const host = resolveCloudHost(settings, opts.host);
261
+ const { image, timeout, maxConcurrent } = cloudHosts(settings);
262
+ // Concurrency cap: each cloud agent clones the repo under the host workdir, so refuse once too many are already
263
+ // running/provisioning (default 2 — the default host, JL1, is disk-tight). Terminal agents (done/failed/stopped)
264
+ // don't count. Checked BEFORE provisioning so nothing is spawned past the cap.
265
+ const active = (await listCloudAgents(deps)).filter((a) => a.status === "running" || a.status === "provisioning").length;
266
+ if (active >= maxConcurrent) {
267
+ throw new Error(`cloud-agent concurrency cap reached (${active}/${maxConcurrent} running) — stop one with stop_cloud_agent or raise settings.cloudAgents.maxConcurrent`);
268
+ }
269
+ const env = deps.env ?? process.env;
270
+ const now = deps.now ?? Date.now;
271
+ const id = (deps.newId ?? shortId)();
272
+ const branch = cloudBranchName(id);
273
+ const container = cloudContainerName(id);
274
+ const baseBranch = (opts.baseBranch ?? "").trim() || "main";
275
+ const secrets = collectSecrets(env);
276
+ const secretValues = Object.values(secrets);
277
+ const dockerArgs = buildDockerRunArgs({
278
+ id, host, image: host.image || image, workdir: host.workdir || DEFAULT_CLOUD_WORKDIR,
279
+ repo, baseBranch, branch, task, agent, model: opts.model?.trim() || undefined, timeout, secrets,
280
+ });
281
+ const redactedCmd = ["docker", ...redactDockerArgs(dockerArgs, secretValues)].join(" ");
282
+ let record = {
283
+ id, host: host.id, container, agent, task, branch, repo,
284
+ status: "provisioning", startedAt: now(), logTail: redactedCmd,
285
+ };
286
+ await saveAgent(deps, record);
287
+ const { file, args } = invocationFor(host, dockerArgs);
288
+ const runner = deps.runner ?? defaultRunner;
289
+ const r = await runner(file, args, { timeoutMs: deps.timeoutMs ?? CLOUD_CMD_TIMEOUT_MS });
290
+ if (r.error || r.timedOut || r.code !== 0) {
291
+ const detail = r.error
292
+ ? `could not launch the container (${r.error})`
293
+ : r.timedOut
294
+ ? "docker/ssh timed out launching the container"
295
+ : `docker exited ${r.code}${(r.stderr || r.stdout).trim() ? `: ${redactText((r.stderr || r.stdout).trim().slice(-600), secretValues)}` : ""}`;
296
+ record = { ...record, status: "failed", error: detail, logTail: redactText((r.stderr || r.stdout).trim().slice(-600), secretValues) || redactedCmd };
297
+ }
298
+ else {
299
+ record = { ...record, status: "running", logTail: redactedCmd };
300
+ }
301
+ await saveAgent(deps, record);
302
+ return record;
303
+ }
304
+ /** All tracked cloud agents, newest first. */
305
+ export async function listCloudAgents(deps = {}) {
306
+ const state = await readState(deps);
307
+ return Object.values(state.agents).sort((a, b) => b.startedAt - a.startedAt);
308
+ }
309
+ async function getAgent(deps, id) {
310
+ return (await readState(deps)).agents[id];
311
+ }
312
+ /** One docker command on the agent's host, via the injectable runner. */
313
+ async function dockerOnHost(deps, settings, hostId, dockerArgs) {
314
+ const { hosts } = cloudHosts(settings);
315
+ const host = hosts.find((h) => h.id === hostId);
316
+ if (!host)
317
+ return { code: null, stdout: "", stderr: "", error: `host "${hostId}" is no longer configured` };
318
+ const { file, args } = invocationFor(host, dockerArgs);
319
+ return (deps.runner ?? defaultRunner)(file, args, { timeoutMs: deps.timeoutMs ?? CLOUD_CMD_TIMEOUT_MS });
320
+ }
321
+ /** Refresh one agent's status: `docker inspect` the container's State + tail its logs, update the record (status,
322
+ * logTail, prUrl when the entrypoint has printed it), persist, and return it. Terminal states (done/failed/stopped)
323
+ * still refresh the log tail. */
324
+ export async function cloudAgentStatus(id, deps = {}) {
325
+ const existing = await getAgent(deps, id);
326
+ if (!existing)
327
+ return undefined;
328
+ const settings = await resolveSettings(deps);
329
+ const secretValues = Object.values(collectSecrets(deps.env ?? process.env));
330
+ const tail = deps.logTailLines ?? DEFAULT_LOG_TAIL_LINES;
331
+ const inspect = await dockerOnHost(deps, settings, existing.host, ["inspect", "--format", "{{json .State}}", existing.container]);
332
+ const logs = await dockerOnHost(deps, settings, existing.host, ["logs", "--tail", String(tail), existing.container]);
333
+ let next = { ...existing };
334
+ if (!inspect.error && inspect.code === 0 && inspect.stdout.trim()) {
335
+ // Don't resurrect a user-stopped agent just because its container still reports a state.
336
+ if (existing.status !== "stopped")
337
+ next.status = statusFromInspect(inspect.stdout.trim()).status;
338
+ }
339
+ else if (inspect.error) {
340
+ next.error = inspect.error;
341
+ }
342
+ const logText = redactText(`${logs.stdout}${logs.stderr}`, secretValues).trim();
343
+ if (logText)
344
+ next.logTail = logText.slice(-4000);
345
+ const pr = PR_MARKER.exec(`${logs.stdout}\n${logs.stderr}`);
346
+ if (pr)
347
+ next.prUrl = pr[1];
348
+ await saveAgent(deps, next);
349
+ return next;
350
+ }
351
+ /** Stop + remove the container and mark the agent "stopped". Idempotent: a missing container is not an error. */
352
+ export async function stopCloudAgent(id, deps = {}) {
353
+ const existing = await getAgent(deps, id);
354
+ if (!existing)
355
+ return undefined;
356
+ const settings = await resolveSettings(deps);
357
+ await dockerOnHost(deps, settings, existing.host, ["stop", existing.container]);
358
+ await dockerOnHost(deps, settings, existing.host, ["rm", "-f", existing.container]);
359
+ const next = { ...existing, status: "stopped" };
360
+ await saveAgent(deps, next);
361
+ return next;
362
+ }
363
+ /** Collect a run's outcome: refresh status/logs, then return the handle with its final branch + PR + log tail. */
364
+ export async function collectCloudAgent(id, deps = {}) {
365
+ return cloudAgentStatus(id, deps);
366
+ }
367
+ // ── Tool-wrapper run() functions (never throw; return a string) ──────────────────
368
+ const errStr = (e) => `error: ${msg(e)}`;
369
+ function fmtAgent(a) {
370
+ const bits = [
371
+ `${a.id} [${a.status}]`, `host=${a.host}`, `agent=${a.agent}`, `container=${a.container}`, `branch=${a.branch}`,
372
+ ];
373
+ if (a.repo)
374
+ bits.push(`repo=${a.repo}`);
375
+ if (a.prUrl)
376
+ bits.push(`pr=${a.prUrl}`);
377
+ if (a.error)
378
+ bits.push(`error=${a.error}`);
379
+ return bits.join(" · ");
380
+ }
381
+ export async function runSpawnCloudAgent(args, deps = {}) {
382
+ try {
383
+ const a = await spawnCloudAgent({
384
+ task: String(args.task ?? ""),
385
+ agent: String(args.agent ?? ""),
386
+ repo: args.repo !== undefined ? String(args.repo) : undefined,
387
+ baseBranch: args.base_branch !== undefined ? String(args.base_branch) : undefined,
388
+ host: args.host !== undefined ? String(args.host) : undefined,
389
+ model: args.model !== undefined ? String(args.model) : undefined,
390
+ }, deps);
391
+ const head = a.status === "failed"
392
+ ? `cloud agent ${a.id} FAILED to provision`
393
+ : `cloud agent ${a.id} is now ${a.status} in an isolated container on "${a.host}"`;
394
+ return `${head}. ${fmtAgent(a)}. It clones ${a.repo}, runs "${a.agent}" autonomously on the task, pushes ${a.branch} and opens a PR. Track it with cloud_agent_status("${a.id}") or list_cloud_agents; stop it with stop_cloud_agent("${a.id}").`;
395
+ }
396
+ catch (e) {
397
+ return errStr(e);
398
+ }
399
+ }
400
+ export async function runListCloudAgents(_args, deps = {}) {
401
+ try {
402
+ const all = await listCloudAgents(deps);
403
+ if (!all.length)
404
+ return "no cloud agents tracked yet — spawn one with spawn_cloud_agent.";
405
+ return all.map(fmtAgent).join("\n");
406
+ }
407
+ catch (e) {
408
+ return errStr(e);
409
+ }
410
+ }
411
+ export async function runCloudAgentStatus(args, deps = {}) {
412
+ const id = String(args.id ?? "").trim();
413
+ if (!id)
414
+ return "error: cloud_agent_status needs an `id` (from spawn_cloud_agent / list_cloud_agents)";
415
+ try {
416
+ const a = await cloudAgentStatus(id, deps);
417
+ if (!a)
418
+ return `error: no cloud agent "${id}" is tracked — list_cloud_agents shows the known ids`;
419
+ const log = a.logTail ? `\n--- log tail ---\n${a.logTail}` : "";
420
+ return `${fmtAgent(a)}${log}`;
421
+ }
422
+ catch (e) {
423
+ return errStr(e);
424
+ }
425
+ }
426
+ export async function runStopCloudAgent(args, deps = {}) {
427
+ const id = String(args.id ?? "").trim();
428
+ if (!id)
429
+ return "error: stop_cloud_agent needs an `id` (from spawn_cloud_agent / list_cloud_agents)";
430
+ try {
431
+ const a = await stopCloudAgent(id, deps);
432
+ if (!a)
433
+ return `error: no cloud agent "${id}" is tracked — nothing to stop`;
434
+ return `cloud agent ${a.id} stopped and its container removed. ${fmtAgent(a)}.`;
435
+ }
436
+ catch (e) {
437
+ return errStr(e);
438
+ }
439
+ }
@@ -0,0 +1,78 @@
1
+ // Cron run lifecycle (PV2-21) — the 6-state machine for one scheduled run:
2
+ //
3
+ // defined → claimed → preflight → executing → delivered → archived
4
+ //
5
+ // "defined" is the JOB's resting state (no active run; it simply sits in jobs.json with a
6
+ // nextRunAt). A RUN record exists from the moment a tick CLAIMS the job (PV2-20's atomic
7
+ // claim) and is archived into executions.jsonl when it finishes; the job then rests again
8
+ // until its next fire. Two extra legal edges keep reality representable:
9
+ // claimed → delivered (recovery of an ABANDONED run — the claiming process died)
10
+ // preflight → delivered (preflight failed: the run completes as a failure, never executes)
11
+ //
12
+ // WHY a state machine at all: before this, a run was invisible between claim and the final
13
+ // log line — a crash mid-execute left no trace of what was in flight and no way for the next
14
+ // tick to know a job was wedged. The run record makes every in-flight run observable
15
+ // (who claimed it, where, how far it got) and recoverable (an abandoned run is archived as
16
+ // such and the job becomes claimable again instead of being stuck forever).
17
+ //
18
+ // This module is PURE — no I/O, no node builtins, no clock or pid reads (callers inject
19
+ // them) — so it is unit-testable and safe in any bundle. cron.ts owns persistence.
20
+ /** Every legal edge. Anything else is a programming error and throws. */
21
+ const TRANSITIONS = {
22
+ claimed: ["preflight", "delivered"], // → delivered only via abandoned-run recovery
23
+ preflight: ["executing", "delivered"], // → delivered when preflight fails
24
+ executing: ["delivered"],
25
+ delivered: ["archived"],
26
+ archived: [],
27
+ };
28
+ export class IllegalRunTransition extends Error {
29
+ constructor(from, to) {
30
+ super(`illegal run transition ${from} → ${to}`);
31
+ this.name = "IllegalRunTransition";
32
+ }
33
+ }
34
+ /** States in which a run occupies its job (the job must not be claimed again). */
35
+ export function runInFlight(run) {
36
+ return !!run && (run.state === "claimed" || run.state === "preflight" || run.state === "executing");
37
+ }
38
+ /** Open a new run at "claimed". `by`/`now` are injected so this stays pure. */
39
+ export function newRun(runId, by, now) {
40
+ return { runId, state: "claimed", claimedBy: by, claimedAt: now, history: [{ state: "claimed", t: now }] };
41
+ }
42
+ /**
43
+ * Move a run to `to`, appending the trail and stamping the state's timestamp field
44
+ * (executing → startedAt, delivered → finishedAt). Throws IllegalRunTransition on any
45
+ * edge not in the machine. Mutates and returns the same record.
46
+ */
47
+ export function advanceRun(run, to, now, patch) {
48
+ if (!TRANSITIONS[run.state]?.includes(to))
49
+ throw new IllegalRunTransition(run.state, to);
50
+ run.state = to;
51
+ if (to === "executing")
52
+ run.startedAt = now;
53
+ if (to === "delivered")
54
+ run.finishedAt = now;
55
+ if (patch?.ok !== undefined)
56
+ run.ok = patch.ok;
57
+ if (patch?.note !== undefined)
58
+ run.note = patch.note;
59
+ run.history.push({ state: to, t: now });
60
+ return run;
61
+ }
62
+ export const DEFAULT_RUN_STALE_MS = 15 * 60_000;
63
+ /**
64
+ * Is this run ABANDONED — in flight, but its claiming process is provably gone (dead pid on
65
+ * this host) or past the stale deadline (crashed elsewhere / unprovable)? Abandoned runs are
66
+ * recovered at the next claim: archived as a failure with an "abandoned" note, freeing the job.
67
+ */
68
+ export function runIsAbandoned(run, now, opts = {}) {
69
+ if (!runInFlight(run))
70
+ return false;
71
+ const r = run;
72
+ if (now - r.claimedAt > (opts.staleMs ?? DEFAULT_RUN_STALE_MS))
73
+ return true;
74
+ if (opts.host !== undefined && opts.isAlive && r.claimedBy.host === opts.host && r.claimedBy.pid > 0) {
75
+ return !opts.isAlive(r.claimedBy.pid);
76
+ }
77
+ return false;
78
+ }
@@ -0,0 +1,121 @@
1
+ // Cross-process advisory lock for the cron job store (PV2-20).
2
+ //
3
+ // WHY: two Operator processes can tick the same `<home>/cron/jobs.json` (an interactive session's
4
+ // in-process scheduler plus a headless routine, or two sessions) — without mutual exclusion both
5
+ // load the same due list and DOUBLE-RUN every due job, and their read-modify-writes clobber each
6
+ // other. This module provides the mutex; cron.ts holds it only around the CLAIM (load → advance
7
+ // schedules → save), never around execution, so the critical section is milliseconds.
8
+ //
9
+ // HOW: an atomic lock DIRECTORY beside the store (`cron/jobs.lock/`) — mkdir is atomic on every
10
+ // platform, so exactly one process can create it. The holder records {pid, host, acquiredAt} in
11
+ // owner.json. A contender takes over a STALE lock: owner pid dead on this host, or lock older
12
+ // than staleMs (a crash mid-claim must never wedge cron forever). On acquire timeout the caller
13
+ // skips its tick — the jobs run in whichever process holds the lock.
14
+ //
15
+ // House rules: node builtins load lazily (platform-neutral bundle safety); paths go through
16
+ // operatorPath(); zero dependencies.
17
+ import { operatorPath } from "../config/home.js";
18
+ const nodeImport = (m) => import(/* @vite-ignore */ m);
19
+ export class CronLockBusyError extends Error {
20
+ constructor(holder) { super(`cron store is locked by ${holder}`); this.name = "CronLockBusyError"; }
21
+ }
22
+ const DEFAULT_TIMEOUT_MS = 5_000;
23
+ const DEFAULT_POLL_MS = 50;
24
+ const DEFAULT_STALE_MS = 120_000;
25
+ function cronLockDir() { return operatorPath("cron", "jobs.lock"); }
26
+ /** Is the recorded owner provably stale? Dead pid on this host, or past the stale deadline. */
27
+ function ownerIsStale(owner, nowMs, staleMs, hostname) {
28
+ if (!owner)
29
+ return true; // unreadable owner.json — mkdir raced a crash; age gate below still applies
30
+ if (nowMs - owner.acquiredAt > staleMs)
31
+ return true;
32
+ if (owner.host === hostname && owner.pid > 0) {
33
+ try {
34
+ process.kill(owner.pid, 0);
35
+ return false;
36
+ } // alive
37
+ catch (e) {
38
+ return e?.code === "ESRCH";
39
+ } // ESRCH = dead; EPERM = alive, not ours
40
+ }
41
+ return false; // other host, within stale window — respect it
42
+ }
43
+ async function tryTakeover(fs, path, dir, nowMs, staleMs, hostname) {
44
+ let owner = null;
45
+ let ageOk = false;
46
+ try {
47
+ owner = JSON.parse(fs.readFileSync(path.join(dir, "owner.json"), "utf8"));
48
+ }
49
+ catch {
50
+ // No/corrupt owner.json: fall back to the directory's own age so a crash between
51
+ // mkdir and the owner write cannot wedge the store.
52
+ try {
53
+ ageOk = nowMs - fs.statSync(dir).mtimeMs > staleMs;
54
+ }
55
+ catch {
56
+ return true;
57
+ } // dir vanished — free
58
+ }
59
+ const stale = owner ? ownerIsStale(owner, nowMs, staleMs, hostname) : ageOk;
60
+ if (!stale)
61
+ return false;
62
+ try {
63
+ fs.rmSync(dir, { recursive: true, force: true });
64
+ return true;
65
+ }
66
+ catch {
67
+ return false;
68
+ } // a concurrent takeover won — treat as still held this round
69
+ }
70
+ /**
71
+ * Run `fn` holding the cron-store lock. Always releases (including on throw).
72
+ * Throws CronLockBusyError when the lock cannot be acquired within timeoutMs.
73
+ */
74
+ export async function withJobsLock(fn, opts = {}) {
75
+ const fs = (await nodeImport("node:fs"));
76
+ const path = (await nodeImport("node:path"));
77
+ const os = (await nodeImport("node:os"));
78
+ const dir = opts.lockDir ?? cronLockDir();
79
+ const timeoutMs = opts.timeoutMs ?? DEFAULT_TIMEOUT_MS;
80
+ const pollMs = opts.pollMs ?? DEFAULT_POLL_MS;
81
+ const staleMs = opts.staleMs ?? DEFAULT_STALE_MS;
82
+ const hostname = os.hostname();
83
+ const deadline = Date.now() + timeoutMs;
84
+ fs.mkdirSync(path.dirname(dir), { recursive: true });
85
+ for (;;) {
86
+ try {
87
+ fs.mkdirSync(dir); // atomic: exactly one winner
88
+ break;
89
+ }
90
+ catch (e) {
91
+ if (e?.code !== "EEXIST")
92
+ throw e;
93
+ if (await tryTakeover(fs, path, dir, Date.now(), staleMs, hostname))
94
+ continue;
95
+ if (Date.now() >= deadline) {
96
+ let holder = "another process";
97
+ try {
98
+ const o = JSON.parse(fs.readFileSync(path.join(dir, "owner.json"), "utf8"));
99
+ holder = `pid ${o.pid}@${o.host}`;
100
+ }
101
+ catch { /* unreadable */ }
102
+ throw new CronLockBusyError(holder);
103
+ }
104
+ await new Promise((r) => setTimeout(r, pollMs));
105
+ }
106
+ }
107
+ try {
108
+ const owner = { pid: process.pid, host: hostname, acquiredAt: Date.now() };
109
+ fs.writeFileSync(path.join(dir, "owner.json"), JSON.stringify(owner), "utf8");
110
+ }
111
+ catch { /* best-effort metadata — the dir itself is the lock */ }
112
+ try {
113
+ return await fn();
114
+ }
115
+ finally {
116
+ try {
117
+ fs.rmSync(dir, { recursive: true, force: true });
118
+ }
119
+ catch { /* released by takeover */ }
120
+ }
121
+ }