@speculoai/baton 0.0.0-stage → 0.5.0

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.
@@ -0,0 +1,320 @@
1
+ import fs from "node:fs";
2
+ import path from "node:path";
3
+ import { spawn } from "node:child_process";
4
+ import { createInterface } from "node:readline";
5
+ import { getAdapter } from "./adapters/index.js";
6
+ import { buildPrompt, interpret } from "./contract.js";
7
+ import { baselineToSnapshot, gitChanges, gitRepoRoot, gitSnapshot, pathsSinceBaseline } from "./git.js";
8
+ import { applyScopePolicy, findScopeViolations, isDirUnderCwd, relativizeToTaskCwd } from "./scope.js";
9
+ import { resolveRulesync, rulesGitRoot, rulesyncCheck } from "./rules.js";
10
+ import { appendEvent, readMeta, writeMeta, readTurn, writeTurn, taskDir, lockTask } from "./store.js";
11
+ import { redact } from "./redact.js";
12
+ import { killGroup } from "./process.js";
13
+ const QUOTA_PHRASES = ["usage limit", "quota exceeded", "rate limit"];
14
+ function withoutHtml(text) {
15
+ return String(text || "")
16
+ .replace(/<!doctype[\s\S]*?(?:<\/html>|$)/gi, "")
17
+ .replace(/<html[\s\S]*?(?:<\/html>|$)/gi, "")
18
+ .trim();
19
+ }
20
+ function terminalReason(text) {
21
+ let found = "";
22
+ for (const line of String(text || "").split(/\r?\n/)) {
23
+ const trimmed = line.trim();
24
+ if (!/turn\.failed/i.test(trimmed))
25
+ continue;
26
+ try {
27
+ const obj = JSON.parse(trimmed);
28
+ const msg = obj?.error?.message || obj?.message;
29
+ if (typeof msg === "string" && msg.trim()) {
30
+ found = msg.trim();
31
+ continue;
32
+ }
33
+ }
34
+ catch {
35
+ // Plain log line, not a JSON event.
36
+ }
37
+ found = trimmed;
38
+ }
39
+ return found;
40
+ }
41
+ function isQuotaFailure(text) {
42
+ const hay = String(text || "").toLowerCase();
43
+ return QUOTA_PHRASES.some((phrase) => hay.includes(phrase));
44
+ }
45
+ function quotaSentence(text) {
46
+ const lines = String(text || "").split(/\r?\n/);
47
+ for (let i = lines.length - 1; i >= 0; i -= 1) {
48
+ if (isQuotaFailure(lines[i]))
49
+ return lines[i].trim();
50
+ }
51
+ return "";
52
+ }
53
+ function failureSummary(stdout, stderr) {
54
+ const combined = `${stdout || ""}\n${stderr || ""}`;
55
+ const reason = terminalReason(combined);
56
+ if (reason)
57
+ return reason.slice(-8192);
58
+ return (withoutHtml(stderr) || withoutHtml(stdout)).slice(-8192);
59
+ }
60
+ export async function supervise(id) {
61
+ const release = lockTask(id);
62
+ if (!release)
63
+ return;
64
+ const meta = readMeta(id);
65
+ if (!meta || meta.status !== "running" || meta.supervisor_pid !== null) {
66
+ release();
67
+ return;
68
+ }
69
+ let childPid = null;
70
+ let stopped = null;
71
+ const stop = (reason) => {
72
+ if (!stopped)
73
+ stopped = reason;
74
+ killGroup(childPid);
75
+ };
76
+ const cancel = () => stop("cancelled");
77
+ process.on("SIGTERM", cancel);
78
+ try {
79
+ meta.supervisor_pid = process.pid;
80
+ meta.heartbeat_at = new Date().toISOString();
81
+ writeMeta(meta);
82
+ }
83
+ finally {
84
+ release();
85
+ }
86
+ const turn = readTurn(id, meta.turn);
87
+ const adapter = getAdapter(meta.target);
88
+ if (!adapter)
89
+ throw new Error("Unknown target.");
90
+ const save = () => { meta.updated_at = new Date().toISOString(); writeMeta(meta); };
91
+ const emit = (data) => {
92
+ meta.last_event_at = new Date().toISOString();
93
+ appendEvent(id, { ...data, ts: meta.last_event_at, turn: meta.turn });
94
+ save();
95
+ };
96
+ emit({ type: "turn_started", author: turn.author, prompt_preview: redact(turn.prompt).slice(0, 200) });
97
+ const heartbeat = setInterval(() => { meta.heartbeat_at = new Date().toISOString(); save(); }, 10_000);
98
+ // rulesync --check before the idle timer so its duration does not count against the worker.
99
+ if (meta.turn === 1 && meta.rules?.rulesync?.status === "pending") {
100
+ const repoRoot = rulesGitRoot(meta.cwd) ?? meta.cwd;
101
+ const rulesyncBin = resolveRulesync(repoRoot);
102
+ if (rulesyncBin) {
103
+ const checked = await rulesyncCheck(rulesyncBin, repoRoot);
104
+ meta.rules.rulesync = {
105
+ ...meta.rules.rulesync,
106
+ status: checked.status,
107
+ detail: checked.detail,
108
+ };
109
+ save();
110
+ }
111
+ else {
112
+ meta.rules.rulesync = {
113
+ ...meta.rules.rulesync,
114
+ status: "skipped",
115
+ detail: "rulesync not found in node_modules/.bin or PATH",
116
+ };
117
+ save();
118
+ }
119
+ }
120
+ const before = gitSnapshot(meta.cwd);
121
+ let stdout = "";
122
+ let stderr = "";
123
+ let message = "";
124
+ let code = null;
125
+ let spec;
126
+ let lastMessageCreated = false;
127
+ const startedAt = Date.now();
128
+ let lastByteAt = startedAt;
129
+ const timeout = setInterval(() => {
130
+ if (Date.now() - lastByteAt >= meta.idle_timeout_s * 1000)
131
+ stop("idle");
132
+ else if (meta.max_duration_s !== null && Date.now() - startedAt >= meta.max_duration_s * 1000)
133
+ stop("max_duration");
134
+ }, 50);
135
+ try {
136
+ const bin = adapter.resolve(process.env);
137
+ if (!bin)
138
+ throw new Error(`${meta.target} is not on PATH.`);
139
+ spec = adapter.build({
140
+ bin,
141
+ cwd: meta.cwd,
142
+ prompt: buildPrompt(turn.prompt, turn.files),
143
+ sessionId: meta.session_id,
144
+ reasoningEffort: meta.reasoning_effort ?? null,
145
+ model: meta.model ?? null,
146
+ mode: meta.mode ?? null,
147
+ });
148
+ meta.warning = spec.warning;
149
+ if (meta.mode !== "readonly" && !gitRepoRoot(meta.cwd)) {
150
+ const note = "cwd is not a git repository; changes cannot be tracked or reverted.";
151
+ meta.warning = meta.warning ? `${meta.warning}; ${note}` : note;
152
+ }
153
+ if (spec.modelArg !== undefined)
154
+ meta.model_argv = spec.modelArg;
155
+ else
156
+ delete meta.model_argv;
157
+ if (spec.lastMessagePath) {
158
+ fs.writeFileSync(spec.lastMessagePath, "", { mode: 0o600, flag: "wx" });
159
+ lastMessageCreated = true;
160
+ }
161
+ const child = spawn(spec.command, spec.args, { cwd: meta.cwd, env: { ...process.env, BATON_DELEGATION: "1" }, detached: true, stdio: [spec.stdin == null ? "ignore" : "pipe", "pipe", "pipe"] });
162
+ childPid = child.pid ?? null;
163
+ meta.child_pid = childPid;
164
+ if (stopped)
165
+ killGroup(childPid);
166
+ save();
167
+ for (const stream of ["stdout", "stderr"]) {
168
+ const file = path.join(taskDir(id), "raw", `${meta.turn}.${stream}.log`);
169
+ fs.writeFileSync(file, "", { mode: 0o600 });
170
+ const output = child[stream];
171
+ output.on("data", (chunk) => {
172
+ lastByteAt = Date.now();
173
+ fs.appendFileSync(file, chunk);
174
+ // shortcut: Only the most recent 2MB is kept for interpretation; full output always stays in raw; extend parsing if markers must span windows.
175
+ if (stream === "stdout")
176
+ stdout = (stdout + chunk.toString()).slice(-2_000_000);
177
+ else
178
+ stderr = (stderr + chunk.toString()).slice(-2_000_000);
179
+ });
180
+ const reader = createInterface({ input: output, crlfDelay: Infinity });
181
+ reader.on("line", (line) => {
182
+ const session = stream === "stdout" ? adapter.sessionIdFrom(line) : null;
183
+ if (session)
184
+ meta.session_id = session;
185
+ const events = stream === "stdout" ? adapter.parseLine(line) : null;
186
+ if (events === null)
187
+ emit({ type: "raw", stream, line });
188
+ else
189
+ for (const event of events) {
190
+ if (event.type === "message")
191
+ message = event.text;
192
+ emit(event);
193
+ }
194
+ });
195
+ }
196
+ const exited = new Promise((resolve, reject) => {
197
+ child.once("error", reject);
198
+ child.once("close", resolve);
199
+ });
200
+ child.stdin?.on("error", () => { }); // the child CLI may exit before reading stdin; close will deliver the final result.
201
+ child.stdin?.end(spec.stdin ?? undefined);
202
+ code = await exited;
203
+ if (spec.lastMessagePath) {
204
+ try {
205
+ const last = fs.readFileSync(spec.lastMessagePath, "utf8").trim();
206
+ if (last)
207
+ message = last;
208
+ }
209
+ catch { /* keep legacy behavior: use stream messages when the CLI wrote no file. */ }
210
+ }
211
+ }
212
+ catch (error) {
213
+ killGroup(childPid);
214
+ stderr += error.message;
215
+ emit({ type: "error", text: error.message });
216
+ code = 1;
217
+ }
218
+ finally {
219
+ clearInterval(heartbeat);
220
+ clearInterval(timeout);
221
+ if (lastMessageCreated && spec?.lastMessagePath)
222
+ fs.rmSync(spec.lastMessagePath, { force: true });
223
+ }
224
+ const raw = `${stderr}\n${stdout}`;
225
+ const marker = interpret(message || stdout);
226
+ let final = "failed";
227
+ let summary = failureSummary(stdout, stderr);
228
+ if (stopped) {
229
+ final = stopped === "cancelled" ? "cancelled" : "timed_out";
230
+ summary = stopped === "cancelled" ? "Cancelled." : `Timed out: ${stopped}.`;
231
+ }
232
+ else if (code !== 0 && adapter.isAuthFailure(raw)) {
233
+ final = "not_authenticated";
234
+ summary = stderr || message || stdout;
235
+ }
236
+ else if (code !== 0 && isQuotaFailure(raw)) {
237
+ final = "quota_exceeded";
238
+ summary = terminalReason(raw) || quotaSentence(raw);
239
+ }
240
+ else if (marker?.kind === "decision") {
241
+ final = "needs_input";
242
+ meta.decision = { question: marker.question, options: marker.options };
243
+ summary = marker.question;
244
+ }
245
+ else if (code === 0) {
246
+ final = "success";
247
+ summary = marker?.kind === "result" ? marker.summary : message || stdout;
248
+ }
249
+ meta.summary = redact(summary).slice(-8192);
250
+ meta.status = final;
251
+ const after = gitSnapshot(meta.cwd);
252
+ turn.git_changes = gitChanges(meta.cwd, before, after);
253
+ if (meta.mode === "readonly" && final === "success") {
254
+ if (!meta.readonly_baseline) {
255
+ const note = "readonly: not a git directory; skipping post-run check";
256
+ meta.warning = meta.warning ? `${meta.warning}; ${note}` : note;
257
+ }
258
+ else if (!after) {
259
+ final = "readonly_violation";
260
+ meta.status = final;
261
+ meta.summary = `readonly_violation: git snapshot failed\n${meta.summary ?? ""}`;
262
+ }
263
+ else {
264
+ const dirty = pathsSinceBaseline(meta.cwd, baselineToSnapshot(meta.readonly_baseline), after);
265
+ if (dirty.length) {
266
+ final = "readonly_violation";
267
+ meta.status = final;
268
+ meta.summary = `readonly_violation: ${dirty.length} file(s)\n${meta.summary ?? ""}`;
269
+ }
270
+ }
271
+ }
272
+ if (meta.scope?.length && meta.scope_baseline && final !== "readonly_violation") {
273
+ if (!after) {
274
+ const note = "scope_violation: git snapshot failed; cannot verify scope";
275
+ meta.warning = meta.warning ? `${meta.warning}; ${note}` : note;
276
+ meta.scope_violations = ["<snapshot-unavailable>"];
277
+ if ((meta.scope_on_violation ?? "warn") === "fail" && final === "success") {
278
+ final = "scope_violation";
279
+ meta.status = final;
280
+ meta.summary = `scope_violation: see scope_violations\n${meta.summary ?? ""}`;
281
+ }
282
+ }
283
+ else {
284
+ try {
285
+ const repoRoot = gitRepoRoot(meta.cwd) ?? meta.cwd;
286
+ const relPaths = relativizeToTaskCwd(pathsSinceBaseline(meta.cwd, baselineToSnapshot(meta.scope_baseline), after), repoRoot, meta.cwd);
287
+ const violations = findScopeViolations(relPaths, meta.scope, {
288
+ isDir: (pattern) => isDirUnderCwd(meta.cwd, pattern),
289
+ });
290
+ const applied = applyScopePolicy({
291
+ final,
292
+ policy: meta.scope_on_violation ?? "warn",
293
+ violations,
294
+ summary: meta.summary,
295
+ warning: meta.warning,
296
+ });
297
+ final = applied.status;
298
+ meta.status = final;
299
+ meta.summary = applied.summary;
300
+ meta.warning = applied.warning;
301
+ meta.scope_violations = applied.scope_violations;
302
+ }
303
+ catch (error) {
304
+ const note = `scope_violation: ${error.message}`;
305
+ meta.warning = meta.warning ? `${meta.warning}; ${note}` : note;
306
+ meta.scope_violations = ["<diff-unavailable>"];
307
+ if ((meta.scope_on_violation ?? "warn") === "fail" && final === "success") {
308
+ final = "scope_violation";
309
+ meta.status = final;
310
+ meta.summary = `scope_violation: see scope_violations\n${meta.summary ?? ""}`;
311
+ }
312
+ }
313
+ }
314
+ }
315
+ turn.status = final;
316
+ turn.summary = meta.summary;
317
+ writeTurn(id, turn);
318
+ emit({ type: "turn_ended", status: final, exit_code: code });
319
+ process.off("SIGTERM", cancel);
320
+ }
package/dist/tail.js ADDED
@@ -0,0 +1,64 @@
1
+ import fs from "node:fs";
2
+ import path from "node:path";
3
+ import { setTimeout as sleep } from "node:timers/promises";
4
+ import { taskDir } from "./store.js";
5
+ import { status } from "./tasks.js";
6
+ import { StringDecoder } from "node:string_decoder";
7
+ export function formatEvent(event) {
8
+ const prefix = `[${event.ts}] turn ${event.turn}`;
9
+ switch (event.type) {
10
+ case "turn_started": return `${prefix} ${event.author}: ${event.prompt_preview}`;
11
+ case "message": return `${prefix} ${event.text}`;
12
+ case "tool_call": return `${prefix} call ${event.name}: ${event.detail}`;
13
+ case "tool_result": return `${prefix} ${event.name} ${event.ok ? "ok" : "failed"}: ${event.detail}`;
14
+ case "error": return `${prefix} error: ${event.text}`;
15
+ case "raw": return `${prefix} ${event.stream}: ${event.line}`;
16
+ case "turn_ended": return `${prefix} ended: ${event.status} (exit ${event.exit_code})`;
17
+ }
18
+ }
19
+ export async function tail(id, options = {}) {
20
+ status(id);
21
+ const file = path.join(taskDir(id), "events.jsonl");
22
+ let offset = 0;
23
+ let pending = "";
24
+ const decoder = new StringDecoder("utf8");
25
+ const drain = () => {
26
+ let fd;
27
+ try {
28
+ fd = fs.openSync(file, "r");
29
+ }
30
+ catch (error) {
31
+ if (error.code === "ENOENT")
32
+ return;
33
+ throw error;
34
+ }
35
+ try {
36
+ const buffer = Buffer.alloc(64 * 1024);
37
+ let bytes;
38
+ while ((bytes = fs.readSync(fd, buffer, 0, buffer.length, offset)) > 0) {
39
+ offset += bytes;
40
+ pending += decoder.write(buffer.subarray(0, bytes));
41
+ }
42
+ let newline;
43
+ while ((newline = pending.indexOf("\n")) !== -1) {
44
+ const line = pending.slice(0, newline);
45
+ pending = pending.slice(newline + 1);
46
+ if (line)
47
+ process.stdout.write(`${options.raw ? line : formatEvent(JSON.parse(line))}\n`);
48
+ }
49
+ }
50
+ finally {
51
+ fs.closeSync(fd);
52
+ }
53
+ };
54
+ for (;;) {
55
+ drain();
56
+ if (!options.follow)
57
+ return;
58
+ if (status(id).status !== "running") {
59
+ drain();
60
+ return;
61
+ }
62
+ await sleep(100);
63
+ }
64
+ }