benignswarm 0.12.91 → 0.12.93

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/index.js CHANGED
@@ -31,6 +31,7 @@ import { commandWarnings } from "./commands/hook.js";
31
31
  import { loadAgent, resolveAgentName } from "./config.js";
32
32
  import { agentNotice } from "./commands/notices.js";
33
33
  import { versionLine, warnLegacyAlias } from "./legacy-alias.js";
34
+ import { gitCredentialMain } from "./commands/git-credential.js";
34
35
  const COMMANDS = {
35
36
  join,
36
37
  setup,
@@ -39,6 +40,7 @@ const COMMANDS = {
39
40
  identities: a.identities,
40
41
  me: a.me,
41
42
  resume,
43
+ "git-credential": async (p) => gitCredentialMain(p),
42
44
  notice: agentNotice,
43
45
  who: a.who,
44
46
  status: a.status,
@@ -104,7 +106,7 @@ const COMMANDS = {
104
106
  // These commands establish identity, own their startup validation, or inspect/change only local
105
107
  // machine state. Their dispatch must run before any notice lookup attempts to load an agent.
106
108
  const NOTICE_PREFLIGHT_EXEMPT_COMMANDS = new Set([
107
- "join", "setup", "login", "logout", "identities", "skill", "hook", "machine", "install", "doctor", "update", "version", "admin", "start",
109
+ "join", "setup", "login", "logout", "identities", "skill", "hook", "machine", "install", "doctor", "update", "version", "admin", "start", "git-credential",
108
110
  ]);
109
111
  let invokedCommand;
110
112
  async function main(argv) {
package/dist/install.js CHANGED
@@ -240,6 +240,29 @@ export function watcherServices() {
240
240
  .filter((f) => f.endsWith(".service") && isOurService(f.slice(0, -".service".length)))
241
241
  .map((f) => ({ kind: "systemd", label: f.slice(0, -".service".length), path: join(dir, f), args: unitArgs(readFileSync(join(dir, f), "utf8")) }));
242
242
  }
243
+ /** Read the recorded working directory for a watcher; pruning must fail closed on an unreadable service. */
244
+ export function watcherWorkingDirectory(service) {
245
+ if (service.kind === "systemd") {
246
+ const text = readFileSync(service.path, "utf8");
247
+ const match = /^WorkingDirectory=(.+)$/m.exec(text);
248
+ if (!match)
249
+ throw new CliError("service_unreadable", `${service.label} has no recorded WorkingDirectory`);
250
+ return match[1].replace(/%%/g, "%");
251
+ }
252
+ const read = spawnSync("plutil", ["-convert", "json", "-o", "-", service.path], { encoding: "utf8" });
253
+ if (read.status !== 0)
254
+ throw new CliError("service_unreadable", `could not read ${service.path} as a launchd plist`, (read.stderr ?? "").trim());
255
+ let plist;
256
+ try {
257
+ plist = JSON.parse(read.stdout);
258
+ }
259
+ catch {
260
+ throw new CliError("service_unreadable", `${service.path} is not valid plist JSON`);
261
+ }
262
+ if (typeof plist.WorkingDirectory !== "string" || !plist.WorkingDirectory)
263
+ throw new CliError("service_unreadable", `${service.label} has no readable WorkingDirectory`);
264
+ return plist.WorkingDirectory;
265
+ }
243
266
  export function plistArgs(path) {
244
267
  const r = spawnSync("plutil", ["-convert", "json", "-o", "-", path], { encoding: "utf8" });
245
268
  return r.status === 0 ? (JSON.parse(r.stdout).ProgramArguments ?? null) : null;
@@ -2,7 +2,7 @@ import { existsSync, mkdirSync, readFileSync, renameSync, rmSync, writeFileSync
2
2
  import { dirname, join } from "node:path";
3
3
  import { configRoot } from "./config.js";
4
4
  export const DRAIN_MS = 15 * 60_000;
5
- const file = () => join(configRoot(), "state", "maintenance.json");
5
+ const file = (env = process.env) => join(configRoot(env), "state", "maintenance.json");
6
6
  export function writeMaintenance(w) {
7
7
  if (!w) {
8
8
  rmSync(file(), { force: true });
@@ -14,8 +14,8 @@ export function writeMaintenance(w) {
14
14
  renameSync(tmp, file());
15
15
  }
16
16
  /** The window holding turns back now, or null. */
17
- export function drainingUntil(nowMs = Date.now(), text) {
18
- const raw = text ?? (existsSync(file()) ? readFileSync(file(), "utf8") : null);
17
+ export function drainingUntil(nowMs = Date.now(), text, env = process.env) {
18
+ const raw = text ?? (existsSync(file(env)) ? readFileSync(file(env), "utf8") : null);
19
19
  if (!raw)
20
20
  return null;
21
21
  const w = JSON.parse(raw);
@@ -0,0 +1,113 @@
1
+ import { existsSync, readFileSync } from "node:fs";
2
+ import { isAbsolute, join } from "node:path";
3
+ import { Client } from "./client.js";
4
+ import { configRoot } from "./config.js";
5
+ import { CliError } from "./errors.js";
6
+ import { WATCH_LABEL_PREFIX, watcherServices, watcherWorkingDirectory } from "./install.js";
7
+ function readMachineCredentials() {
8
+ const file = join(configRoot(), "machine.json");
9
+ if (!existsSync(file))
10
+ return null;
11
+ try {
12
+ const value = JSON.parse(readFileSync(file, "utf8"));
13
+ if (typeof value.url !== "string" || !value.url || typeof value.key !== "string" || !value.key)
14
+ throw new Error("url and key are required");
15
+ return { url: value.url, key: value.key };
16
+ }
17
+ catch (error) {
18
+ throw new CliError("machine_sessions_unreadable", `could not read this machine's session list from ${file}: ${error.message}`);
19
+ }
20
+ }
21
+ async function fetchMachineSessions() {
22
+ const machine = readMachineCredentials();
23
+ if (!machine)
24
+ return [];
25
+ const response = await Client.raw(machine.url, machine.key).call("GET", "/machines/me");
26
+ if (!Array.isArray(response.sessions))
27
+ throw new Error("GET /machines/me returned no sessions array");
28
+ return response.sessions;
29
+ }
30
+ async function fetchProjectAgents(creds, project) {
31
+ return Client.forAgent(creds, undefined, { presence: false }).call("GET", `/projects/${project}/agents`);
32
+ }
33
+ function argument(args, name) {
34
+ const index = args.indexOf(name);
35
+ if (index >= 0)
36
+ return args[index + 1] ?? null;
37
+ const inline = args.find((arg) => arg.startsWith(`${name}=`));
38
+ return inline ? inline.slice(name.length + 1) : null;
39
+ }
40
+ function watcherUses(services) {
41
+ return services.filter((service) => service.label.startsWith(WATCH_LABEL_PREFIX)).map((service) => {
42
+ if (!service.args?.length)
43
+ throw new CliError("watcher_unreadable", `${service.label} has no readable service arguments`);
44
+ const agent = argument(service.args, "--as");
45
+ if (!agent)
46
+ throw new CliError("watcher_unreadable", `${service.label} has no recorded --as agent`);
47
+ const dir = argument(service.args, "--dir") ?? watcherWorkingDirectory(service);
48
+ if (!isAbsolute(dir))
49
+ throw new CliError("watcher_unreadable", `${service.label} has no absolute working directory`);
50
+ return { path: dir, agent };
51
+ });
52
+ }
53
+ function sessionUses(value) {
54
+ if (!Array.isArray(value))
55
+ throw new Error("machine session list is not an array");
56
+ return value.flatMap((row, index) => {
57
+ if (!row || typeof row !== "object" || Array.isArray(row))
58
+ throw new Error(`machine session ${index + 1} is malformed`);
59
+ const session = row;
60
+ if (typeof session.agent !== "string" || !session.agent)
61
+ throw new Error(`machine session ${index + 1} has no agent`);
62
+ const reported = session.reported;
63
+ if (reported !== undefined && reported !== null && (typeof reported !== "object" || Array.isArray(reported)))
64
+ throw new Error(`machine session ${session.agent} has malformed reported state`);
65
+ const reportedDir = reported && typeof reported === "object" ? reported.dir : undefined;
66
+ const dir = typeof session.dir === "string" && session.dir ? session.dir : typeof reportedDir === "string" ? reportedDir : "";
67
+ if (!dir)
68
+ return [];
69
+ if (!isAbsolute(dir))
70
+ throw new Error(`machine session ${session.agent} has a non-absolute directory`);
71
+ return [{ path: dir, agent: session.agent }];
72
+ });
73
+ }
74
+ function retiredAgents(value) {
75
+ if (!value || typeof value !== "object" || !Array.isArray(value.agents))
76
+ throw new CliError("home_agents_unreadable", "project agent list has no agents array");
77
+ const result = new Set();
78
+ for (const [index, item] of (value.agents).entries()) {
79
+ if (!item || typeof item !== "object" || Array.isArray(item) || typeof item.name !== "string") {
80
+ throw new CliError("home_agents_unreadable", `project agent ${index + 1} is malformed`);
81
+ }
82
+ const agent = item;
83
+ if (agent.retired_at)
84
+ result.add(agent.name);
85
+ }
86
+ return result;
87
+ }
88
+ /** Read machine sessions, watcher services and retirement state before any worktree can be removed. */
89
+ export async function collectPruneProtection(creds, project, dependencies = {}) {
90
+ const services = (dependencies.watchers ?? watcherServices)();
91
+ const inUse = watcherUses(services);
92
+ let sessions;
93
+ try {
94
+ sessions = await (dependencies.machineSessions ?? fetchMachineSessions)();
95
+ }
96
+ catch (error) {
97
+ throw new CliError("machine_sessions_unreadable", `could not read this machine's session list: ${error.message}`);
98
+ }
99
+ try {
100
+ inUse.push(...sessionUses(sessions));
101
+ }
102
+ catch (error) {
103
+ throw new CliError("machine_sessions_unreadable", `could not read this machine's session list: ${error.message}`);
104
+ }
105
+ let agents;
106
+ try {
107
+ agents = await (dependencies.projectAgents ?? (() => fetchProjectAgents(creds, project)))();
108
+ }
109
+ catch (error) {
110
+ throw new CliError("home_agents_unreadable", `could not read project agents for home worktrees: ${error.message}`);
111
+ }
112
+ return { inUse, retiredHomeAgents: retiredAgents(agents) };
113
+ }
@@ -0,0 +1,64 @@
1
+ import { existsSync, statSync } from "node:fs";
2
+ import { homedir } from "node:os";
3
+ import { join } from "node:path";
4
+ import { agentRef, loadAgent } from "./config.js";
5
+ import { CliError } from "./errors.js";
6
+ /** Package-manager and build caches available to workspace-write sessions when present. */
7
+ export const WORKSPACE_WRITE_CACHE_PATHS = [
8
+ ".npm",
9
+ ".cache",
10
+ ".expo",
11
+ ".cargo/registry",
12
+ ".cargo/git",
13
+ ];
14
+ function directoryExists(path) {
15
+ try {
16
+ return existsSync(path) && statSync(path).isDirectory();
17
+ }
18
+ catch {
19
+ return false;
20
+ }
21
+ }
22
+ export function defaultWorkspaceWritableRoots(home = homedir(), isDirectory = directoryExists) {
23
+ return WORKSPACE_WRITE_CACHE_PATHS.map((path) => join(home, path)).filter(isDirectory);
24
+ }
25
+ function absoluteWritablePath(value, flag, home) {
26
+ const path = value.startsWith("~/") ? join(home, value.slice(2)) : value;
27
+ if (!path.startsWith("/"))
28
+ throw new CliError("usage", `--${flag} paths must be absolute or start with ~/`);
29
+ return path;
30
+ }
31
+ /** Defaults plus machine-configured roots and explicit `b9s start --writable-root` paths. */
32
+ export function startWritableRoots(sandbox, machineRoots, explicitRoots, home = homedir(), isDirectory = directoryExists) {
33
+ if (sandbox !== "workspace-write" && explicitRoots.length) {
34
+ throw new CliError("usage", "--writable-root only applies to --sandbox workspace-write");
35
+ }
36
+ const machine = machineRoots.map((path) => absoluteWritablePath(path, "writable", home));
37
+ if (sandbox !== "workspace-write")
38
+ return [...new Set(machine)];
39
+ const requested = explicitRoots.map((path) => absoluteWritablePath(path, "writable-root", home));
40
+ return [...new Set([...defaultWorkspaceWritableRoots(home, isDirectory), ...machine, ...requested])];
41
+ }
42
+ export function startAgentIdentity(name, env = process.env) {
43
+ const credentials = loadAgent(name, env);
44
+ return { credentials, ref: agentRef(credentials) };
45
+ }
46
+ /** Split b9s start's optional project/name identity from the bare name accepted by enrollment. */
47
+ export function startEnrollmentIdentity(identity) {
48
+ const parts = identity.split("/");
49
+ if (parts.length === 1 && parts[0])
50
+ return { name: parts[0] };
51
+ if (parts.length !== 2 || !parts[0] || !parts[1]) {
52
+ throw new CliError("usage", "--as must be <agent-name> or <project>/<agent-name>");
53
+ }
54
+ return { project: parts[0], name: parts[1] };
55
+ }
56
+ /** When a qualified start name accompanies an invite, the token must enroll in that project. */
57
+ export function assertEnrolledStartProject(expected, actual) {
58
+ if (!expected)
59
+ return;
60
+ if (actual !== expected) {
61
+ const actualText = actual === null ? "an account-wide agent, not a project" : `project "${actual}"`;
62
+ throw new CliError("project_mismatch", `--as requested project "${expected}", but the enrollment token belongs to ${actualText}`);
63
+ }
64
+ }
package/dist/turn.js CHANGED
@@ -57,9 +57,17 @@ export function readTurnPhase(rollout) {
57
57
  */
58
58
  export function startTurn(cmd, env, seq, stdin) {
59
59
  const child = spawn("/bin/sh", ["-c", cmd], { stdio: [stdin === undefined ? "ignore" : "pipe", "inherit", "inherit"], env: { ...process.env, ...env }, detached: true });
60
- if (stdin !== undefined)
61
- child.stdin?.end(stdin);
62
60
  const turn = { seq, child, startedMs: Date.now(), confirmed: false };
61
+ if (stdin !== undefined && child.stdin) {
62
+ child.stdin.on("error", (error) => {
63
+ if (error.code === "EPIPE") {
64
+ turn.stdinError = "harness exited before reading its prompt";
65
+ return;
66
+ }
67
+ throw error;
68
+ });
69
+ child.stdin.end(stdin);
70
+ }
63
71
  child.on("close", (code, signal) => { turn.exit = { code, signal }; });
64
72
  child.on("error", () => { turn.exit = { code: 127, signal: null }; });
65
73
  return turn;
package/dist/usage.js CHANGED
@@ -1,5 +1,5 @@
1
1
  import { existsSync, readFileSync } from "node:fs";
2
- import { dshUsage } from "./harnesses.js";
2
+ import { claudeTranscript, dshUsage } from "./harnesses.js";
3
3
  const zero = () => ({ input: 0, cached_input: 0, output: 0, reasoning: 0, total: 0 });
4
4
  function lines(path) {
5
5
  return readFileSync(path, "utf8").split("\n").filter(Boolean).flatMap((l) => {
@@ -69,15 +69,19 @@ export function claudeUsage(path, since, until) {
69
69
  }
70
70
  /** The usage for a harness session the hook recorded, or an honest "unavailable" record. */
71
71
  export function sessionUsage(session, since, until) {
72
- const none = (harness, reason) => ({ harness, source: "none", scope: "session", since, until, tokens: null, reason });
72
+ const none = (harness, reason) => ({ harness, ...(session?.provider ? { provider: session.provider } : {}), source: "none", scope: "session", since, until, tokens: null, reason });
73
73
  if (!session)
74
74
  return none("unknown", "no hook has reported this agent's session on this machine");
75
- if (!existsSync(session.transcript))
76
- return none(session.harness, `the session file ${session.transcript} is gone`);
75
+ const transcript = session.harness === "claude-code" && session.session_id
76
+ ? (session.transcript && existsSync(session.transcript) ? session.transcript : claudeTranscript(session.session_id) ?? session.transcript)
77
+ : session.transcript;
78
+ if (!existsSync(transcript))
79
+ return none(session.harness, `the session file ${transcript || session.session_id || "(unknown)"} is gone`);
80
+ const withProvider = (usage) => session.provider ? { ...usage, provider: session.provider } : usage;
77
81
  if (session.harness === "codex")
78
- return codexUsage(session.transcript, since, until);
82
+ return withProvider(codexUsage(transcript, since, until));
79
83
  if (session.harness === "claude-code")
80
- return claudeUsage(session.transcript, since, until);
84
+ return withProvider(claudeUsage(transcript, since, until));
81
85
  if (session.harness === "dsh") {
82
86
  const text = readFileSync(session.transcript, "utf8");
83
87
  if (!/"type"\s*:\s*"b9s_invocation_start"/.test(text))
@@ -88,3 +92,13 @@ export function sessionUsage(session, since, until) {
88
92
  }
89
93
  return none(session.harness, `${session.harness} keeps no readable token counts locally`);
90
94
  }
95
+ /** Usage for a Claude Code session identified by the watcher, when no hook bound it to this agent. */
96
+ export function watcherClaudeUsage(sessionId, since, until, provider) {
97
+ const transcript = claudeTranscript(sessionId);
98
+ if (!transcript)
99
+ return {
100
+ harness: "claude-code", ...(provider ? { provider } : {}), source: "none", scope: "session", since, until, tokens: null,
101
+ reason: `no Claude Code transcript for watcher session ${sessionId} under ~/.claude/projects on this machine`,
102
+ };
103
+ return sessionUsage({ harness: "claude-code", transcript, provider }, since, until);
104
+ }
package/dist/version.js CHANGED
@@ -1 +1 @@
1
- export const CLI_VERSION = "0.12.91";
1
+ export const CLI_VERSION = "0.12.93";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "benignswarm",
3
- "version": "0.12.91",
3
+ "version": "0.12.93",
4
4
  "description": "b9s: chat, status board and evidence store for coding agents (benignswarm.org)",
5
5
  "license": "UNLICENSED",
6
6
  "repository": {
@@ -31,7 +31,7 @@
31
31
  "scripts": {
32
32
  "build": "tsc -p tsconfig.build.json",
33
33
  "typecheck": "tsc --noEmit",
34
- "test": "npm run build && vitest run",
34
+ "test": "npm run typecheck && npm run build && vitest run",
35
35
  "prepack": "npm run build"
36
36
  },
37
37
  "devDependencies": {