@bunshin-cc/bunshin 0.12.2 → 0.13.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +7 -6
- package/dist/bin.js +415 -165
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -7,22 +7,23 @@ Bunshin lets your company’s AI agents (and robots) learn from each other. Your
|
|
|
7
7
|
You need Node.js 20 or later, a signed-in Codex, Claude Code, or Pi installation, and an account in your company’s [Bunshin workspace](https://bunshin.cc/dashboard/).
|
|
8
8
|
|
|
9
9
|
```sh
|
|
10
|
-
npm install -g @bunshin-cc/bunshin
|
|
11
10
|
cd /path/to/your/project
|
|
12
|
-
bunshin
|
|
11
|
+
npm install -g @bunshin-cc/bunshin && bunshin setup
|
|
13
12
|
```
|
|
14
13
|
|
|
15
|
-
|
|
14
|
+
Setup finds your agent (`--harness claude-code|codex|pi` picks one when several are installed). The first time on a computer it opens Bunshin on **Connect this computer?** with a short code: check it matches your terminal and click Approve. There is no key to copy. Setup then reads your role, team, and permissions from the workspace, saves the computer's key in a private file outside the project, and configures the project hooks (five for Codex, six plus an MCP server for Claude Code). Every later project on the same computer connects with `bunshin setup` alone. It does not need a separate model API key.
|
|
15
|
+
|
|
16
|
+
When an agent runs setup for you, it uses `bunshin login --no-wait` (prints the link and returns), shows you the link, then runs `bunshin setup` once you have approved. `bunshin logout` forgets the computer's sign-in.
|
|
16
17
|
|
|
17
18
|
Run `codex` interactively in the same project. Review and accept its project trust prompt, then run `/hooks` and review and trust the five Bunshin hooks. Project trust and hook trust are separate steps. If `/hooks` does not list Bunshin, check that you opened the connected project and trusted its configuration. This guide tests interactive sessions; `codex exec` is not a substitute for this setup check.
|
|
18
19
|
|
|
19
20
|
For a linked Git worktree, setup puts Codex hooks in the primary checkout, where Codex reads them. The printed path identifies that shared hook file. Each connected worktree keeps its own `.bunshin` store and private connection. Worktrees created from a bare repository are not supported yet; use a full checkout.
|
|
20
21
|
|
|
21
|
-
For Claude Code,
|
|
22
|
+
For Claude Code, start a new session in the project and approve the `bunshin` MCP server it adds to `.mcp.json` (it gives the model the `bunshin_recall` and `bunshin_load` tools). `/learn` in the Claude Code plugin, or `bunshin learn "<what to remember>"`, captures knowledge on demand.
|
|
22
23
|
|
|
23
24
|
To connect a whole folder of projects (each its own repository), run setup there with `--hooks user`: the hooks go in your user settings and every session under that folder uses its workspace, while sessions elsewhere are untouched. `bunshin sources` shows and changes which of its folders take part (`exclude <folder>`, `only <folders…>`, `include <folder>`, `all`).
|
|
24
25
|
|
|
25
|
-
For Pi, use Node.js 22.19 or later
|
|
26
|
+
For Pi, use Node.js 22.19 or later. Setup installs a project extension in `.pi/extensions/bunshin.js`. Start Pi in the project (or run `/reload` in an existing session), review its project resources, and check `/bunshin status`. The extension ships in this npm package; you do not need a second package or a repository checkout.
|
|
26
27
|
|
|
27
28
|
## Check it works
|
|
28
29
|
|
|
@@ -45,7 +46,7 @@ Sessions uploaded by a CLI before 0.6.2 carry a clipped trace (at most 60,000 ch
|
|
|
45
46
|
|
|
46
47
|
## Scope and removal
|
|
47
48
|
|
|
48
|
-
Setup applies to the current project. The local `.bunshin/` directory contains lessons and session state and is added to `.gitignore`.
|
|
49
|
+
Setup applies to the current project. The local `.bunshin/` directory contains lessons and session state and is added to `.gitignore`. Keys are stored under `~/.config/bunshin/` with owner-only permissions. For CI, set `BUNSHIN_API_KEY` or pipe a key from **Agent keys** to `bunshin setup --key-stdin`. Your existing hooks remain in place.
|
|
49
50
|
|
|
50
51
|
```sh
|
|
51
52
|
bunshin init --harness codex --remove-hooks
|
package/dist/bin.js
CHANGED
|
@@ -1207,10 +1207,10 @@ function isLocalLayer(layer) {
|
|
|
1207
1207
|
return kind === "user" || kind === "robot";
|
|
1208
1208
|
}
|
|
1209
1209
|
function withScope(layers, scope) {
|
|
1210
|
-
const
|
|
1211
|
-
if (!
|
|
1210
|
+
const path32 = scopePath(scope?.tree, scope?.source);
|
|
1211
|
+
if (!path32.length) return layers;
|
|
1212
1212
|
const i = layers.findIndex((l) => isLocalLayer(l));
|
|
1213
|
-
return i < 0 ? [...layers, ...
|
|
1213
|
+
return i < 0 ? [...layers, ...path32] : [...layers.slice(0, i), ...path32, ...layers.slice(i)];
|
|
1214
1214
|
}
|
|
1215
1215
|
function readerFor(ctx, ownerClearance, scope) {
|
|
1216
1216
|
if (ctx.kind === "robot" && !scope?.source) scope = { ...scope, source: `robot:${ctx.id}` };
|
|
@@ -1257,11 +1257,11 @@ function baseAffinity(section, reader) {
|
|
|
1257
1257
|
const kind = layerKind(section.layer);
|
|
1258
1258
|
if (kind === "group" || kind === "source") {
|
|
1259
1259
|
if (!reader.layers.includes(section.layer)) return 0.05;
|
|
1260
|
-
const
|
|
1260
|
+
const path32 = reader.layers.filter((l) => {
|
|
1261
1261
|
const k = layerKind(l);
|
|
1262
1262
|
return k === "group" || k === "source";
|
|
1263
1263
|
});
|
|
1264
|
-
return 0.6 + 0.4 * ((
|
|
1264
|
+
return 0.6 + 0.4 * ((path32.indexOf(section.layer) + 1) / path32.length);
|
|
1265
1265
|
}
|
|
1266
1266
|
if (isLocalLayer(section.layer)) return reader.layers.includes(section.layer) ? 1 : 0;
|
|
1267
1267
|
return 0.5;
|
|
@@ -1461,17 +1461,17 @@ var init_document = __esm({
|
|
|
1461
1461
|
function repoLayer(repo) {
|
|
1462
1462
|
return `source:${repo.includes("/") ? "repo" : "folder"}:${repo}`;
|
|
1463
1463
|
}
|
|
1464
|
-
function repoSectionId(repo,
|
|
1465
|
-
return anchor ? `repo:${repo}/${
|
|
1464
|
+
function repoSectionId(repo, path32, anchor = "") {
|
|
1465
|
+
return anchor ? `repo:${repo}/${path32}#${anchor}` : `repo:${repo}/${path32}`;
|
|
1466
1466
|
}
|
|
1467
|
-
function docKind(
|
|
1468
|
-
const base =
|
|
1467
|
+
function docKind(path32) {
|
|
1468
|
+
const base = path32.split("/").pop()?.toLowerCase() ?? "";
|
|
1469
1469
|
if (base === "testing.md") return "verification";
|
|
1470
1470
|
if (base === "skill.md") return "skill";
|
|
1471
1471
|
return "spec";
|
|
1472
1472
|
}
|
|
1473
|
-
function defaultPaths(
|
|
1474
|
-
const dir2 =
|
|
1473
|
+
function defaultPaths(path32) {
|
|
1474
|
+
const dir2 = path32.split("/").slice(0, -1).join("/");
|
|
1475
1475
|
if (!dir2 || dir2.startsWith(".claude/") || dir2.startsWith(".codex/")) return [];
|
|
1476
1476
|
return [`${dir2}/**`];
|
|
1477
1477
|
}
|
|
@@ -1616,11 +1616,11 @@ function lintSkills(sections) {
|
|
|
1616
1616
|
}
|
|
1617
1617
|
const state = /* @__PURE__ */ new Map();
|
|
1618
1618
|
const cycles = /* @__PURE__ */ new Set();
|
|
1619
|
-
const dfs = (n,
|
|
1619
|
+
const dfs = (n, path32) => {
|
|
1620
1620
|
state.set(n, 1);
|
|
1621
1621
|
for (const d of edges[n] ?? []) {
|
|
1622
|
-
if (state.get(d) === 1) cycles.add([...
|
|
1623
|
-
else if (!state.get(d)) dfs(d, [...
|
|
1622
|
+
if (state.get(d) === 1) cycles.add([...path32.slice(path32.indexOf(d)), d].join(" -> "));
|
|
1623
|
+
else if (!state.get(d)) dfs(d, [...path32, d]);
|
|
1624
1624
|
}
|
|
1625
1625
|
state.set(n, 2);
|
|
1626
1626
|
};
|
|
@@ -1707,8 +1707,8 @@ function parsePythonSkills(text2) {
|
|
|
1707
1707
|
}
|
|
1708
1708
|
return { skills, constants };
|
|
1709
1709
|
}
|
|
1710
|
-
function harnessSectionId(
|
|
1711
|
-
return `harness:${
|
|
1710
|
+
function harnessSectionId(path32, symbol) {
|
|
1711
|
+
return `harness:${path32}#${symbol}`;
|
|
1712
1712
|
}
|
|
1713
1713
|
var DEF_RE;
|
|
1714
1714
|
var init_python = __esm({
|
|
@@ -1834,11 +1834,11 @@ function globToRegExp(glob) {
|
|
|
1834
1834
|
globCache.set(glob, out);
|
|
1835
1835
|
return out;
|
|
1836
1836
|
}
|
|
1837
|
-
function normalPath(
|
|
1838
|
-
return
|
|
1837
|
+
function normalPath(path32) {
|
|
1838
|
+
return path32.replace(/\\/g, "/").split("/").filter((s) => s !== "" && s !== ".").join("/");
|
|
1839
1839
|
}
|
|
1840
|
-
function matchesGlob(
|
|
1841
|
-
return globToRegExp(glob.replace(/^\.\//, "")).test(normalPath(
|
|
1840
|
+
function matchesGlob(path32, glob) {
|
|
1841
|
+
return globToRegExp(glob.replace(/^\.\//, "")).test(normalPath(path32));
|
|
1842
1842
|
}
|
|
1843
1843
|
var DEFAULT_EMBEDDERS, globCache;
|
|
1844
1844
|
var init_text_index = __esm({
|
|
@@ -1929,10 +1929,10 @@ function push(sections, reader, query) {
|
|
|
1929
1929
|
for (const s of recallable(sections, reader).filter((x) => reachesReader(x, reader))) {
|
|
1930
1930
|
const triggers = [...(s.triggers ?? []).filter((t) => t.anchor), { anchor: "", paths: s.paths, entities: s.entities, skills: s.skills }];
|
|
1931
1931
|
for (const t of triggers) {
|
|
1932
|
-
const
|
|
1933
|
-
const entity =
|
|
1934
|
-
const skill =
|
|
1935
|
-
const trigger =
|
|
1932
|
+
const path32 = paths.find((p) => t.paths.some((g) => matchesGlob(p, g)));
|
|
1933
|
+
const entity = path32 ? void 0 : t.entities.find((e) => entities.has(e) || text2 && text2.includes(e));
|
|
1934
|
+
const skill = path32 || entity ? void 0 : skills.find((k) => t.skills.includes(k));
|
|
1935
|
+
const trigger = path32 ? `path:${path32}` : entity ? `entity:${entity}` : skill ? `skill:${skill}` : "";
|
|
1936
1936
|
if (trigger) {
|
|
1937
1937
|
hits.set(s.id, { section: s, trigger, anchor: t.anchor });
|
|
1938
1938
|
break;
|
|
@@ -9309,13 +9309,16 @@ var init_init = __esm({
|
|
|
9309
9309
|
// src/setup.ts
|
|
9310
9310
|
var setup_exports = {};
|
|
9311
9311
|
__export(setup_exports, {
|
|
9312
|
+
HARNESS_NAMES: () => HARNESS_NAMES,
|
|
9312
9313
|
HOSTED_API: () => HOSTED_API,
|
|
9313
9314
|
apiAddress: () => apiAddress,
|
|
9314
9315
|
askSources: () => askSources,
|
|
9315
9316
|
autoConnect: () => autoConnect,
|
|
9317
|
+
chooseHarness: () => chooseHarness,
|
|
9316
9318
|
connectionProfile: () => connectionProfile,
|
|
9317
9319
|
executable: () => executable,
|
|
9318
9320
|
hookBinary: () => hookBinary,
|
|
9321
|
+
installedHarnesses: () => installedHarnesses,
|
|
9319
9322
|
readKey: () => readKey,
|
|
9320
9323
|
repositoryRoot: () => repositoryRoot,
|
|
9321
9324
|
setupEnvironment: () => setupEnvironment,
|
|
@@ -9338,6 +9341,31 @@ function executable(name) {
|
|
|
9338
9341
|
}
|
|
9339
9342
|
return void 0;
|
|
9340
9343
|
}
|
|
9344
|
+
function installedHarnesses() {
|
|
9345
|
+
return ["claude-code", "codex", "pi"].filter((h) => executable(h === "claude-code" ? "claude" : h));
|
|
9346
|
+
}
|
|
9347
|
+
async function chooseHarness(out, interactive = !!process.stdin.isTTY) {
|
|
9348
|
+
const found = installedHarnesses();
|
|
9349
|
+
if (!found.length) throw new Error("No agent found here. Install Claude Code (https://claude.com/claude-code), Codex or Pi, sign in to it, then run bunshin setup again.");
|
|
9350
|
+
if (found.length === 1 || !interactive) {
|
|
9351
|
+
out(`Agent: ${HARNESS_NAMES[found[0]]}${found.length > 1 ? ` (also found ${found.slice(1).map((h) => HARNESS_NAMES[h]).join(", ")}: choose with --harness)` : ""}
|
|
9352
|
+
`);
|
|
9353
|
+
return found[0];
|
|
9354
|
+
}
|
|
9355
|
+
const readline2 = await import("node:readline/promises");
|
|
9356
|
+
const rl = readline2.createInterface({ input: process.stdin, output: process.stderr });
|
|
9357
|
+
try {
|
|
9358
|
+
found.forEach((h, i) => out(` ${i + 1}. ${HARNESS_NAMES[h]}
|
|
9359
|
+
`));
|
|
9360
|
+
const answer = (await rl.question(`Which agent should Bunshin connect? [1] `)).trim();
|
|
9361
|
+
const picked = found[(Number(answer) || 1) - 1] ?? found.find((h) => HARNESS_NAMES[h].toLowerCase().startsWith(answer.toLowerCase())) ?? found[0];
|
|
9362
|
+
out(`Agent: ${HARNESS_NAMES[picked]}
|
|
9363
|
+
`);
|
|
9364
|
+
return picked;
|
|
9365
|
+
} finally {
|
|
9366
|
+
rl.close();
|
|
9367
|
+
}
|
|
9368
|
+
}
|
|
9341
9369
|
function hookBinary(harness) {
|
|
9342
9370
|
const agent = executable(harness === "claude-code" ? "claude" : harness);
|
|
9343
9371
|
const directories = [.../* @__PURE__ */ new Set([path19.dirname(process.execPath), path19.join(homeDir(), ".local/bin"), ...agent ? [path19.dirname(agent)] : []])];
|
|
@@ -9519,7 +9547,7 @@ async function autoConnect(cwd, env = process.env) {
|
|
|
9519
9547
|
return { connected: false, reason: "failed", error: error instanceof Error ? error.message : String(error) };
|
|
9520
9548
|
}
|
|
9521
9549
|
}
|
|
9522
|
-
var shellQuote;
|
|
9550
|
+
var shellQuote, HARNESS_NAMES;
|
|
9523
9551
|
var init_setup = __esm({
|
|
9524
9552
|
"src/setup.ts"() {
|
|
9525
9553
|
"use strict";
|
|
@@ -9529,6 +9557,7 @@ var init_setup = __esm({
|
|
|
9529
9557
|
init_util();
|
|
9530
9558
|
init_trust();
|
|
9531
9559
|
shellQuote = (value) => `'${value.replace(/'/g, `'"'"'`)}'`;
|
|
9560
|
+
HARNESS_NAMES = { "claude-code": "Claude Code", codex: "Codex", pi: "Pi" };
|
|
9532
9561
|
}
|
|
9533
9562
|
});
|
|
9534
9563
|
|
|
@@ -10157,6 +10186,168 @@ var init_commands = __esm({
|
|
|
10157
10186
|
}
|
|
10158
10187
|
});
|
|
10159
10188
|
|
|
10189
|
+
// src/login.ts
|
|
10190
|
+
var login_exports = {};
|
|
10191
|
+
__export(login_exports, {
|
|
10192
|
+
DeviceLoginUnavailable: () => DeviceLoginUnavailable,
|
|
10193
|
+
canOpenBrowser: () => canOpenBrowser,
|
|
10194
|
+
deviceLogin: () => deviceLogin,
|
|
10195
|
+
forgetLogin: () => forgetLogin,
|
|
10196
|
+
openBrowser: () => openBrowser,
|
|
10197
|
+
readLogin: () => readLogin,
|
|
10198
|
+
readPending: () => readPending,
|
|
10199
|
+
saveLogin: () => saveLogin
|
|
10200
|
+
});
|
|
10201
|
+
import fs26 from "node:fs";
|
|
10202
|
+
import os5 from "node:os";
|
|
10203
|
+
import path22 from "node:path";
|
|
10204
|
+
import { spawn as spawn5 } from "node:child_process";
|
|
10205
|
+
import { createHash as createHash8, randomBytes as randomBytes6 } from "node:crypto";
|
|
10206
|
+
function readLogin(apiUrl) {
|
|
10207
|
+
try {
|
|
10208
|
+
const saved = JSON.parse(fs26.readFileSync(loginFile(apiUrl), "utf8"));
|
|
10209
|
+
return saved.apiUrl === apiUrl && typeof saved.apiKey === "string" && saved.apiKey ? saved : void 0;
|
|
10210
|
+
} catch {
|
|
10211
|
+
return void 0;
|
|
10212
|
+
}
|
|
10213
|
+
}
|
|
10214
|
+
function saveLogin(login) {
|
|
10215
|
+
const directory = loginDirectory();
|
|
10216
|
+
fs26.mkdirSync(directory, { recursive: true, mode: 448 });
|
|
10217
|
+
const file2 = loginFile(login.apiUrl);
|
|
10218
|
+
const temporary = `${file2}.${randomBytes6(4).toString("hex")}.tmp`;
|
|
10219
|
+
fs26.writeFileSync(temporary, JSON.stringify({ ...login, savedAt: (/* @__PURE__ */ new Date()).toISOString() }) + "\n", { mode: 384, flag: "wx" });
|
|
10220
|
+
fs26.renameSync(temporary, file2);
|
|
10221
|
+
return file2;
|
|
10222
|
+
}
|
|
10223
|
+
function forgetLogin(apiUrl) {
|
|
10224
|
+
try {
|
|
10225
|
+
fs26.unlinkSync(loginFile(apiUrl));
|
|
10226
|
+
return true;
|
|
10227
|
+
} catch {
|
|
10228
|
+
return false;
|
|
10229
|
+
}
|
|
10230
|
+
}
|
|
10231
|
+
function canOpenBrowser(env = process.env) {
|
|
10232
|
+
if (env.BUNSHIN_NO_BROWSER === "1" || env.CI || env.CLAUDE_CODE_REMOTE === "true" || env.BUNSHIN_EPHEMERAL === "1") return false;
|
|
10233
|
+
if (env.SSH_CONNECTION || env.SSH_TTY) return false;
|
|
10234
|
+
if (process.platform === "darwin" || process.platform === "win32") return true;
|
|
10235
|
+
return !!(env.DISPLAY || env.WAYLAND_DISPLAY);
|
|
10236
|
+
}
|
|
10237
|
+
function openBrowser(url) {
|
|
10238
|
+
try {
|
|
10239
|
+
const [command, args] = process.platform === "darwin" ? ["open", [url]] : process.platform === "win32" ? ["cmd", ["/c", "start", "", url.replace(/&/g, "^&")]] : ["xdg-open", [url]];
|
|
10240
|
+
const child = spawn5(command, args, { stdio: "ignore", detached: true });
|
|
10241
|
+
child.on("error", () => {
|
|
10242
|
+
});
|
|
10243
|
+
child.unref();
|
|
10244
|
+
return true;
|
|
10245
|
+
} catch {
|
|
10246
|
+
return false;
|
|
10247
|
+
}
|
|
10248
|
+
}
|
|
10249
|
+
function readPending(apiUrl, now = Date.now()) {
|
|
10250
|
+
try {
|
|
10251
|
+
const p = JSON.parse(fs26.readFileSync(pendingFile(apiUrl), "utf8"));
|
|
10252
|
+
return p.apiUrl === apiUrl && p.deviceCode && p.expiresAt > now ? p : void 0;
|
|
10253
|
+
} catch {
|
|
10254
|
+
return void 0;
|
|
10255
|
+
}
|
|
10256
|
+
}
|
|
10257
|
+
function savePending(p) {
|
|
10258
|
+
fs26.mkdirSync(loginDirectory(), { recursive: true, mode: 448 });
|
|
10259
|
+
const file2 = pendingFile(p.apiUrl);
|
|
10260
|
+
const temporary = `${file2}.${randomBytes6(4).toString("hex")}.tmp`;
|
|
10261
|
+
fs26.writeFileSync(temporary, JSON.stringify(p) + "\n", { mode: 384, flag: "wx" });
|
|
10262
|
+
fs26.renameSync(temporary, file2);
|
|
10263
|
+
}
|
|
10264
|
+
function clearPending(apiUrl) {
|
|
10265
|
+
try {
|
|
10266
|
+
fs26.unlinkSync(pendingFile(apiUrl));
|
|
10267
|
+
} catch {
|
|
10268
|
+
}
|
|
10269
|
+
}
|
|
10270
|
+
function poster(opts) {
|
|
10271
|
+
const f = opts.fetchImpl ?? fetch;
|
|
10272
|
+
return async (p, body) => {
|
|
10273
|
+
let res;
|
|
10274
|
+
try {
|
|
10275
|
+
res = await f(`${opts.apiUrl}${p}`, { method: "POST", redirect: "error", signal: AbortSignal.timeout(15e3), headers: { "content-type": "application/json" }, body: JSON.stringify(body) });
|
|
10276
|
+
} catch {
|
|
10277
|
+
throw new Error("Could not reach Bunshin. Check your connection, then run setup again.");
|
|
10278
|
+
}
|
|
10279
|
+
if (res.status === 404 || res.status === 405) throw new DeviceLoginUnavailable("This Bunshin server cannot approve computers from the browser.");
|
|
10280
|
+
if (res.status === 429) return { status: "slow_down" };
|
|
10281
|
+
if (!res.ok) throw new Error(`Bunshin returned HTTP ${res.status}.`);
|
|
10282
|
+
return await res.json();
|
|
10283
|
+
};
|
|
10284
|
+
}
|
|
10285
|
+
async function deviceLogin(opts) {
|
|
10286
|
+
const post = poster(opts);
|
|
10287
|
+
const sleep = opts.sleep ?? ((ms) => new Promise((r) => setTimeout(r, ms)));
|
|
10288
|
+
let pending = opts.noWait ? void 0 : readPending(opts.apiUrl);
|
|
10289
|
+
if (pending) {
|
|
10290
|
+
opts.out(`Waiting for the approval started earlier (code ${pending.userCode}):
|
|
10291
|
+
|
|
10292
|
+
${pending.url}
|
|
10293
|
+
|
|
10294
|
+
`);
|
|
10295
|
+
} else {
|
|
10296
|
+
const host = opts.host ?? os5.hostname().split(".")[0] ?? "";
|
|
10297
|
+
const start = await post("/saas/device/start", { client: opts.client, host });
|
|
10298
|
+
const deviceCode = String(start.deviceCode ?? "");
|
|
10299
|
+
const userCode = String(start.userCode ?? "");
|
|
10300
|
+
const url = String(start.verificationUriComplete ?? start.verificationUri ?? "");
|
|
10301
|
+
if (!deviceCode || !userCode || !url) throw new DeviceLoginUnavailable("This Bunshin server cannot approve computers from the browser.");
|
|
10302
|
+
pending = { apiUrl: opts.apiUrl, deviceCode, userCode, url, interval: Math.max(1, Number(start.interval) || 2), expiresAt: Date.now() + Math.max(60, Number(start.expiresIn) || 600) * 1e3 };
|
|
10303
|
+
if (opts.noWait) {
|
|
10304
|
+
savePending(pending);
|
|
10305
|
+
opts.out(`Open this link to approve this computer (it shows the code ${userCode}; check it matches, then click Approve):
|
|
10306
|
+
|
|
10307
|
+
${url}
|
|
10308
|
+
|
|
10309
|
+
Then run bunshin setup: it finishes once the computer is approved. The link is valid for 10 minutes.
|
|
10310
|
+
`);
|
|
10311
|
+
return null;
|
|
10312
|
+
}
|
|
10313
|
+
const opened = opts.open !== false && canOpenBrowser() && openBrowser(url);
|
|
10314
|
+
opts.out(
|
|
10315
|
+
`${opened ? "Approve this computer in the browser window that just opened" : "Open this link to approve this computer"}:
|
|
10316
|
+
|
|
10317
|
+
${url}
|
|
10318
|
+
|
|
10319
|
+
It shows the code ${userCode}; check it matches, then click Approve. Waiting\u2026
|
|
10320
|
+
`
|
|
10321
|
+
);
|
|
10322
|
+
}
|
|
10323
|
+
let interval = pending.interval * 1e3;
|
|
10324
|
+
try {
|
|
10325
|
+
while (Date.now() < pending.expiresAt) {
|
|
10326
|
+
await sleep(interval);
|
|
10327
|
+
const r = await post("/saas/device/token", { deviceCode: pending.deviceCode });
|
|
10328
|
+
if (r.status === "approved" && typeof r.key === "string") return { key: r.key };
|
|
10329
|
+
if (r.status === "denied") throw new Error("The request was declined in the browser. Run setup again to retry.");
|
|
10330
|
+
if (r.status === "expired") throw new Error("The request expired before it was approved. Run setup again for a new code.");
|
|
10331
|
+
if (r.status === "slow_down") interval += 1e3;
|
|
10332
|
+
}
|
|
10333
|
+
throw new Error("The request expired before it was approved. Run setup again for a new code.");
|
|
10334
|
+
} finally {
|
|
10335
|
+
clearPending(opts.apiUrl);
|
|
10336
|
+
}
|
|
10337
|
+
}
|
|
10338
|
+
var loginDirectory, loginFile, DeviceLoginUnavailable, pendingFile;
|
|
10339
|
+
var init_login = __esm({
|
|
10340
|
+
"src/login.ts"() {
|
|
10341
|
+
"use strict";
|
|
10342
|
+
init_util();
|
|
10343
|
+
loginDirectory = () => path22.join(homeDir(), ".config/bunshin");
|
|
10344
|
+
loginFile = (apiUrl) => path22.join(loginDirectory(), `login-${createHash8("sha256").update(apiUrl).digest("hex").slice(0, 16)}.json`);
|
|
10345
|
+
DeviceLoginUnavailable = class extends Error {
|
|
10346
|
+
};
|
|
10347
|
+
pendingFile = (apiUrl) => path22.join(loginDirectory(), `pending-${createHash8("sha256").update(apiUrl).digest("hex").slice(0, 16)}.json`);
|
|
10348
|
+
}
|
|
10349
|
+
});
|
|
10350
|
+
|
|
10160
10351
|
// src/prompts.ts
|
|
10161
10352
|
function renderLessonForInjection(l) {
|
|
10162
10353
|
const head = `### ${l.title} \`${l.id}\` (${l.kind}${l.tags.length ? `; ${l.tags.join(", ")}` : ""})`;
|
|
@@ -10295,9 +10486,9 @@ __export(sync_exports2, {
|
|
|
10295
10486
|
resolveConflict: () => resolveConflict,
|
|
10296
10487
|
runSync: () => runSync
|
|
10297
10488
|
});
|
|
10298
|
-
import { createHash as
|
|
10299
|
-
import
|
|
10300
|
-
import
|
|
10489
|
+
import { createHash as createHash9 } from "node:crypto";
|
|
10490
|
+
import path23 from "node:path";
|
|
10491
|
+
import fs27 from "node:fs";
|
|
10301
10492
|
async function api(config, method, route, body, timeoutMs = 1e4) {
|
|
10302
10493
|
const ctrl = new AbortController();
|
|
10303
10494
|
const timer = setTimeout(() => ctrl.abort(), timeoutMs);
|
|
@@ -10335,22 +10526,22 @@ async function mothershipLookup(config, ids, timeoutMs = 8e3) {
|
|
|
10335
10526
|
}
|
|
10336
10527
|
}
|
|
10337
10528
|
async function runSync(store) {
|
|
10338
|
-
const lock =
|
|
10529
|
+
const lock = path23.join(store.root, "sync.lock");
|
|
10339
10530
|
const deadline = Date.now() + 12e4;
|
|
10340
10531
|
for (; ; ) {
|
|
10341
10532
|
try {
|
|
10342
|
-
|
|
10533
|
+
fs27.writeFileSync(lock, String(process.pid), { flag: "wx", mode: 384 });
|
|
10343
10534
|
break;
|
|
10344
10535
|
} catch (error) {
|
|
10345
10536
|
if (error.code !== "EEXIST") throw error;
|
|
10346
10537
|
try {
|
|
10347
|
-
const owner = Number(
|
|
10538
|
+
const owner = Number(fs27.readFileSync(lock, "utf8"));
|
|
10348
10539
|
if (Number.isInteger(owner) && owner > 0) {
|
|
10349
10540
|
try {
|
|
10350
10541
|
process.kill(owner, 0);
|
|
10351
10542
|
} catch (error2) {
|
|
10352
10543
|
if (error2.code === "ESRCH") {
|
|
10353
|
-
|
|
10544
|
+
fs27.unlinkSync(lock);
|
|
10354
10545
|
continue;
|
|
10355
10546
|
}
|
|
10356
10547
|
}
|
|
@@ -10369,7 +10560,7 @@ async function runSync(store) {
|
|
|
10369
10560
|
return await syncStore(store);
|
|
10370
10561
|
} finally {
|
|
10371
10562
|
try {
|
|
10372
|
-
|
|
10563
|
+
fs27.unlinkSync(lock);
|
|
10373
10564
|
} catch {
|
|
10374
10565
|
}
|
|
10375
10566
|
}
|
|
@@ -10397,9 +10588,9 @@ async function syncStore(store) {
|
|
|
10397
10588
|
result.errors.push(String(e instanceof Error ? e.message : e));
|
|
10398
10589
|
}
|
|
10399
10590
|
}
|
|
10400
|
-
const acknowledgementsFile =
|
|
10591
|
+
const acknowledgementsFile = path23.join(store.root, "synced-traces.json");
|
|
10401
10592
|
const acknowledgements = readJson(acknowledgementsFile, {});
|
|
10402
|
-
const fingerprint2 = (trace) =>
|
|
10593
|
+
const fingerprint2 = (trace) => createHash9("sha256").update(JSON.stringify(trace)).digest("hex");
|
|
10403
10594
|
const traces = store.allTraces().filter((t) => acknowledgements[t.id] !== fingerprint2(t)).slice(0, 50);
|
|
10404
10595
|
for (const t of traces) {
|
|
10405
10596
|
try {
|
|
@@ -10652,11 +10843,11 @@ __export(demo_exports, {
|
|
|
10652
10843
|
runDemo: () => runDemo
|
|
10653
10844
|
});
|
|
10654
10845
|
import assert from "node:assert/strict";
|
|
10655
|
-
import
|
|
10656
|
-
import
|
|
10657
|
-
import
|
|
10846
|
+
import fs28 from "node:fs";
|
|
10847
|
+
import os6 from "node:os";
|
|
10848
|
+
import path24 from "node:path";
|
|
10658
10849
|
async function runDemo(write) {
|
|
10659
|
-
const root =
|
|
10850
|
+
const root = fs28.mkdtempSync(path24.join(os6.tmpdir(), "bunshin-demo-"));
|
|
10660
10851
|
try {
|
|
10661
10852
|
const store = Store.init(root, { ...DEMO_ENGINEER, apiUrl: "" });
|
|
10662
10853
|
const { lessons, constraint, workflow } = demoScenario();
|
|
@@ -10673,7 +10864,7 @@ Task: ${DEMO_TASK}
|
|
|
10673
10864
|
write(result.text);
|
|
10674
10865
|
write("\nPASS: Legal hold constraint and deletion workflow recalled; C-suite, other-company, and superseded lessons excluded.\n");
|
|
10675
10866
|
} finally {
|
|
10676
|
-
|
|
10867
|
+
fs28.rmSync(root, { recursive: true, force: true });
|
|
10677
10868
|
}
|
|
10678
10869
|
}
|
|
10679
10870
|
var init_demo2 = __esm({
|
|
@@ -10686,21 +10877,21 @@ var init_demo2 = __esm({
|
|
|
10686
10877
|
});
|
|
10687
10878
|
|
|
10688
10879
|
// src/v2/gitremote.ts
|
|
10689
|
-
import
|
|
10690
|
-
import
|
|
10691
|
-
import { createHash as
|
|
10880
|
+
import fs29 from "node:fs";
|
|
10881
|
+
import path25 from "node:path";
|
|
10882
|
+
import { createHash as createHash10 } from "node:crypto";
|
|
10692
10883
|
function saveGitCredential(apiUrl, apiKey) {
|
|
10693
10884
|
const file2 = gitCredentialFile();
|
|
10694
|
-
|
|
10885
|
+
fs29.mkdirSync(path25.dirname(file2), { recursive: true, mode: 448 });
|
|
10695
10886
|
let all = {};
|
|
10696
10887
|
try {
|
|
10697
|
-
all = JSON.parse(
|
|
10888
|
+
all = JSON.parse(fs29.readFileSync(file2, "utf8"));
|
|
10698
10889
|
} catch {
|
|
10699
10890
|
}
|
|
10700
10891
|
all[apiUrl.replace(/\/$/, "")] = apiKey;
|
|
10701
10892
|
const tmp = `${file2}.${process.pid}.tmp`;
|
|
10702
|
-
|
|
10703
|
-
|
|
10893
|
+
fs29.writeFileSync(tmp, JSON.stringify(all, null, 2) + "\n", { mode: 384 });
|
|
10894
|
+
fs29.renameSync(tmp, file2);
|
|
10704
10895
|
}
|
|
10705
10896
|
function resolveGitKey(apiUrl) {
|
|
10706
10897
|
const base = apiUrl.replace(/\/$/, "");
|
|
@@ -10708,20 +10899,20 @@ function resolveGitKey(apiUrl) {
|
|
|
10708
10899
|
const origin = urlOrigin(base);
|
|
10709
10900
|
if (process.env.BUNSHIN_API_KEY && origin && trustedOrigins().has(origin)) return process.env.BUNSHIN_API_KEY;
|
|
10710
10901
|
try {
|
|
10711
|
-
const all = JSON.parse(
|
|
10902
|
+
const all = JSON.parse(fs29.readFileSync(gitCredentialFile(), "utf8"));
|
|
10712
10903
|
if (all[base]) return all[base];
|
|
10713
10904
|
} catch {
|
|
10714
10905
|
}
|
|
10715
|
-
const dir2 =
|
|
10906
|
+
const dir2 = path25.join(homeDir(), ".config/bunshin/credentials");
|
|
10716
10907
|
let files = [];
|
|
10717
10908
|
try {
|
|
10718
|
-
files =
|
|
10909
|
+
files = fs29.readdirSync(dir2).filter((f) => f.endsWith(".json"));
|
|
10719
10910
|
} catch {
|
|
10720
10911
|
return void 0;
|
|
10721
10912
|
}
|
|
10722
10913
|
for (const f of files.sort()) {
|
|
10723
10914
|
try {
|
|
10724
|
-
const c = JSON.parse(
|
|
10915
|
+
const c = JSON.parse(fs29.readFileSync(path25.join(dir2, f), "utf8"));
|
|
10725
10916
|
if (c.apiKey && c.apiUrl?.replace(/\/$/, "") === base) return c.apiKey;
|
|
10726
10917
|
} catch {
|
|
10727
10918
|
}
|
|
@@ -10729,7 +10920,7 @@ function resolveGitKey(apiUrl) {
|
|
|
10729
10920
|
return void 0;
|
|
10730
10921
|
}
|
|
10731
10922
|
function refsDigest(refs) {
|
|
10732
|
-
return
|
|
10923
|
+
return createHash10("sha256").update(
|
|
10733
10924
|
[...refs].sort((a, b) => a.ref.localeCompare(b.ref)).map((r) => `${r.sha} ${r.ref}`).join("\n")
|
|
10734
10925
|
).digest("hex").slice(0, 12);
|
|
10735
10926
|
}
|
|
@@ -10742,7 +10933,7 @@ var init_gitremote = __esm({
|
|
|
10742
10933
|
ZERO_SHA = "0".repeat(40);
|
|
10743
10934
|
REMOTE_PATH = "/v1/git/repos/";
|
|
10744
10935
|
remoteUrl = (apiUrl, repo) => `bunshin::${apiUrl.replace(/\/$/, "")}${REMOTE_PATH}${repo}`;
|
|
10745
|
-
gitCredentialFile = () =>
|
|
10936
|
+
gitCredentialFile = () => path25.join(homeDir(), ".config/bunshin/git-credentials.json");
|
|
10746
10937
|
GitApiError = class extends Error {
|
|
10747
10938
|
constructor(status, message, body = null) {
|
|
10748
10939
|
super(message);
|
|
@@ -10834,8 +11025,8 @@ __export(gitrepo_exports, {
|
|
|
10834
11025
|
githubReferences: () => githubReferences,
|
|
10835
11026
|
repoFromUrl: () => repoFromUrl
|
|
10836
11027
|
});
|
|
10837
|
-
import
|
|
10838
|
-
import
|
|
11028
|
+
import fs30 from "node:fs";
|
|
11029
|
+
import path26 from "node:path";
|
|
10839
11030
|
import { spawnSync as spawnSync2 } from "node:child_process";
|
|
10840
11031
|
function git3(cwd, args, opts = {}) {
|
|
10841
11032
|
const r = spawnSync2("git", ["-C", cwd, ...args], { encoding: "utf8", stdio: opts.inherit ? ["ignore", "inherit", "inherit"] : ["ignore", "pipe", "pipe"], maxBuffer: 256 * 1024 * 1024 });
|
|
@@ -10844,9 +11035,9 @@ function git3(cwd, args, opts = {}) {
|
|
|
10844
11035
|
return res;
|
|
10845
11036
|
}
|
|
10846
11037
|
function onPath(name) {
|
|
10847
|
-
for (const dir2 of (process.env.PATH ?? "").split(
|
|
11038
|
+
for (const dir2 of (process.env.PATH ?? "").split(path26.delimiter)) {
|
|
10848
11039
|
try {
|
|
10849
|
-
|
|
11040
|
+
fs30.accessSync(path26.join(dir2, name), fs30.constants.X_OK);
|
|
10850
11041
|
return true;
|
|
10851
11042
|
} catch {
|
|
10852
11043
|
}
|
|
@@ -10930,11 +11121,11 @@ function switchOrigin(root, url, out) {
|
|
|
10930
11121
|
}
|
|
10931
11122
|
async function cmdImport(args, cwd, out, err) {
|
|
10932
11123
|
requireHelper();
|
|
10933
|
-
const root = toplevel(
|
|
11124
|
+
const root = toplevel(path26.resolve(str4(args.flags.path) ?? args._[1] ?? cwd));
|
|
10934
11125
|
if (git3(root, ["rev-parse", "--is-shallow-repository"]).out.trim() === "true") throw new Error("this clone is shallow; fetch the full history first: git fetch --unshallow");
|
|
10935
11126
|
const rs = remotes(root);
|
|
10936
11127
|
const originUrl = rs.get("origin");
|
|
10937
|
-
const name = str4(args.flags.name) ?? (originUrl && !originUrl.startsWith("bunshin::") ? repoFromUrl(originUrl) : null) ?? `${
|
|
11128
|
+
const name = str4(args.flags.name) ?? (originUrl && !originUrl.startsWith("bunshin::") ? repoFromUrl(originUrl) : null) ?? `${path26.basename(path26.dirname(root))}/${path26.basename(root)}`;
|
|
10938
11129
|
const client = await connect(args, cwd);
|
|
10939
11130
|
const url = remoteUrl(client.apiUrl, name);
|
|
10940
11131
|
const fromOrigin = !!originUrl && !originUrl.startsWith("bunshin::") && !bool3(args.flags.local);
|
|
@@ -11010,7 +11201,7 @@ ${refsToGithub.length} line${refsToGithub.length === 1 ? "" : "s"} in the reposi
|
|
|
11010
11201
|
if (refsToGithub.length > 40) out(` \u2026 and ${refsToGithub.length - 40} more (git grep for ${name})
|
|
11011
11202
|
`);
|
|
11012
11203
|
}
|
|
11013
|
-
if (
|
|
11204
|
+
if (fs30.existsSync(path26.join(root, ".github"))) out(`
|
|
11014
11205
|
Note: .github/ (Actions, CODEOWNERS, templates) only works on GitHub; Bunshin does not run it.
|
|
11015
11206
|
`);
|
|
11016
11207
|
out(`
|
|
@@ -11021,7 +11212,7 @@ New machines clone with: bunshin repo clone ${name}
|
|
|
11021
11212
|
}
|
|
11022
11213
|
async function cmdAttach(args, cwd, out, err) {
|
|
11023
11214
|
requireHelper();
|
|
11024
|
-
const root = toplevel(
|
|
11215
|
+
const root = toplevel(path26.resolve(str4(args.flags.path) ?? cwd));
|
|
11025
11216
|
const rs = remotes(root);
|
|
11026
11217
|
const originUrl = rs.get("origin");
|
|
11027
11218
|
const name = str4(args.flags.name) ?? args._[1] ?? (originUrl ? repoFromUrl(originUrl) : null);
|
|
@@ -11069,12 +11260,12 @@ async function cmdClone(args, cwd, out) {
|
|
|
11069
11260
|
const dir2 = args._[2] ?? name.split("/")[1];
|
|
11070
11261
|
const r = spawnSync2("git", ["clone", remoteUrl(client.apiUrl, name), dir2], { cwd, stdio: "inherit" });
|
|
11071
11262
|
if (r.status !== 0) return r.status ?? 1;
|
|
11072
|
-
out(`Cloned ${name} into ${
|
|
11263
|
+
out(`Cloned ${name} into ${path26.resolve(cwd, dir2)}
|
|
11073
11264
|
`);
|
|
11074
11265
|
return 0;
|
|
11075
11266
|
}
|
|
11076
11267
|
async function cmdVerify(args, cwd, out, err) {
|
|
11077
|
-
const root = toplevel(
|
|
11268
|
+
const root = toplevel(path26.resolve(str4(args.flags.path) ?? cwd));
|
|
11078
11269
|
const rs = remotes(root);
|
|
11079
11270
|
const originUrl = rs.get("origin") ?? "";
|
|
11080
11271
|
if (!originUrl.startsWith("bunshin::")) throw new Error("origin is not a Bunshin repository (run bunshin repo attach)");
|
|
@@ -11237,28 +11428,28 @@ __export(runner_exports, {
|
|
|
11237
11428
|
setupText: () => setupText
|
|
11238
11429
|
});
|
|
11239
11430
|
import { spawnSync as spawnSync3 } from "node:child_process";
|
|
11240
|
-
import
|
|
11241
|
-
import
|
|
11242
|
-
import
|
|
11243
|
-
function runnerHome(home = process.env.BUNSHIN_RUNNER_HOME ||
|
|
11244
|
-
return
|
|
11431
|
+
import fs31 from "node:fs";
|
|
11432
|
+
import os7 from "node:os";
|
|
11433
|
+
import path27 from "node:path";
|
|
11434
|
+
function runnerHome(home = process.env.BUNSHIN_RUNNER_HOME || os7.homedir()) {
|
|
11435
|
+
return path27.join(home, ".bunshin", "runner");
|
|
11245
11436
|
}
|
|
11246
11437
|
function readInstalled(home) {
|
|
11247
11438
|
try {
|
|
11248
|
-
return JSON.parse(
|
|
11439
|
+
return JSON.parse(fs31.readFileSync(path27.join(runnerHome(home), "config.json"), "utf8"));
|
|
11249
11440
|
} catch {
|
|
11250
11441
|
return null;
|
|
11251
11442
|
}
|
|
11252
11443
|
}
|
|
11253
11444
|
function connection(args, cwd) {
|
|
11254
11445
|
const saved = readInstalled();
|
|
11255
|
-
const store = saved &&
|
|
11446
|
+
const store = saved && path27.resolve(cwd).startsWith(runnerHome()) ? null : Store.discover(cwd);
|
|
11256
11447
|
const config = store?.config();
|
|
11257
11448
|
const key = str5(args.flags.key) || process.env.BUNSHIN_RUNNER_KEY || process.env.BUNSHIN_API_KEY || config?.apiKey || saved?.key || "";
|
|
11258
11449
|
const apiUrl = (str5(args.flags["api-url"]) || process.env.BUNSHIN_API_URL || config?.apiUrl || saved?.apiUrl || DEFAULT_API).replace(/\/$/, "");
|
|
11259
11450
|
if (!key) throw new Error("no key: set BUNSHIN_RUNNER_KEY (create a runner key in the console: Runners \u2192 New runner key) or run inside a connected project");
|
|
11260
11451
|
if (!secureUrl(apiUrl)) throw new Error(`refusing ${apiUrl}: the runner's key travels only over https (http only on localhost)`);
|
|
11261
|
-
const name = str5(args.flags.name) ?? process.env.BUNSHIN_RUNNER_NAME ?? saved?.name ?? `${
|
|
11452
|
+
const name = str5(args.flags.name) ?? process.env.BUNSHIN_RUNNER_NAME ?? saved?.name ?? `${os7.hostname().split(".")[0] || "runner"}`;
|
|
11262
11453
|
return { apiUrl, key, name: name.replace(/[^\w.:@/-]/g, "-").slice(0, 80) };
|
|
11263
11454
|
}
|
|
11264
11455
|
async function call(c, method, route, body, timeoutMs = 6e4) {
|
|
@@ -11312,9 +11503,9 @@ async function runOnce(c, args, out, err) {
|
|
|
11312
11503
|
const [job] = await lease(c, args);
|
|
11313
11504
|
if (!job) break;
|
|
11314
11505
|
const started = Date.now();
|
|
11315
|
-
const scratch =
|
|
11506
|
+
const scratch = fs31.mkdtempSync(path27.join(os7.tmpdir(), "bunshin-job-"));
|
|
11316
11507
|
const res = await askJson(config, { system: job.system, user: job.prompt, schema: job.schema, enforceSchema: false, timeoutMs: 15 * 6e4, maxTokens: 16e3, cwd: scratch }).finally(
|
|
11317
|
-
() =>
|
|
11508
|
+
() => fs31.rmSync(scratch, { recursive: true, force: true })
|
|
11318
11509
|
);
|
|
11319
11510
|
const model = config.backend === "codex-cli" ? config.codexModel ?? "codex default" : config.backend === "pi-cli" ? config.piModel ?? "pi default" : config.model;
|
|
11320
11511
|
if (!res.ok) {
|
|
@@ -11404,24 +11595,24 @@ function renderCheck(id, c) {
|
|
|
11404
11595
|
}
|
|
11405
11596
|
function logAnswer(entry) {
|
|
11406
11597
|
try {
|
|
11407
|
-
|
|
11408
|
-
|
|
11598
|
+
fs31.mkdirSync(runnerHome(), { recursive: true });
|
|
11599
|
+
fs31.appendFileSync(path27.join(runnerHome(), "log.jsonl"), `${JSON.stringify({ at: (/* @__PURE__ */ new Date()).toISOString(), ...entry })}
|
|
11409
11600
|
`);
|
|
11410
11601
|
} catch {
|
|
11411
11602
|
}
|
|
11412
11603
|
}
|
|
11413
11604
|
function which(name) {
|
|
11414
|
-
for (const d of [...(process.env.PATH || "").split(
|
|
11415
|
-
if (d &&
|
|
11605
|
+
for (const d of [...(process.env.PATH || "").split(path27.delimiter), path27.join(os7.homedir(), ".local", "bin")]) {
|
|
11606
|
+
if (d && fs31.existsSync(path27.join(d, name))) return path27.join(d, name);
|
|
11416
11607
|
}
|
|
11417
11608
|
return null;
|
|
11418
11609
|
}
|
|
11419
11610
|
function scheduledCommand(backend) {
|
|
11420
|
-
const node =
|
|
11421
|
-
const npx =
|
|
11611
|
+
const node = path27.dirname(process.execPath);
|
|
11612
|
+
const npx = fs31.existsSync(path27.join(node, "npx")) ? path27.join(node, "npx") : which("npx") ?? "npx";
|
|
11422
11613
|
const bin = BIN_OF[backend] ? which(BIN_OF[backend]) : null;
|
|
11423
|
-
const dirs = [.../* @__PURE__ */ new Set([node, ...bin ? [
|
|
11424
|
-
return { argv: [npx, "-y", PKG2, "runner", "--once"], path: dirs.join(
|
|
11614
|
+
const dirs = [.../* @__PURE__ */ new Set([node, ...bin ? [path27.dirname(bin)] : [], path27.join(os7.homedir(), ".local", "bin"), "/opt/homebrew/bin", "/usr/local/bin", "/usr/bin", "/bin", "/usr/sbin", "/sbin"])];
|
|
11615
|
+
return { argv: [npx, "-y", PKG2, "runner", "--once"], path: dirs.join(path27.delimiter) };
|
|
11425
11616
|
}
|
|
11426
11617
|
function launchdPlist(backend, everyMinutes, home = runnerHome()) {
|
|
11427
11618
|
const cmd = scheduledCommand(backend);
|
|
@@ -11436,8 +11627,8 @@ function launchdPlist(backend, everyMinutes, home = runnerHome()) {
|
|
|
11436
11627
|
<dict><key>PATH</key><string>${xml(cmd.path)}</string></dict>
|
|
11437
11628
|
<key>WorkingDirectory</key><string>${xml(home)}</string>
|
|
11438
11629
|
<key>StartInterval</key><integer>${everyMinutes * 60}</integer>
|
|
11439
|
-
<key>StandardOutPath</key><string>${xml(
|
|
11440
|
-
<key>StandardErrorPath</key><string>${xml(
|
|
11630
|
+
<key>StandardOutPath</key><string>${xml(path27.join(home, "runner.log"))}</string>
|
|
11631
|
+
<key>StandardErrorPath</key><string>${xml(path27.join(home, "runner.log"))}</string>
|
|
11441
11632
|
<key>ProcessType</key><string>Background</string>
|
|
11442
11633
|
<key>LowPriorityIO</key><true/>
|
|
11443
11634
|
</dict>
|
|
@@ -11448,19 +11639,19 @@ function cronLine(backend, everyMinutes, home = runnerHome()) {
|
|
|
11448
11639
|
const cmd = scheduledCommand(backend);
|
|
11449
11640
|
const when = everyMinutes >= 60 ? `17 */${Math.max(1, Math.round(everyMinutes / 60))} * * *` : `*/${everyMinutes} * * * *`;
|
|
11450
11641
|
const q = (v) => `'${v.replace(/'/g, `'\\''`)}'`;
|
|
11451
|
-
return `${when} cd ${q(home)} && PATH=${q(cmd.path)} ${cmd.argv.map(q).join(" ")} >> ${q(
|
|
11642
|
+
return `${when} cd ${q(home)} && PATH=${q(cmd.path)} ${cmd.argv.map(q).join(" ")} >> ${q(path27.join(home, "runner.log"))} 2>&1 ${CRON_MARK}`;
|
|
11452
11643
|
}
|
|
11453
11644
|
function launchAgentsDir(opts) {
|
|
11454
|
-
return opts.launchAgents ??
|
|
11645
|
+
return opts.launchAgents ?? path27.join(process.env.BUNSHIN_RUNNER_HOME || os7.homedir(), "Library", "LaunchAgents");
|
|
11455
11646
|
}
|
|
11456
11647
|
function installSchedule(backend, everyMinutes, opts = {}) {
|
|
11457
11648
|
const platform = opts.platform ?? process.platform;
|
|
11458
11649
|
const run2 = opts.run ?? realRun;
|
|
11459
11650
|
if (platform === "darwin") {
|
|
11460
11651
|
const dir2 = launchAgentsDir(opts);
|
|
11461
|
-
const plist =
|
|
11462
|
-
|
|
11463
|
-
|
|
11652
|
+
const plist = path27.join(dir2, `${LAUNCHD_LABEL}.plist`);
|
|
11653
|
+
fs31.mkdirSync(dir2, { recursive: true });
|
|
11654
|
+
fs31.writeFileSync(plist, launchdPlist(backend, everyMinutes));
|
|
11464
11655
|
const domain = `gui/${process.getuid?.() ?? 501}`;
|
|
11465
11656
|
run2("launchctl", ["bootout", `${domain}/${LAUNCHD_LABEL}`]);
|
|
11466
11657
|
const r = run2("launchctl", ["bootstrap", domain, plist]);
|
|
@@ -11480,10 +11671,10 @@ function removeSchedule(opts = {}) {
|
|
|
11480
11671
|
const platform = opts.platform ?? process.platform;
|
|
11481
11672
|
const run2 = opts.run ?? realRun;
|
|
11482
11673
|
if (platform === "darwin") {
|
|
11483
|
-
const plist =
|
|
11674
|
+
const plist = path27.join(launchAgentsDir(opts), `${LAUNCHD_LABEL}.plist`);
|
|
11484
11675
|
run2("launchctl", ["bootout", `gui/${process.getuid?.() ?? 501}/${LAUNCHD_LABEL}`]);
|
|
11485
|
-
if (!
|
|
11486
|
-
|
|
11676
|
+
if (!fs31.existsSync(plist)) return "no schedule";
|
|
11677
|
+
fs31.rmSync(plist, { force: true });
|
|
11487
11678
|
return `removed ${plist}`;
|
|
11488
11679
|
}
|
|
11489
11680
|
const current = run2("crontab", ["-l"]);
|
|
@@ -11510,10 +11701,10 @@ async function install(args, cwd, out, err, opts = {}) {
|
|
|
11510
11701
|
}
|
|
11511
11702
|
const every = Math.max(15, Number(str5(args.flags.every) ?? 60) || 60);
|
|
11512
11703
|
const home = runnerHome();
|
|
11513
|
-
|
|
11704
|
+
fs31.mkdirSync(home, { recursive: true, mode: 448 });
|
|
11514
11705
|
const saved = { apiUrl: c.apiUrl, key: c.key, backend, ...config.model && str5(args.flags.model) ? { model: config.model } : {}, name: c.name, every };
|
|
11515
|
-
|
|
11516
|
-
|
|
11706
|
+
fs31.writeFileSync(path27.join(home, "config.json"), JSON.stringify(saved, null, 2) + "\n", { mode: 384 });
|
|
11707
|
+
fs31.chmodSync(path27.join(home, "config.json"), 384);
|
|
11517
11708
|
let schedule;
|
|
11518
11709
|
try {
|
|
11519
11710
|
schedule = installSchedule(backend, every, opts);
|
|
@@ -11526,7 +11717,7 @@ Run it yourself: npx -y ${PKG2} runner --once
|
|
|
11526
11717
|
out(`\u2713 Runner "${c.name}" answers ${c.apiUrl}'s model jobs with ${BACKEND_NAME[backend] ?? backend} on this computer.
|
|
11527
11718
|
`);
|
|
11528
11719
|
out(schedule.kind === "none" ? ` No scheduler here: run \`npx -y ${PKG2} runner --once\` on a schedule yourself.
|
|
11529
|
-
` : ` Every ${every} minutes while this computer is on (${schedule.kind}). Log: ${
|
|
11720
|
+
` : ` Every ${every} minutes while this computer is on (${schedule.kind}). Log: ${path27.join(home, "runner.log")}
|
|
11530
11721
|
`);
|
|
11531
11722
|
out(` Stop: npx -y ${PKG2} runner uninstall
|
|
11532
11723
|
`);
|
|
@@ -11543,9 +11734,9 @@ Answering what waits now\u2026
|
|
|
11543
11734
|
function uninstall(out, opts = {}) {
|
|
11544
11735
|
out(`${removeSchedule(opts)}
|
|
11545
11736
|
`);
|
|
11546
|
-
const file2 =
|
|
11547
|
-
if (
|
|
11548
|
-
|
|
11737
|
+
const file2 = path27.join(runnerHome(), "config.json");
|
|
11738
|
+
if (fs31.existsSync(file2)) {
|
|
11739
|
+
fs31.rmSync(file2, { force: true });
|
|
11549
11740
|
out(`removed ${file2} (revoke the key in the console: Agent keys)
|
|
11550
11741
|
`);
|
|
11551
11742
|
}
|
|
@@ -11725,7 +11916,7 @@ async function cmdRunner(args, cwd, out, err, opts = {}) {
|
|
|
11725
11916
|
out(text2);
|
|
11726
11917
|
return 0;
|
|
11727
11918
|
}
|
|
11728
|
-
|
|
11919
|
+
fs31.writeFileSync(file2, text2, { mode: 384 });
|
|
11729
11920
|
const left = Math.round((Date.parse(job.leaseUntil) - Date.now()) / 6e4);
|
|
11730
11921
|
out(
|
|
11731
11922
|
[
|
|
@@ -11743,7 +11934,7 @@ async function cmdRunner(args, cwd, out, err, opts = {}) {
|
|
|
11743
11934
|
const id = args._[2];
|
|
11744
11935
|
const file2 = args._[3] ?? "-";
|
|
11745
11936
|
if (!id) throw new Error("usage: bunshin runner validate <job id> <file|->");
|
|
11746
|
-
const text2 = file2 === "-" ?
|
|
11937
|
+
const text2 = file2 === "-" ? fs31.readFileSync(0, "utf8") : fs31.readFileSync(file2, "utf8");
|
|
11747
11938
|
const r = await call(c, "POST", `/jobs/${id}/check`, { answer: text2, runner: c.name }, 12e4);
|
|
11748
11939
|
out(renderCheck(id, r.body));
|
|
11749
11940
|
return r.body.ok ? 0 : 1;
|
|
@@ -11752,7 +11943,7 @@ async function cmdRunner(args, cwd, out, err, opts = {}) {
|
|
|
11752
11943
|
const id = args._[2];
|
|
11753
11944
|
const file2 = args._[3] ?? "-";
|
|
11754
11945
|
if (!id) throw new Error("usage: bunshin runner submit <job id> <file|-> [--force]");
|
|
11755
|
-
const text2 = file2 === "-" ?
|
|
11946
|
+
const text2 = file2 === "-" ? fs31.readFileSync(0, "utf8") : fs31.readFileSync(file2, "utf8");
|
|
11756
11947
|
const check = await call(c, "POST", `/jobs/${id}/check`, { answer: text2, runner: c.name }, 12e4).catch(() => null);
|
|
11757
11948
|
if (check?.body && (check.status < 400 || check.body.problems)) {
|
|
11758
11949
|
out(renderCheck(id, check.body));
|
|
@@ -11776,7 +11967,7 @@ async function cmdRunner(args, cwd, out, err, opts = {}) {
|
|
|
11776
11967
|
const since = Date.parse(str5(args.flags.since) ?? "") || Date.now() - 12 * 36e5;
|
|
11777
11968
|
const entries = (() => {
|
|
11778
11969
|
try {
|
|
11779
|
-
return
|
|
11970
|
+
return fs31.readFileSync(path27.join(runnerHome(), "log.jsonl"), "utf8").split("\n").filter(Boolean).map((l) => JSON.parse(l)).filter((e) => Date.parse(e.at) >= since);
|
|
11780
11971
|
} catch {
|
|
11781
11972
|
return [];
|
|
11782
11973
|
}
|
|
@@ -11846,8 +12037,8 @@ var init_runner = __esm({
|
|
|
11846
12037
|
|
|
11847
12038
|
// src/v2/importer.ts
|
|
11848
12039
|
import { execFileSync as execFileSync7 } from "node:child_process";
|
|
11849
|
-
import
|
|
11850
|
-
import
|
|
12040
|
+
import fs32 from "node:fs";
|
|
12041
|
+
import path28 from "node:path";
|
|
11851
12042
|
function rewriteRepoPaths(text2, repoName2, pack) {
|
|
11852
12043
|
const re = new RegExp(`(?<=^|[\\s\`'"(=:])(?:~|\\$\\{?[A-Za-z_][A-Za-z0-9_]*\\}?)?(?:/[\\w.@+-]+)*/${escapeRe(repoName2)}(?=[/\\s\`'")\\]]|[.,;:](?:\\s|$)|$)`, "gm");
|
|
11853
12044
|
return text2.replace(re, `~/.bunshin/library/${pack}`);
|
|
@@ -11886,7 +12077,7 @@ function buildDocs(files, opts) {
|
|
|
11886
12077
|
const main2 = `${dir2}/SKILL.md`;
|
|
11887
12078
|
const text2 = rw(files.get(main2).content);
|
|
11888
12079
|
const fm = frontmatterDescription(text2);
|
|
11889
|
-
const name =
|
|
12080
|
+
const name = path28.posix.basename(dir2);
|
|
11890
12081
|
const bundle = {};
|
|
11891
12082
|
for (const p of all.filter((x) => x.startsWith(`${dir2}/`))) {
|
|
11892
12083
|
claimed.add(p);
|
|
@@ -11984,22 +12175,22 @@ function isGitRepo(root) {
|
|
|
11984
12175
|
function workingTreeFiles(root) {
|
|
11985
12176
|
const out = /* @__PURE__ */ new Map();
|
|
11986
12177
|
const list2 = isGitRepo(root) ? git4(root, ["ls-files", "-z"]).split("\0").filter(Boolean) : (function walk(dir2, base = "") {
|
|
11987
|
-
return
|
|
12178
|
+
return fs32.readdirSync(dir2, { withFileTypes: true }).flatMap((e) => {
|
|
11988
12179
|
if (e.name === ".git" || e.name === "node_modules") return [];
|
|
11989
12180
|
const rel = base ? `${base}/${e.name}` : e.name;
|
|
11990
|
-
return e.isDirectory() ? walk(
|
|
12181
|
+
return e.isDirectory() ? walk(path28.join(dir2, e.name), rel) : e.isFile() ? [rel] : [];
|
|
11991
12182
|
});
|
|
11992
12183
|
})(root);
|
|
11993
12184
|
for (const rel of list2) {
|
|
11994
|
-
const abs =
|
|
12185
|
+
const abs = path28.join(root, rel);
|
|
11995
12186
|
let buf;
|
|
11996
12187
|
try {
|
|
11997
|
-
buf =
|
|
12188
|
+
buf = fs32.readFileSync(abs);
|
|
11998
12189
|
} catch {
|
|
11999
12190
|
continue;
|
|
12000
12191
|
}
|
|
12001
12192
|
if (!isText(buf)) continue;
|
|
12002
|
-
const exec = (
|
|
12193
|
+
const exec = (fs32.statSync(abs).mode & 73) !== 0;
|
|
12003
12194
|
out.set(rel, { content: buf.toString("utf8"), ...exec ? { mode: "x" } : {} });
|
|
12004
12195
|
}
|
|
12005
12196
|
return out;
|
|
@@ -12033,7 +12224,7 @@ function diffDocs(prev, next) {
|
|
|
12033
12224
|
return { docs: next.filter((d) => before.get(d.path) !== fingerprint(d)), removed: [...before.keys()].filter((p) => !after.has(p)) };
|
|
12034
12225
|
}
|
|
12035
12226
|
function readSkillSystem(root, opts) {
|
|
12036
|
-
const repoName2 =
|
|
12227
|
+
const repoName2 = path28.basename(path28.resolve(root));
|
|
12037
12228
|
const build = (files2) => buildDocs(files2, { pack: opts.pack, repoName: repoName2, ...opts.rewrite === false ? { rewrite: false } : {} });
|
|
12038
12229
|
const tree = build(workingTreeFiles(root));
|
|
12039
12230
|
if (!opts.history || !isGitRepo(root)) return { versions: [{ summary: `import ${opts.pack}`, docs: tree, removed: [], complete: true }], docs: tree };
|
|
@@ -12110,7 +12301,7 @@ var init_importer = __esm({
|
|
|
12110
12301
|
escapeRe = (s) => s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
12111
12302
|
looksGenerated = (text2) => /generated by|do not edit( by hand)?/i.test(text2.slice(0, 600));
|
|
12112
12303
|
isStopHook = (text2) => /"decision"\s*:\s*"block"|decision.{0,4}block/.test(text2) && /REASON=/.test(text2);
|
|
12113
|
-
isUpdateHook = (p, text2) => /auto-?update/i.test(
|
|
12304
|
+
isUpdateHook = (p, text2) => /auto-?update/i.test(path28.basename(p)) || /git (pull|fetch)/.test(text2) && /SessionStart|session start/i.test(text2);
|
|
12114
12305
|
fingerprint = (d) => JSON.stringify(d);
|
|
12115
12306
|
REWRITE_SYSTEM = `You adapt a company's skill documents after its skill system moved into Bunshin.
|
|
12116
12307
|
|
|
@@ -12146,8 +12337,8 @@ __export(skills_exports, {
|
|
|
12146
12337
|
cmdSkill: () => cmdSkill,
|
|
12147
12338
|
parsePin: () => parsePin
|
|
12148
12339
|
});
|
|
12149
|
-
import
|
|
12150
|
-
import
|
|
12340
|
+
import fs33 from "node:fs";
|
|
12341
|
+
import path29 from "node:path";
|
|
12151
12342
|
function requireOnline(store, what) {
|
|
12152
12343
|
if (!canCall(store.config())) throw new Error(`${what} needs the hosted library: run \`bunshin setup\` first`);
|
|
12153
12344
|
}
|
|
@@ -12156,9 +12347,9 @@ async function cmdImport2(store, args, cwd, out, err) {
|
|
|
12156
12347
|
err("usage: bunshin import skills <dir> [--pack <name>] [--layer org|team:<unit>] [--owner-team <unit>] [--no-history] [--dry-run] [--propose-rewrites]\n");
|
|
12157
12348
|
return 1;
|
|
12158
12349
|
}
|
|
12159
|
-
const root =
|
|
12160
|
-
if (!
|
|
12161
|
-
const pack = str6(args.flags.pack) ??
|
|
12350
|
+
const root = path29.resolve(cwd, args._[2]);
|
|
12351
|
+
if (!fs33.existsSync(root)) throw new Error(`${root} does not exist`);
|
|
12352
|
+
const pack = str6(args.flags.pack) ?? path29.basename(root);
|
|
12162
12353
|
const history = args.flags.history !== false && !bool4(args.flags["no-history"]);
|
|
12163
12354
|
const read = readSkillSystem(root, { pack, history, ...str6(args.flags.since) ? { since: str6(args.flags.since) } : {} });
|
|
12164
12355
|
const kinds = /* @__PURE__ */ new Map();
|
|
@@ -12193,7 +12384,7 @@ async function cmdImport2(store, args, cwd, out, err) {
|
|
|
12193
12384
|
const propose = args.flags["propose-rewrites"];
|
|
12194
12385
|
if (propose) {
|
|
12195
12386
|
const only = typeof propose === "string" && propose !== "true" ? propose.split(",").map((x) => x.trim()).filter(Boolean) : [];
|
|
12196
|
-
await proposeRewrites(store, read.docs.filter((d) => !only.length || only.some((o) => d.path.includes(o))), pack,
|
|
12387
|
+
await proposeRewrites(store, read.docs.filter((d) => !only.length || only.some((o) => d.path.includes(o))), pack, path29.basename(root), out, err);
|
|
12197
12388
|
}
|
|
12198
12389
|
out("Run `bunshin sync` on each machine (it runs at session start) to install the skills, instructions and files.\n");
|
|
12199
12390
|
return 0;
|
|
@@ -12333,7 +12524,7 @@ ${report.skills} skills, ${report.references} references, ${report.errors.length
|
|
|
12333
12524
|
}
|
|
12334
12525
|
const graph = str6(args.flags.graph) ?? (bool4(args.flags.graph) ? "SKILLS-GRAPH.md" : void 0);
|
|
12335
12526
|
if (graph) {
|
|
12336
|
-
|
|
12527
|
+
fs33.writeFileSync(path29.resolve(cwd, graph), renderSkillGraph(report));
|
|
12337
12528
|
out(`graph written to ${graph}
|
|
12338
12529
|
`);
|
|
12339
12530
|
}
|
|
@@ -12403,8 +12594,8 @@ async function splitSkill(store, args, skill, name, out, err) {
|
|
|
12403
12594
|
const files = splitPaths(v2, skill.skill.name);
|
|
12404
12595
|
const sourceWords = words3(skill.body.slice(parseFrontmatter2(skill.body).bodyStart));
|
|
12405
12596
|
if (bool4(args.flags.submit)) {
|
|
12406
|
-
if (!
|
|
12407
|
-
const f2 = JSON.parse(
|
|
12597
|
+
if (!fs33.existsSync(files.json)) throw new Error(`no split of ${skill.skill.name} yet: run \`bunshin skill split ${skill.skill.name}\` first`);
|
|
12598
|
+
const f2 = JSON.parse(fs33.readFileSync(files.json, "utf8"));
|
|
12408
12599
|
if (f2.version !== skill.version) throw new Error(`${skill.skill.name} changed since the split (v${f2.version} \u2192 v${skill.version}): split it again`);
|
|
12409
12600
|
const plan2 = parseSplit(f2.plan);
|
|
12410
12601
|
if (!plan2) throw new Error(`${files.json} holds no spine`);
|
|
@@ -12415,7 +12606,7 @@ async function splitSkill(store, args, skill, name, out, err) {
|
|
|
12415
12606
|
throw new Error(`the split loses ${coverage2.missing.length} of ${coverage2.lines} lines of the skill; fix ${files.json} (or send it anyway with --force)`);
|
|
12416
12607
|
}
|
|
12417
12608
|
const made = splitSuggestions(v2, config, skill, plan2);
|
|
12418
|
-
|
|
12609
|
+
fs33.rmSync(files.json, { force: true });
|
|
12419
12610
|
if (!canCall(config)) {
|
|
12420
12611
|
out(`${made} suggestions queued (${plan2.units.length} atoms and the spine); they leave with the next sync and wait for owner review.
|
|
12421
12612
|
`);
|
|
@@ -12440,9 +12631,9 @@ async function splitSkill(store, args, skill, name, out, err) {
|
|
|
12440
12631
|
if (!plan) throw new Error("the model's answer holds no spine");
|
|
12441
12632
|
const coverage = splitCoverage(skill.body, [plan.spine, ...plan.units]);
|
|
12442
12633
|
const f = { skill: skill.id, name: skill.skill.name, version: skill.version, at: (/* @__PURE__ */ new Date()).toISOString(), plan, coverage };
|
|
12443
|
-
|
|
12444
|
-
|
|
12445
|
-
|
|
12634
|
+
fs33.mkdirSync(path29.dirname(files.json), { recursive: true });
|
|
12635
|
+
fs33.writeFileSync(files.json, JSON.stringify(f, null, 2));
|
|
12636
|
+
fs33.writeFileSync(files.md, splitPreview(f, sourceWords));
|
|
12446
12637
|
out(`spine ${words3(plan.spine.body)} words, ${plan.units.length} atoms; ${coverage.missing.length ? `NOT lossless: ${coverage.missing.length} of ${coverage.lines} lines are in no unit` : `lossless (${coverage.lines} lines)`}
|
|
12447
12638
|
`);
|
|
12448
12639
|
out(`Read ${files.md}; edit ${files.json} if needed; then send it with \`bunshin skill split ${skill.skill.name} --submit\`.
|
|
@@ -12549,9 +12740,9 @@ async function cmdLibrary(store, args, cwd, out, err) {
|
|
|
12549
12740
|
`;
|
|
12550
12741
|
const file2 = str6(args.flags.write) ?? (bool4(args.flags.write) ? ".claude/skills-version" : void 0);
|
|
12551
12742
|
if (file2) {
|
|
12552
|
-
const abs =
|
|
12553
|
-
|
|
12554
|
-
|
|
12743
|
+
const abs = path29.resolve(cwd, file2);
|
|
12744
|
+
fs33.mkdirSync(path29.dirname(abs), { recursive: true });
|
|
12745
|
+
fs33.writeFileSync(abs, line);
|
|
12555
12746
|
out(`${file2}: ${line}`);
|
|
12556
12747
|
} else out(line);
|
|
12557
12748
|
return 0;
|
|
@@ -12561,12 +12752,12 @@ async function cmdLibrary(store, args, cwd, out, err) {
|
|
|
12561
12752
|
const to = str6(args.flags.to);
|
|
12562
12753
|
if (!to) throw new Error("--to <dir> is required");
|
|
12563
12754
|
const pinFile = str6(args.flags.pin);
|
|
12564
|
-
const pin = str6(args.flags.git) ? { git: str6(args.flags.git) } : pinFile ? parsePin(
|
|
12755
|
+
const pin = str6(args.flags.git) ? { git: str6(args.flags.git) } : pinFile ? parsePin(fs33.readFileSync(path29.resolve(cwd, pinFile), "utf8")) : parsePin(args._[2] ?? "");
|
|
12565
12756
|
const q = pin.git ? `git=${pin.git}` : pin.version ? `version=${pin.version}` : "";
|
|
12566
12757
|
if (!q) throw new Error("name a version: lib@N, --git <sha>, or --pin <file>");
|
|
12567
12758
|
const snap = await v2api(config, "GET", `/library/snapshot?${q}`, void 0, { timeoutMs: 12e4 });
|
|
12568
|
-
const dir2 =
|
|
12569
|
-
if (
|
|
12759
|
+
const dir2 = path29.resolve(cwd, to);
|
|
12760
|
+
if (fs33.existsSync(dir2) && fs33.readdirSync(dir2).length && !bool4(args.flags.force)) throw new Error(`${dir2} is not empty (use --force)`);
|
|
12570
12761
|
const pack = str6(args.flags.pack);
|
|
12571
12762
|
const docs = snap.sections.filter((s) => !pack || s.pack === pack);
|
|
12572
12763
|
const res = materialize(docs, dir2);
|
|
@@ -12597,7 +12788,7 @@ var init_skills = __esm({
|
|
|
12597
12788
|
skillsOf = (sections) => sections.filter((s) => s.skill && (s.status === "active" || s.status === "stale"));
|
|
12598
12789
|
words3 = (t) => t.split(/\s+/).filter(Boolean).length;
|
|
12599
12790
|
splitPaths = (v2, name) => {
|
|
12600
|
-
const base =
|
|
12791
|
+
const base = path29.join(v2.dir, "split", name.replace(/[^\w.-]/g, "_"));
|
|
12601
12792
|
return { json: `${base}.json`, md: `${base}.md` };
|
|
12602
12793
|
};
|
|
12603
12794
|
}
|
|
@@ -12610,27 +12801,27 @@ __export(reflect_exports, {
|
|
|
12610
12801
|
buildLesson: () => buildLesson,
|
|
12611
12802
|
runReflection: () => runReflection
|
|
12612
12803
|
});
|
|
12613
|
-
import
|
|
12614
|
-
import
|
|
12615
|
-
import { createHash as
|
|
12804
|
+
import fs34 from "node:fs";
|
|
12805
|
+
import path30 from "node:path";
|
|
12806
|
+
import { createHash as createHash11 } from "node:crypto";
|
|
12616
12807
|
async function runReflection(store, opts) {
|
|
12617
12808
|
const empty = { lessonIds: [], used: [], missed: [], attribution: [] };
|
|
12618
|
-
const lock =
|
|
12809
|
+
const lock = path30.join(store.root, `reflect-${createHash11("sha256").update(opts.sessionId).digest("hex")}.lock`);
|
|
12619
12810
|
const deadline = Date.now() + 66e4;
|
|
12620
12811
|
for (; ; ) {
|
|
12621
12812
|
try {
|
|
12622
|
-
|
|
12813
|
+
fs34.writeFileSync(lock, String(process.pid), { flag: "wx", mode: 384 });
|
|
12623
12814
|
break;
|
|
12624
12815
|
} catch (error) {
|
|
12625
12816
|
if (error.code !== "EEXIST") throw error;
|
|
12626
12817
|
try {
|
|
12627
|
-
const owner = Number(
|
|
12818
|
+
const owner = Number(fs34.readFileSync(lock, "utf8"));
|
|
12628
12819
|
if (Number.isInteger(owner) && owner > 0) {
|
|
12629
12820
|
try {
|
|
12630
12821
|
process.kill(owner, 0);
|
|
12631
12822
|
} catch (error2) {
|
|
12632
12823
|
if (error2.code === "ESRCH") {
|
|
12633
|
-
|
|
12824
|
+
fs34.unlinkSync(lock);
|
|
12634
12825
|
continue;
|
|
12635
12826
|
}
|
|
12636
12827
|
}
|
|
@@ -12645,7 +12836,7 @@ async function runReflection(store, opts) {
|
|
|
12645
12836
|
return await reflectSession(store, opts);
|
|
12646
12837
|
} finally {
|
|
12647
12838
|
try {
|
|
12648
|
-
|
|
12839
|
+
fs34.unlinkSync(lock);
|
|
12649
12840
|
} catch {
|
|
12650
12841
|
}
|
|
12651
12842
|
}
|
|
@@ -12988,8 +13179,8 @@ __export(cli_exports, {
|
|
|
12988
13179
|
setupMod: () => setupMod,
|
|
12989
13180
|
version: () => version
|
|
12990
13181
|
});
|
|
12991
|
-
import
|
|
12992
|
-
import
|
|
13182
|
+
import fs35 from "node:fs";
|
|
13183
|
+
import path31 from "node:path";
|
|
12993
13184
|
function parseArgs(argv) {
|
|
12994
13185
|
const out = { _: [], flags: {} };
|
|
12995
13186
|
const valueless = /* @__PURE__ */ new Set(["json", "quiet", "force", "sync", "global", "help", "version", "dry-run", "offline", "apply", "no-hooks", "remove-hooks", "key-stdin", "debug", "verbose", "robot", "fork", "upload", "index", "all", "legacy", "depth", "local", "skip-github", "propose-rewrites", "clear", "watch", "once", "allow-codex-shell", "retrace", "across", "env"]);
|
|
@@ -13098,7 +13289,7 @@ async function main(argv, opts = {}) {
|
|
|
13098
13289
|
out(result.mcp.error ? `! bunshin MCP server not registered (${result.mcp.error}); sessions still learn and recall through the hooks.
|
|
13099
13290
|
` : "bunshin MCP server registered for this user.\n");
|
|
13100
13291
|
for (const command of [result.learnCommand, result.borrowCommand]) {
|
|
13101
|
-
if (command.error) err(`! ${
|
|
13292
|
+
if (command.error) err(`! ${path31.basename(command.file, ".md")} not installed at ${command.file}: ${command.error}
|
|
13102
13293
|
`);
|
|
13103
13294
|
}
|
|
13104
13295
|
out("No key is needed now. Give sessions BUNSHIN_API_KEY as an environment variable; a repository with no `.bunshin/` store is connected when a session starts in it.\n");
|
|
@@ -13111,15 +13302,18 @@ async function main(argv, opts = {}) {
|
|
|
13111
13302
|
}
|
|
13112
13303
|
if (cmd === "setup") {
|
|
13113
13304
|
try {
|
|
13114
|
-
const { setupProject: setupProject2, executable: executable2,
|
|
13115
|
-
const
|
|
13116
|
-
if (
|
|
13305
|
+
const { setupProject: setupProject2, executable: executable2, chooseHarness: chooseHarness2, apiAddress: apiAddress2, HOSTED_API: HOSTED_API3 } = await Promise.resolve().then(() => (init_setup(), setup_exports));
|
|
13306
|
+
const flag = str7(args.flags.harness);
|
|
13307
|
+
if (flag && flag !== "codex" && flag !== "claude-code" && flag !== "pi") throw new Error("--harness must be claude-code, codex or pi (or leave it out: setup finds your agent).");
|
|
13308
|
+
const harness = flag ? flag : await chooseHarness2(out);
|
|
13117
13309
|
const agent = harness === "claude-code" ? "claude" : harness;
|
|
13118
13310
|
if (!executable2(agent)) throw new Error(`${agent} was not found. Install and sign in to your agent, then run setup again.`);
|
|
13119
|
-
const prior = new Store(
|
|
13311
|
+
const prior = new Store(path31.join(cwd, ".bunshin"));
|
|
13120
13312
|
const existing = prior.trusted ? prior.config() : { apiUrl: "", apiKey: void 0 };
|
|
13121
13313
|
const apiUrl = str7(args.flags["api-url"]);
|
|
13122
|
-
const
|
|
13314
|
+
const address = apiAddress2(apiUrl ?? HOSTED_API3);
|
|
13315
|
+
const relogin = bool5(args.flags.login);
|
|
13316
|
+
const given = bool5(args.flags["key-stdin"]) ? await new Promise((resolve, reject) => {
|
|
13123
13317
|
let value = "";
|
|
13124
13318
|
process.stdin.setEncoding("utf8");
|
|
13125
13319
|
process.stdin.on("data", (chunk) => {
|
|
@@ -13127,7 +13321,11 @@ async function main(argv, opts = {}) {
|
|
|
13127
13321
|
});
|
|
13128
13322
|
process.stdin.on("end", () => resolve(value.trim()));
|
|
13129
13323
|
process.stdin.on("error", reject);
|
|
13130
|
-
}) : process.env.BUNSHIN_API_KEY || (!apiUrl || apiUrl === existing.apiUrl) && existing.apiKey ||
|
|
13324
|
+
}) : process.env.BUNSHIN_API_KEY || !relogin && (!apiUrl || apiUrl === existing.apiUrl) && existing.apiKey || void 0;
|
|
13325
|
+
const { readLogin: readLogin2, saveLogin: saveLogin2 } = await Promise.resolve().then(() => (init_login(), login_exports));
|
|
13326
|
+
const signedIn = given || relogin ? void 0 : readLogin2(address)?.apiKey;
|
|
13327
|
+
const fresh = given || signedIn ? void 0 : await signIn(address, harness, out);
|
|
13328
|
+
const key = given || signedIn || fresh;
|
|
13131
13329
|
const hooksFlag = str7(args.flags.hooks);
|
|
13132
13330
|
if (hooksFlag && hooksFlag !== "user" && hooksFlag !== "project") throw new Error("--hooks must be user (every session under this folder) or project (this folder only)");
|
|
13133
13331
|
const only = str7(args.flags.only);
|
|
@@ -13145,8 +13343,9 @@ async function main(argv, opts = {}) {
|
|
|
13145
13343
|
});
|
|
13146
13344
|
if (result.config.hooks === "user" && !only && !exclude && !bool5(args.flags.all) && process.stdin.isTTY && !bool5(args.flags["key-stdin"])) {
|
|
13147
13345
|
const { askSources: askSources2 } = await Promise.resolve().then(() => (init_setup(), setup_exports));
|
|
13148
|
-
await askSources2(new Store(
|
|
13346
|
+
await askSources2(new Store(path31.join(cwd, ".bunshin")), out);
|
|
13149
13347
|
}
|
|
13348
|
+
if (fresh) saveLogin2({ apiUrl: address, apiKey: key, orgId: result.profile.orgId, userId: result.profile.userId });
|
|
13150
13349
|
out(`Connected as ${result.profile.role}${result.profile.orgUnit ? ` in ${result.profile.orgUnit}` : " (company-wide)"}.
|
|
13151
13350
|
`);
|
|
13152
13351
|
out(result.config.hooks === "user" ? `Folder: ${cwd} (every session in it or below it uses this workspace)
|
|
@@ -13179,11 +13378,41 @@ Key saved privately outside the project.
|
|
|
13179
13378
|
return 1;
|
|
13180
13379
|
}
|
|
13181
13380
|
}
|
|
13381
|
+
if (cmd === "login") {
|
|
13382
|
+
try {
|
|
13383
|
+
const { apiAddress: apiAddress2, connectionProfile: connectionProfile2, HOSTED_API: HOSTED_API3 } = await Promise.resolve().then(() => (init_setup(), setup_exports));
|
|
13384
|
+
const { saveLogin: saveLogin2 } = await Promise.resolve().then(() => (init_login(), login_exports));
|
|
13385
|
+
const address = apiAddress2(str7(args.flags["api-url"]) ?? HOSTED_API3);
|
|
13386
|
+
if (bool5(args.flags["no-wait"])) {
|
|
13387
|
+
const { deviceLogin: deviceLogin2 } = await Promise.resolve().then(() => (init_login(), login_exports));
|
|
13388
|
+
await deviceLogin2({ apiUrl: address, client: `bunshin ${version()} (login)`, out, noWait: true });
|
|
13389
|
+
return 0;
|
|
13390
|
+
}
|
|
13391
|
+
const key = await signIn(address, "login", out);
|
|
13392
|
+
const profile = await connectionProfile2(address, key);
|
|
13393
|
+
const file2 = saveLogin2({ apiUrl: address, apiKey: key, orgId: profile.orgId, userId: profile.userId });
|
|
13394
|
+
out(`Signed in as ${profile.role}${profile.orgUnit ? ` in ${profile.orgUnit}` : ""}. Saved privately in ${file2}.
|
|
13395
|
+
Run bunshin setup in any project to connect it; nothing more to paste.
|
|
13396
|
+
`);
|
|
13397
|
+
return 0;
|
|
13398
|
+
} catch (error) {
|
|
13399
|
+
err(`bunshin login: ${error instanceof Error ? error.message : String(error)}
|
|
13400
|
+
`);
|
|
13401
|
+
return 1;
|
|
13402
|
+
}
|
|
13403
|
+
}
|
|
13404
|
+
if (cmd === "logout") {
|
|
13405
|
+
const { apiAddress: apiAddress2, HOSTED_API: HOSTED_API3 } = await Promise.resolve().then(() => (init_setup(), setup_exports));
|
|
13406
|
+
const { forgetLogin: forgetLogin2 } = await Promise.resolve().then(() => (init_login(), login_exports));
|
|
13407
|
+
const forgot = forgetLogin2(apiAddress2(str7(args.flags["api-url"]) ?? HOSTED_API3));
|
|
13408
|
+
out(forgot ? "This computer's sign-in is removed: new projects will ask for approval again. Projects already connected keep their own key; revoke it in the console (Agent keys) to cut them off.\n" : "This computer was not signed in.\n");
|
|
13409
|
+
return 0;
|
|
13410
|
+
}
|
|
13182
13411
|
if (cmd === "init") return cmdInit(args, cwd, out, err);
|
|
13183
13412
|
if (cmd === "mcp") {
|
|
13184
13413
|
const { runMcpServer: runMcpServer2 } = await Promise.resolve().then(() => (init_mcp(), mcp_exports));
|
|
13185
13414
|
const root = str7(args.flags.root);
|
|
13186
|
-
await runMcpServer2({ cwd, ...root ? { store: new Store(
|
|
13415
|
+
await runMcpServer2({ cwd, ...root ? { store: new Store(path31.resolve(root)) } : {}, version: version() });
|
|
13187
13416
|
return 0;
|
|
13188
13417
|
}
|
|
13189
13418
|
if (cmd === "demo") {
|
|
@@ -13297,7 +13526,7 @@ ${HELP2}`);
|
|
|
13297
13526
|
function openStore(args, cwd) {
|
|
13298
13527
|
const root = str7(args.flags.root);
|
|
13299
13528
|
if (root) {
|
|
13300
|
-
const store = new Store(
|
|
13529
|
+
const store = new Store(path31.resolve(root));
|
|
13301
13530
|
store.ensureLayout();
|
|
13302
13531
|
return store;
|
|
13303
13532
|
}
|
|
@@ -13313,7 +13542,7 @@ async function cmdInit(args, cwd, out, err) {
|
|
|
13313
13542
|
orgId: str7(args.flags["org-id"]),
|
|
13314
13543
|
userId: str7(args.flags["user-id"]),
|
|
13315
13544
|
apiUrl: str7(args.flags["api-url"]),
|
|
13316
|
-
apiKey: bool5(args.flags["key-stdin"]) ?
|
|
13545
|
+
apiKey: bool5(args.flags["key-stdin"]) ? fs35.readFileSync(0, "utf8").trim() || void 0 : str7(args.flags["api-key"]),
|
|
13317
13546
|
scope: bool5(args.flags.global) ? "global" : str7(args.flags.scope),
|
|
13318
13547
|
harness,
|
|
13319
13548
|
noHooks: args.flags.hooks === false || bool5(args.flags["no-hooks"]),
|
|
@@ -13356,10 +13585,10 @@ function cmdStatus(store, args, out, v2) {
|
|
|
13356
13585
|
const conflicts = store.listConflicts().filter((c) => c.status === "open");
|
|
13357
13586
|
const metrics = store.readMetrics(void 0);
|
|
13358
13587
|
const last50 = metrics?.windows?.find((w) => w.name === "last50");
|
|
13359
|
-
const hookFiles = config.harness === "codex" ? [.../* @__PURE__ */ new Set([
|
|
13588
|
+
const hookFiles = config.harness === "codex" ? [.../* @__PURE__ */ new Set([path31.join(process.env.CODEX_HOME ?? path31.join(homeDir(), ".codex"), "hooks.json"), codexProjectHooks(path31.dirname(store.root)).file])] : config.harness === "claude-code" ? [path31.join(homeDir(), ".claude", "settings.json"), path31.join(path31.dirname(store.root), ".claude", "settings.local.json")] : config.harness === "pi" ? [path31.join(homeDir(), ".pi/agent/extensions/bunshin.js"), path31.join(path31.dirname(store.root), ".pi/extensions/bunshin.js")] : [];
|
|
13360
13589
|
const hooks = config.harness === "pi" ? hookFiles.filter((file2) => {
|
|
13361
13590
|
try {
|
|
13362
|
-
return
|
|
13591
|
+
return fs35.readFileSync(file2, "utf8").startsWith("// Managed by Bunshin setup.");
|
|
13363
13592
|
} catch {
|
|
13364
13593
|
return false;
|
|
13365
13594
|
}
|
|
@@ -13378,7 +13607,7 @@ function cmdStatus(store, args, out, v2) {
|
|
|
13378
13607
|
llmBackend: resolveBackend(config) ?? "none (set ANTHROPIC_API_KEY or install the claude/codex CLI)",
|
|
13379
13608
|
recallRouter: recallRouter(config),
|
|
13380
13609
|
hooks: { [config.harness]: hooks },
|
|
13381
|
-
hookFiles: hookFiles.filter((file2) =>
|
|
13610
|
+
hookFiles: hookFiles.filter((file2) => fs35.existsSync(file2)),
|
|
13382
13611
|
recallQuality: last50 ? { precision: last50.precision, recall: last50.recall, f1: last50.f1, traces: last50.traces } : null,
|
|
13383
13612
|
v2
|
|
13384
13613
|
};
|
|
@@ -13431,7 +13660,7 @@ function cmdStatus(store, args, out, v2) {
|
|
|
13431
13660
|
}
|
|
13432
13661
|
function hookCount(file2) {
|
|
13433
13662
|
try {
|
|
13434
|
-
const raw = JSON.parse(
|
|
13663
|
+
const raw = JSON.parse(fs35.readFileSync(file2, "utf8"));
|
|
13435
13664
|
let n = 0;
|
|
13436
13665
|
for (const groups of Object.values(raw.hooks ?? {})) {
|
|
13437
13666
|
for (const g of groups ?? []) {
|
|
@@ -13551,7 +13780,7 @@ function cmdLessonAdd(store, args, out, err) {
|
|
|
13551
13780
|
let content = str7(args.flags.content) ?? "";
|
|
13552
13781
|
if (!content || content === "-" || args._.includes("-")) {
|
|
13553
13782
|
try {
|
|
13554
|
-
content =
|
|
13783
|
+
content = fs35.readFileSync(0, "utf8");
|
|
13555
13784
|
} catch {
|
|
13556
13785
|
}
|
|
13557
13786
|
}
|
|
@@ -13617,7 +13846,7 @@ async function cmdReflect(store, args, cwd, out, err) {
|
|
|
13617
13846
|
}
|
|
13618
13847
|
const { runReflection: runReflection2 } = await Promise.resolve().then(() => (init_reflect4(), reflect_exports));
|
|
13619
13848
|
const result = await runReflection2(store, {
|
|
13620
|
-
sessionId: str7(args.flags.session) ??
|
|
13849
|
+
sessionId: str7(args.flags.session) ?? path31.basename(transcript).replace(/\.jsonl?$/, ""),
|
|
13621
13850
|
transcriptPath: transcript,
|
|
13622
13851
|
cwd,
|
|
13623
13852
|
force: bool5(args.flags.force)
|
|
@@ -13720,6 +13949,20 @@ async function cmdConflict(store, args, out, err) {
|
|
|
13720
13949
|
}
|
|
13721
13950
|
return 0;
|
|
13722
13951
|
}
|
|
13952
|
+
async function signIn(apiUrl, harness, out) {
|
|
13953
|
+
const { deviceLogin: deviceLogin2, DeviceLoginUnavailable: DeviceLoginUnavailable2 } = await Promise.resolve().then(() => (init_login(), login_exports));
|
|
13954
|
+
try {
|
|
13955
|
+
const r = await deviceLogin2({ apiUrl, client: `bunshin ${version()} (${harness})`, out });
|
|
13956
|
+
if (!r) throw new Error("The computer was not approved.");
|
|
13957
|
+
return r.key;
|
|
13958
|
+
} catch (error) {
|
|
13959
|
+
if (!(error instanceof DeviceLoginUnavailable2)) throw error;
|
|
13960
|
+
out(`${error.message} Paste an agent key instead (Agent keys, in the console).
|
|
13961
|
+
`);
|
|
13962
|
+
const { readKey: readKey2 } = await Promise.resolve().then(() => (init_setup(), setup_exports));
|
|
13963
|
+
return readKey2();
|
|
13964
|
+
}
|
|
13965
|
+
}
|
|
13723
13966
|
function store0HasKey(store) {
|
|
13724
13967
|
return !!store.config().apiKey;
|
|
13725
13968
|
}
|
|
@@ -13732,8 +13975,8 @@ async function setupMod(config) {
|
|
|
13732
13975
|
if (installedModVersion2() === v) return `Bunshin UI: bunshin-ui ${v} is installed (a band above the prompt, /bunshin).
|
|
13733
13976
|
`;
|
|
13734
13977
|
try {
|
|
13735
|
-
|
|
13736
|
-
|
|
13978
|
+
fs35.mkdirSync(modHome2(), { recursive: true });
|
|
13979
|
+
fs35.writeFileSync(path31.join(modHome2(), `.attempted-${v}`), nowIso());
|
|
13737
13980
|
const res = installMod2(v);
|
|
13738
13981
|
if (res.steps.some((st) => st.ok && /plugin (install|update)/.test(st.command))) {
|
|
13739
13982
|
return `Bunshin UI: bunshin-ui ${v} installed (a band above the prompt, /bunshin). It needs Claude Code mods on your account.
|
|
@@ -13763,9 +14006,13 @@ var init_cli = __esm({
|
|
|
13763
14006
|
|
|
13764
14007
|
Usage: bunshin <command> [options]
|
|
13765
14008
|
|
|
13766
|
-
setup
|
|
13767
|
-
|
|
13768
|
-
|
|
14009
|
+
setup connect this project: finds your agent (Claude Code, Codex or Pi),
|
|
14010
|
+
and the first time on this computer opens the console to approve
|
|
14011
|
+
it (no key to copy); later projects connect without asking
|
|
14012
|
+
--harness codex|claude-code|pi pick the agent when several are installed
|
|
14013
|
+
--login approve again (another workspace: select it in the console first)
|
|
14014
|
+
--api-url <url> --no-hooks a self-hosted workspace; hooks off
|
|
14015
|
+
--key-stdin read an agent key from stdin (for automated setup)
|
|
13769
14016
|
--hooks user a folder of projects: hooks in your user settings, so every
|
|
13770
14017
|
session under this folder uses its workspace (default: project)
|
|
13771
14018
|
--only a,b | --exclude c | --all
|
|
@@ -13777,6 +14024,9 @@ Usage: bunshin <command> [options]
|
|
|
13777
14024
|
setup --robot --robot-id <id> --arm so101 --gripper <g> --mount <m> --cameras scene,wrist
|
|
13778
14025
|
--domain <d> --site <s> --cell <c> [--depth] [--api-url <url>] [--harness claude-code]
|
|
13779
14026
|
register this machine as a robot context (x-bunshin-context)
|
|
14027
|
+
login [--api-url <url>] approve this computer in the browser once; setup then needs no key
|
|
14028
|
+
--no-wait print the link and return (an agent running setup); setup then waits
|
|
14029
|
+
logout forget this computer's sign-in (revoke keys under Agent keys)
|
|
13780
14030
|
init create a local store and configure the selected harness
|
|
13781
14031
|
--role <r> --org-unit <u> --org-id <id> --user-id <id>
|
|
13782
14032
|
--api-url <url> --api-key <key> (or --key-stdin) --scope repo|global (--global)
|
|
@@ -13853,7 +14103,7 @@ Global: --root <dir> (use this .bunshin store) --version --help
|
|
|
13853
14103
|
Env: BUNSHIN_API_KEY, BUNSHIN_API_URL (setup --env), BUNSHIN_HARNESS, BUNSHIN_DISABLE, BUNSHIN_CHILD, BUNSHIN_CLAUDE_BIN,
|
|
13854
14104
|
CLAUDE_CODE_SESSION_ID (learn / mcp session), ANTHROPIC_API_KEY (non-fork reflection)
|
|
13855
14105
|
`;
|
|
13856
|
-
untrustedNote = (root) => `${root} was not created by you (e.g. it is committed to the repository), so Bunshin ignores it. If it is yours, run \`bunshin setup\` (or \`bunshin init\`) in ${
|
|
14106
|
+
untrustedNote = (root) => `${root} was not created by you (e.g. it is committed to the repository), so Bunshin ignores it. If it is yours, run \`bunshin setup\` (or \`bunshin init\`) in ${path31.dirname(root)} to trust it.`;
|
|
13857
14107
|
}
|
|
13858
14108
|
});
|
|
13859
14109
|
|