benignswarm 0.12.110 → 0.12.112
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/antigravity.js +3 -1
- package/dist/client.js +2 -2
- package/dist/commands/install.js +77 -13
- package/dist/commands/join.js +3 -5
- package/dist/commands/lists.js +2 -2
- package/dist/commands/machine-admin.js +5 -2
- package/dist/commands/machine.js +176 -34
- package/dist/commands/watch.js +3 -3
- package/dist/commands/worktrees.js +11 -2
- package/dist/commands/wu.js +4 -2
- package/dist/git.js +57 -4
- package/dist/harness-server-sweep.js +78 -0
- package/dist/harnesses.js +57 -12
- package/dist/help.js +3 -0
- package/dist/install.js +122 -24
- package/dist/lock.js +2 -1
- package/dist/log-rotation.js +65 -0
- package/dist/tail-lines.js +90 -0
- package/dist/turn.js +51 -2
- package/dist/usage.js +48 -12
- package/dist/version.js +1 -1
- package/package.json +1 -1
package/dist/harnesses.js
CHANGED
|
@@ -6,7 +6,8 @@ import { CliError } from "./errors.js";
|
|
|
6
6
|
import { configRoot } from "./config.js";
|
|
7
7
|
import { readState, writeState } from "./state.js";
|
|
8
8
|
import { codexArchivedRollout, codexRollout } from "./sessions.js";
|
|
9
|
-
import {
|
|
9
|
+
import { readTurnPhase, usageLimitUntil } from "./turn.js";
|
|
10
|
+
import { FileFactsCache, scanLinesBackward, TAIL_CHUNK_BYTES, TAIL_MAX_BYTES } from "./tail-lines.js";
|
|
10
11
|
import { antigravityProbe } from "./antigravity.js";
|
|
11
12
|
/**
|
|
12
13
|
* Harnesses a machine can run headless in turn mode (docs/REMOTE-MACHINES.md, "Harness adapters").
|
|
@@ -331,12 +332,15 @@ export function dshProbe(session, ref, path = dshTurnLog(ref), processes) {
|
|
|
331
332
|
};
|
|
332
333
|
}
|
|
333
334
|
function codexProbe(thread) {
|
|
334
|
-
const read = () => { const r = codexRollout(thread); return r ?
|
|
335
|
+
const read = () => { const r = codexRollout(thread); return r ? readTurnPhase(r) : null; };
|
|
335
336
|
return {
|
|
336
337
|
label: "Codex",
|
|
337
338
|
what: `thread ${thread}`,
|
|
338
339
|
phase() {
|
|
339
340
|
const ph = read();
|
|
341
|
+
// A reader that hit its cap without deciding never reports idle: start nothing, report unknown.
|
|
342
|
+
if (ph?.unknown)
|
|
343
|
+
return { missing: `${ph.unknown}; cannot tell whether a turn is running, so starting none`, unknown: true };
|
|
340
344
|
if (ph)
|
|
341
345
|
return { ...ph, lastErrorAt: ph.lastEventAt };
|
|
342
346
|
return {
|
|
@@ -351,17 +355,24 @@ function codexProbe(thread) {
|
|
|
351
355
|
const path = codexRollout(thread);
|
|
352
356
|
if (!path)
|
|
353
357
|
return "";
|
|
354
|
-
|
|
358
|
+
// The last 800 characters of assistant text: read from the end until that much is collected (WU #474).
|
|
359
|
+
const messages = [];
|
|
360
|
+
let collected = 0;
|
|
361
|
+
scanLinesBackward(path, (line) => {
|
|
362
|
+
let event;
|
|
355
363
|
try {
|
|
356
|
-
|
|
357
|
-
if (event.type !== "response_item" || event.payload?.type !== "message" || event.payload.message?.role !== "assistant")
|
|
358
|
-
return [];
|
|
359
|
-
const content = event.payload.message.content;
|
|
360
|
-
return typeof content === "string" ? [content] : Array.isArray(content) ? content.flatMap((part) => typeof part.text === "string" ? [part.text] : []) : [];
|
|
364
|
+
event = JSON.parse(line);
|
|
361
365
|
}
|
|
362
366
|
catch {
|
|
363
|
-
return
|
|
367
|
+
return false;
|
|
364
368
|
}
|
|
369
|
+
if (event.type !== "response_item" || event.payload?.type !== "message" || event.payload.message?.role !== "assistant")
|
|
370
|
+
return false;
|
|
371
|
+
const content = event.payload.message.content;
|
|
372
|
+
const parts = typeof content === "string" ? [content] : Array.isArray(content) ? content.flatMap((part) => typeof part.text === "string" ? [part.text] : []) : [];
|
|
373
|
+
messages.unshift(...parts);
|
|
374
|
+
collected += parts.reduce((n, t) => n + t.length + 1, 0);
|
|
375
|
+
return collected >= 800;
|
|
365
376
|
});
|
|
366
377
|
return messages.join("\n").slice(-800);
|
|
367
378
|
},
|
|
@@ -370,7 +381,7 @@ function codexProbe(thread) {
|
|
|
370
381
|
};
|
|
371
382
|
}
|
|
372
383
|
// ---- Claude Code ----
|
|
373
|
-
const claudeHome = () => process.env.CLAUDE_CONFIG_DIR ?? join(homedir(), ".claude");
|
|
384
|
+
export const claudeHome = () => process.env.CLAUDE_CONFIG_DIR ?? join(homedir(), ".claude");
|
|
374
385
|
/** A Claude Code session's transcript (~/.claude/projects/<folder>/<id>.jsonl), wherever its folder is. */
|
|
375
386
|
export function claudeTranscript(session) {
|
|
376
387
|
const root = join(claudeHome(), "projects");
|
|
@@ -409,6 +420,37 @@ export function claudeTranscriptTimes(text) {
|
|
|
409
420
|
}
|
|
410
421
|
return { lastEventAt, promptAt };
|
|
411
422
|
}
|
|
423
|
+
/**
|
|
424
|
+
* claudeTranscriptTimes for a transcript file, read from the end to the latest user prompt (WU #474).
|
|
425
|
+
* `capped` is set when the prompt was not found within the read cap: the prompt time is then unknown.
|
|
426
|
+
*/
|
|
427
|
+
export function claudeTranscriptTimesFromFile(path, chunkBytes = TAIL_CHUNK_BYTES, maxBytes = TAIL_MAX_BYTES) {
|
|
428
|
+
let lastEventAt = null;
|
|
429
|
+
let promptAt = null;
|
|
430
|
+
const scan = scanLinesBackward(path, (line) => {
|
|
431
|
+
let j;
|
|
432
|
+
try {
|
|
433
|
+
j = JSON.parse(line);
|
|
434
|
+
}
|
|
435
|
+
catch {
|
|
436
|
+
return false;
|
|
437
|
+
} // a line still being written
|
|
438
|
+
if (!j.timestamp)
|
|
439
|
+
return false;
|
|
440
|
+
if (lastEventAt === null)
|
|
441
|
+
lastEventAt = j.timestamp;
|
|
442
|
+
if (j.type === "user" && typeof j.message?.content === "string") {
|
|
443
|
+
promptAt = j.timestamp;
|
|
444
|
+
return true;
|
|
445
|
+
}
|
|
446
|
+
return false;
|
|
447
|
+
}, chunkBytes, maxBytes);
|
|
448
|
+
return scan.capped ? { lastEventAt, promptAt, capped: true } : { lastEventAt, promptAt };
|
|
449
|
+
}
|
|
450
|
+
const claudeTimesCache = new FileFactsCache();
|
|
451
|
+
function readClaudeTranscriptTimes(path) {
|
|
452
|
+
return claudeTimesCache.get(path, (p) => claudeTranscriptTimesFromFile(p));
|
|
453
|
+
}
|
|
412
454
|
/**
|
|
413
455
|
* The error a `claude -p --output-format json` run ended with, or null when it succeeded. Output
|
|
414
456
|
* that is not the result object (a missing session prints plain text) is returned as the error.
|
|
@@ -484,15 +526,18 @@ function claudeProbe(session, ref) {
|
|
|
484
526
|
const tr = claudeTranscript(session);
|
|
485
527
|
if (!tr)
|
|
486
528
|
return { missing: `no transcript for Claude Code session ${session} under ${join(claudeHome(), "projects")}; cannot tell whether a turn is running, so starting none` };
|
|
487
|
-
const times =
|
|
529
|
+
const times = readClaudeTranscriptTimes(tr);
|
|
488
530
|
// Claude Code writes no turn-ended marker, so a running turn is a process holding the session.
|
|
489
531
|
const running = sessionProcesses(session).length > 0;
|
|
532
|
+
// No process and no prompt within the read cap: the bounded read can't place the latest turn, so it never reports idle.
|
|
533
|
+
if (!running && times.capped)
|
|
534
|
+
return { missing: `no user prompt within the last ${Math.round(TAIL_MAX_BYTES / 1048576)} MB of ${tr}; cannot tell where the latest turn stands, so starting none`, unknown: true };
|
|
490
535
|
const res = lastResult();
|
|
491
536
|
return { running, startedAt: times.promptAt, lastEventAt: times.lastEventAt, lastError: running ? null : res?.error ?? null, lastErrorAt: res?.at ?? null };
|
|
492
537
|
},
|
|
493
538
|
startedSince(ms) {
|
|
494
539
|
const tr = claudeTranscript(session);
|
|
495
|
-
const p = tr ?
|
|
540
|
+
const p = tr ? readClaudeTranscriptTimes(tr).promptAt : null;
|
|
496
541
|
return !!p && Date.parse(p) >= ms - 5_000;
|
|
497
542
|
},
|
|
498
543
|
turnError: () => lastResult()?.error ?? null,
|
package/dist/help.js
CHANGED
|
@@ -22,6 +22,7 @@ GET /account/usage reports used and allowed micro-dollars, uncertain calls and t
|
|
|
22
22
|
Session/admin clients can use GET /assistant/conversations, GET /assistant/conversations/:id/messages (paged history with saved tool notices), POST /assistant/conversations/:id/messages (SSE), and DELETE /assistant/conversations/:id. Old assistant messages report notices_available=false. The assistant can draft changes; POST /assistant/proposals/:id/apply or /discard is the operator's explicit action. See the agent/operator skill API reference for events and tools.
|
|
23
23
|
Free and paid accounts without a live Stripe subscription use the UTC calendar month; subscribed paid accounts reset at current_period_end.
|
|
24
24
|
|
|
25
|
+
Mac capacity/signing records and the hosted lease allocate/drain intents are documented in docs/MACOS-MACHINES-API.md. Allocation consumes WU #403's reviewed controller outputs; the API does not widen IAM. There is no CLI stop/release bypass. Operator controls are in the named hosted Mac lease console unit WU #381; signing remains a separate trusted worker.
|
|
25
26
|
Mac capacity/signing API (profiles, leases, signer-only references, TestFlight approvals, and the isolated signer job contract) is documented in docs/MACOS-MACHINES-API.md. There is no CLI command to issue signer-host credentials or trigger release; operator controls are WU #286, real host/provider integration is WU #288.
|
|
26
27
|
Standing rules are resolved by account, project, role, and exact-agent scope. GET /agents/me/standing-rules and GET /projects/:p/standing-rules return complete authorized sets and fingerprints; their separate ack endpoints accept only a current fingerprint after complete delivery. Operators and authorized assigners manage rules through the API; limits, compatibility confirmation, audit, and authorization are in packages/skill/references/api.md. Console management and chat promotion are planned in implementation unit 3 of docs/STANDING-RULES.md.
|
|
27
28
|
|
|
@@ -118,6 +119,7 @@ Agent commands
|
|
|
118
119
|
b9s milestone review <key> assigner or operator: request a closure review now (the steward does it when the last unit closes)
|
|
119
120
|
b9s lock <name> [--unit n] [--note ..] [--shared] take this machine's <name> (build slot, scratch) or queue; --shared for a project-wide resource (a test board)
|
|
120
121
|
acquisition queues through a machine maintenance drain/window and resumes after it
|
|
122
|
+
machine identity is this host's hostname plus its registered label, shared by all agents here
|
|
121
123
|
b9s unlock <name> [--machine <label>|--shared] [--remove-empty] | b9s locks
|
|
122
124
|
release it (also released when your unit closes); assigners/operators can remove an empty scoped lock with --remove-empty
|
|
123
125
|
lock names acquire/list/release/show/status are reserved: use lock <name>, locks, or unlock <name> as suggested
|
|
@@ -234,6 +236,7 @@ Machine placement shares capacity across the account's projects: session seats a
|
|
|
234
236
|
b9s machine run [--interval seconds] | once | build-images | status | prepare [--agy-userns] [--print-apparmor] | service
|
|
235
237
|
default interval 30s, 1..3600; prepare checks harnesses; --agy-userns opts into an AppArmor
|
|
236
238
|
profile for the resolved agy binary if Ubuntu blocks its workspace-write terminal sandbox (passwordless sudo)
|
|
239
|
+
Antigravity workspace-write readiness makes an authenticated b9s me call inside the sandbox
|
|
237
240
|
b9s machine processes --worktree <path> [--as <project>/<agent>] [--json] read-only host process sample for a project-owned worktree
|
|
238
241
|
includes pid/parent, start/elapsed, command (120 chars), cwd, TCP listeners and sample time
|
|
239
242
|
project agents only; stale samples are labelled; command credentials are redacted; no environment values or signaling
|
package/dist/install.js
CHANGED
|
@@ -134,14 +134,20 @@ export function binVersion(bin) {
|
|
|
134
134
|
return m ? m[1] : null;
|
|
135
135
|
}
|
|
136
136
|
/** The npm belonging to the Node running this process: the same runtime installs and runs b9s. */
|
|
137
|
-
function ownNpm() {
|
|
138
|
-
const npm = join(dirname(
|
|
137
|
+
export function ownNpm(execPath = process.execPath) {
|
|
138
|
+
const npm = join(dirname(execPath), "npm");
|
|
139
139
|
if (!existsSync(npm))
|
|
140
|
-
throw new CliError("no_npm", `no npm next to the Node running b9s (${
|
|
140
|
+
throw new CliError("no_npm", `no npm next to the Node running b9s (${execPath})`, "Install b9s with that Node's npm yourself (npm i -g benignswarm), then run: b9s install");
|
|
141
141
|
return npm;
|
|
142
142
|
}
|
|
143
|
+
/** npm scripts commonly use /usr/bin/env node, so PATH must select the Node beside this npm. */
|
|
144
|
+
function npmEnv(npm) {
|
|
145
|
+
const npmBin = dirname(resolve(npm));
|
|
146
|
+
const rest = (process.env.PATH ?? "").split(delimiter).filter((entry) => entry && resolve(entry) !== npmBin);
|
|
147
|
+
return { ...process.env, PATH: [npmBin, ...rest].join(delimiter) };
|
|
148
|
+
}
|
|
143
149
|
export function latestPublished(npm) {
|
|
144
|
-
const r = spawnSync(npm, ["view", "benignswarm", "version", "--prefer-online"], { encoding: "utf8", timeout: 60_000 });
|
|
150
|
+
const r = spawnSync(npm, ["view", "benignswarm", "version", "--prefer-online"], { encoding: "utf8", timeout: 60_000, env: npmEnv(npm) });
|
|
145
151
|
const v = (r.stdout ?? "").trim();
|
|
146
152
|
if (r.status !== 0 || !/^\d+\.\d+\.\d+$/.test(v))
|
|
147
153
|
throw new CliError("npm_view_failed", `could not ask npm for the latest benignswarm version (${npm})`, (r.stderr ?? "").trim().slice(0, 300));
|
|
@@ -154,7 +160,8 @@ export function latestPublished(npm) {
|
|
|
154
160
|
*/
|
|
155
161
|
export function ensureInstall(version, log, npmOverride) {
|
|
156
162
|
const npm = npmOverride ?? ownNpm();
|
|
157
|
-
const
|
|
163
|
+
const env = npmEnv(npm);
|
|
164
|
+
const pre = spawnSync(npm, ["prefix", "-g"], { encoding: "utf8", timeout: 30_000, env });
|
|
158
165
|
if (pre.status !== 0)
|
|
159
166
|
throw new CliError("npm_prefix_failed", `${npm} prefix -g failed`, (pre.stderr ?? "").trim().slice(0, 300));
|
|
160
167
|
const bin = join(pre.stdout.trim(), "bin", "b9s");
|
|
@@ -164,7 +171,7 @@ export function ensureInstall(version, log, npmOverride) {
|
|
|
164
171
|
}
|
|
165
172
|
else {
|
|
166
173
|
log(`${current ? `upgrading b9s ${current}` : "installing b9s"} to ${version} with ${npm}`);
|
|
167
|
-
const r = spawnSync(npm, ["i", "-g", `benignswarm@${version}`, "--prefer-online"], { stdio: ["ignore", 2, 2], timeout: 300_000 });
|
|
174
|
+
const r = spawnSync(npm, ["i", "-g", `benignswarm@${version}`, "--prefer-online"], { stdio: ["ignore", 2, 2], timeout: 300_000, env });
|
|
168
175
|
if (r.status !== 0)
|
|
169
176
|
throw new CliError("install_failed", `npm i -g benignswarm@${version} failed (exit ${r.status}) using ${npm}`, "Fix that npm's global prefix (permissions, network) or install it yourself, then run: b9s install");
|
|
170
177
|
const got = binVersion(bin);
|
|
@@ -179,6 +186,34 @@ export function ensureInstall(version, log, npmOverride) {
|
|
|
179
186
|
writeFileSync(installFile(), JSON.stringify(rec, null, 2) + "\n");
|
|
180
187
|
return rec;
|
|
181
188
|
}
|
|
189
|
+
/**
|
|
190
|
+
* Join/setup may refresh the machine install, but only within its recorded prefix. If the invoking
|
|
191
|
+
* CLI is older than the record, refuse before writing hooks instead of risking a downgrade. A first
|
|
192
|
+
* install uses this process's Node; changing the selected Node/npm is reserved for `b9s install`.
|
|
193
|
+
*/
|
|
194
|
+
export function ensureMachineInstall(version, log) {
|
|
195
|
+
const previous = readInstall();
|
|
196
|
+
if (!previous)
|
|
197
|
+
return ensureInstall(version, log, ownNpm());
|
|
198
|
+
if (!previous.npm || !existsSync(previous.npm)) {
|
|
199
|
+
throw new CliError("recorded_npm_missing", `the recorded install npm ${previous.npm || "(missing)"} is unavailable`, `Run ${previous.bin} install --latest from the Node installation you want this machine to use`);
|
|
200
|
+
}
|
|
201
|
+
const prefix = spawnSync(previous.npm, ["prefix", "-g"], { encoding: "utf8", timeout: 30_000, env: npmEnv(previous.npm) });
|
|
202
|
+
if (prefix.status !== 0)
|
|
203
|
+
throw new CliError("recorded_npm_prefix_failed", `${previous.npm} prefix -g failed`, (prefix.stderr ?? "").trim().slice(0, 300));
|
|
204
|
+
const expectedBin = join(dirname(previous.bin), "b9s");
|
|
205
|
+
const resolvedBin = join((prefix.stdout ?? "").trim(), "bin", "b9s");
|
|
206
|
+
if (resolve(expectedBin) !== resolve(resolvedBin)) {
|
|
207
|
+
throw new CliError("recorded_install_prefix_mismatch", `${previous.npm} resolves to ${resolvedBin}, but this machine records ${previous.bin}`, `Run ${previous.bin} install --latest from the Node installation you want this machine to use`);
|
|
208
|
+
}
|
|
209
|
+
// A join/setup invoked by an older npx or global copy must never write its own version back
|
|
210
|
+
// into a newer machine install. The operator can intentionally select or upgrade the install
|
|
211
|
+
// by invoking the explicit install command from the desired Node installation.
|
|
212
|
+
if (/^\d+\.\d+\.\d+$/.test(previous.version) && cmp(previous.version, version) > 0) {
|
|
213
|
+
throw new CliError("recorded_install_newer", `the recorded b9s ${previous.version} at ${previous.bin} is newer than this CLI ${version}`, `Run ${previous.bin} install --latest from the Node installation you want this machine to use`);
|
|
214
|
+
}
|
|
215
|
+
return ensureInstall(version, log, previous.npm);
|
|
216
|
+
}
|
|
182
217
|
/** Creates b9s-named shell links beside aliases of the same recorded install, without replacing another copy. */
|
|
183
218
|
export function ensureCommandLinks(installBin) {
|
|
184
219
|
const prefixBin = dirname(installBin);
|
|
@@ -245,11 +280,38 @@ export function watcherPlists() {
|
|
|
245
280
|
return [];
|
|
246
281
|
return readdirSync(dir).filter((f) => f.endsWith(".plist") && isOurService(f.slice(0, -".plist".length))).map((f) => ({ label: f.slice(0, -".plist".length), path: join(dir, f) }));
|
|
247
282
|
}
|
|
248
|
-
/**
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
|
|
283
|
+
/**
|
|
284
|
+
* The launchd domain for this user's services (WU #478). With a desktop session that is gui/<uid>, as
|
|
285
|
+
* always. A Mac with no one signed in at its desktop (FileVault unlocked over SSH, no auto-login) has no
|
|
286
|
+
* gui domain; there services are Background agents in user/<uid>, which load without a desktop session
|
|
287
|
+
* and keep running after the SSH session that loaded them ends. This is a deliberate mode, reported by
|
|
288
|
+
* doctor and machine status, never a silent substitute.
|
|
289
|
+
*/
|
|
290
|
+
export function launchdSessionNow() {
|
|
291
|
+
return spawnSync("launchctl", ["print", `gui/${process.getuid()}`], { stdio: "ignore" }).status === 0 ? "gui" : "headless";
|
|
292
|
+
}
|
|
293
|
+
/**
|
|
294
|
+
* The session-type key every LaunchAgent b9s writes carries on a Mac with no desktop session, so it loads
|
|
295
|
+
* as a Background agent in user/<uid> (WU #478). One function for every plist template: the watcher's
|
|
296
|
+
* own template in commands/watch.ts missed it at first, and mini1's first headless watcher was written for
|
|
297
|
+
* gui/<uid> and failed to load.
|
|
298
|
+
*/
|
|
299
|
+
export function launchdSessionTypeXml() {
|
|
300
|
+
return launchdSessionNow() === "headless" ? "\n <key>LimitLoadToSessionType</key><string>Background</string>" : "";
|
|
301
|
+
}
|
|
302
|
+
/** Which domain a written plist belongs to: a Background agent lives in user/<uid>, any other in gui/<uid>. */
|
|
303
|
+
export function plistLaunchdDomain(path) {
|
|
304
|
+
const r = spawnSync("plutil", ["-extract", "LimitLoadToSessionType", "raw", "-o", "-", path], { encoding: "utf8" });
|
|
305
|
+
const background = r.status === 0 && (r.stdout ?? "").trim() === "Background";
|
|
306
|
+
return `${background ? "user" : "gui"}/${process.getuid()}`;
|
|
307
|
+
}
|
|
308
|
+
export function launchdLoadedIn(label) {
|
|
309
|
+
const uid = process.getuid();
|
|
310
|
+
return [`gui/${uid}`, `user/${uid}`].filter((d) => spawnSync("launchctl", ["print", `${d}/${label}`], { stdio: "ignore" }).status === 0);
|
|
311
|
+
}
|
|
312
|
+
function launchdBootout(label, path) {
|
|
313
|
+
// A service may be loaded in either domain (a Mac that gained or lost a desktop session); unload it from each.
|
|
314
|
+
for (const domain of launchdLoadedIn(label)) {
|
|
253
315
|
const out = spawnSync("launchctl", ["bootout", `${domain}/${label}`], { encoding: "utf8" });
|
|
254
316
|
if (out.status !== 0)
|
|
255
317
|
throw new CliError("launchctl_failed", `launchctl bootout ${domain}/${label} failed`, (out.stderr ?? "").trim());
|
|
@@ -258,17 +320,60 @@ export function reloadLaunchAgent(label, path) {
|
|
|
258
320
|
const until = Date.now() + 15_000;
|
|
259
321
|
while (spawnSync("launchctl", ["print", `${domain}/${label}`], { stdio: "ignore" }).status === 0) {
|
|
260
322
|
if (Date.now() > until)
|
|
261
|
-
throw new CliError("launchctl_failed", `launchd still lists ${domain}/${label} 15 s after bootout; nothing was loaded`, `Load it yourself: launchctl bootstrap ${
|
|
323
|
+
throw new CliError("launchctl_failed", `launchd still lists ${domain}/${label} 15 s after bootout; nothing was loaded`, `Load it yourself: launchctl bootstrap ${plistLaunchdDomain(path)} ${path}`);
|
|
262
324
|
spawnSync("sleep", ["0.2"]);
|
|
263
325
|
}
|
|
264
326
|
}
|
|
327
|
+
}
|
|
328
|
+
/** The pid of a loaded LaunchAgent in whichever domain holds it, or null when it is not running. */
|
|
329
|
+
export function launchdPid(label) {
|
|
330
|
+
for (const domain of launchdLoadedIn(label)) {
|
|
331
|
+
const out = spawnSync("launchctl", ["print", `${domain}/${label}`], { encoding: "utf8" }).stdout ?? "";
|
|
332
|
+
const pid = Number(/^\s*pid = (\d+)$/m.exec(out)?.[1]);
|
|
333
|
+
if (Number.isInteger(pid) && pid > 0)
|
|
334
|
+
return pid;
|
|
335
|
+
}
|
|
336
|
+
return null;
|
|
337
|
+
}
|
|
338
|
+
/** What launchd mode this Mac's services use, for the machine report, machine status and doctor (WU #478). */
|
|
339
|
+
export function launchdFacts() {
|
|
340
|
+
const daemonPlist = join(launchAgentsDir(), `${MACHINE_LABEL}.plist`);
|
|
341
|
+
const watchers = {};
|
|
342
|
+
for (const w of watcherServices()) {
|
|
343
|
+
if (w.kind !== "launchd" || w.label === MACHINE_LABEL)
|
|
344
|
+
continue; // the daemon is reported on its own
|
|
345
|
+
const d = plistLaunchdDomain(w.path);
|
|
346
|
+
watchers[d] = (watchers[d] ?? 0) + 1;
|
|
347
|
+
}
|
|
348
|
+
return { session: launchdSessionNow(), daemon_domain: existsSync(daemonPlist) ? plistLaunchdDomain(daemonPlist) : null, watchers };
|
|
349
|
+
}
|
|
350
|
+
/**
|
|
351
|
+
* What an operator needs to know about this Mac's launchd mode when provisioning it (WU #478): which domain
|
|
352
|
+
* the services use and what a reboot or sign-out does to them.
|
|
353
|
+
*/
|
|
354
|
+
export function launchdGuidance(session = launchdSessionNow()) {
|
|
355
|
+
const uid = process.getuid();
|
|
356
|
+
return session === "headless"
|
|
357
|
+
? `launchd: headless Mac, services are Background agents in user/${uid}. After a reboot they start once someone logs in over SSH (that also unlocks FileVault); a desktop sign-in is not needed. Harness sign-ins kept in the login keychain (Claude Code's by default) are unreadable without a desktop session; Codex and Antigravity keep theirs in files. External volumes may be refused to processes started while no one is signed in at the desktop: keep the workdir on the internal disk.`
|
|
358
|
+
: `launchd: desktop session, services are LaunchAgents in gui/${uid}. They stop when that user signs out and start again at the next desktop sign-in; for a Mac meant to run unattended, use automatic sign-in, or install the services while no one is signed in so they run headless.`;
|
|
359
|
+
}
|
|
360
|
+
/** One line for status output. */
|
|
361
|
+
export function launchdFactsLine(f) {
|
|
362
|
+
const w = Object.entries(f.watchers).map(([d, n]) => `${n} in ${d}`).join(", ") || "none";
|
|
363
|
+
return `launchd: ${f.session === "headless" ? "headless Mac (no desktop session)" : "desktop session"}; daemon ${f.daemon_domain ?? "not installed"}; watchers ${w}`;
|
|
364
|
+
}
|
|
365
|
+
/** Loads (or reloads) a LaunchAgent from its plist, so what runs is what the file says. */
|
|
366
|
+
export function reloadLaunchAgent(label, path) {
|
|
367
|
+
launchdBootout(label, path);
|
|
368
|
+
const domain = plistLaunchdDomain(path);
|
|
265
369
|
const r = spawnSync("launchctl", ["bootstrap", domain, path], { encoding: "utf8" });
|
|
266
370
|
if (r.status !== 0)
|
|
267
371
|
throw new CliError("launchctl_failed", `launchctl bootstrap ${domain} ${path} failed`, (r.stderr ?? "").trim());
|
|
268
372
|
}
|
|
269
373
|
/** Restarts a loaded LaunchAgent in place (new code, same definition). */
|
|
270
374
|
export function restartLaunchAgent(label) {
|
|
271
|
-
|
|
375
|
+
const domain = launchdLoadedIn(label)[0];
|
|
376
|
+
return !!domain && spawnSync("launchctl", ["kickstart", "-k", `${domain}/${label}`], { stdio: "ignore" }).status === 0;
|
|
272
377
|
}
|
|
273
378
|
export const systemdUserDir = () => join(process.env.XDG_CONFIG_HOME ?? join(homedir(), ".config"), "systemd", "user");
|
|
274
379
|
/** Every watcher service on this machine. */
|
|
@@ -522,7 +627,7 @@ export function installService(label, args, cwd, env, logName) {
|
|
|
522
627
|
<key>WorkingDirectory</key><string>${esc(cwd)}</string>
|
|
523
628
|
<key>RunAtLoad</key><true/>
|
|
524
629
|
<key>KeepAlive</key><true/>
|
|
525
|
-
<key>AbandonProcessGroup</key><true
|
|
630
|
+
<key>AbandonProcessGroup</key><true/>${launchdSessionTypeXml()}
|
|
526
631
|
<key>StandardOutPath</key><string>${join(logDir, `${logName}.out.log`)}</string>
|
|
527
632
|
<key>StandardErrorPath</key><string>${join(logDir, `${logName}.err.log`)}</string>
|
|
528
633
|
</dict></plist>
|
|
@@ -540,19 +645,14 @@ export function removeService(s) {
|
|
|
540
645
|
spawnSync("systemctl", ["--user", "daemon-reload"], { stdio: "ignore" });
|
|
541
646
|
return;
|
|
542
647
|
}
|
|
543
|
-
|
|
544
|
-
if (spawnSync("launchctl", ["print", `${domain}/${s.label}`], { stdio: "ignore" }).status === 0) {
|
|
545
|
-
const r = spawnSync("launchctl", ["bootout", `${domain}/${s.label}`], { encoding: "utf8" });
|
|
546
|
-
if (r.status !== 0)
|
|
547
|
-
throw new CliError("launchctl_failed", `launchctl bootout ${domain}/${s.label} failed`, (r.stderr ?? "").trim());
|
|
548
|
-
}
|
|
648
|
+
launchdBootout(s.label, s.path);
|
|
549
649
|
rmSync(s.path, { force: true });
|
|
550
650
|
}
|
|
551
651
|
/** Whether a service's process is running now. */
|
|
552
652
|
export function serviceActive(s) {
|
|
553
653
|
if (s.kind === "systemd")
|
|
554
654
|
return (spawnSync("systemctl", ["--user", "is-active", `${s.label}.service`], { encoding: "utf8" }).stdout ?? "").trim() === "active";
|
|
555
|
-
return
|
|
655
|
+
return launchdPid(s.label) !== null;
|
|
556
656
|
}
|
|
557
657
|
/** Restarts a watcher service in place (new code, same definition); false when it is not loaded. */
|
|
558
658
|
export function restartWatcher(s) {
|
|
@@ -572,9 +672,7 @@ function watcherPid(service) {
|
|
|
572
672
|
const pid = Number((r.stdout ?? "").trim());
|
|
573
673
|
return r.status === 0 && Number.isInteger(pid) && pid > 0 ? pid : null;
|
|
574
674
|
}
|
|
575
|
-
|
|
576
|
-
const pid = Number(/"PID" = (\d+);/.exec(output)?.[1]);
|
|
577
|
-
return Number.isInteger(pid) && pid > 0 ? pid : null;
|
|
675
|
+
return launchdPid(service.label);
|
|
578
676
|
}
|
|
579
677
|
const watcherRestartDriver = {
|
|
580
678
|
pid: watcherPid,
|
package/dist/lock.js
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { launchdLoadedIn } from "./install.js";
|
|
1
2
|
import { mkdirSync, openSync, closeSync, readFileSync, unlinkSync, writeSync } from "node:fs";
|
|
2
3
|
import { join } from "node:path";
|
|
3
4
|
import { configRoot } from "./config.js";
|
|
@@ -44,7 +45,7 @@ export function acquireWatchLock(ref, env = process.env, pid = process.pid) {
|
|
|
44
45
|
throw e;
|
|
45
46
|
const holder = Number(readFileSync(p, "utf8").trim());
|
|
46
47
|
if (Number.isInteger(holder) && holder > 0 && alive(holder)) {
|
|
47
|
-
throw new CliError("watch_running", `a watcher for ${ref} is already running (pid ${holder})`, `Stop it first: kill ${holder}, or launchctl bootout gui/$(id -u)/org.benignswarm.watch.${ref.replace("/", ".")} if launchd started it. Lock file: ${p}`);
|
|
48
|
+
throw new CliError("watch_running", `a watcher for ${ref} is already running (pid ${holder})`, `Stop it first: kill ${holder}, or launchctl bootout ${process.platform === "darwin" ? (launchdLoadedIn(`org.benignswarm.watch.${ref.replace("/", ".")}`)[0] ?? `gui/$(id -u)`) : `gui/$(id -u)`}/org.benignswarm.watch.${ref.replace("/", ".")} if launchd started it. Lock file: ${p}`);
|
|
48
49
|
}
|
|
49
50
|
unlinkSync(p); // stale: the process that wrote it is gone
|
|
50
51
|
}
|
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
import { closeSync, fstatSync, openSync, readdirSync, readSync, renameSync, statSync, truncateSync, writeFileSync } from "node:fs";
|
|
2
|
+
import { join } from "node:path";
|
|
3
|
+
/**
|
|
4
|
+
* Bounded service logs (WU #481). launchd (StandardErrorPath) and systemd (StandardError=append:)
|
|
5
|
+
* keep the watcher and daemon logs open for the life of the service and nothing rotated them: on
|
|
6
|
+
* 2026-11-18 mbp held 594 MB of watcher logs, one 190 MB file, and the daemon read them every pass.
|
|
7
|
+
*
|
|
8
|
+
* Rotation is copy-and-truncate because the service manager holds the open file: renaming it would
|
|
9
|
+
* leave the service writing to the renamed file. Both managers open these files for append (systemd
|
|
10
|
+
* "append:", launchd's Standard*Path), so after the truncate the next write lands at the new end
|
|
11
|
+
* instead of leaving a hole. The newest `keepBytes` (from a line start) become `<name>.1`, replacing
|
|
12
|
+
* the previous one. A line written between the copy and the truncate is lost; that window is the
|
|
13
|
+
* copy of at most `keepBytes`, once per rotation.
|
|
14
|
+
*/
|
|
15
|
+
export const LOG_ROTATE_BYTES = 20 * 1024 * 1024;
|
|
16
|
+
/** Rotates every `*.log` in `dir` larger than `maxBytes`. Files it cannot read or truncate throw: a failed rotation is never silent. */
|
|
17
|
+
export function rotateLogs(dir, maxBytes = LOG_ROTATE_BYTES, keepBytes = maxBytes) {
|
|
18
|
+
const done = [];
|
|
19
|
+
let names;
|
|
20
|
+
try {
|
|
21
|
+
names = readdirSync(dir);
|
|
22
|
+
}
|
|
23
|
+
catch (e) {
|
|
24
|
+
if (e.code === "ENOENT")
|
|
25
|
+
return done;
|
|
26
|
+
throw e;
|
|
27
|
+
}
|
|
28
|
+
for (const name of names) {
|
|
29
|
+
if (!name.endsWith(".log"))
|
|
30
|
+
continue;
|
|
31
|
+
const path = join(dir, name);
|
|
32
|
+
const size = statSync(path).size;
|
|
33
|
+
if (size <= maxBytes)
|
|
34
|
+
continue;
|
|
35
|
+
done.push({ file: name, bytes_before: size, kept_bytes: rotateOne(path, keepBytes) });
|
|
36
|
+
}
|
|
37
|
+
return done;
|
|
38
|
+
}
|
|
39
|
+
function rotateOne(path, keepBytes) {
|
|
40
|
+
const fd = openSync(path, "r");
|
|
41
|
+
let tail;
|
|
42
|
+
try {
|
|
43
|
+
const size = fstatSync(fd).size;
|
|
44
|
+
const start = Math.max(0, size - keepBytes);
|
|
45
|
+
const buf = Buffer.alloc(size - start);
|
|
46
|
+
let got = 0;
|
|
47
|
+
while (got < buf.length) {
|
|
48
|
+
const n = readSync(fd, buf, got, buf.length - got, start + got);
|
|
49
|
+
if (n === 0)
|
|
50
|
+
break;
|
|
51
|
+
got += n;
|
|
52
|
+
}
|
|
53
|
+
// Start the kept copy at a line boundary unless the whole file fits.
|
|
54
|
+
const nl = start > 0 ? buf.indexOf(0x0a) : -1;
|
|
55
|
+
tail = buf.subarray(nl >= 0 ? nl + 1 : 0, got);
|
|
56
|
+
}
|
|
57
|
+
finally {
|
|
58
|
+
closeSync(fd);
|
|
59
|
+
}
|
|
60
|
+
const previous = `${path}.1`;
|
|
61
|
+
writeFileSync(`${previous}.tmp`, tail);
|
|
62
|
+
renameSync(`${previous}.tmp`, previous);
|
|
63
|
+
truncateSync(path, 0);
|
|
64
|
+
return tail.length;
|
|
65
|
+
}
|
|
@@ -0,0 +1,90 @@
|
|
|
1
|
+
import { closeSync, fstatSync, openSync, readSync } from "node:fs";
|
|
2
|
+
/**
|
|
3
|
+
* Reading append-only session logs (Codex rollouts, Claude Code transcripts) from the end. The daemon
|
|
4
|
+
* and the watchers need only the newest facts in these files, yet they grow for the life of a thread
|
|
5
|
+
* (120-150 MB per Codex rollout on aws1, 2026-11-17), and reading them whole every pass churned
|
|
6
|
+
* gigabytes per machine (WU #474).
|
|
7
|
+
*/
|
|
8
|
+
export const TAIL_CHUNK_BYTES = 256 * 1024;
|
|
9
|
+
/** How far back a per-pass reader may look (WU #474 scope: a hard cap). Past it the answer is "unknown", never "idle". */
|
|
10
|
+
export const TAIL_MAX_BYTES = 8 * 1024 * 1024;
|
|
11
|
+
/** Counts scans and bytes read, so tests can prove an unchanged file is not read again and a scan stops at its cap. */
|
|
12
|
+
export const tailReadStats = { scans: 0, bytes: 0 };
|
|
13
|
+
/**
|
|
14
|
+
* Calls `visit` with each complete line of the file from the last to the first, until it returns true
|
|
15
|
+
* (stop), the file's start is reached, or `maxBytes` have been read (then `capped` is true and the
|
|
16
|
+
* piece of a line cut by the cap is never visited). Lines split on the newline byte, which never occurs
|
|
17
|
+
* inside a multi-byte UTF-8 sequence, so decoding each line separately is exact. A final line without a
|
|
18
|
+
* newline is still visited (a writer may be mid-line; callers skip what doesn't parse, as the full reads
|
|
19
|
+
* did). A single line longer than the cap is never assembled: memory stays within the cap.
|
|
20
|
+
*/
|
|
21
|
+
export function scanLinesBackward(path, visit, chunkBytes = TAIL_CHUNK_BYTES, maxBytes = TAIL_MAX_BYTES) {
|
|
22
|
+
const fd = openSync(path, "r");
|
|
23
|
+
tailReadStats.scans++;
|
|
24
|
+
let bytesRead = 0;
|
|
25
|
+
try {
|
|
26
|
+
let pos = fstatSync(fd).size;
|
|
27
|
+
let carry = Buffer.alloc(0);
|
|
28
|
+
while (pos > 0) {
|
|
29
|
+
if (bytesRead >= maxBytes)
|
|
30
|
+
return { bytesRead, capped: true };
|
|
31
|
+
const start = Math.max(0, pos - Math.min(chunkBytes, maxBytes - bytesRead));
|
|
32
|
+
const chunk = Buffer.alloc(pos - start);
|
|
33
|
+
let got = 0;
|
|
34
|
+
while (got < chunk.length) {
|
|
35
|
+
const n = readSync(fd, chunk, got, chunk.length - got, start + got);
|
|
36
|
+
if (n === 0)
|
|
37
|
+
break;
|
|
38
|
+
got += n;
|
|
39
|
+
}
|
|
40
|
+
bytesRead += got;
|
|
41
|
+
tailReadStats.bytes += got;
|
|
42
|
+
const data = carry.length ? Buffer.concat([chunk.subarray(0, got), carry]) : chunk.subarray(0, got);
|
|
43
|
+
let end = data.length;
|
|
44
|
+
// Walk newline positions from the end; the piece before the first newline may continue in the previous chunk.
|
|
45
|
+
for (let i = data.length - 1; i >= 0; i--) {
|
|
46
|
+
if (data[i] !== 0x0a)
|
|
47
|
+
continue;
|
|
48
|
+
if (end > i + 1 && visit(data.subarray(i + 1, end).toString("utf8")))
|
|
49
|
+
return { bytesRead, capped: false };
|
|
50
|
+
end = i;
|
|
51
|
+
}
|
|
52
|
+
carry = Buffer.from(data.subarray(0, end));
|
|
53
|
+
pos = start;
|
|
54
|
+
}
|
|
55
|
+
if (carry.length && visit(carry.toString("utf8")))
|
|
56
|
+
return { bytesRead, capped: false };
|
|
57
|
+
return { bytesRead, capped: false };
|
|
58
|
+
}
|
|
59
|
+
finally {
|
|
60
|
+
closeSync(fd);
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
/** Results computed from a file, reused while the file's identity (device, inode), size and mtime are unchanged. */
|
|
64
|
+
export class FileFactsCache {
|
|
65
|
+
max;
|
|
66
|
+
entries = new Map();
|
|
67
|
+
constructor(max = 256) {
|
|
68
|
+
this.max = max;
|
|
69
|
+
}
|
|
70
|
+
get(path, compute) {
|
|
71
|
+
const fd = openSync(path, "r");
|
|
72
|
+
let key;
|
|
73
|
+
try {
|
|
74
|
+
const s = fstatSync(fd, { bigint: true });
|
|
75
|
+
key = `${s.dev}:${s.ino}:${s.size}:${s.mtimeNs}`;
|
|
76
|
+
}
|
|
77
|
+
finally {
|
|
78
|
+
closeSync(fd);
|
|
79
|
+
}
|
|
80
|
+
const hit = this.entries.get(path);
|
|
81
|
+
if (hit && hit.key === key)
|
|
82
|
+
return hit.value;
|
|
83
|
+
const value = compute(path);
|
|
84
|
+
this.entries.delete(path);
|
|
85
|
+
this.entries.set(path, { key, value });
|
|
86
|
+
if (this.entries.size > this.max)
|
|
87
|
+
this.entries.delete(this.entries.keys().next().value);
|
|
88
|
+
return value;
|
|
89
|
+
}
|
|
90
|
+
}
|
package/dist/turn.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { spawn } from "node:child_process";
|
|
2
|
-
import {
|
|
2
|
+
import { FileFactsCache, scanLinesBackward, TAIL_CHUNK_BYTES, TAIL_MAX_BYTES } from "./tail-lines.js";
|
|
3
3
|
export const DEFAULT_TURN_COALESCE_SECONDS = 180;
|
|
4
4
|
export const MAX_TURN_COALESCE_SECONDS = 3600;
|
|
5
5
|
/** Whether direct pending work is still inside its per-session coalescing window. */
|
|
@@ -53,8 +53,57 @@ export function usageLimitUntil(error) {
|
|
|
53
53
|
const t = Date.parse(`${m[1]}, ${m[2]} ${m[3]}`);
|
|
54
54
|
return Number.isNaN(t) ? null : t;
|
|
55
55
|
}
|
|
56
|
+
/**
|
|
57
|
+
* codexTurnPhase for a rollout file, reading it from the end: the latest timestamp, then back to the
|
|
58
|
+
* latest task_started, noting the latest close (task_complete / turn_aborted) on the way. That is the
|
|
59
|
+
* same answer the whole-file read gives, but it reads only back to the start of the current turn, and an
|
|
60
|
+
* unchanged file is not read again (WU #474).
|
|
61
|
+
*/
|
|
62
|
+
export function codexTurnPhaseFromFile(rollout, chunkBytes = TAIL_CHUNK_BYTES, maxBytes = TAIL_MAX_BYTES) {
|
|
63
|
+
let lastEventAt = null;
|
|
64
|
+
let closed = false;
|
|
65
|
+
let closeError = null;
|
|
66
|
+
let startedAt = null;
|
|
67
|
+
let started = false;
|
|
68
|
+
const scan = scanLinesBackward(rollout, (line) => {
|
|
69
|
+
let j;
|
|
70
|
+
try {
|
|
71
|
+
j = JSON.parse(line);
|
|
72
|
+
}
|
|
73
|
+
catch {
|
|
74
|
+
return false;
|
|
75
|
+
} // a line still being written
|
|
76
|
+
if (lastEventAt === null && j.timestamp)
|
|
77
|
+
lastEventAt = j.timestamp;
|
|
78
|
+
// Past the latest task_started only the newest timestamp is still wanted (that line may have had none).
|
|
79
|
+
if (started)
|
|
80
|
+
return lastEventAt !== null;
|
|
81
|
+
if (j.type !== "event_msg")
|
|
82
|
+
return false;
|
|
83
|
+
const t = j.payload?.type;
|
|
84
|
+
if ((t === "task_complete" || t === "turn_aborted") && !closed) {
|
|
85
|
+
closed = true;
|
|
86
|
+
closeError = j.payload?.error?.message ?? null;
|
|
87
|
+
return false;
|
|
88
|
+
}
|
|
89
|
+
if (t === "task_started") {
|
|
90
|
+
started = true;
|
|
91
|
+
startedAt = j.timestamp ?? null;
|
|
92
|
+
return lastEventAt !== null;
|
|
93
|
+
}
|
|
94
|
+
return false;
|
|
95
|
+
}, chunkBytes, maxBytes);
|
|
96
|
+
if (!started && !closed && scan.capped) {
|
|
97
|
+
return { running: false, startedAt: null, lastEventAt, lastError: null, unknown: `neither the start nor the end of the latest turn is within the last ${Math.round(maxBytes / 1048576)} MB of ${rollout}` };
|
|
98
|
+
}
|
|
99
|
+
if (!started)
|
|
100
|
+
return { running: false, startedAt: null, lastEventAt, lastError: closed ? closeError : null };
|
|
101
|
+
return { running: !closed && startedAt !== null, startedAt, lastEventAt, lastError: closed ? closeError : null };
|
|
102
|
+
}
|
|
103
|
+
const turnPhaseCache = new FileFactsCache();
|
|
104
|
+
/** The turn phase of a rollout file; an unchanged file (same inode, size and mtime) is answered from memory. */
|
|
56
105
|
export function readTurnPhase(rollout) {
|
|
57
|
-
return
|
|
106
|
+
return turnPhaseCache.get(rollout, (path) => codexTurnPhaseFromFile(path));
|
|
58
107
|
}
|
|
59
108
|
/**
|
|
60
109
|
* Starts the turn command in its own process group, so a watcher restart (an upgrade reloads every
|