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/args.js +15 -4
- package/dist/capabilities.js +84 -9
- package/dist/commands/codex-start.js +171 -22
- package/dist/commands/git-credential.js +128 -0
- package/dist/commands/hook.js +1 -1
- package/dist/commands/join.js +5 -1
- package/dist/commands/machine-admin.js +21 -2
- package/dist/commands/machine.js +49 -13
- package/dist/commands/watch.js +65 -45
- package/dist/commands/worktrees.js +3 -1
- package/dist/commands/wu.js +116 -23
- package/dist/git.js +103 -10
- package/dist/harnesses.js +97 -2
- package/dist/help.js +15 -8
- package/dist/index.js +3 -1
- package/dist/install.js +23 -0
- package/dist/maintenance.js +3 -3
- package/dist/prune-protection.js +113 -0
- package/dist/start-options.js +64 -0
- package/dist/turn.js +10 -2
- package/dist/usage.js +20 -6
- package/dist/version.js +1 -1
- package/package.json +2 -2
package/dist/args.js
CHANGED
|
@@ -2,9 +2,9 @@ import { parseArgs } from "node:util";
|
|
|
2
2
|
import { CliError } from "./errors.js";
|
|
3
3
|
// These options accept comma-separated collections, so repeating them should
|
|
4
4
|
// append another collection instead of discarding earlier values.
|
|
5
|
-
export const LIST_FLAGS = ["tags", "projects", "evidence", "statuses", "depends-on", "default-tags", "units", "waits-on", "needs", "exclude", "remove", "post", "harness", "variant", "requires", "reworks"];
|
|
6
|
-
export const STRING_FLAGS = ["as", "admin", "key", "url", "label", "model", "since", "limit", "after", "topic", "goal", "task", "state", "blocked-on", "tags", "custom", "vendor", "role", "tier", "description", "permissions", "cardinality", "assign-outside-qualifications", "machine", "dir", "confirm", "type", "name", "out", "token", "prefix", "uses", "expires-hours", "skill-dir", "harness", "provider", "reply-to", "event", "project", "projects", "post", "title", "body", "body-file", "handoff-to", "evidence", "agent", "parent", "parent-item", "channel", "statuses", "assign", "if-status", "status", "exec", "interval", "requeue-after", "unacked-after", "category", "command", "command-pattern", "follow-delay", "env", "scope", "scope-file", "scope-from", "append", "pr", "note", "add", "remove", "merged", "tag", "activity", "max-unanswered", "to", "replay-of", "branch", "effort", "by", "target", "milestone", "file", "exit", "depends-on", "default-tags", "source", "on", "partial", "question", "ruling", "gaps", "unit", "units", "blocks", "sla", "takeover", "max-open", "max-in-progress", "require-scope", "require-evidence", "default-approver", "merged-by", "integrator-role", "require-rebased", "require-merge-commit", "require-pushed", "quiet", "summary", "meaning", "expert-role", "reviews", "works", "trials", "email", "repeat", "summary-minutes", "churn", "unmet", "require-cited-changes", "checks-every", "propose", "waits-on", "sandbox", "thread", "turn-timeout", "turns-per-hour", "session", "plain", "if-yes", "if-no", "ssh", "variant", "count", "needs", "min-ram", "exclude", "carry", "from", "to-ssh", "wait", "writable", "dsh", "for", "until", "reason", "at", "requires", "priority", "informs", "amend", "waive-informs", "text", "kind", "claim", "decision", "sha", "value", "expect", "expectations", "reworks"];
|
|
7
|
-
export const BOOL_FLAGS = ["latest", "no-restart", "json", "follow", "account", "help", "version", "broadcast", "create-channels", "read-account-status", "replace-key", "mentions-me", "no-skill", "replace", "template", "scope-only", "unread", "pending", "force", "no-hooks", "yes", "open", "bind-here", "peek", "once", "launchd", "full", "no-bind", "all", "here", "keep-worktree", "prune", "abandon", "defer", "hold", "clear", "met", "shared", "archive", "approve", "turn", "service", "print-hooks", "create", "rotate", "codex-userns", "bwrap-userns", "print-apparmor", "cancel", "rerun", "confirmed", "refuted", "no-source"];
|
|
5
|
+
export const LIST_FLAGS = ["tags", "projects", "evidence", "statuses", "depends-on", "default-tags", "units", "waits-on", "writable-root", "needs", "exclude", "remove", "post", "harness", "variant", "requires", "reworks", "confirm-causes"];
|
|
6
|
+
export const STRING_FLAGS = ["as", "admin", "key", "url", "label", "model", "since", "limit", "after", "topic", "goal", "task", "state", "blocked-on", "tags", "custom", "vendor", "role", "tier", "description", "permissions", "cardinality", "assign-outside-qualifications", "machine", "dir", "confirm", "type", "name", "out", "token", "prefix", "uses", "expires-hours", "skill-dir", "harness", "provider", "reply-to", "event", "project", "projects", "post", "title", "body", "body-file", "handoff-to", "evidence", "agent", "parent", "parent-item", "channel", "statuses", "assign", "if-status", "status", "exec", "interval", "requeue-after", "unacked-after", "category", "command", "command-pattern", "follow-delay", "env", "scope", "scope-file", "scope-from", "append", "pr", "note", "add", "remove", "merged", "tag", "activity", "max-unanswered", "to", "replay-of", "branch", "effort", "max-budget-usd", "by", "target", "milestone", "file", "exit", "depends-on", "default-tags", "source", "on", "partial", "question", "ruling", "gaps", "unit", "units", "blocks", "sla", "takeover", "max-open", "max-in-progress", "require-scope", "require-evidence", "default-approver", "merged-by", "integrator-role", "require-rebased", "require-merge-commit", "require-pushed", "quiet", "summary", "meaning", "expert-role", "reviews", "works", "trials", "email", "repeat", "summary-minutes", "churn", "unmet", "require-cited-changes", "checks-every", "propose", "waits-on", "sandbox", "thread", "turn-timeout", "turns-per-hour", "session", "plain", "if-yes", "if-no", "ssh", "variant", "count", "needs", "min-ram", "exclude", "carry", "from", "to-ssh", "wait", "writable", "writable-root", "dsh", "for", "until", "reason", "at", "requires", "priority", "informs", "amend", "waive-informs", "text", "kind", "claim", "decision", "sha", "value", "expect", "expectations", "reworks", "cause", "lesson", "disputes", "annotation", "send-back-event", "confirm-causes"];
|
|
7
|
+
export const BOOL_FLAGS = ["latest", "no-restart", "json", "follow", "account", "help", "version", "broadcast", "create-channels", "read-account-status", "replace-key", "mentions-me", "no-skill", "replace", "template", "scope-only", "unread", "pending", "force", "no-hooks", "yes", "open", "bind-here", "peek", "once", "launchd", "full", "no-bind", "all", "here", "keep-worktree", "prune", "abandon", "defer", "hold", "clear", "met", "shared", "archive", "approve", "turn", "service", "print-hooks", "create", "rotate", "codex-userns", "bwrap-userns", "print-apparmor", "cancel", "rerun", "confirmed", "refuted", "no-source", "allow-lower-tier"];
|
|
8
8
|
export function parse(argv) {
|
|
9
9
|
const options = {};
|
|
10
10
|
for (const f of STRING_FLAGS)
|
|
@@ -25,7 +25,15 @@ export function parse(argv) {
|
|
|
25
25
|
}
|
|
26
26
|
const { values, positionals } = parseArgs({ args: argv, options, allowPositionals: true, strict: true });
|
|
27
27
|
const flags = values;
|
|
28
|
-
|
|
28
|
+
const repeatValues = {};
|
|
29
|
+
for (const [key, value] of Object.entries(flags))
|
|
30
|
+
if (Array.isArray(value))
|
|
31
|
+
repeatValues[key] = value;
|
|
32
|
+
return {
|
|
33
|
+
positionals,
|
|
34
|
+
flags: Object.fromEntries(Object.entries(flags).map(([k, v]) => [k, Array.isArray(v) ? v.join(",") : v])),
|
|
35
|
+
repeated: repeatValues,
|
|
36
|
+
};
|
|
29
37
|
}
|
|
30
38
|
catch (e) {
|
|
31
39
|
if (e instanceof CliError)
|
|
@@ -37,6 +45,9 @@ export function str(flags, k) {
|
|
|
37
45
|
const v = flags[k];
|
|
38
46
|
return typeof v === "string" ? v : undefined;
|
|
39
47
|
}
|
|
48
|
+
export function repeated(parsed, k) {
|
|
49
|
+
return parsed.repeated?.[k] ?? [];
|
|
50
|
+
}
|
|
40
51
|
export function bool(flags, k) {
|
|
41
52
|
return flags[k] === true;
|
|
42
53
|
}
|
package/dist/capabilities.js
CHANGED
|
@@ -1,10 +1,80 @@
|
|
|
1
|
-
import { spawnSync } from "node:child_process";
|
|
1
|
+
import { spawn, spawnSync } from "node:child_process";
|
|
2
2
|
import { mkdtempSync, rmSync } from "node:fs";
|
|
3
3
|
import { homedir, tmpdir } from "node:os";
|
|
4
4
|
import { join } from "node:path";
|
|
5
|
+
import { performance } from "node:perf_hooks";
|
|
6
|
+
export const DEFAULT_CAPABILITY_TIMEOUT_MS = 60_000;
|
|
7
|
+
const MAX_OUTPUT_BYTES = 64 * 1024;
|
|
8
|
+
function appendLimited(chunks, capturedBytes, chunk) {
|
|
9
|
+
const remaining = MAX_OUTPUT_BYTES - capturedBytes;
|
|
10
|
+
if (remaining > 0)
|
|
11
|
+
chunks.push(chunk.subarray(0, remaining));
|
|
12
|
+
return { capturedBytes: capturedBytes + Math.min(chunk.length, Math.max(remaining, 0)), exceeded: chunk.length > remaining };
|
|
13
|
+
}
|
|
14
|
+
function runProbe(command, cwd, timeoutMs) {
|
|
15
|
+
const startedAt = performance.now();
|
|
16
|
+
const stdout = [];
|
|
17
|
+
const stderr = [];
|
|
18
|
+
let stdoutBytes = 0;
|
|
19
|
+
let stderrBytes = 0;
|
|
20
|
+
let outputExceeded = false;
|
|
21
|
+
let spawnError = null;
|
|
22
|
+
let killError = null;
|
|
23
|
+
let timedOut = false;
|
|
24
|
+
const child = spawn("/bin/sh", ["-lc", command], {
|
|
25
|
+
cwd,
|
|
26
|
+
detached: process.platform !== "win32",
|
|
27
|
+
stdio: ["ignore", "pipe", "pipe"],
|
|
28
|
+
});
|
|
29
|
+
child.stdout.on("data", (chunk) => {
|
|
30
|
+
const next = appendLimited(stdout, stdoutBytes, chunk);
|
|
31
|
+
stdoutBytes = next.capturedBytes;
|
|
32
|
+
outputExceeded ||= next.exceeded;
|
|
33
|
+
});
|
|
34
|
+
child.stderr.on("data", (chunk) => {
|
|
35
|
+
const next = appendLimited(stderr, stderrBytes, chunk);
|
|
36
|
+
stderrBytes = next.capturedBytes;
|
|
37
|
+
outputExceeded ||= next.exceeded;
|
|
38
|
+
});
|
|
39
|
+
child.on("error", (error) => { spawnError = error; });
|
|
40
|
+
const timer = setTimeout(() => {
|
|
41
|
+
timedOut = true;
|
|
42
|
+
if (process.platform !== "win32" && child.pid !== undefined) {
|
|
43
|
+
// detached gives the shell and its descendants a private process group. Kill the group,
|
|
44
|
+
// since killing only the shell leaves tools such as xcrun holding its output pipes open.
|
|
45
|
+
try {
|
|
46
|
+
process.kill(-child.pid, "SIGKILL");
|
|
47
|
+
}
|
|
48
|
+
catch (error) {
|
|
49
|
+
if (error.code !== "ESRCH") {
|
|
50
|
+
killError = error;
|
|
51
|
+
child.kill("SIGKILL");
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
else {
|
|
56
|
+
child.kill("SIGKILL");
|
|
57
|
+
}
|
|
58
|
+
}, timeoutMs);
|
|
59
|
+
return new Promise((resolve) => {
|
|
60
|
+
child.on("close", (status) => {
|
|
61
|
+
clearTimeout(timer);
|
|
62
|
+
resolve({
|
|
63
|
+
status,
|
|
64
|
+
stdout: Buffer.concat(stdout).toString("utf8"),
|
|
65
|
+
stderr: Buffer.concat(stderr).toString("utf8"),
|
|
66
|
+
error: spawnError ?? (outputExceeded ? new Error(`probe output exceeded ${MAX_OUTPUT_BYTES} bytes`) : null),
|
|
67
|
+
killError,
|
|
68
|
+
timedOut,
|
|
69
|
+
elapsedMs: Math.round(performance.now() - startedAt),
|
|
70
|
+
});
|
|
71
|
+
});
|
|
72
|
+
});
|
|
73
|
+
}
|
|
5
74
|
/** Run every declaration and preserve failures as results, so dispatch can explain a missing tool. */
|
|
6
|
-
export function probeCapabilities(definitions, projectDir) {
|
|
7
|
-
|
|
75
|
+
export async function probeCapabilities(definitions, projectDir) {
|
|
76
|
+
const results = [];
|
|
77
|
+
for (const definition of definitions) {
|
|
8
78
|
let cwd = homedir();
|
|
9
79
|
let temporary = null;
|
|
10
80
|
try {
|
|
@@ -19,13 +89,17 @@ export function probeCapabilities(definitions, projectDir) {
|
|
|
19
89
|
throw new Error(full.error?.message ?? (full.stderr || full.stdout || "git sparse-checkout disable failed").trim());
|
|
20
90
|
cwd = path;
|
|
21
91
|
}
|
|
22
|
-
const
|
|
23
|
-
const
|
|
24
|
-
const
|
|
25
|
-
|
|
92
|
+
const timeoutMs = definition.timeout_ms ?? DEFAULT_CAPABILITY_TIMEOUT_MS;
|
|
93
|
+
const result = await runProbe(definition.probe, cwd, timeoutMs);
|
|
94
|
+
const output = `${result.stdout}${result.stderr}`.trim().split(/\r?\n/, 1)[0] ?? "";
|
|
95
|
+
const ok = result.status === 0 && !result.error && !result.timedOut;
|
|
96
|
+
const error = result.timedOut
|
|
97
|
+
? `timed out after ${result.elapsedMs} ms${result.killError ? `; failed to kill probe process group: ${result.killError.message}` : ""}`
|
|
98
|
+
: result.error?.message ?? (ok ? null : output || `probe exited ${result.status}`);
|
|
99
|
+
results.push({ name: definition.name, ok, version: ok ? (result.stdout.trim().split(/\r?\n/, 1)[0]?.slice(0, 200) || null) : null, error: error?.slice(0, 500) ?? null });
|
|
26
100
|
}
|
|
27
101
|
catch (error) {
|
|
28
|
-
|
|
102
|
+
results.push({ name: definition.name, ok: false, version: null, error: error.message.split(/\r?\n/, 1)[0].slice(0, 500) });
|
|
29
103
|
}
|
|
30
104
|
finally {
|
|
31
105
|
if (temporary) {
|
|
@@ -37,5 +111,6 @@ export function probeCapabilities(definitions, projectDir) {
|
|
|
37
111
|
}
|
|
38
112
|
}
|
|
39
113
|
}
|
|
40
|
-
}
|
|
114
|
+
}
|
|
115
|
+
return results;
|
|
41
116
|
}
|
|
@@ -1,9 +1,10 @@
|
|
|
1
1
|
import { spawn, spawnSync } from "node:child_process";
|
|
2
|
-
import { closeSync, existsSync, mkdirSync, openSync, readFileSync, unlinkSync } from "node:fs";
|
|
2
|
+
import { closeSync, existsSync, mkdirSync, openSync, readFileSync, unlinkSync, writeFileSync } from "node:fs";
|
|
3
3
|
import { homedir } from "node:os";
|
|
4
4
|
import { dirname, join as joinPath } from "node:path";
|
|
5
|
-
import { bool, str } from "../args.js";
|
|
6
|
-
import {
|
|
5
|
+
import { bool, repeated, str } from "../args.js";
|
|
6
|
+
import { configRoot } from "../config.js";
|
|
7
|
+
import { startAgentIdentity, startEnrollmentIdentity, startWritableRoots } from "../start-options.js";
|
|
7
8
|
import { CliError } from "../errors.js";
|
|
8
9
|
import { requireInstall } from "../install.js";
|
|
9
10
|
import { bindSession, codexArchivedRollout, codexRollout } from "../sessions.js";
|
|
@@ -13,10 +14,12 @@ import { readState, writeState } from "../state.js";
|
|
|
13
14
|
import { join } from "./join.js";
|
|
14
15
|
import { beginTurnGuardAttempt, completePendingTurnGuard, installWatcherService } from "./watch.js";
|
|
15
16
|
import { randomUUID } from "node:crypto";
|
|
16
|
-
import { HARNESS_BIN, HARNESS_LABEL, claudeResultError, claudeResultFile, claudeSettings, claudeTranscript, dshPath, dshResultError, dshSessionFromEvents, dshSettings, dshTurnLog, probeFor } from "../harnesses.js";
|
|
17
|
+
import { HARNESS_BIN, HARNESS_LABEL, assertClaudeSelfCheck, claudeCodePath, claudeResultError, claudeResultFile, claudeSandboxEnv, claudeSettings, claudeTranscript, claudeTurnArgs, dshPath, dshResultError, dshSessionFromEvents, dshSettings, dshTurnLog, probeFor } from "../harnesses.js";
|
|
17
18
|
import { claudeTurnEnv } from "../providers.js";
|
|
18
19
|
import { DEFAULT_TURNS_PER_HOUR } from "../turn-guard.js";
|
|
20
|
+
import { configureGitCredentialForWorktree } from "./git-credential.js";
|
|
19
21
|
const SANDBOXES = ["read-only", "workspace-write", "danger-full-access"];
|
|
22
|
+
export const DEFAULT_CLAUDE_MAX_BUDGET_USD = 1;
|
|
20
23
|
/**
|
|
21
24
|
* `b9s start` (and `b9s codex start`): one command that brings an agent up on this machine
|
|
22
25
|
* headless, with no app involved, so it works the same over ssh on a remote machine. It enrolls the
|
|
@@ -31,6 +34,22 @@ const SANDBOXES = ["read-only", "workspace-write", "danger-full-access"];
|
|
|
31
34
|
export async function codexStart(p, out) {
|
|
32
35
|
return harnessStart(p, out, "codex");
|
|
33
36
|
}
|
|
37
|
+
/** Builds the token enrollment call used by start; the token supplies project scope. */
|
|
38
|
+
export function startJoinArgs(p, harness, model) {
|
|
39
|
+
const identity = startEnrollmentIdentity(str(p.flags, "as") ?? "");
|
|
40
|
+
return {
|
|
41
|
+
parsed: {
|
|
42
|
+
...p,
|
|
43
|
+
flags: {
|
|
44
|
+
...p.flags,
|
|
45
|
+
as: identity.name,
|
|
46
|
+
vendor: harness,
|
|
47
|
+
model,
|
|
48
|
+
},
|
|
49
|
+
},
|
|
50
|
+
...(identity.project ? { expectedProject: identity.project } : {}),
|
|
51
|
+
};
|
|
52
|
+
}
|
|
34
53
|
export async function harnessStart(p, out, harness) {
|
|
35
54
|
const label = HARNESS_LABEL[harness];
|
|
36
55
|
const cmd = harness === "codex" ? "codex start" : "start";
|
|
@@ -62,37 +81,50 @@ export async function harnessStart(p, out, harness) {
|
|
|
62
81
|
if (provider === "deepseek" && harness !== "claude-code")
|
|
63
82
|
throw new CliError("usage", "--provider deepseek requires --harness claude-code");
|
|
64
83
|
const model = str(p.flags, "model") ?? (provider === "deepseek" ? "deepseek-flash" : undefined);
|
|
84
|
+
const budgetFlag = str(p.flags, "max-budget-usd");
|
|
85
|
+
if (budgetFlag !== undefined && (harness !== "claude-code" || sandbox !== "workspace-write"))
|
|
86
|
+
throw new CliError("usage", "--max-budget-usd is only valid for Claude Code workspace-write sessions");
|
|
87
|
+
const maxBudgetUsd = budgetFlag === undefined ? DEFAULT_CLAUDE_MAX_BUDGET_USD : Number(budgetFlag);
|
|
88
|
+
if (harness === "claude-code" && sandbox === "workspace-write" && (!Number.isFinite(maxBudgetUsd) || maxBudgetUsd <= 0))
|
|
89
|
+
throw new CliError("usage", "--max-budget-usd must be a positive dollar amount");
|
|
65
90
|
const bin = harness === "dsh"
|
|
66
91
|
? dshPath(dshOverride)
|
|
67
|
-
:
|
|
92
|
+
: harness === "claude-code" && sandbox === "workspace-write"
|
|
93
|
+
? claudeCodePath() ?? (() => { throw new CliError("not_found", "Claude Code was not found on PATH or under ~/.local/share/claude/versions; add the native installer's active version to PATH or install Claude Code with `npm i -g @anthropic-ai/claude-code`"); })()
|
|
94
|
+
: which(HARNESS_BIN[harness], harness === "codex" ? "install the Codex CLI (npm i -g @openai/codex)" : "install Claude Code (npm i -g @anthropic-ai/claude-code)");
|
|
68
95
|
if (!bin)
|
|
69
96
|
throw new CliError("not_found", "DeepSeek Harness CLI dsh was not found; install DeepSeek Harness or pass --dsh <path>");
|
|
70
97
|
if (harness === "dsh" && !existsSync(bin))
|
|
71
98
|
throw new CliError("not_found", `DeepSeek Harness CLI ${bin} does not exist; pass --dsh <path> to its runtime/cli/bin/dsh`);
|
|
72
99
|
const effort = str(p.flags, "effort");
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
100
|
+
const requestedAdopt = str(p.flags, "thread") ?? str(p.flags, "session");
|
|
101
|
+
// Machine-configured folders and explicit extra roots are combined with existing package caches
|
|
102
|
+
// only for workspace-write. Full-access sessions keep their previous root settings.
|
|
103
|
+
const machineWritable = (str(p.flags, "writable") ?? "").split(",").map((w) => w.trim()).filter(Boolean);
|
|
104
|
+
const explicitWritable = repeated(p, "writable-root").map((w) => w.trim());
|
|
105
|
+
const writable = startWritableRoots(sandbox, machineWritable, explicitWritable);
|
|
77
106
|
// Refuses a sandbox the harness cannot honour before anything is enrolled.
|
|
78
107
|
const settings = harness === "codex"
|
|
79
108
|
? codexSettings(sandbox, model, effort, process.cwd(), configRoot(), [...writable, ...ownWorktreeGitDir(process.cwd())])
|
|
80
109
|
: harness === "dsh"
|
|
81
110
|
? dshSettings(sandbox, process.cwd(), configRoot(), [...writable, ...ownWorktreeGitDir(process.cwd())])
|
|
82
111
|
: claudeSettings(sandbox, model, effort, process.cwd(), configRoot(), writable);
|
|
83
|
-
const providerEnv = claudeTurnEnv(harness === "claude-code" ? provider : undefined, model);
|
|
112
|
+
const providerEnv = { ...claudeTurnEnv(harness === "claude-code" ? provider : undefined, model), ...(harness === "claude-code" ? claudeSandboxEnv(sandbox) : {}) };
|
|
84
113
|
// 1. Who: enroll with the invite token, or use credentials already on this machine.
|
|
85
114
|
const lines = [];
|
|
86
115
|
const token = str(p.flags, "token");
|
|
87
116
|
if (token) {
|
|
88
117
|
const joined = [];
|
|
89
|
-
|
|
118
|
+
const enrollment = startJoinArgs(p, harness, model);
|
|
119
|
+
await join(enrollment.parsed, { json: false, print: (h) => joined.push(h) }, enrollment.expectedProject);
|
|
90
120
|
lines.push(joined.join("\n").split("\n")[0]);
|
|
91
121
|
}
|
|
92
|
-
const creds =
|
|
122
|
+
const { credentials: creds, ref } = startAgentIdentity(name);
|
|
123
|
+
if (harness === "claude-code" && sandbox === "workspace-write")
|
|
124
|
+
configureHttpsOriginForWorktree(process.cwd());
|
|
125
|
+
await configureGitCredentialForWorktree(process.cwd(), creds);
|
|
93
126
|
if (creds.vendor && creds.vendor !== harness)
|
|
94
|
-
throw new CliError("vendor_mismatch", `${
|
|
95
|
-
const ref = agentRef(creds);
|
|
127
|
+
throw new CliError("vendor_mismatch", `${ref} is saved as ${creds.vendor}, not ${harness}`);
|
|
96
128
|
const priorState = readState(ref);
|
|
97
129
|
if (priorState.turn_guard?.fault) {
|
|
98
130
|
const fault = priorState.turn_guard.fault;
|
|
@@ -100,7 +132,7 @@ export async function harnessStart(p, out, harness) {
|
|
|
100
132
|
}
|
|
101
133
|
const initialTurnPending = priorState.turn_guard?.turns.some((attempt) => attempt.productive === null) ?? false;
|
|
102
134
|
const rememberedSession = initialTurnPending && priorState.harness_session?.harness === harness ? priorState.harness_session.session_id : null;
|
|
103
|
-
const adopt =
|
|
135
|
+
const adopt = requestedAdopt ?? rememberedSession ?? undefined;
|
|
104
136
|
requireInstall();
|
|
105
137
|
// 2. Its session: adopt one, or start one headless with an onboarding turn.
|
|
106
138
|
let session;
|
|
@@ -122,6 +154,9 @@ export async function harnessStart(p, out, harness) {
|
|
|
122
154
|
if (harness === "claude-code") {
|
|
123
155
|
if (!claudeTranscript(session))
|
|
124
156
|
throw new CliError("not_found", `no Claude Code transcript for session ${session} under ~/.claude/projects on this machine`);
|
|
157
|
+
if (sandbox === "workspace-write") {
|
|
158
|
+
await runGuardedClaudeSandboxSelfCheck(ref, turnsPerHour, bin, settings, maxBudgetUsd, providerEnv, process.cwd(), randomUUID());
|
|
159
|
+
}
|
|
125
160
|
lines.push(`Adopted Claude Code session ${session}. Do not resume it in a terminal while the watcher runs it: two clients on one session conflict.`);
|
|
126
161
|
}
|
|
127
162
|
else {
|
|
@@ -132,6 +167,12 @@ export async function harnessStart(p, out, harness) {
|
|
|
132
167
|
}
|
|
133
168
|
}
|
|
134
169
|
else {
|
|
170
|
+
// The proxy/Git preflight spends model tokens, so it is its own guarded harness launch. The
|
|
171
|
+
// first real turn resumes this same checked session and receives a separate reservation below.
|
|
172
|
+
if (harness === "claude-code" && sandbox === "workspace-write") {
|
|
173
|
+
session = randomUUID();
|
|
174
|
+
await runGuardedClaudeSandboxSelfCheck(ref, turnsPerHour, bin, settings, maxBudgetUsd, providerEnv, process.cwd(), session);
|
|
175
|
+
}
|
|
135
176
|
const logDir = joinPath(configRoot(), "logs");
|
|
136
177
|
mkdirSync(logDir, { recursive: true });
|
|
137
178
|
firstTurnLog = harness === "dsh" ? dshTurnLog(ref) : harness === "claude-code" ? claudeResultFile(ref) : joinPath(logDir, `${harness}.${ref.replace("/", ".")}.first-turn.jsonl`);
|
|
@@ -158,8 +199,8 @@ export async function harnessStart(p, out, harness) {
|
|
|
158
199
|
}
|
|
159
200
|
else {
|
|
160
201
|
// Claude Code takes the session id from us, so nothing has to be read back from its output.
|
|
161
|
-
session
|
|
162
|
-
await startClaudeSession(bin, ["-p", prompt, ...settings, "
|
|
202
|
+
session ??= randomUUID();
|
|
203
|
+
await startClaudeSession(bin, ["-p", prompt, ...settings, ...(sandbox === "workspace-write" ? claudeTurnArgs(maxBudgetUsd) : []), ...claudeSessionStartArgs(sandbox, session), "--output-format", "json"], firstTurnLog, ref, session, providerEnv, model, provider);
|
|
163
204
|
lines.push(`Started Claude Code session ${session}; its first turn (reading its role and inbox) is running, result: ${firstTurnLog}`);
|
|
164
205
|
}
|
|
165
206
|
}
|
|
@@ -179,7 +220,7 @@ export async function harnessStart(p, out, harness) {
|
|
|
179
220
|
if (harness === "codex")
|
|
180
221
|
bindSession("codex", session, ref);
|
|
181
222
|
const transcript = harness === "dsh" ? dshTurnLog(ref) : harness === "claude-code" ? claudeTranscript(session) ?? firstTurnLog ?? "" : codexRollout(session) ?? firstTurnLog ?? "";
|
|
182
|
-
writeState(ref, { ...readState(ref), harness_session: { harness, transcript, session_id: session, at: Date.now(), ...(initialPid ? { initial_pid: initialPid } : {}) } });
|
|
223
|
+
writeState(ref, { ...readState(ref), harness_session: { harness, transcript, session_id: session, at: Date.now(), ...(harness === "claude-code" ? { provider } : {}), ...(initialPid ? { initial_pid: initialPid } : {}) } });
|
|
183
224
|
// A session adopted here may end in a usage-limit error from the machine it came from, written in
|
|
184
225
|
// that machine's local time ("3:32 PM" Central read as UTC on ronald: six hours off). Only errors
|
|
185
226
|
// from turns on this machine pause it; if the account is still limited, the next turn says so here.
|
|
@@ -191,7 +232,7 @@ export async function harnessStart(p, out, harness) {
|
|
|
191
232
|
: harness === "dsh"
|
|
192
233
|
? dshResumeCommand(bin, session, settings, dshTurnLog(ref))
|
|
193
234
|
// The result goes to a file the watcher reads when the turn ends: Claude Code can exit 0 with is_error set.
|
|
194
|
-
: `${shq(bin)} -p {text} ${[...settings, "--resume", session, "--output-format", "json"].map(shq).join(" ")} > ${shq(claudeResultFile(ref))}`;
|
|
235
|
+
: `${shq(bin)} -p {text} ${[...settings, ...(sandbox === "workspace-write" ? claudeTurnArgs(maxBudgetUsd) : []), "--resume", session, "--output-format", "json"].map(shq).join(" ")} > ${shq(claudeResultFile(ref))}`;
|
|
195
236
|
const watcherOut = [];
|
|
196
237
|
// Scratch space beside the checkout, not the system's /tmp: on a machine the checkout lives on the
|
|
197
238
|
// work volume, the folder is inside what the sandbox may write, and it survives a reboot. Learned
|
|
@@ -199,7 +240,7 @@ export async function harnessStart(p, out, harness) {
|
|
|
199
240
|
// volume had 750 GB free, and which empties /tmp at every boot.
|
|
200
241
|
const tmp = sessionTmpDir(process.cwd(), creds.agent);
|
|
201
242
|
mkdirSync(tmp, { recursive: true });
|
|
202
|
-
installWatcherService(ref, exec, interval, Number(str(p.flags, "follow-delay") ?? "300"), { TMPDIR: tmp }, undefined, { json: false, print: (h) => watcherOut.push(h) }, bool(p.flags, "prune"), { harness, session, timeout: turnTimeout, turnsPerHour, provider, model });
|
|
243
|
+
installWatcherService(ref, exec, interval, Number(str(p.flags, "follow-delay") ?? "300"), { TMPDIR: tmp, ...(harness === "claude-code" ? claudeSandboxEnv(sandbox) : {}) }, undefined, { json: false, print: (h) => watcherOut.push(h) }, bool(p.flags, "prune"), { harness, session, timeout: turnTimeout, turnsPerHour, provider, model });
|
|
203
244
|
const wl = watcherOut.join("\n").split("\n");
|
|
204
245
|
lines.push(wl[0].replace(/^Wrote /, "Watcher: wrote "), ...wl.filter((l) => l.startsWith("Linger is off")));
|
|
205
246
|
// 5. Hooks.
|
|
@@ -267,9 +308,19 @@ export async function startDshSession(bin, args, logPath, agent, prompt) {
|
|
|
267
308
|
* minutes; this command does not wait for it) and returns once its transcript exists, or fails
|
|
268
309
|
* with Claude Code's own error when it exits first.
|
|
269
310
|
*/
|
|
270
|
-
async function startClaudeSession(bin, args, logPath, agent, session, providerEnv) {
|
|
311
|
+
async function startClaudeSession(bin, args, logPath, agent, session, providerEnv, model, provider) {
|
|
271
312
|
const fd = openSync(logPath, "w");
|
|
272
|
-
const child = spawn(bin, args, {
|
|
313
|
+
const child = spawn(bin, args, {
|
|
314
|
+
stdio: ["ignore", fd, fd], detached: true, cwd: process.cwd(),
|
|
315
|
+
env: {
|
|
316
|
+
...process.env,
|
|
317
|
+
BSCHAT_AGENT: agent,
|
|
318
|
+
...(model ? { BSCHAT_MODEL: model } : {}),
|
|
319
|
+
BSCHAT_SESSION_ID: session,
|
|
320
|
+
BSCHAT_PROVIDER: provider,
|
|
321
|
+
...providerEnv,
|
|
322
|
+
},
|
|
323
|
+
});
|
|
273
324
|
closeSync(fd);
|
|
274
325
|
let exited = null;
|
|
275
326
|
child.on("exit", (code) => { exited = code ?? 1; });
|
|
@@ -287,6 +338,104 @@ async function startClaudeSession(bin, args, logPath, agent, session, providerEn
|
|
|
287
338
|
}
|
|
288
339
|
throw new CliError("claude_failed", `Claude Code wrote no transcript for session ${session} within 90 s; see ${logPath}`);
|
|
289
340
|
}
|
|
341
|
+
/** GitHub/other SSH origins cannot traverse Claude Code's HTTP-only workspace proxy. */
|
|
342
|
+
export function configureHttpsOriginForWorktree(cwd) {
|
|
343
|
+
const remote = spawnSync("git", ["remote", "get-url", "origin"], { cwd, encoding: "utf8" });
|
|
344
|
+
if (remote.status !== 0)
|
|
345
|
+
throw new CliError("git_origin", `cannot read origin in ${cwd}: ${(remote.stderr ?? "").trim() || "git remote get-url origin failed"}`);
|
|
346
|
+
const url = remote.stdout.trim();
|
|
347
|
+
let host;
|
|
348
|
+
let prefix;
|
|
349
|
+
const scp = /^git@([^:]+):/.exec(url);
|
|
350
|
+
const ssh = /^ssh:\/\/(?:git@)?([^/]+)\//.exec(url);
|
|
351
|
+
if (scp) {
|
|
352
|
+
host = scp[1];
|
|
353
|
+
prefix = `git@${host}:`;
|
|
354
|
+
}
|
|
355
|
+
else if (ssh) {
|
|
356
|
+
host = ssh[1];
|
|
357
|
+
prefix = url.startsWith("ssh://git@") ? `ssh://git@${host}/` : `ssh://${host}/`;
|
|
358
|
+
}
|
|
359
|
+
else if (/^https:\/\//.test(url))
|
|
360
|
+
return;
|
|
361
|
+
else
|
|
362
|
+
throw new CliError("git_origin", `unsupported origin URL for a sandboxed Claude session: ${url || "(empty)"}`, "Set this worktree's origin to an HTTPS URL and configure its existing Git credential helper, then rerun b9s start");
|
|
363
|
+
const enabled = spawnSync("git", ["config", "extensions.worktreeConfig", "true"], { cwd, encoding: "utf8" });
|
|
364
|
+
if (enabled.status !== 0)
|
|
365
|
+
throw new CliError("git_origin", `could not enable per-worktree Git configuration: ${(enabled.stderr ?? "").trim()}`);
|
|
366
|
+
const base = `https://${host}/`;
|
|
367
|
+
const existing = spawnSync("git", ["config", "--worktree", "--get-all", `url.${base}.insteadOf`], { cwd, encoding: "utf8" });
|
|
368
|
+
if ((existing.stdout ?? "").split(/\r?\n/).includes(prefix))
|
|
369
|
+
return;
|
|
370
|
+
const added = spawnSync("git", ["config", "--worktree", "--add", `url.${base}.insteadOf`, prefix], { cwd, encoding: "utf8" });
|
|
371
|
+
if (added.status !== 0)
|
|
372
|
+
throw new CliError("git_origin", `could not add per-worktree HTTPS rewrite for ${url}: ${(added.stderr ?? "").trim()}`, `Run git config --worktree --add 'url.${base}.insteadOf' '${prefix}' in ${cwd}, then rerun b9s start`);
|
|
373
|
+
}
|
|
374
|
+
/** The workspace-write connectivity probe creates the session; the real first turn resumes it. */
|
|
375
|
+
export function claudeSessionStartArgs(sandbox, session) {
|
|
376
|
+
return sandbox === "workspace-write" ? ["--resume", session] : ["--session-id", session];
|
|
377
|
+
}
|
|
378
|
+
export function runClaudeSandboxSelfCheck(bin, settings, maxBudgetUsd, env, cwd, session, agent) {
|
|
379
|
+
const prompt = [
|
|
380
|
+
"BenignSwarm sandbox startup check. Use your Bash tool to execute these two commands separately, exactly as written:",
|
|
381
|
+
"1. b9s me",
|
|
382
|
+
"2. git ls-remote origin",
|
|
383
|
+
"Capture each real exit code and complete stdout/stderr. Do not infer or invent results.",
|
|
384
|
+
'Return only one JSON object with this shape: {"b9s_me":{"status":0,"output":"..."},"git_ls_remote_origin":{"status":0,"output":"..."}}.',
|
|
385
|
+
].join("\n");
|
|
386
|
+
const logPath = joinPath(configRoot(), "logs", `claude-sandbox-self-check.${process.pid}.json`);
|
|
387
|
+
const check = spawnSync(bin, ["-p", prompt, ...settings, ...claudeTurnArgs(maxBudgetUsd), ...(session ? ["--session-id", session] : []), "--output-format", "json"], {
|
|
388
|
+
encoding: "utf8", timeout: 180_000, cwd, env: { ...process.env, ...env, ...(agent ? { BSCHAT_AGENT: agent } : {}) }, maxBuffer: 2 * 1024 * 1024,
|
|
389
|
+
});
|
|
390
|
+
const output = check.stdout ?? "";
|
|
391
|
+
try {
|
|
392
|
+
writeFileSync(logPath, output + (check.stderr ? `\n${check.stderr}` : ""));
|
|
393
|
+
}
|
|
394
|
+
catch { /* the CLI error still includes bounded output */ }
|
|
395
|
+
if (check.error || check.status !== 0) {
|
|
396
|
+
const detail = [check.error?.message, check.status !== 0 ? `Claude Code exited ${check.status ?? "unknown"}: ${(check.stderr ?? "").trim()}` : "", output.trim() ? `Harness output: ${output.trim().slice(-1500)}` : "Harness stdout was empty"].filter(Boolean).join("\n");
|
|
397
|
+
throw new CliError("sandbox_self_check_failed", `Claude Code workspace-write self-check failed; watcher was not enabled.\n${detail || "Claude Code did not complete the check"}\nFull harness output: ${logPath}`, "Ensure the configured HTTPS credential helper can read this repository and that the b9s install is on PATH, then rerun b9s start");
|
|
398
|
+
}
|
|
399
|
+
try {
|
|
400
|
+
assertClaudeSelfCheck(output);
|
|
401
|
+
}
|
|
402
|
+
catch (error) {
|
|
403
|
+
const message = error.message;
|
|
404
|
+
throw new CliError("sandbox_self_check_failed", `${message}\nFull harness output: ${logPath}`, "For GitHub, run `gh auth setup-git`; otherwise configure the existing HTTPS credential helper for this worktree, then rerun b9s start. If SSH access is required, use --sandbox danger-full-access");
|
|
405
|
+
}
|
|
406
|
+
let tokens = null;
|
|
407
|
+
try {
|
|
408
|
+
const usage = JSON.parse(output).usage;
|
|
409
|
+
if (usage)
|
|
410
|
+
tokens = (usage.input_tokens ?? 0) + (usage.output_tokens ?? 0) + (usage.cache_read_input_tokens ?? 0) + (usage.cache_creation_input_tokens ?? 0);
|
|
411
|
+
}
|
|
412
|
+
catch { /* the accepted report may be emitted without a usage envelope */ }
|
|
413
|
+
return { output, tokens };
|
|
414
|
+
}
|
|
415
|
+
/** Guard a model-spending connectivity preflight independently from the agent's real turn. */
|
|
416
|
+
export async function runGuardedClaudeSandboxSelfCheck(ref, turnsPerHour, bin, settings, maxBudgetUsd, env, cwd, session, run = runClaudeSandboxSelfCheck) {
|
|
417
|
+
const diagnostic = [];
|
|
418
|
+
if (!(await beginTurnGuardAttempt(ref, turnsPerHour, (message) => diagnostic.push(message)))) {
|
|
419
|
+
throw new CliError("turn_mode_fault", diagnostic.at(-1) ?? "turn mode guard refused the sandbox self-check");
|
|
420
|
+
}
|
|
421
|
+
const probe = probeFor("claude-code", session, ref);
|
|
422
|
+
let result;
|
|
423
|
+
try {
|
|
424
|
+
result = run(bin, settings, maxBudgetUsd, env, cwd, session, ref);
|
|
425
|
+
}
|
|
426
|
+
catch (error) {
|
|
427
|
+
const output = error.message;
|
|
428
|
+
await completePendingTurnGuard(ref, probe, (message) => diagnostic.push(message), output, null);
|
|
429
|
+
const fault = readState(ref).turn_guard?.fault;
|
|
430
|
+
if (fault)
|
|
431
|
+
throw new CliError("turn_mode_fault", `turn mode stopped after ${fault.consecutive_unproductive} consecutive turns without a BenignSwarm call; estimated tokens spent: ${fault.estimated_tokens}; last output: ${fault.output_tail || "(empty)"}`);
|
|
432
|
+
throw error;
|
|
433
|
+
}
|
|
434
|
+
await completePendingTurnGuard(ref, probe, (message) => diagnostic.push(message), result.output, result.tokens);
|
|
435
|
+
const fault = readState(ref).turn_guard?.fault;
|
|
436
|
+
if (fault)
|
|
437
|
+
throw new CliError("turn_mode_fault", `turn mode stopped after ${fault.consecutive_unproductive} consecutive turns without a BenignSwarm call; estimated tokens spent: ${fault.estimated_tokens}; last output: ${fault.output_tail || "(empty)"}`);
|
|
438
|
+
}
|
|
290
439
|
/**
|
|
291
440
|
* The Codex settings a headless turn runs with. Under workspace-write the agent still has to reach
|
|
292
441
|
* the API and write its own b9s state (~/.b9s), and `wu start` puts unit worktrees beside the
|
|
@@ -0,0 +1,128 @@
|
|
|
1
|
+
import { spawnSync } from "node:child_process";
|
|
2
|
+
import { Client } from "../client.js";
|
|
3
|
+
import { loadAgent, resolveAgentName } from "../config.js";
|
|
4
|
+
import { CliError } from "../errors.js";
|
|
5
|
+
import { requireInstall } from "../install.js";
|
|
6
|
+
function credentialInput(input) {
|
|
7
|
+
const result = {};
|
|
8
|
+
for (const line of input.split(/\r?\n/)) {
|
|
9
|
+
if (!line)
|
|
10
|
+
break;
|
|
11
|
+
const i = line.indexOf("=");
|
|
12
|
+
if (i < 0)
|
|
13
|
+
continue;
|
|
14
|
+
const key = line.slice(0, i);
|
|
15
|
+
if (key === "protocol" || key === "host" || key === "path")
|
|
16
|
+
result[key] = line.slice(i + 1);
|
|
17
|
+
}
|
|
18
|
+
return result;
|
|
19
|
+
}
|
|
20
|
+
function repositoryPath(path) {
|
|
21
|
+
if (!path)
|
|
22
|
+
return null;
|
|
23
|
+
const normalized = path.replace(/^\//, "").replace(/\.git$/i, "");
|
|
24
|
+
return /^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/.test(normalized) ? normalized.toLowerCase() : null;
|
|
25
|
+
}
|
|
26
|
+
export async function credentialResponse(input, api) {
|
|
27
|
+
const request = credentialInput(input);
|
|
28
|
+
if (request.protocol !== "https" || request.host?.toLowerCase() !== "github.com")
|
|
29
|
+
return "";
|
|
30
|
+
const wanted = repositoryPath(request.path);
|
|
31
|
+
if (!wanted)
|
|
32
|
+
return "";
|
|
33
|
+
const metadata = await api("GET", "");
|
|
34
|
+
if (!metadata.linked || !metadata.repository) {
|
|
35
|
+
throw new CliError("github_not_connected", "GitHub is not connected for this project. Connect GitHub in the console to enable repository access.");
|
|
36
|
+
}
|
|
37
|
+
const linked = `${metadata.repository.owner}/${metadata.repository.name}`.toLowerCase();
|
|
38
|
+
if (wanted !== linked)
|
|
39
|
+
return "";
|
|
40
|
+
const credential = await api("POST", "", {});
|
|
41
|
+
return `username=${credential.username}\npassword=${credential.password}\n\n`;
|
|
42
|
+
}
|
|
43
|
+
export async function gitCredentialOperation(operation, input, api) {
|
|
44
|
+
if (operation === "store" || operation === "erase")
|
|
45
|
+
return "";
|
|
46
|
+
if (operation !== "get")
|
|
47
|
+
throw new CliError("usage", "git-credential get|store|erase");
|
|
48
|
+
return credentialResponse(input, api);
|
|
49
|
+
}
|
|
50
|
+
export async function gitCredential(p) {
|
|
51
|
+
const operation = p.positionals[1];
|
|
52
|
+
const chunks = [];
|
|
53
|
+
for await (const chunk of process.stdin)
|
|
54
|
+
chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));
|
|
55
|
+
const input = Buffer.concat(chunks).toString("utf8");
|
|
56
|
+
if (operation === "store" || operation === "erase")
|
|
57
|
+
return;
|
|
58
|
+
if (operation !== "get")
|
|
59
|
+
throw new CliError("usage", "git-credential get|store|erase");
|
|
60
|
+
const agent = loadAgent(resolveAgentName(undefined));
|
|
61
|
+
if (!agent.project)
|
|
62
|
+
throw new CliError("github_not_connected", "GitHub credential helper requires a project-scoped agent identity.");
|
|
63
|
+
const client = Client.forAgent(agent, undefined, { presence: false });
|
|
64
|
+
const base = `/projects/${encodeURIComponent(agent.project)}/git-credentials`;
|
|
65
|
+
const result = await gitCredentialOperation(operation, input, (method, _path, body) => client.call(method, base, body));
|
|
66
|
+
if (result)
|
|
67
|
+
process.stdout.write(result);
|
|
68
|
+
}
|
|
69
|
+
function remoteRepository(url) {
|
|
70
|
+
const scp = /^git@github\.com:([^?#]+)$/i.exec(url);
|
|
71
|
+
const ssh = /^ssh:\/\/(?:git@)?github\.com\/([^?#]+)$/i.exec(url);
|
|
72
|
+
const https = /^https:\/\/github\.com\/([^?#]+)$/i.exec(url);
|
|
73
|
+
const match = scp ?? ssh ?? https;
|
|
74
|
+
if (!match)
|
|
75
|
+
return null;
|
|
76
|
+
const credentialPath = match[1].replace(/^\//, "");
|
|
77
|
+
const path = repositoryPath(credentialPath);
|
|
78
|
+
if (!path)
|
|
79
|
+
return null;
|
|
80
|
+
return { sshPrefix: scp ? "git@github.com:" : ssh ? "ssh://git@github.com/" : null, path, credentialPath };
|
|
81
|
+
}
|
|
82
|
+
function gitConfig(cwd, args) {
|
|
83
|
+
const result = spawnSync("git", ["config", ...args], { cwd, encoding: "utf8" });
|
|
84
|
+
if (result.status !== 0)
|
|
85
|
+
throw new CliError("git_credential_config", (result.stderr ?? "").trim() || "could not configure the worktree Git credential helper");
|
|
86
|
+
}
|
|
87
|
+
function shellQuote(value) { return `'${value.replace(/'/g, `'\\''`)}'`; }
|
|
88
|
+
/** Adds the exact repo helper only when origin is the repository linked to this project. */
|
|
89
|
+
export async function configureGitCredentialForWorktree(cwd, creds, lookup, installBin) {
|
|
90
|
+
if (!creds.project)
|
|
91
|
+
return;
|
|
92
|
+
const client = Client.forAgent(creds, undefined, { presence: false });
|
|
93
|
+
const metadata = lookup
|
|
94
|
+
? await lookup()
|
|
95
|
+
: await client.call("GET", `/projects/${encodeURIComponent(creds.project)}/git-credentials`);
|
|
96
|
+
if (!metadata.linked || !metadata.repository)
|
|
97
|
+
return;
|
|
98
|
+
// Read the configured value, not `remote get-url`: that command expands existing insteadOf
|
|
99
|
+
// rewrites and would hide the SSH origin when this startup runs a second time.
|
|
100
|
+
const remote = spawnSync("git", ["config", "--get", "remote.origin.url"], { cwd, encoding: "utf8" });
|
|
101
|
+
if (remote.status !== 0)
|
|
102
|
+
throw new CliError("git_origin", `cannot read origin in ${cwd}: ${(remote.stderr ?? "").trim() || "git remote get-url origin failed"}`);
|
|
103
|
+
const parsed = remoteRepository(remote.stdout.trim());
|
|
104
|
+
if (!parsed)
|
|
105
|
+
return;
|
|
106
|
+
if (`${metadata.repository.owner}/${metadata.repository.name}`.toLowerCase() !== parsed.path)
|
|
107
|
+
return;
|
|
108
|
+
const enabled = spawnSync("git", ["config", "extensions.worktreeConfig", "true"], { cwd, encoding: "utf8" });
|
|
109
|
+
if (enabled.status !== 0)
|
|
110
|
+
throw new CliError("git_credential_config", (enabled.stderr ?? "").trim() || "could not enable per-worktree Git configuration");
|
|
111
|
+
if (parsed.sshPrefix) {
|
|
112
|
+
const rewriteKey = `url.https://github.com/${parsed.credentialPath}.insteadOf`;
|
|
113
|
+
const sshOrigin = `${parsed.sshPrefix}${parsed.credentialPath}`;
|
|
114
|
+
const existing = spawnSync("git", ["config", "--worktree", "--get-all", rewriteKey], { cwd, encoding: "utf8" });
|
|
115
|
+
if (!(existing.stdout ?? "").split(/\r?\n/).includes(sshOrigin))
|
|
116
|
+
gitConfig(cwd, ["--worktree", "--add", rewriteKey, sshOrigin]);
|
|
117
|
+
}
|
|
118
|
+
// useHttpPath makes Git send this exact remote path (including an optional .git suffix).
|
|
119
|
+
// Matching the remote spelling and suffix keeps this helper out of other repositories.
|
|
120
|
+
const repoUrl = `https://github.com/${parsed.credentialPath}`;
|
|
121
|
+
const helperKey = `credential.${repoUrl}.helper`;
|
|
122
|
+
gitConfig(cwd, ["--worktree", "--replace-all", helperKey, ""]);
|
|
123
|
+
gitConfig(cwd, ["--worktree", "--add", helperKey, `!${shellQuote(installBin ?? requireInstall().bin)} git-credential`]);
|
|
124
|
+
gitConfig(cwd, ["--worktree", "credential.https://github.com.useHttpPath", "true"]);
|
|
125
|
+
}
|
|
126
|
+
export async function gitCredentialMain(p) {
|
|
127
|
+
return gitCredential(p);
|
|
128
|
+
}
|
package/dist/commands/hook.js
CHANGED
|
@@ -664,5 +664,5 @@ function noteSession(name, harness, transcript, sessionId) {
|
|
|
664
664
|
const cur = st.harness_session;
|
|
665
665
|
if (cur && cur.transcript === transcript && cur.harness === harness)
|
|
666
666
|
return;
|
|
667
|
-
writeState(name, { ...st, harness_session: { harness, transcript, session_id: sessionId, at: Date.now() } });
|
|
667
|
+
writeState(name, { ...st, harness_session: { harness, transcript, session_id: sessionId, at: Date.now(), ...(cur?.harness === harness && cur.session_id === sessionId && cur.provider ? { provider: cur.provider } : {}) } });
|
|
668
668
|
}
|