@bunshin-cc/bunshin 0.12.1 → 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.
Files changed (3) hide show
  1. package/README.md +7 -6
  2. package/dist/bin.js +490 -180
  3. package/package.json +1 -1
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 path31 = scopePath(scope?.tree, scope?.source);
1211
- if (!path31.length) return layers;
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, ...path31] : [...layers.slice(0, i), ...path31, ...layers.slice(i)];
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 path31 = reader.layers.filter((l) => {
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 * ((path31.indexOf(section.layer) + 1) / path31.length);
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, path31, anchor = "") {
1465
- return anchor ? `repo:${repo}/${path31}#${anchor}` : `repo:${repo}/${path31}`;
1464
+ function repoSectionId(repo, path32, anchor = "") {
1465
+ return anchor ? `repo:${repo}/${path32}#${anchor}` : `repo:${repo}/${path32}`;
1466
1466
  }
1467
- function docKind(path31) {
1468
- const base = path31.split("/").pop()?.toLowerCase() ?? "";
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(path31) {
1474
- const dir2 = path31.split("/").slice(0, -1).join("/");
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, path31) => {
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([...path31.slice(path31.indexOf(d)), d].join(" -> "));
1623
- else if (!state.get(d)) dfs(d, [...path31, 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(path31, symbol) {
1711
- return `harness:${path31}#${symbol}`;
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(path31) {
1838
- return path31.replace(/\\/g, "/").split("/").filter((s) => s !== "" && s !== ".").join("/");
1837
+ function normalPath(path32) {
1838
+ return path32.replace(/\\/g, "/").split("/").filter((s) => s !== "" && s !== ".").join("/");
1839
1839
  }
1840
- function matchesGlob(path31, glob) {
1841
- return globToRegExp(glob.replace(/^\.\//, "")).test(normalPath(path31));
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 path31 = paths.find((p) => t.paths.some((g) => matchesGlob(p, g)));
1933
- const entity = path31 ? void 0 : t.entities.find((e) => entities.has(e) || text2 && text2.includes(e));
1934
- const skill = path31 || entity ? void 0 : skills.find((k) => t.skills.includes(k));
1935
- const trigger = path31 ? `path:${path31}` : entity ? `entity:${entity}` : skill ? `skill:${skill}` : "";
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;
@@ -2406,7 +2406,7 @@ anchor "${GUIDELINES_ANCHOR}", one general rule in the imperative, with the reas
2406
2406
 
2407
2407
  ${rules}${route}`;
2408
2408
  }
2409
- var GUIDELINES_ANCHOR, generality;
2409
+ var GUIDELINES_ID, GUIDELINES_ANCHOR, generality;
2410
2410
  var init_guidelines = __esm({
2411
2411
  "../core/src/v2/guidelines.ts"() {
2412
2412
  "use strict";
@@ -2414,6 +2414,7 @@ var init_guidelines = __esm({
2414
2414
  init_layers();
2415
2415
  init_engine();
2416
2416
  init_scopes();
2417
+ GUIDELINES_ID = "reflection:guidelines";
2417
2418
  GUIDELINES_ANCHOR = "rules";
2418
2419
  generality = (l) => ({ org: 0, group: 1, source: 2, robot: 3, user: 3 })[layerKind(l)] ?? 4;
2419
2420
  }
@@ -3146,6 +3147,30 @@ learned about the code or the company), at most 6, most important first: name ea
3146
3147
  say whether it became a lesson or was skipped, and why in one sentence. People read this to see
3147
3148
  what reflection noticed and to steer it; list them even when nothing is new.`;
3148
3149
  }
3150
+ function runSection(r) {
3151
+ const list2 = (xs) => xs.length ? xs.map((x) => `- ${x}`).join("\n") : "- (none)";
3152
+ return `
3153
+ The feedback is about one earlier reflection run on this session (${r.at}${r.turns ? `, turns ${r.turns.from + 1}\u2013${r.turns.to}` : ""}). This is what it did:
3154
+
3155
+ What it considered:
3156
+ ${list2(r.considered.map((c) => `${c.decision === "lesson" ? "took as a lesson" : "skipped"}: ${c.moment} (${c.why})`))}
3157
+
3158
+ What it kept:
3159
+ ${list2(r.kept)}
3160
+ ${r.dropped.length ? `
3161
+ What it proposed that was refused:
3162
+ ${list2(r.dropped.map((d) => `${d.summary} (${d.reason})`))}
3163
+ ` : ""}${r.nothingNew ? "\nIt answered that the turns taught nothing new.\n" : ""}
3164
+ That run did not take what the person expected. Before proposing anything, work out from the
3165
+ above why it missed it: it never noticed the moment (not in what it considered), it noticed and
3166
+ skipped it (on what reasoning), or it took a weaker or wrong lesson. Then propose:
3167
+ 1. the lesson it should have taken, written as the guidelines ask; and
3168
+ 2. a rule for the reflection guidelines (op "append" to ${GUIDELINES_ID}, anchor "rules") that would
3169
+ make a future reflection take that kind of lesson: general, about how to reflect, never about
3170
+ this session's topic, and not a repeat of a rule already there.
3171
+ In "considered", say why that run missed it, in one sentence.
3172
+ `;
3173
+ }
3149
3174
  function feedbackSection(f) {
3150
3175
  return `
3151
3176
  ## Feedback from the person (human steering)
@@ -3162,6 +3187,7 @@ The lesson it is about:
3162
3187
  ${f.lesson.trim()}
3163
3188
  </lesson>
3164
3189
  ` : ""}
3190
+ ${f.run ? runSection(f.run) : ""}
3165
3191
  Treat it as a correction from a person (signal "steering"): the strongest evidence there is. Act on it:
3166
3192
  - If it says the session taught something that was missed, capture that lesson in the right
3167
3193
  document, written as the guidelines below ask. ${f.transcript ? "Find it in the session below." : "The session's trace is no longer available: work from the feedback itself (the person's own account), the lessons already taken and the documents."}
@@ -6841,20 +6867,27 @@ function sessionModel(transcriptPath) {
6841
6867
  }
6842
6868
  return void 0;
6843
6869
  }
6844
- function lastLineWith(file2, needle, tail = 4 * 1024 * 1024) {
6870
+ function lastLineWith(file2, needle, chunk = 1024 * 1024) {
6871
+ let fd;
6845
6872
  try {
6846
- const fd = fs16.openSync(file2, "r");
6847
- try {
6848
- const size = fs16.fstatSync(fd).size;
6849
- const len = Math.min(size, tail);
6873
+ fd = fs16.openSync(file2, "r");
6874
+ let pos = fs16.fstatSync(fd).size;
6875
+ let carry = "";
6876
+ while (pos > 0) {
6877
+ const len = Math.min(chunk, pos);
6878
+ pos -= len;
6850
6879
  const buf = Buffer.alloc(len);
6851
- fs16.readSync(fd, buf, 0, len, size - len);
6852
- return buf.toString("utf8").split("\n").reverse().find((l) => l.includes(needle));
6853
- } finally {
6854
- fs16.closeSync(fd);
6880
+ fs16.readSync(fd, buf, 0, len, pos);
6881
+ const text2 = buf.toString("utf8") + carry;
6882
+ const lines = text2.split("\n");
6883
+ carry = pos > 0 ? lines.shift() ?? "" : "";
6884
+ for (let i = lines.length - 1; i >= 0; i--) if (lines[i].includes(needle)) return lines[i];
6855
6885
  }
6886
+ return void 0;
6856
6887
  } catch {
6857
6888
  return void 0;
6889
+ } finally {
6890
+ if (fd !== void 0) fs16.closeSync(fd);
6858
6891
  }
6859
6892
  }
6860
6893
  function sessionCostSoFar(transcriptPath) {
@@ -6868,6 +6901,14 @@ function sessionCostSoFar(transcriptPath) {
6868
6901
  return void 0;
6869
6902
  }
6870
6903
  }
6904
+ function transcriptIdleMs(transcriptPath, now = Date.now()) {
6905
+ if (!transcriptPath) return void 0;
6906
+ try {
6907
+ return Math.max(0, now - fs16.statSync(transcriptPath).mtimeMs);
6908
+ } catch {
6909
+ return void 0;
6910
+ }
6911
+ }
6871
6912
  function forkOwnCost(reported, before) {
6872
6913
  if (reported === void 0) return void 0;
6873
6914
  return before === void 0 ? reported : Math.max(0, reported - before);
@@ -6895,7 +6936,7 @@ function forkDecision(records, o) {
6895
6936
  if (o.learn) return { fork: true, reason: "asked for (/learn)" };
6896
6937
  if (o.tokens <= o.limit) return { fork: true, reason: "short session" };
6897
6938
  const now = o.now ?? Date.now();
6898
- const latest = [...records].reverse().find((r) => r.mode === "faithful" && r.tokens > o.limit && now - Date.parse(r.at) < MISS_HOLD_MS);
6939
+ const latest = [...records].reverse().find((r) => r.mode === "faithful" && !r.cold && r.tokens > o.limit && now - Date.parse(r.at) < MISS_HOLD_MS);
6899
6940
  if (latest && latest.hitRate < CACHE_MISS) return { fork: false, reason: `the last fork here missed the session's cache (${Math.round(latest.hitRate * 100)}% read from cache): digest of the new turns` };
6900
6941
  return { fork: true, reason: latest ? `forks here read ${Math.round(latest.hitRate * 100)}% from the session's cache` : "first fork of a large session here" };
6901
6942
  }
@@ -6912,7 +6953,7 @@ function reflectionSummary(v2, days = 7, now = Date.now()) {
6912
6953
  read += t.usage.cacheRead ?? 0;
6913
6954
  paid += (t.usage.cacheWrite ?? 0) + (t.usage.input ?? 0);
6914
6955
  const rate = t.cache?.hitRate;
6915
- if (rate !== void 0 && rate < CACHE_MISS) misses++;
6956
+ if (rate !== void 0 && rate < CACHE_MISS && !t.cache?.cold) misses++;
6916
6957
  }
6917
6958
  const latest = [...readForkCache(v2)].reverse()[0];
6918
6959
  return { runs: traces.length, costUsd: traces.reduce((a, t) => a + (t.costUsd ?? 0), 0), forks, hitRate: read + paid > 0 ? read / (read + paid) : null, misses, mode: latest?.mode ?? null };
@@ -7050,6 +7091,18 @@ async function runReflectionV2(store, opts) {
7050
7091
  ...reflectionIndex(view, [...session.loaded, ...session.pushed, ...session.served], session.task, opts.focus, humanTurnsOf(session.transcriptPath)).filter((s) => s.id !== profile?.id)
7051
7092
  ];
7052
7093
  const harness = session.harness ?? config.harness;
7094
+ if (session.serverReflectedTurns === void 0 && canCall(config)) {
7095
+ try {
7096
+ const cur = await v2api(config, "GET", `/episodes/${encodeURIComponent(episodeId)}/cursor`, void 0, { timeoutMs: 5e3 });
7097
+ v2.updateSession(opts.sessionId, session.cwd, (s) => {
7098
+ s.serverReflectedTurns = Math.max(s.serverReflectedTurns ?? 0, typeof cur.reflectedTurns === "number" ? cur.reflectedTurns : 0);
7099
+ if (Array.isArray(cur.lessons)) s.serverLessons = cur.lessons.filter((l) => typeof l === "string").slice(0, 40);
7100
+ });
7101
+ } catch (err) {
7102
+ if (err instanceof ApiError && err.status === 404) v2.updateSession(opts.sessionId, session.cwd, (s) => void (s.serverReflectedTurns ??= 0));
7103
+ }
7104
+ Object.assign(session, v2.readSession(opts.sessionId) ?? {});
7105
+ }
7053
7106
  const facts = readFacts(session.transcriptPath);
7054
7107
  const turns = facts?.turns.length ?? 0;
7055
7108
  const from = reflectCursor(session, turns);
@@ -7071,14 +7124,21 @@ async function runReflectionV2(store, opts) {
7071
7124
  if (mode === "isolated") call2.cacheNote = guard ? "reflect.forkMode is isolated in this machine's config" : "hooks are turned off on this machine (disableAllHooks or allowManagedHooksOnly), so the guard that stops a fork acting cannot run";
7072
7125
  const model = mode === "faithful" ? sessionModel(session.transcriptPath) ?? config.model : config.model;
7073
7126
  const before = sessionCostSoFar(session.transcriptPath);
7127
+ const idleMs = transcriptIdleMs(session.transcriptPath);
7128
+ const cold = idleMs !== void 0 && idleMs > Math.max(config.reflect.cacheTtlMs, 5 * 6e4);
7074
7129
  const fork = await runClaudeFork(opts.sessionId, prompt, { cwd: session.cwd, model, mode });
7075
7130
  fork.costUsd = forkOwnCost(fork.costUsd, before);
7076
7131
  const hitRate = cacheHitRate(fork.usage);
7077
7132
  call2.cacheMode = mode;
7078
7133
  if (hitRate !== void 0) {
7079
7134
  call2.hitRate = hitRate;
7080
- recordForkCache(v2, { at: (/* @__PURE__ */ new Date()).toISOString(), sessionId: opts.sessionId, mode, tokens: sessionTokens, hitRate, ...fork.costUsd !== void 0 ? { costUsd: fork.costUsd } : {} });
7081
- if (mode === "faithful" && hitRate < CACHE_MISS && sessionTokens > limit) {
7135
+ const coldMiss = cold && hitRate < CACHE_MISS;
7136
+ if (coldMiss) {
7137
+ call2.cacheCold = true;
7138
+ call2.cacheNote = `the session's prompt cache had expired (idle ${Math.round(idleMs / 6e4)} min before this fork): not counted as a miss`;
7139
+ }
7140
+ recordForkCache(v2, { at: (/* @__PURE__ */ new Date()).toISOString(), sessionId: opts.sessionId, mode, tokens: sessionTokens, hitRate, ...fork.costUsd !== void 0 ? { costUsd: fork.costUsd } : {}, ...coldMiss ? { cold: true } : {} });
7141
+ if (mode === "faithful" && hitRate < CACHE_MISS && sessionTokens > limit && !coldMiss) {
7082
7142
  const cost = fork.costUsd !== void 0 ? ` ($${fork.costUsd.toFixed(2)})` : "";
7083
7143
  v2.log("v2-reflect-cache-miss", { session: opts.sessionId, hitRate, tokens: sessionTokens, costUsd: fork.costUsd ?? null });
7084
7144
  updateFeed(v2, opts.sessionId, (f) => addEvent(f, "warning", `reflection did not reuse this session's prompt cache${cost}: large sessions here reflect from a digest of their new turns for now`));
@@ -7208,7 +7268,7 @@ async function runReflectionV2(store, opts) {
7208
7268
  nothingNew: result.nothingNew,
7209
7269
  ...call2.usage ? { usage: call2.usage } : {},
7210
7270
  ...call2.costUsd !== void 0 ? { costUsd: call2.costUsd } : {},
7211
- ...call2.cacheNote || call2.hitRate !== void 0 ? { cache: { ...call2.cacheMode ? { mode: call2.cacheMode } : {}, ...call2.hitRate !== void 0 ? { hitRate: Math.round(call2.hitRate * 1e3) / 1e3 } : {}, ...call2.cacheNote ? { note: call2.cacheNote } : {} } } : {},
7271
+ ...call2.cacheNote || call2.hitRate !== void 0 ? { cache: { ...call2.cacheMode ? { mode: call2.cacheMode } : {}, ...call2.hitRate !== void 0 ? { hitRate: Math.round(call2.hitRate * 1e3) / 1e3 } : {}, ...call2.cacheNote ? { note: call2.cacheNote } : {}, ...call2.cacheCold ? { cold: true } : {} } } : {},
7212
7272
  durationMs: Date.now() - Date.parse(startedAt),
7213
7273
  ...result.error ? { error: result.error } : {},
7214
7274
  startedAt,
@@ -9249,13 +9309,16 @@ var init_init = __esm({
9249
9309
  // src/setup.ts
9250
9310
  var setup_exports = {};
9251
9311
  __export(setup_exports, {
9312
+ HARNESS_NAMES: () => HARNESS_NAMES,
9252
9313
  HOSTED_API: () => HOSTED_API,
9253
9314
  apiAddress: () => apiAddress,
9254
9315
  askSources: () => askSources,
9255
9316
  autoConnect: () => autoConnect,
9317
+ chooseHarness: () => chooseHarness,
9256
9318
  connectionProfile: () => connectionProfile,
9257
9319
  executable: () => executable,
9258
9320
  hookBinary: () => hookBinary,
9321
+ installedHarnesses: () => installedHarnesses,
9259
9322
  readKey: () => readKey,
9260
9323
  repositoryRoot: () => repositoryRoot,
9261
9324
  setupEnvironment: () => setupEnvironment,
@@ -9278,6 +9341,31 @@ function executable(name) {
9278
9341
  }
9279
9342
  return void 0;
9280
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
+ }
9281
9369
  function hookBinary(harness) {
9282
9370
  const agent = executable(harness === "claude-code" ? "claude" : harness);
9283
9371
  const directories = [.../* @__PURE__ */ new Set([path19.dirname(process.execPath), path19.join(homeDir(), ".local/bin"), ...agent ? [path19.dirname(agent)] : []])];
@@ -9459,7 +9547,7 @@ async function autoConnect(cwd, env = process.env) {
9459
9547
  return { connected: false, reason: "failed", error: error instanceof Error ? error.message : String(error) };
9460
9548
  }
9461
9549
  }
9462
- var shellQuote;
9550
+ var shellQuote, HARNESS_NAMES;
9463
9551
  var init_setup = __esm({
9464
9552
  "src/setup.ts"() {
9465
9553
  "use strict";
@@ -9469,6 +9557,7 @@ var init_setup = __esm({
9469
9557
  init_util();
9470
9558
  init_trust();
9471
9559
  shellQuote = (value) => `'${value.replace(/'/g, `'"'"'`)}'`;
9560
+ HARNESS_NAMES = { "claude-code": "Claude Code", codex: "Codex", pi: "Pi" };
9472
9561
  }
9473
9562
  });
9474
9563
 
@@ -10097,6 +10186,168 @@ var init_commands = __esm({
10097
10186
  }
10098
10187
  });
10099
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
+
10100
10351
  // src/prompts.ts
10101
10352
  function renderLessonForInjection(l) {
10102
10353
  const head = `### ${l.title} \`${l.id}\` (${l.kind}${l.tags.length ? `; ${l.tags.join(", ")}` : ""})`;
@@ -10235,9 +10486,9 @@ __export(sync_exports2, {
10235
10486
  resolveConflict: () => resolveConflict,
10236
10487
  runSync: () => runSync
10237
10488
  });
10238
- import { createHash as createHash8 } from "node:crypto";
10239
- import path22 from "node:path";
10240
- import fs26 from "node:fs";
10489
+ import { createHash as createHash9 } from "node:crypto";
10490
+ import path23 from "node:path";
10491
+ import fs27 from "node:fs";
10241
10492
  async function api(config, method, route, body, timeoutMs = 1e4) {
10242
10493
  const ctrl = new AbortController();
10243
10494
  const timer = setTimeout(() => ctrl.abort(), timeoutMs);
@@ -10275,22 +10526,22 @@ async function mothershipLookup(config, ids, timeoutMs = 8e3) {
10275
10526
  }
10276
10527
  }
10277
10528
  async function runSync(store) {
10278
- const lock = path22.join(store.root, "sync.lock");
10529
+ const lock = path23.join(store.root, "sync.lock");
10279
10530
  const deadline = Date.now() + 12e4;
10280
10531
  for (; ; ) {
10281
10532
  try {
10282
- fs26.writeFileSync(lock, String(process.pid), { flag: "wx", mode: 384 });
10533
+ fs27.writeFileSync(lock, String(process.pid), { flag: "wx", mode: 384 });
10283
10534
  break;
10284
10535
  } catch (error) {
10285
10536
  if (error.code !== "EEXIST") throw error;
10286
10537
  try {
10287
- const owner = Number(fs26.readFileSync(lock, "utf8"));
10538
+ const owner = Number(fs27.readFileSync(lock, "utf8"));
10288
10539
  if (Number.isInteger(owner) && owner > 0) {
10289
10540
  try {
10290
10541
  process.kill(owner, 0);
10291
10542
  } catch (error2) {
10292
10543
  if (error2.code === "ESRCH") {
10293
- fs26.unlinkSync(lock);
10544
+ fs27.unlinkSync(lock);
10294
10545
  continue;
10295
10546
  }
10296
10547
  }
@@ -10309,7 +10560,7 @@ async function runSync(store) {
10309
10560
  return await syncStore(store);
10310
10561
  } finally {
10311
10562
  try {
10312
- fs26.unlinkSync(lock);
10563
+ fs27.unlinkSync(lock);
10313
10564
  } catch {
10314
10565
  }
10315
10566
  }
@@ -10337,9 +10588,9 @@ async function syncStore(store) {
10337
10588
  result.errors.push(String(e instanceof Error ? e.message : e));
10338
10589
  }
10339
10590
  }
10340
- const acknowledgementsFile = path22.join(store.root, "synced-traces.json");
10591
+ const acknowledgementsFile = path23.join(store.root, "synced-traces.json");
10341
10592
  const acknowledgements = readJson(acknowledgementsFile, {});
10342
- const fingerprint2 = (trace) => createHash8("sha256").update(JSON.stringify(trace)).digest("hex");
10593
+ const fingerprint2 = (trace) => createHash9("sha256").update(JSON.stringify(trace)).digest("hex");
10343
10594
  const traces = store.allTraces().filter((t) => acknowledgements[t.id] !== fingerprint2(t)).slice(0, 50);
10344
10595
  for (const t of traces) {
10345
10596
  try {
@@ -10592,11 +10843,11 @@ __export(demo_exports, {
10592
10843
  runDemo: () => runDemo
10593
10844
  });
10594
10845
  import assert from "node:assert/strict";
10595
- import fs27 from "node:fs";
10596
- import os5 from "node:os";
10597
- import path23 from "node:path";
10846
+ import fs28 from "node:fs";
10847
+ import os6 from "node:os";
10848
+ import path24 from "node:path";
10598
10849
  async function runDemo(write) {
10599
- const root = fs27.mkdtempSync(path23.join(os5.tmpdir(), "bunshin-demo-"));
10850
+ const root = fs28.mkdtempSync(path24.join(os6.tmpdir(), "bunshin-demo-"));
10600
10851
  try {
10601
10852
  const store = Store.init(root, { ...DEMO_ENGINEER, apiUrl: "" });
10602
10853
  const { lessons, constraint, workflow } = demoScenario();
@@ -10613,7 +10864,7 @@ Task: ${DEMO_TASK}
10613
10864
  write(result.text);
10614
10865
  write("\nPASS: Legal hold constraint and deletion workflow recalled; C-suite, other-company, and superseded lessons excluded.\n");
10615
10866
  } finally {
10616
- fs27.rmSync(root, { recursive: true, force: true });
10867
+ fs28.rmSync(root, { recursive: true, force: true });
10617
10868
  }
10618
10869
  }
10619
10870
  var init_demo2 = __esm({
@@ -10626,21 +10877,21 @@ var init_demo2 = __esm({
10626
10877
  });
10627
10878
 
10628
10879
  // src/v2/gitremote.ts
10629
- import fs28 from "node:fs";
10630
- import path24 from "node:path";
10631
- import { createHash as createHash9 } from "node:crypto";
10880
+ import fs29 from "node:fs";
10881
+ import path25 from "node:path";
10882
+ import { createHash as createHash10 } from "node:crypto";
10632
10883
  function saveGitCredential(apiUrl, apiKey) {
10633
10884
  const file2 = gitCredentialFile();
10634
- fs28.mkdirSync(path24.dirname(file2), { recursive: true, mode: 448 });
10885
+ fs29.mkdirSync(path25.dirname(file2), { recursive: true, mode: 448 });
10635
10886
  let all = {};
10636
10887
  try {
10637
- all = JSON.parse(fs28.readFileSync(file2, "utf8"));
10888
+ all = JSON.parse(fs29.readFileSync(file2, "utf8"));
10638
10889
  } catch {
10639
10890
  }
10640
10891
  all[apiUrl.replace(/\/$/, "")] = apiKey;
10641
10892
  const tmp = `${file2}.${process.pid}.tmp`;
10642
- fs28.writeFileSync(tmp, JSON.stringify(all, null, 2) + "\n", { mode: 384 });
10643
- fs28.renameSync(tmp, file2);
10893
+ fs29.writeFileSync(tmp, JSON.stringify(all, null, 2) + "\n", { mode: 384 });
10894
+ fs29.renameSync(tmp, file2);
10644
10895
  }
10645
10896
  function resolveGitKey(apiUrl) {
10646
10897
  const base = apiUrl.replace(/\/$/, "");
@@ -10648,20 +10899,20 @@ function resolveGitKey(apiUrl) {
10648
10899
  const origin = urlOrigin(base);
10649
10900
  if (process.env.BUNSHIN_API_KEY && origin && trustedOrigins().has(origin)) return process.env.BUNSHIN_API_KEY;
10650
10901
  try {
10651
- const all = JSON.parse(fs28.readFileSync(gitCredentialFile(), "utf8"));
10902
+ const all = JSON.parse(fs29.readFileSync(gitCredentialFile(), "utf8"));
10652
10903
  if (all[base]) return all[base];
10653
10904
  } catch {
10654
10905
  }
10655
- const dir2 = path24.join(homeDir(), ".config/bunshin/credentials");
10906
+ const dir2 = path25.join(homeDir(), ".config/bunshin/credentials");
10656
10907
  let files = [];
10657
10908
  try {
10658
- files = fs28.readdirSync(dir2).filter((f) => f.endsWith(".json"));
10909
+ files = fs29.readdirSync(dir2).filter((f) => f.endsWith(".json"));
10659
10910
  } catch {
10660
10911
  return void 0;
10661
10912
  }
10662
10913
  for (const f of files.sort()) {
10663
10914
  try {
10664
- const c = JSON.parse(fs28.readFileSync(path24.join(dir2, f), "utf8"));
10915
+ const c = JSON.parse(fs29.readFileSync(path25.join(dir2, f), "utf8"));
10665
10916
  if (c.apiKey && c.apiUrl?.replace(/\/$/, "") === base) return c.apiKey;
10666
10917
  } catch {
10667
10918
  }
@@ -10669,7 +10920,7 @@ function resolveGitKey(apiUrl) {
10669
10920
  return void 0;
10670
10921
  }
10671
10922
  function refsDigest(refs) {
10672
- return createHash9("sha256").update(
10923
+ return createHash10("sha256").update(
10673
10924
  [...refs].sort((a, b) => a.ref.localeCompare(b.ref)).map((r) => `${r.sha} ${r.ref}`).join("\n")
10674
10925
  ).digest("hex").slice(0, 12);
10675
10926
  }
@@ -10682,7 +10933,7 @@ var init_gitremote = __esm({
10682
10933
  ZERO_SHA = "0".repeat(40);
10683
10934
  REMOTE_PATH = "/v1/git/repos/";
10684
10935
  remoteUrl = (apiUrl, repo) => `bunshin::${apiUrl.replace(/\/$/, "")}${REMOTE_PATH}${repo}`;
10685
- gitCredentialFile = () => path24.join(homeDir(), ".config/bunshin/git-credentials.json");
10936
+ gitCredentialFile = () => path25.join(homeDir(), ".config/bunshin/git-credentials.json");
10686
10937
  GitApiError = class extends Error {
10687
10938
  constructor(status, message, body = null) {
10688
10939
  super(message);
@@ -10774,8 +11025,8 @@ __export(gitrepo_exports, {
10774
11025
  githubReferences: () => githubReferences,
10775
11026
  repoFromUrl: () => repoFromUrl
10776
11027
  });
10777
- import fs29 from "node:fs";
10778
- import path25 from "node:path";
11028
+ import fs30 from "node:fs";
11029
+ import path26 from "node:path";
10779
11030
  import { spawnSync as spawnSync2 } from "node:child_process";
10780
11031
  function git3(cwd, args, opts = {}) {
10781
11032
  const r = spawnSync2("git", ["-C", cwd, ...args], { encoding: "utf8", stdio: opts.inherit ? ["ignore", "inherit", "inherit"] : ["ignore", "pipe", "pipe"], maxBuffer: 256 * 1024 * 1024 });
@@ -10784,9 +11035,9 @@ function git3(cwd, args, opts = {}) {
10784
11035
  return res;
10785
11036
  }
10786
11037
  function onPath(name) {
10787
- for (const dir2 of (process.env.PATH ?? "").split(path25.delimiter)) {
11038
+ for (const dir2 of (process.env.PATH ?? "").split(path26.delimiter)) {
10788
11039
  try {
10789
- fs29.accessSync(path25.join(dir2, name), fs29.constants.X_OK);
11040
+ fs30.accessSync(path26.join(dir2, name), fs30.constants.X_OK);
10790
11041
  return true;
10791
11042
  } catch {
10792
11043
  }
@@ -10870,11 +11121,11 @@ function switchOrigin(root, url, out) {
10870
11121
  }
10871
11122
  async function cmdImport(args, cwd, out, err) {
10872
11123
  requireHelper();
10873
- const root = toplevel(path25.resolve(str4(args.flags.path) ?? args._[1] ?? cwd));
11124
+ const root = toplevel(path26.resolve(str4(args.flags.path) ?? args._[1] ?? cwd));
10874
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");
10875
11126
  const rs = remotes(root);
10876
11127
  const originUrl = rs.get("origin");
10877
- const name = str4(args.flags.name) ?? (originUrl && !originUrl.startsWith("bunshin::") ? repoFromUrl(originUrl) : null) ?? `${path25.basename(path25.dirname(root))}/${path25.basename(root)}`;
11128
+ const name = str4(args.flags.name) ?? (originUrl && !originUrl.startsWith("bunshin::") ? repoFromUrl(originUrl) : null) ?? `${path26.basename(path26.dirname(root))}/${path26.basename(root)}`;
10878
11129
  const client = await connect(args, cwd);
10879
11130
  const url = remoteUrl(client.apiUrl, name);
10880
11131
  const fromOrigin = !!originUrl && !originUrl.startsWith("bunshin::") && !bool3(args.flags.local);
@@ -10950,7 +11201,7 @@ ${refsToGithub.length} line${refsToGithub.length === 1 ? "" : "s"} in the reposi
10950
11201
  if (refsToGithub.length > 40) out(` \u2026 and ${refsToGithub.length - 40} more (git grep for ${name})
10951
11202
  `);
10952
11203
  }
10953
- if (fs29.existsSync(path25.join(root, ".github"))) out(`
11204
+ if (fs30.existsSync(path26.join(root, ".github"))) out(`
10954
11205
  Note: .github/ (Actions, CODEOWNERS, templates) only works on GitHub; Bunshin does not run it.
10955
11206
  `);
10956
11207
  out(`
@@ -10961,7 +11212,7 @@ New machines clone with: bunshin repo clone ${name}
10961
11212
  }
10962
11213
  async function cmdAttach(args, cwd, out, err) {
10963
11214
  requireHelper();
10964
- const root = toplevel(path25.resolve(str4(args.flags.path) ?? cwd));
11215
+ const root = toplevel(path26.resolve(str4(args.flags.path) ?? cwd));
10965
11216
  const rs = remotes(root);
10966
11217
  const originUrl = rs.get("origin");
10967
11218
  const name = str4(args.flags.name) ?? args._[1] ?? (originUrl ? repoFromUrl(originUrl) : null);
@@ -11009,12 +11260,12 @@ async function cmdClone(args, cwd, out) {
11009
11260
  const dir2 = args._[2] ?? name.split("/")[1];
11010
11261
  const r = spawnSync2("git", ["clone", remoteUrl(client.apiUrl, name), dir2], { cwd, stdio: "inherit" });
11011
11262
  if (r.status !== 0) return r.status ?? 1;
11012
- out(`Cloned ${name} into ${path25.resolve(cwd, dir2)}
11263
+ out(`Cloned ${name} into ${path26.resolve(cwd, dir2)}
11013
11264
  `);
11014
11265
  return 0;
11015
11266
  }
11016
11267
  async function cmdVerify(args, cwd, out, err) {
11017
- const root = toplevel(path25.resolve(str4(args.flags.path) ?? cwd));
11268
+ const root = toplevel(path26.resolve(str4(args.flags.path) ?? cwd));
11018
11269
  const rs = remotes(root);
11019
11270
  const originUrl = rs.get("origin") ?? "";
11020
11271
  if (!originUrl.startsWith("bunshin::")) throw new Error("origin is not a Bunshin repository (run bunshin repo attach)");
@@ -11177,28 +11428,28 @@ __export(runner_exports, {
11177
11428
  setupText: () => setupText
11178
11429
  });
11179
11430
  import { spawnSync as spawnSync3 } from "node:child_process";
11180
- import fs30 from "node:fs";
11181
- import os6 from "node:os";
11182
- import path26 from "node:path";
11183
- function runnerHome(home = process.env.BUNSHIN_RUNNER_HOME || os6.homedir()) {
11184
- return path26.join(home, ".bunshin", "runner");
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");
11185
11436
  }
11186
11437
  function readInstalled(home) {
11187
11438
  try {
11188
- return JSON.parse(fs30.readFileSync(path26.join(runnerHome(home), "config.json"), "utf8"));
11439
+ return JSON.parse(fs31.readFileSync(path27.join(runnerHome(home), "config.json"), "utf8"));
11189
11440
  } catch {
11190
11441
  return null;
11191
11442
  }
11192
11443
  }
11193
11444
  function connection(args, cwd) {
11194
11445
  const saved = readInstalled();
11195
- const store = saved && path26.resolve(cwd).startsWith(runnerHome()) ? null : Store.discover(cwd);
11446
+ const store = saved && path27.resolve(cwd).startsWith(runnerHome()) ? null : Store.discover(cwd);
11196
11447
  const config = store?.config();
11197
11448
  const key = str5(args.flags.key) || process.env.BUNSHIN_RUNNER_KEY || process.env.BUNSHIN_API_KEY || config?.apiKey || saved?.key || "";
11198
11449
  const apiUrl = (str5(args.flags["api-url"]) || process.env.BUNSHIN_API_URL || config?.apiUrl || saved?.apiUrl || DEFAULT_API).replace(/\/$/, "");
11199
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");
11200
11451
  if (!secureUrl(apiUrl)) throw new Error(`refusing ${apiUrl}: the runner's key travels only over https (http only on localhost)`);
11201
- const name = str5(args.flags.name) ?? process.env.BUNSHIN_RUNNER_NAME ?? saved?.name ?? `${os6.hostname().split(".")[0] || "runner"}`;
11452
+ const name = str5(args.flags.name) ?? process.env.BUNSHIN_RUNNER_NAME ?? saved?.name ?? `${os7.hostname().split(".")[0] || "runner"}`;
11202
11453
  return { apiUrl, key, name: name.replace(/[^\w.:@/-]/g, "-").slice(0, 80) };
11203
11454
  }
11204
11455
  async function call(c, method, route, body, timeoutMs = 6e4) {
@@ -11252,9 +11503,9 @@ async function runOnce(c, args, out, err) {
11252
11503
  const [job] = await lease(c, args);
11253
11504
  if (!job) break;
11254
11505
  const started = Date.now();
11255
- const scratch = fs30.mkdtempSync(path26.join(os6.tmpdir(), "bunshin-job-"));
11506
+ const scratch = fs31.mkdtempSync(path27.join(os7.tmpdir(), "bunshin-job-"));
11256
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(
11257
- () => fs30.rmSync(scratch, { recursive: true, force: true })
11508
+ () => fs31.rmSync(scratch, { recursive: true, force: true })
11258
11509
  );
11259
11510
  const model = config.backend === "codex-cli" ? config.codexModel ?? "codex default" : config.backend === "pi-cli" ? config.piModel ?? "pi default" : config.model;
11260
11511
  if (!res.ok) {
@@ -11344,24 +11595,24 @@ function renderCheck(id, c) {
11344
11595
  }
11345
11596
  function logAnswer(entry) {
11346
11597
  try {
11347
- fs30.mkdirSync(runnerHome(), { recursive: true });
11348
- fs30.appendFileSync(path26.join(runnerHome(), "log.jsonl"), `${JSON.stringify({ at: (/* @__PURE__ */ new Date()).toISOString(), ...entry })}
11598
+ fs31.mkdirSync(runnerHome(), { recursive: true });
11599
+ fs31.appendFileSync(path27.join(runnerHome(), "log.jsonl"), `${JSON.stringify({ at: (/* @__PURE__ */ new Date()).toISOString(), ...entry })}
11349
11600
  `);
11350
11601
  } catch {
11351
11602
  }
11352
11603
  }
11353
11604
  function which(name) {
11354
- for (const d of [...(process.env.PATH || "").split(path26.delimiter), path26.join(os6.homedir(), ".local", "bin")]) {
11355
- if (d && fs30.existsSync(path26.join(d, name))) return path26.join(d, name);
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);
11356
11607
  }
11357
11608
  return null;
11358
11609
  }
11359
11610
  function scheduledCommand(backend) {
11360
- const node = path26.dirname(process.execPath);
11361
- const npx = fs30.existsSync(path26.join(node, "npx")) ? path26.join(node, "npx") : which("npx") ?? "npx";
11611
+ const node = path27.dirname(process.execPath);
11612
+ const npx = fs31.existsSync(path27.join(node, "npx")) ? path27.join(node, "npx") : which("npx") ?? "npx";
11362
11613
  const bin = BIN_OF[backend] ? which(BIN_OF[backend]) : null;
11363
- const dirs = [.../* @__PURE__ */ new Set([node, ...bin ? [path26.dirname(bin)] : [], path26.join(os6.homedir(), ".local", "bin"), "/opt/homebrew/bin", "/usr/local/bin", "/usr/bin", "/bin", "/usr/sbin", "/sbin"])];
11364
- return { argv: [npx, "-y", PKG2, "runner", "--once"], path: dirs.join(path26.delimiter) };
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) };
11365
11616
  }
11366
11617
  function launchdPlist(backend, everyMinutes, home = runnerHome()) {
11367
11618
  const cmd = scheduledCommand(backend);
@@ -11376,8 +11627,8 @@ function launchdPlist(backend, everyMinutes, home = runnerHome()) {
11376
11627
  <dict><key>PATH</key><string>${xml(cmd.path)}</string></dict>
11377
11628
  <key>WorkingDirectory</key><string>${xml(home)}</string>
11378
11629
  <key>StartInterval</key><integer>${everyMinutes * 60}</integer>
11379
- <key>StandardOutPath</key><string>${xml(path26.join(home, "runner.log"))}</string>
11380
- <key>StandardErrorPath</key><string>${xml(path26.join(home, "runner.log"))}</string>
11630
+ <key>StandardOutPath</key><string>${xml(path27.join(home, "runner.log"))}</string>
11631
+ <key>StandardErrorPath</key><string>${xml(path27.join(home, "runner.log"))}</string>
11381
11632
  <key>ProcessType</key><string>Background</string>
11382
11633
  <key>LowPriorityIO</key><true/>
11383
11634
  </dict>
@@ -11388,19 +11639,19 @@ function cronLine(backend, everyMinutes, home = runnerHome()) {
11388
11639
  const cmd = scheduledCommand(backend);
11389
11640
  const when = everyMinutes >= 60 ? `17 */${Math.max(1, Math.round(everyMinutes / 60))} * * *` : `*/${everyMinutes} * * * *`;
11390
11641
  const q = (v) => `'${v.replace(/'/g, `'\\''`)}'`;
11391
- return `${when} cd ${q(home)} && PATH=${q(cmd.path)} ${cmd.argv.map(q).join(" ")} >> ${q(path26.join(home, "runner.log"))} 2>&1 ${CRON_MARK}`;
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}`;
11392
11643
  }
11393
11644
  function launchAgentsDir(opts) {
11394
- return opts.launchAgents ?? path26.join(process.env.BUNSHIN_RUNNER_HOME || os6.homedir(), "Library", "LaunchAgents");
11645
+ return opts.launchAgents ?? path27.join(process.env.BUNSHIN_RUNNER_HOME || os7.homedir(), "Library", "LaunchAgents");
11395
11646
  }
11396
11647
  function installSchedule(backend, everyMinutes, opts = {}) {
11397
11648
  const platform = opts.platform ?? process.platform;
11398
11649
  const run2 = opts.run ?? realRun;
11399
11650
  if (platform === "darwin") {
11400
11651
  const dir2 = launchAgentsDir(opts);
11401
- const plist = path26.join(dir2, `${LAUNCHD_LABEL}.plist`);
11402
- fs30.mkdirSync(dir2, { recursive: true });
11403
- fs30.writeFileSync(plist, launchdPlist(backend, everyMinutes));
11652
+ const plist = path27.join(dir2, `${LAUNCHD_LABEL}.plist`);
11653
+ fs31.mkdirSync(dir2, { recursive: true });
11654
+ fs31.writeFileSync(plist, launchdPlist(backend, everyMinutes));
11404
11655
  const domain = `gui/${process.getuid?.() ?? 501}`;
11405
11656
  run2("launchctl", ["bootout", `${domain}/${LAUNCHD_LABEL}`]);
11406
11657
  const r = run2("launchctl", ["bootstrap", domain, plist]);
@@ -11420,10 +11671,10 @@ function removeSchedule(opts = {}) {
11420
11671
  const platform = opts.platform ?? process.platform;
11421
11672
  const run2 = opts.run ?? realRun;
11422
11673
  if (platform === "darwin") {
11423
- const plist = path26.join(launchAgentsDir(opts), `${LAUNCHD_LABEL}.plist`);
11674
+ const plist = path27.join(launchAgentsDir(opts), `${LAUNCHD_LABEL}.plist`);
11424
11675
  run2("launchctl", ["bootout", `gui/${process.getuid?.() ?? 501}/${LAUNCHD_LABEL}`]);
11425
- if (!fs30.existsSync(plist)) return "no schedule";
11426
- fs30.rmSync(plist, { force: true });
11676
+ if (!fs31.existsSync(plist)) return "no schedule";
11677
+ fs31.rmSync(plist, { force: true });
11427
11678
  return `removed ${plist}`;
11428
11679
  }
11429
11680
  const current = run2("crontab", ["-l"]);
@@ -11450,10 +11701,10 @@ async function install(args, cwd, out, err, opts = {}) {
11450
11701
  }
11451
11702
  const every = Math.max(15, Number(str5(args.flags.every) ?? 60) || 60);
11452
11703
  const home = runnerHome();
11453
- fs30.mkdirSync(home, { recursive: true, mode: 448 });
11704
+ fs31.mkdirSync(home, { recursive: true, mode: 448 });
11454
11705
  const saved = { apiUrl: c.apiUrl, key: c.key, backend, ...config.model && str5(args.flags.model) ? { model: config.model } : {}, name: c.name, every };
11455
- fs30.writeFileSync(path26.join(home, "config.json"), JSON.stringify(saved, null, 2) + "\n", { mode: 384 });
11456
- fs30.chmodSync(path26.join(home, "config.json"), 384);
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);
11457
11708
  let schedule;
11458
11709
  try {
11459
11710
  schedule = installSchedule(backend, every, opts);
@@ -11466,7 +11717,7 @@ Run it yourself: npx -y ${PKG2} runner --once
11466
11717
  out(`\u2713 Runner "${c.name}" answers ${c.apiUrl}'s model jobs with ${BACKEND_NAME[backend] ?? backend} on this computer.
11467
11718
  `);
11468
11719
  out(schedule.kind === "none" ? ` No scheduler here: run \`npx -y ${PKG2} runner --once\` on a schedule yourself.
11469
- ` : ` Every ${every} minutes while this computer is on (${schedule.kind}). Log: ${path26.join(home, "runner.log")}
11720
+ ` : ` Every ${every} minutes while this computer is on (${schedule.kind}). Log: ${path27.join(home, "runner.log")}
11470
11721
  `);
11471
11722
  out(` Stop: npx -y ${PKG2} runner uninstall
11472
11723
  `);
@@ -11483,9 +11734,9 @@ Answering what waits now\u2026
11483
11734
  function uninstall(out, opts = {}) {
11484
11735
  out(`${removeSchedule(opts)}
11485
11736
  `);
11486
- const file2 = path26.join(runnerHome(), "config.json");
11487
- if (fs30.existsSync(file2)) {
11488
- fs30.rmSync(file2, { force: true });
11737
+ const file2 = path27.join(runnerHome(), "config.json");
11738
+ if (fs31.existsSync(file2)) {
11739
+ fs31.rmSync(file2, { force: true });
11489
11740
  out(`removed ${file2} (revoke the key in the console: Agent keys)
11490
11741
  `);
11491
11742
  }
@@ -11665,7 +11916,7 @@ async function cmdRunner(args, cwd, out, err, opts = {}) {
11665
11916
  out(text2);
11666
11917
  return 0;
11667
11918
  }
11668
- fs30.writeFileSync(file2, text2, { mode: 384 });
11919
+ fs31.writeFileSync(file2, text2, { mode: 384 });
11669
11920
  const left = Math.round((Date.parse(job.leaseUntil) - Date.now()) / 6e4);
11670
11921
  out(
11671
11922
  [
@@ -11683,7 +11934,7 @@ async function cmdRunner(args, cwd, out, err, opts = {}) {
11683
11934
  const id = args._[2];
11684
11935
  const file2 = args._[3] ?? "-";
11685
11936
  if (!id) throw new Error("usage: bunshin runner validate <job id> <file|->");
11686
- const text2 = file2 === "-" ? fs30.readFileSync(0, "utf8") : fs30.readFileSync(file2, "utf8");
11937
+ const text2 = file2 === "-" ? fs31.readFileSync(0, "utf8") : fs31.readFileSync(file2, "utf8");
11687
11938
  const r = await call(c, "POST", `/jobs/${id}/check`, { answer: text2, runner: c.name }, 12e4);
11688
11939
  out(renderCheck(id, r.body));
11689
11940
  return r.body.ok ? 0 : 1;
@@ -11692,7 +11943,7 @@ async function cmdRunner(args, cwd, out, err, opts = {}) {
11692
11943
  const id = args._[2];
11693
11944
  const file2 = args._[3] ?? "-";
11694
11945
  if (!id) throw new Error("usage: bunshin runner submit <job id> <file|-> [--force]");
11695
- const text2 = file2 === "-" ? fs30.readFileSync(0, "utf8") : fs30.readFileSync(file2, "utf8");
11946
+ const text2 = file2 === "-" ? fs31.readFileSync(0, "utf8") : fs31.readFileSync(file2, "utf8");
11696
11947
  const check = await call(c, "POST", `/jobs/${id}/check`, { answer: text2, runner: c.name }, 12e4).catch(() => null);
11697
11948
  if (check?.body && (check.status < 400 || check.body.problems)) {
11698
11949
  out(renderCheck(id, check.body));
@@ -11716,7 +11967,7 @@ async function cmdRunner(args, cwd, out, err, opts = {}) {
11716
11967
  const since = Date.parse(str5(args.flags.since) ?? "") || Date.now() - 12 * 36e5;
11717
11968
  const entries = (() => {
11718
11969
  try {
11719
- return fs30.readFileSync(path26.join(runnerHome(), "log.jsonl"), "utf8").split("\n").filter(Boolean).map((l) => JSON.parse(l)).filter((e) => Date.parse(e.at) >= since);
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);
11720
11971
  } catch {
11721
11972
  return [];
11722
11973
  }
@@ -11786,8 +12037,8 @@ var init_runner = __esm({
11786
12037
 
11787
12038
  // src/v2/importer.ts
11788
12039
  import { execFileSync as execFileSync7 } from "node:child_process";
11789
- import fs31 from "node:fs";
11790
- import path27 from "node:path";
12040
+ import fs32 from "node:fs";
12041
+ import path28 from "node:path";
11791
12042
  function rewriteRepoPaths(text2, repoName2, pack) {
11792
12043
  const re = new RegExp(`(?<=^|[\\s\`'"(=:])(?:~|\\$\\{?[A-Za-z_][A-Za-z0-9_]*\\}?)?(?:/[\\w.@+-]+)*/${escapeRe(repoName2)}(?=[/\\s\`'")\\]]|[.,;:](?:\\s|$)|$)`, "gm");
11793
12044
  return text2.replace(re, `~/.bunshin/library/${pack}`);
@@ -11826,7 +12077,7 @@ function buildDocs(files, opts) {
11826
12077
  const main2 = `${dir2}/SKILL.md`;
11827
12078
  const text2 = rw(files.get(main2).content);
11828
12079
  const fm = frontmatterDescription(text2);
11829
- const name = path27.posix.basename(dir2);
12080
+ const name = path28.posix.basename(dir2);
11830
12081
  const bundle = {};
11831
12082
  for (const p of all.filter((x) => x.startsWith(`${dir2}/`))) {
11832
12083
  claimed.add(p);
@@ -11924,22 +12175,22 @@ function isGitRepo(root) {
11924
12175
  function workingTreeFiles(root) {
11925
12176
  const out = /* @__PURE__ */ new Map();
11926
12177
  const list2 = isGitRepo(root) ? git4(root, ["ls-files", "-z"]).split("\0").filter(Boolean) : (function walk(dir2, base = "") {
11927
- return fs31.readdirSync(dir2, { withFileTypes: true }).flatMap((e) => {
12178
+ return fs32.readdirSync(dir2, { withFileTypes: true }).flatMap((e) => {
11928
12179
  if (e.name === ".git" || e.name === "node_modules") return [];
11929
12180
  const rel = base ? `${base}/${e.name}` : e.name;
11930
- return e.isDirectory() ? walk(path27.join(dir2, e.name), rel) : e.isFile() ? [rel] : [];
12181
+ return e.isDirectory() ? walk(path28.join(dir2, e.name), rel) : e.isFile() ? [rel] : [];
11931
12182
  });
11932
12183
  })(root);
11933
12184
  for (const rel of list2) {
11934
- const abs = path27.join(root, rel);
12185
+ const abs = path28.join(root, rel);
11935
12186
  let buf;
11936
12187
  try {
11937
- buf = fs31.readFileSync(abs);
12188
+ buf = fs32.readFileSync(abs);
11938
12189
  } catch {
11939
12190
  continue;
11940
12191
  }
11941
12192
  if (!isText(buf)) continue;
11942
- const exec = (fs31.statSync(abs).mode & 73) !== 0;
12193
+ const exec = (fs32.statSync(abs).mode & 73) !== 0;
11943
12194
  out.set(rel, { content: buf.toString("utf8"), ...exec ? { mode: "x" } : {} });
11944
12195
  }
11945
12196
  return out;
@@ -11973,7 +12224,7 @@ function diffDocs(prev, next) {
11973
12224
  return { docs: next.filter((d) => before.get(d.path) !== fingerprint(d)), removed: [...before.keys()].filter((p) => !after.has(p)) };
11974
12225
  }
11975
12226
  function readSkillSystem(root, opts) {
11976
- const repoName2 = path27.basename(path27.resolve(root));
12227
+ const repoName2 = path28.basename(path28.resolve(root));
11977
12228
  const build = (files2) => buildDocs(files2, { pack: opts.pack, repoName: repoName2, ...opts.rewrite === false ? { rewrite: false } : {} });
11978
12229
  const tree = build(workingTreeFiles(root));
11979
12230
  if (!opts.history || !isGitRepo(root)) return { versions: [{ summary: `import ${opts.pack}`, docs: tree, removed: [], complete: true }], docs: tree };
@@ -12050,7 +12301,7 @@ var init_importer = __esm({
12050
12301
  escapeRe = (s) => s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
12051
12302
  looksGenerated = (text2) => /generated by|do not edit( by hand)?/i.test(text2.slice(0, 600));
12052
12303
  isStopHook = (text2) => /"decision"\s*:\s*"block"|decision.{0,4}block/.test(text2) && /REASON=/.test(text2);
12053
- isUpdateHook = (p, text2) => /auto-?update/i.test(path27.basename(p)) || /git (pull|fetch)/.test(text2) && /SessionStart|session start/i.test(text2);
12304
+ isUpdateHook = (p, text2) => /auto-?update/i.test(path28.basename(p)) || /git (pull|fetch)/.test(text2) && /SessionStart|session start/i.test(text2);
12054
12305
  fingerprint = (d) => JSON.stringify(d);
12055
12306
  REWRITE_SYSTEM = `You adapt a company's skill documents after its skill system moved into Bunshin.
12056
12307
 
@@ -12086,8 +12337,8 @@ __export(skills_exports, {
12086
12337
  cmdSkill: () => cmdSkill,
12087
12338
  parsePin: () => parsePin
12088
12339
  });
12089
- import fs32 from "node:fs";
12090
- import path28 from "node:path";
12340
+ import fs33 from "node:fs";
12341
+ import path29 from "node:path";
12091
12342
  function requireOnline(store, what) {
12092
12343
  if (!canCall(store.config())) throw new Error(`${what} needs the hosted library: run \`bunshin setup\` first`);
12093
12344
  }
@@ -12096,9 +12347,9 @@ async function cmdImport2(store, args, cwd, out, err) {
12096
12347
  err("usage: bunshin import skills <dir> [--pack <name>] [--layer org|team:<unit>] [--owner-team <unit>] [--no-history] [--dry-run] [--propose-rewrites]\n");
12097
12348
  return 1;
12098
12349
  }
12099
- const root = path28.resolve(cwd, args._[2]);
12100
- if (!fs32.existsSync(root)) throw new Error(`${root} does not exist`);
12101
- const pack = str6(args.flags.pack) ?? path28.basename(root);
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);
12102
12353
  const history = args.flags.history !== false && !bool4(args.flags["no-history"]);
12103
12354
  const read = readSkillSystem(root, { pack, history, ...str6(args.flags.since) ? { since: str6(args.flags.since) } : {} });
12104
12355
  const kinds = /* @__PURE__ */ new Map();
@@ -12133,7 +12384,7 @@ async function cmdImport2(store, args, cwd, out, err) {
12133
12384
  const propose = args.flags["propose-rewrites"];
12134
12385
  if (propose) {
12135
12386
  const only = typeof propose === "string" && propose !== "true" ? propose.split(",").map((x) => x.trim()).filter(Boolean) : [];
12136
- await proposeRewrites(store, read.docs.filter((d) => !only.length || only.some((o) => d.path.includes(o))), pack, path28.basename(root), out, err);
12387
+ await proposeRewrites(store, read.docs.filter((d) => !only.length || only.some((o) => d.path.includes(o))), pack, path29.basename(root), out, err);
12137
12388
  }
12138
12389
  out("Run `bunshin sync` on each machine (it runs at session start) to install the skills, instructions and files.\n");
12139
12390
  return 0;
@@ -12273,7 +12524,7 @@ ${report.skills} skills, ${report.references} references, ${report.errors.length
12273
12524
  }
12274
12525
  const graph = str6(args.flags.graph) ?? (bool4(args.flags.graph) ? "SKILLS-GRAPH.md" : void 0);
12275
12526
  if (graph) {
12276
- fs32.writeFileSync(path28.resolve(cwd, graph), renderSkillGraph(report));
12527
+ fs33.writeFileSync(path29.resolve(cwd, graph), renderSkillGraph(report));
12277
12528
  out(`graph written to ${graph}
12278
12529
  `);
12279
12530
  }
@@ -12343,8 +12594,8 @@ async function splitSkill(store, args, skill, name, out, err) {
12343
12594
  const files = splitPaths(v2, skill.skill.name);
12344
12595
  const sourceWords = words3(skill.body.slice(parseFrontmatter2(skill.body).bodyStart));
12345
12596
  if (bool4(args.flags.submit)) {
12346
- if (!fs32.existsSync(files.json)) throw new Error(`no split of ${skill.skill.name} yet: run \`bunshin skill split ${skill.skill.name}\` first`);
12347
- const f2 = JSON.parse(fs32.readFileSync(files.json, "utf8"));
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"));
12348
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`);
12349
12600
  const plan2 = parseSplit(f2.plan);
12350
12601
  if (!plan2) throw new Error(`${files.json} holds no spine`);
@@ -12355,7 +12606,7 @@ async function splitSkill(store, args, skill, name, out, err) {
12355
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)`);
12356
12607
  }
12357
12608
  const made = splitSuggestions(v2, config, skill, plan2);
12358
- fs32.rmSync(files.json, { force: true });
12609
+ fs33.rmSync(files.json, { force: true });
12359
12610
  if (!canCall(config)) {
12360
12611
  out(`${made} suggestions queued (${plan2.units.length} atoms and the spine); they leave with the next sync and wait for owner review.
12361
12612
  `);
@@ -12380,9 +12631,9 @@ async function splitSkill(store, args, skill, name, out, err) {
12380
12631
  if (!plan) throw new Error("the model's answer holds no spine");
12381
12632
  const coverage = splitCoverage(skill.body, [plan.spine, ...plan.units]);
12382
12633
  const f = { skill: skill.id, name: skill.skill.name, version: skill.version, at: (/* @__PURE__ */ new Date()).toISOString(), plan, coverage };
12383
- fs32.mkdirSync(path28.dirname(files.json), { recursive: true });
12384
- fs32.writeFileSync(files.json, JSON.stringify(f, null, 2));
12385
- fs32.writeFileSync(files.md, splitPreview(f, sourceWords));
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));
12386
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)`}
12387
12638
  `);
12388
12639
  out(`Read ${files.md}; edit ${files.json} if needed; then send it with \`bunshin skill split ${skill.skill.name} --submit\`.
@@ -12489,9 +12740,9 @@ async function cmdLibrary(store, args, cwd, out, err) {
12489
12740
  `;
12490
12741
  const file2 = str6(args.flags.write) ?? (bool4(args.flags.write) ? ".claude/skills-version" : void 0);
12491
12742
  if (file2) {
12492
- const abs = path28.resolve(cwd, file2);
12493
- fs32.mkdirSync(path28.dirname(abs), { recursive: true });
12494
- fs32.writeFileSync(abs, line);
12743
+ const abs = path29.resolve(cwd, file2);
12744
+ fs33.mkdirSync(path29.dirname(abs), { recursive: true });
12745
+ fs33.writeFileSync(abs, line);
12495
12746
  out(`${file2}: ${line}`);
12496
12747
  } else out(line);
12497
12748
  return 0;
@@ -12501,12 +12752,12 @@ async function cmdLibrary(store, args, cwd, out, err) {
12501
12752
  const to = str6(args.flags.to);
12502
12753
  if (!to) throw new Error("--to <dir> is required");
12503
12754
  const pinFile = str6(args.flags.pin);
12504
- const pin = str6(args.flags.git) ? { git: str6(args.flags.git) } : pinFile ? parsePin(fs32.readFileSync(path28.resolve(cwd, pinFile), "utf8")) : parsePin(args._[2] ?? "");
12755
+ const pin = str6(args.flags.git) ? { git: str6(args.flags.git) } : pinFile ? parsePin(fs33.readFileSync(path29.resolve(cwd, pinFile), "utf8")) : parsePin(args._[2] ?? "");
12505
12756
  const q = pin.git ? `git=${pin.git}` : pin.version ? `version=${pin.version}` : "";
12506
12757
  if (!q) throw new Error("name a version: lib@N, --git <sha>, or --pin <file>");
12507
12758
  const snap = await v2api(config, "GET", `/library/snapshot?${q}`, void 0, { timeoutMs: 12e4 });
12508
- const dir2 = path28.resolve(cwd, to);
12509
- if (fs32.existsSync(dir2) && fs32.readdirSync(dir2).length && !bool4(args.flags.force)) throw new Error(`${dir2} is not empty (use --force)`);
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)`);
12510
12761
  const pack = str6(args.flags.pack);
12511
12762
  const docs = snap.sections.filter((s) => !pack || s.pack === pack);
12512
12763
  const res = materialize(docs, dir2);
@@ -12537,7 +12788,7 @@ var init_skills = __esm({
12537
12788
  skillsOf = (sections) => sections.filter((s) => s.skill && (s.status === "active" || s.status === "stale"));
12538
12789
  words3 = (t) => t.split(/\s+/).filter(Boolean).length;
12539
12790
  splitPaths = (v2, name) => {
12540
- const base = path28.join(v2.dir, "split", name.replace(/[^\w.-]/g, "_"));
12791
+ const base = path29.join(v2.dir, "split", name.replace(/[^\w.-]/g, "_"));
12541
12792
  return { json: `${base}.json`, md: `${base}.md` };
12542
12793
  };
12543
12794
  }
@@ -12550,27 +12801,27 @@ __export(reflect_exports, {
12550
12801
  buildLesson: () => buildLesson,
12551
12802
  runReflection: () => runReflection
12552
12803
  });
12553
- import fs33 from "node:fs";
12554
- import path29 from "node:path";
12555
- import { createHash as createHash10 } from "node:crypto";
12804
+ import fs34 from "node:fs";
12805
+ import path30 from "node:path";
12806
+ import { createHash as createHash11 } from "node:crypto";
12556
12807
  async function runReflection(store, opts) {
12557
12808
  const empty = { lessonIds: [], used: [], missed: [], attribution: [] };
12558
- const lock = path29.join(store.root, `reflect-${createHash10("sha256").update(opts.sessionId).digest("hex")}.lock`);
12809
+ const lock = path30.join(store.root, `reflect-${createHash11("sha256").update(opts.sessionId).digest("hex")}.lock`);
12559
12810
  const deadline = Date.now() + 66e4;
12560
12811
  for (; ; ) {
12561
12812
  try {
12562
- fs33.writeFileSync(lock, String(process.pid), { flag: "wx", mode: 384 });
12813
+ fs34.writeFileSync(lock, String(process.pid), { flag: "wx", mode: 384 });
12563
12814
  break;
12564
12815
  } catch (error) {
12565
12816
  if (error.code !== "EEXIST") throw error;
12566
12817
  try {
12567
- const owner = Number(fs33.readFileSync(lock, "utf8"));
12818
+ const owner = Number(fs34.readFileSync(lock, "utf8"));
12568
12819
  if (Number.isInteger(owner) && owner > 0) {
12569
12820
  try {
12570
12821
  process.kill(owner, 0);
12571
12822
  } catch (error2) {
12572
12823
  if (error2.code === "ESRCH") {
12573
- fs33.unlinkSync(lock);
12824
+ fs34.unlinkSync(lock);
12574
12825
  continue;
12575
12826
  }
12576
12827
  }
@@ -12585,7 +12836,7 @@ async function runReflection(store, opts) {
12585
12836
  return await reflectSession(store, opts);
12586
12837
  } finally {
12587
12838
  try {
12588
- fs33.unlinkSync(lock);
12839
+ fs34.unlinkSync(lock);
12589
12840
  } catch {
12590
12841
  }
12591
12842
  }
@@ -12928,8 +13179,8 @@ __export(cli_exports, {
12928
13179
  setupMod: () => setupMod,
12929
13180
  version: () => version
12930
13181
  });
12931
- import fs34 from "node:fs";
12932
- import path30 from "node:path";
13182
+ import fs35 from "node:fs";
13183
+ import path31 from "node:path";
12933
13184
  function parseArgs(argv) {
12934
13185
  const out = { _: [], flags: {} };
12935
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"]);
@@ -13038,7 +13289,7 @@ async function main(argv, opts = {}) {
13038
13289
  out(result.mcp.error ? `! bunshin MCP server not registered (${result.mcp.error}); sessions still learn and recall through the hooks.
13039
13290
  ` : "bunshin MCP server registered for this user.\n");
13040
13291
  for (const command of [result.learnCommand, result.borrowCommand]) {
13041
- if (command.error) err(`! ${path30.basename(command.file, ".md")} not installed at ${command.file}: ${command.error}
13292
+ if (command.error) err(`! ${path31.basename(command.file, ".md")} not installed at ${command.file}: ${command.error}
13042
13293
  `);
13043
13294
  }
13044
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");
@@ -13051,15 +13302,18 @@ async function main(argv, opts = {}) {
13051
13302
  }
13052
13303
  if (cmd === "setup") {
13053
13304
  try {
13054
- const { setupProject: setupProject2, executable: executable2, readKey: readKey2 } = await Promise.resolve().then(() => (init_setup(), setup_exports));
13055
- const harness = str7(args.flags.harness);
13056
- if (harness !== "codex" && harness !== "claude-code" && harness !== "pi") throw new Error("Choose your agent: bunshin setup --harness codex, claude-code, or pi.");
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);
13057
13309
  const agent = harness === "claude-code" ? "claude" : harness;
13058
13310
  if (!executable2(agent)) throw new Error(`${agent} was not found. Install and sign in to your agent, then run setup again.`);
13059
- const prior = new Store(path30.join(cwd, ".bunshin"));
13311
+ const prior = new Store(path31.join(cwd, ".bunshin"));
13060
13312
  const existing = prior.trusted ? prior.config() : { apiUrl: "", apiKey: void 0 };
13061
13313
  const apiUrl = str7(args.flags["api-url"]);
13062
- const key = bool5(args.flags["key-stdin"]) ? await new Promise((resolve, reject) => {
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) => {
13063
13317
  let value = "";
13064
13318
  process.stdin.setEncoding("utf8");
13065
13319
  process.stdin.on("data", (chunk) => {
@@ -13067,7 +13321,11 @@ async function main(argv, opts = {}) {
13067
13321
  });
13068
13322
  process.stdin.on("end", () => resolve(value.trim()));
13069
13323
  process.stdin.on("error", reject);
13070
- }) : process.env.BUNSHIN_API_KEY || (!apiUrl || apiUrl === existing.apiUrl) && existing.apiKey || await readKey2();
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;
13071
13329
  const hooksFlag = str7(args.flags.hooks);
13072
13330
  if (hooksFlag && hooksFlag !== "user" && hooksFlag !== "project") throw new Error("--hooks must be user (every session under this folder) or project (this folder only)");
13073
13331
  const only = str7(args.flags.only);
@@ -13085,8 +13343,9 @@ async function main(argv, opts = {}) {
13085
13343
  });
13086
13344
  if (result.config.hooks === "user" && !only && !exclude && !bool5(args.flags.all) && process.stdin.isTTY && !bool5(args.flags["key-stdin"])) {
13087
13345
  const { askSources: askSources2 } = await Promise.resolve().then(() => (init_setup(), setup_exports));
13088
- await askSources2(new Store(path30.join(cwd, ".bunshin")), out);
13346
+ await askSources2(new Store(path31.join(cwd, ".bunshin")), out);
13089
13347
  }
13348
+ if (fresh) saveLogin2({ apiUrl: address, apiKey: key, orgId: result.profile.orgId, userId: result.profile.userId });
13090
13349
  out(`Connected as ${result.profile.role}${result.profile.orgUnit ? ` in ${result.profile.orgUnit}` : " (company-wide)"}.
13091
13350
  `);
13092
13351
  out(result.config.hooks === "user" ? `Folder: ${cwd} (every session in it or below it uses this workspace)
@@ -13119,11 +13378,41 @@ Key saved privately outside the project.
13119
13378
  return 1;
13120
13379
  }
13121
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
+ }
13122
13411
  if (cmd === "init") return cmdInit(args, cwd, out, err);
13123
13412
  if (cmd === "mcp") {
13124
13413
  const { runMcpServer: runMcpServer2 } = await Promise.resolve().then(() => (init_mcp(), mcp_exports));
13125
13414
  const root = str7(args.flags.root);
13126
- await runMcpServer2({ cwd, ...root ? { store: new Store(path30.resolve(root)) } : {}, version: version() });
13415
+ await runMcpServer2({ cwd, ...root ? { store: new Store(path31.resolve(root)) } : {}, version: version() });
13127
13416
  return 0;
13128
13417
  }
13129
13418
  if (cmd === "demo") {
@@ -13237,7 +13526,7 @@ ${HELP2}`);
13237
13526
  function openStore(args, cwd) {
13238
13527
  const root = str7(args.flags.root);
13239
13528
  if (root) {
13240
- const store = new Store(path30.resolve(root));
13529
+ const store = new Store(path31.resolve(root));
13241
13530
  store.ensureLayout();
13242
13531
  return store;
13243
13532
  }
@@ -13253,7 +13542,7 @@ async function cmdInit(args, cwd, out, err) {
13253
13542
  orgId: str7(args.flags["org-id"]),
13254
13543
  userId: str7(args.flags["user-id"]),
13255
13544
  apiUrl: str7(args.flags["api-url"]),
13256
- apiKey: bool5(args.flags["key-stdin"]) ? fs34.readFileSync(0, "utf8").trim() || void 0 : str7(args.flags["api-key"]),
13545
+ apiKey: bool5(args.flags["key-stdin"]) ? fs35.readFileSync(0, "utf8").trim() || void 0 : str7(args.flags["api-key"]),
13257
13546
  scope: bool5(args.flags.global) ? "global" : str7(args.flags.scope),
13258
13547
  harness,
13259
13548
  noHooks: args.flags.hooks === false || bool5(args.flags["no-hooks"]),
@@ -13296,10 +13585,10 @@ function cmdStatus(store, args, out, v2) {
13296
13585
  const conflicts = store.listConflicts().filter((c) => c.status === "open");
13297
13586
  const metrics = store.readMetrics(void 0);
13298
13587
  const last50 = metrics?.windows?.find((w) => w.name === "last50");
13299
- const hookFiles = config.harness === "codex" ? [.../* @__PURE__ */ new Set([path30.join(process.env.CODEX_HOME ?? path30.join(homeDir(), ".codex"), "hooks.json"), codexProjectHooks(path30.dirname(store.root)).file])] : config.harness === "claude-code" ? [path30.join(homeDir(), ".claude", "settings.json"), path30.join(path30.dirname(store.root), ".claude", "settings.local.json")] : config.harness === "pi" ? [path30.join(homeDir(), ".pi/agent/extensions/bunshin.js"), path30.join(path30.dirname(store.root), ".pi/extensions/bunshin.js")] : [];
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")] : [];
13300
13589
  const hooks = config.harness === "pi" ? hookFiles.filter((file2) => {
13301
13590
  try {
13302
- return fs34.readFileSync(file2, "utf8").startsWith("// Managed by Bunshin setup.");
13591
+ return fs35.readFileSync(file2, "utf8").startsWith("// Managed by Bunshin setup.");
13303
13592
  } catch {
13304
13593
  return false;
13305
13594
  }
@@ -13318,7 +13607,7 @@ function cmdStatus(store, args, out, v2) {
13318
13607
  llmBackend: resolveBackend(config) ?? "none (set ANTHROPIC_API_KEY or install the claude/codex CLI)",
13319
13608
  recallRouter: recallRouter(config),
13320
13609
  hooks: { [config.harness]: hooks },
13321
- hookFiles: hookFiles.filter((file2) => fs34.existsSync(file2)),
13610
+ hookFiles: hookFiles.filter((file2) => fs35.existsSync(file2)),
13322
13611
  recallQuality: last50 ? { precision: last50.precision, recall: last50.recall, f1: last50.f1, traces: last50.traces } : null,
13323
13612
  v2
13324
13613
  };
@@ -13371,7 +13660,7 @@ function cmdStatus(store, args, out, v2) {
13371
13660
  }
13372
13661
  function hookCount(file2) {
13373
13662
  try {
13374
- const raw = JSON.parse(fs34.readFileSync(file2, "utf8"));
13663
+ const raw = JSON.parse(fs35.readFileSync(file2, "utf8"));
13375
13664
  let n = 0;
13376
13665
  for (const groups of Object.values(raw.hooks ?? {})) {
13377
13666
  for (const g of groups ?? []) {
@@ -13491,7 +13780,7 @@ function cmdLessonAdd(store, args, out, err) {
13491
13780
  let content = str7(args.flags.content) ?? "";
13492
13781
  if (!content || content === "-" || args._.includes("-")) {
13493
13782
  try {
13494
- content = fs34.readFileSync(0, "utf8");
13783
+ content = fs35.readFileSync(0, "utf8");
13495
13784
  } catch {
13496
13785
  }
13497
13786
  }
@@ -13557,7 +13846,7 @@ async function cmdReflect(store, args, cwd, out, err) {
13557
13846
  }
13558
13847
  const { runReflection: runReflection2 } = await Promise.resolve().then(() => (init_reflect4(), reflect_exports));
13559
13848
  const result = await runReflection2(store, {
13560
- sessionId: str7(args.flags.session) ?? path30.basename(transcript).replace(/\.jsonl?$/, ""),
13849
+ sessionId: str7(args.flags.session) ?? path31.basename(transcript).replace(/\.jsonl?$/, ""),
13561
13850
  transcriptPath: transcript,
13562
13851
  cwd,
13563
13852
  force: bool5(args.flags.force)
@@ -13660,6 +13949,20 @@ async function cmdConflict(store, args, out, err) {
13660
13949
  }
13661
13950
  return 0;
13662
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
+ }
13663
13966
  function store0HasKey(store) {
13664
13967
  return !!store.config().apiKey;
13665
13968
  }
@@ -13672,8 +13975,8 @@ async function setupMod(config) {
13672
13975
  if (installedModVersion2() === v) return `Bunshin UI: bunshin-ui ${v} is installed (a band above the prompt, /bunshin).
13673
13976
  `;
13674
13977
  try {
13675
- fs34.mkdirSync(modHome2(), { recursive: true });
13676
- fs34.writeFileSync(path30.join(modHome2(), `.attempted-${v}`), nowIso());
13978
+ fs35.mkdirSync(modHome2(), { recursive: true });
13979
+ fs35.writeFileSync(path31.join(modHome2(), `.attempted-${v}`), nowIso());
13677
13980
  const res = installMod2(v);
13678
13981
  if (res.steps.some((st) => st.ok && /plugin (install|update)/.test(st.command))) {
13679
13982
  return `Bunshin UI: bunshin-ui ${v} installed (a band above the prompt, /bunshin). It needs Claude Code mods on your account.
@@ -13703,9 +14006,13 @@ var init_cli = __esm({
13703
14006
 
13704
14007
  Usage: bunshin <command> [options]
13705
14008
 
13706
- setup --harness codex|claude-code|pi connect this project to your hosted workspace
13707
- --api-url <url> --no-hooks paste the key at the hidden prompt; profile is read from Bunshin
13708
- --key-stdin read the key from stdin (for automated setup)
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)
13709
14016
  --hooks user a folder of projects: hooks in your user settings, so every
13710
14017
  session under this folder uses its workspace (default: project)
13711
14018
  --only a,b | --exclude c | --all
@@ -13717,6 +14024,9 @@ Usage: bunshin <command> [options]
13717
14024
  setup --robot --robot-id <id> --arm so101 --gripper <g> --mount <m> --cameras scene,wrist
13718
14025
  --domain <d> --site <s> --cell <c> [--depth] [--api-url <url>] [--harness claude-code]
13719
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)
13720
14030
  init create a local store and configure the selected harness
13721
14031
  --role <r> --org-unit <u> --org-id <id> --user-id <id>
13722
14032
  --api-url <url> --api-key <key> (or --key-stdin) --scope repo|global (--global)
@@ -13793,7 +14103,7 @@ Global: --root <dir> (use this .bunshin store) --version --help
13793
14103
  Env: BUNSHIN_API_KEY, BUNSHIN_API_URL (setup --env), BUNSHIN_HARNESS, BUNSHIN_DISABLE, BUNSHIN_CHILD, BUNSHIN_CLAUDE_BIN,
13794
14104
  CLAUDE_CODE_SESSION_ID (learn / mcp session), ANTHROPIC_API_KEY (non-fork reflection)
13795
14105
  `;
13796
- 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 ${path30.dirname(root)} to trust it.`;
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.`;
13797
14107
  }
13798
14108
  });
13799
14109