@bunshin-cc/bunshin 0.12.2 → 0.13.1

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 +501 -200
  3. package/package.json +1 -1
package/dist/bin.js CHANGED
@@ -1115,14 +1115,14 @@ function isScopeLayer(layer) {
1115
1115
  return k === "group" || k === "source";
1116
1116
  }
1117
1117
  function groupChain(tree, groupId) {
1118
- const byId = new Map(tree.groups.map((g) => [g.id, g]));
1118
+ const byId2 = new Map(tree.groups.map((g) => [g.id, g]));
1119
1119
  const out = [];
1120
1120
  const seen = /* @__PURE__ */ new Set();
1121
- let cur = groupId ? byId.get(groupId) : void 0;
1121
+ let cur = groupId ? byId2.get(groupId) : void 0;
1122
1122
  while (cur && !seen.has(cur.id)) {
1123
1123
  seen.add(cur.id);
1124
1124
  out.unshift(cur.id);
1125
- cur = cur.parent ? byId.get(cur.parent) : void 0;
1125
+ cur = cur.parent ? byId2.get(cur.parent) : void 0;
1126
1126
  }
1127
1127
  return out;
1128
1128
  }
@@ -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({
@@ -1852,15 +1852,15 @@ var init_text_index = __esm({
1852
1852
 
1853
1853
  // ../core/src/v2/recall/engine.ts
1854
1854
  function servable(sections, reader) {
1855
- const byId = new Map(sections.map((s) => [s.id, s]));
1855
+ const byId2 = new Map(sections.map((s) => [s.id, s]));
1856
1856
  const out = /* @__PURE__ */ new Map();
1857
1857
  for (const s of sections) {
1858
1858
  if (s.status === "superseded" || s.status === "retired" || s.status === "pending") continue;
1859
- if (s.supersededBy && byId.get(s.supersededBy)?.status === "active") continue;
1859
+ if (s.supersededBy && byId2.get(s.supersededBy)?.status === "active") continue;
1860
1860
  if (!canRead(s, reader)) continue;
1861
1861
  let chosen = s;
1862
1862
  if (s.canonicalRoot && s.canonicalRoot !== s.id) {
1863
- const root = byId.get(s.canonicalRoot);
1863
+ const root = byId2.get(s.canonicalRoot);
1864
1864
  if (root && root.status !== "retired" && canRead(root, reader)) chosen = root;
1865
1865
  }
1866
1866
  out.set(chosen.id, chosen);
@@ -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;
@@ -2159,8 +2159,8 @@ function cardsOf(spine, sections) {
2159
2159
  function renderCardIndex(spine, cards, opts = {}) {
2160
2160
  if (!cards.length) return "";
2161
2161
  const stepTitle = new Map((spine.outline ?? []).map((h) => [h.anchor, h.title]));
2162
- const oneLine = (t) => t.replace(/\s+/g, " ").trim().slice(0, 240);
2163
- const lines = cards.map((c) => `- ${c.title} (${c.kind}, id: ${c.id}${c.step ? `, step: ${stepTitle.get(c.step) ?? c.step}` : ""}) \u2014 when: ${oneLine(c.when || c.title)}`);
2162
+ const oneLine2 = (t) => t.replace(/\s+/g, " ").trim().slice(0, 240);
2163
+ const lines = cards.map((c) => `- ${c.title} (${c.kind}, id: ${c.id}${c.step ? `, step: ${stepTitle.get(c.step) ?? c.step}` : ""}) \u2014 when: ${oneLine2(c.when || c.title)}`);
2164
2164
  const load = opts.mcp ? `bunshin_load {"section_id": "<id>"}` : "`bunshin load <id>`";
2165
2165
  return [
2166
2166
  `### CARDS of ${spine.skill ? `the \`${spine.skill.name}\` skill` : spine.title}`,
@@ -2246,10 +2246,10 @@ function parseSplit(raw) {
2246
2246
  }
2247
2247
  function withSpineAtoms(chosen, sections, max = 30) {
2248
2248
  const have = new Set(chosen.map((s) => s.id));
2249
- const byId = new Map(sections.map((s) => [s.id, s]));
2249
+ const byId2 = new Map(sections.map((s) => [s.id, s]));
2250
2250
  const extra = [];
2251
2251
  for (const c of chosen) {
2252
- const s = byId.get(c.id);
2252
+ const s = byId2.get(c.id);
2253
2253
  if (!s?.skill) continue;
2254
2254
  for (const a of cardsOf(s, sections)) if (!have.has(a.id) && extra.length < max) have.add(a.id), extra.push(a);
2255
2255
  }
@@ -2312,6 +2312,33 @@ var init_atoms = __esm({
2312
2312
  });
2313
2313
 
2314
2314
  // ../core/src/v2/recall/router.ts
2315
+ function indexItems(pool) {
2316
+ const sorted = [...pool].sort(byId);
2317
+ const item = (s, kind) => `<item id="${attr(s.id)}" kind="${kind}" title="${attr(s.skill?.name ?? s.title)}">
2318
+ WHEN: ${whenOf(s)}
2319
+ </item>`;
2320
+ const names = new Map(pool.map((s) => [s.id, s.skill?.name ?? s.title]));
2321
+ const atomKind = (s) => s.kind === "card" ? `card${s.partOf && names.has(s.partOf) ? ` of ${attr(names.get(s.partOf))}` : ""}` : s.kind === "fact" ? "fact" : "lesson";
2322
+ return { docs: sorted.filter((s) => !isLesson(s)).map((s) => item(s, s.skill ? "skill" : s.kind)), atoms: sorted.filter(isLesson).map((s) => item(s, atomKind(s))) };
2323
+ }
2324
+ function withRecent(system, recent) {
2325
+ if (!recent.length) return system;
2326
+ const { docs, atoms } = indexItems(recent);
2327
+ const at = system.lastIndexOf(ATOMS_HEADER);
2328
+ const docsAt = system.lastIndexOf(DOCS_HEADER);
2329
+ if (at < 0 || docsAt < 0 || docsAt > at) return system;
2330
+ const listed = (block2, extra) => [block2.trim() === "(none)" ? "" : block2.trim(), ...extra].filter(Boolean).join("\n\n") || "(none)";
2331
+ const head = system.slice(0, docsAt);
2332
+ const docBlock = system.slice(docsAt + DOCS_HEADER.length, at);
2333
+ const atomBlock = system.slice(at + ATOMS_HEADER.length);
2334
+ return `${head}${DOCS_HEADER}
2335
+
2336
+ ${listed(docBlock, docs)}
2337
+
2338
+ ${ATOMS_HEADER}
2339
+
2340
+ ${listed(atomBlock, atoms)}`;
2341
+ }
2315
2342
  function routerMessage(prompt, ctx, inContext2) {
2316
2343
  const lines = ["Session context:"];
2317
2344
  lines.push(ctx.first ? `- First prompt of this session: ${ctx.first.slice(0, 600)}` : "- This is the first prompt of the session.");
@@ -2350,19 +2377,21 @@ function parseRouterAnswer(text2, items, skip = []) {
2350
2377
  return null;
2351
2378
  }
2352
2379
  const skipped = new Set(skip);
2353
- const byId = new Map(items.filter((i) => !skipped.has(i.id)).map((i) => [i.id, i]));
2354
- const ids = (v) => Array.isArray(v) ? v.filter((x) => typeof x === "string" && byId.has(x)) : [];
2355
- const serve = typeof o.serve === "string" && byId.has(o.serve) ? o.serve : void 0;
2356
- const rules = [...new Set(ids(o.rules).filter((id) => byId.get(id).lesson && id !== serve))].slice(0, MAX_RULES);
2380
+ const byId2 = new Map(items.filter((i) => !skipped.has(i.id)).map((i) => [i.id, i]));
2381
+ const ids = (v) => Array.isArray(v) ? v.filter((x) => typeof x === "string" && byId2.has(x)) : [];
2382
+ const serve = typeof o.serve === "string" && byId2.has(o.serve) ? o.serve : void 0;
2383
+ const rules = [...new Set(ids(o.rules).filter((id) => byId2.get(id).lesson && id !== serve))].slice(0, MAX_RULES);
2357
2384
  const hint = ids(o.hints).filter((id) => id !== serve && !rules.includes(id)).slice(0, 2);
2358
2385
  return { ...serve ? { serve } : {}, rules, hint };
2359
2386
  }
2360
- var MAX_RULES, RULES;
2387
+ var MAX_RULES, WHEN_CHARS, isLesson, RULES, oneLine, whenOf, attr, routerItems, DOCS_HEADER, ATOMS_HEADER, byId;
2361
2388
  var init_router = __esm({
2362
2389
  "../core/src/v2/recall/router.ts"() {
2363
2390
  "use strict";
2364
2391
  init_atoms();
2365
2392
  MAX_RULES = 3;
2393
+ WHEN_CHARS = 400;
2394
+ isLesson = (s) => isAtom(s);
2366
2395
  RULES = `You are the recall router for an engineering team's agent library. A coding agent is working; you see the moment (the user's latest prompt with session context, or at a checkpoint the agent's recent actions) and the items already in the agent's context. Decide what, if anything, to inject now. The library holds long documents (skills are workflows: a spine of steps) and short ATOMS: lessons (corrections or preferences taught before), facts (how something is, a trap and what works) and cards (the detail of one workflow step).
2367
2396
 
2368
2397
  - "serve": at most ONE skill or document, injected in full (long). Serve only when this prompt STARTS or clearly redirects the workflow the item is the procedure for, and it is not already in context. A narrow question (how to find one value, why one command misbehaves, what one step needs) is answered by atoms, never by serving the whole skill. Follow-ups, approvals, status questions, chatter, and continuing work already under way need none.
@@ -2370,6 +2399,13 @@ var init_router = __esm({
2370
2399
  - "hints": up to 2 other possibly relevant document ids, shown as titles only.
2371
2400
 
2372
2401
  Only use ids from the library. Output exactly one line of JSON and nothing else: {"serve": "<id or null>", "rules": ["<atom id>", ...], "hints": ["<id>", ...]}`;
2402
+ oneLine = (t) => t.replace(/\s+/g, " ").trim();
2403
+ whenOf = (s) => oneLine(s.skill ? s.skill.description : s.when || s.title).slice(0, WHEN_CHARS);
2404
+ attr = (t) => oneLine(t).replace(/"/g, "'");
2405
+ routerItems = (pool) => pool.map((s) => ({ id: s.id, lesson: isLesson(s) }));
2406
+ DOCS_HEADER = "LIBRARY: SKILLS AND DOCUMENTS";
2407
+ ATOMS_HEADER = "LIBRARY: ATOMS (LESSONS, FACTS, CARDS)";
2408
+ byId = (a, b) => a.id < b.id ? -1 : a.id > b.id ? 1 : 0;
2373
2409
  }
2374
2410
  });
2375
2411
 
@@ -3858,7 +3894,7 @@ function matchingRecallLessons(task, rules) {
3858
3894
  }
3859
3895
  function prepareRecall(inputs, request, profile, rules = [], opts = {}) {
3860
3896
  const recallLessons = matchingRecallLessons(request.task, rules);
3861
- const byId = /* @__PURE__ */ new Map();
3897
+ const byId2 = /* @__PURE__ */ new Map();
3862
3898
  for (const { lesson, relevance } of inputs) {
3863
3899
  if (!canSee(lesson, profile) || !["active", "stale", "conflicted"].includes(lesson.status) || opts.excludeIds?.has(lesson.id)) continue;
3864
3900
  const lexical = lexicalRelevance(lesson, request.task);
@@ -3875,10 +3911,10 @@ function prepareRecall(inputs, request, profile, rules = [], opts = {}) {
3875
3911
  if (Math.max(taskRelevance, expanded) <= 0) continue;
3876
3912
  const result = score(lesson, request, profile, Math.max(taskRelevance, expanded), opts);
3877
3913
  const candidate = { lessonId: lesson.id, lesson, score: result.score, reasons: [...result.reasons, ...reasons], taskRelevance };
3878
- const previous = byId.get(lesson.id);
3879
- if (!previous || previous.lesson.version < lesson.version || previous.lesson.version === lesson.version && previous.score < candidate.score) byId.set(lesson.id, candidate);
3914
+ const previous = byId2.get(lesson.id);
3915
+ if (!previous || previous.lesson.version < lesson.version || previous.lesson.version === lesson.version && previous.score < candidate.score) byId2.set(lesson.id, candidate);
3880
3916
  }
3881
- const candidates = [...byId.values()].sort((a, b) => b.score - a.score || a.lessonId.localeCompare(b.lessonId)).slice(0, opts.poolSize ?? 30);
3917
+ const candidates = [...byId2.values()].sort((a, b) => b.score - a.score || a.lessonId.localeCompare(b.lessonId)).slice(0, opts.poolSize ?? 30);
3882
3918
  return { candidates, recallLessons };
3883
3919
  }
3884
3920
  function fallbackRecall(candidates, limit) {
@@ -6064,8 +6100,8 @@ function localView(v2, config, cwd, opts = {}) {
6064
6100
  source = void 0;
6065
6101
  }
6066
6102
  const reader = readerFor(ctx, void 0, { ...source ? { source } : {}, ...bundle?.scopes ? { tree: bundle.scopes } : {} });
6067
- const byId = /* @__PURE__ */ new Map();
6068
- for (const s of bundle?.sections ?? []) byId.set(s.id, s);
6103
+ const byId2 = /* @__PURE__ */ new Map();
6104
+ for (const s of bundle?.sections ?? []) byId2.set(s.id, s);
6069
6105
  let root = cwd;
6070
6106
  let repo = "";
6071
6107
  if (opts.index !== false) {
@@ -6074,8 +6110,8 @@ function localView(v2, config, cwd, opts = {}) {
6074
6110
  root = idx.root;
6075
6111
  repo = idx.index.repo;
6076
6112
  for (const s of idx.sections) {
6077
- const upstream = byId.get(s.id);
6078
- byId.set(s.id, upstream ? { ...upstream, ...s, stats: upstream.stats, situations: upstream.situations, experience: upstream.experience } : s);
6113
+ const upstream = byId2.get(s.id);
6114
+ byId2.set(s.id, upstream ? { ...upstream, ...s, stats: upstream.stats, situations: upstream.situations, experience: upstream.experience } : s);
6079
6115
  }
6080
6116
  } catch {
6081
6117
  }
@@ -6083,10 +6119,10 @@ function localView(v2, config, cwd, opts = {}) {
6083
6119
  const overlays = v2.readOverlays();
6084
6120
  if (bundle?.pending?.length) {
6085
6121
  const local = /* @__PURE__ */ new Set([...overlays.map((o) => o.suggestionId), ...v2.listSuggestions().map((s) => s.id)]);
6086
- applyPending(byId, bundle.pending, local);
6122
+ applyPending(byId2, bundle.pending, local);
6087
6123
  }
6088
- applyOverlays(byId, overlays, ctx);
6089
- return { ctx, reader, ...source ? { source } : {}, layers: reader.layers, bundle, sections: [...byId.values()], byId, root, repo };
6124
+ applyOverlays(byId2, overlays, ctx);
6125
+ return { ctx, reader, ...source ? { source } : {}, layers: reader.layers, bundle, sections: [...byId2.values()], byId: byId2, root, repo };
6090
6126
  }
6091
6127
  var ACTIVE_OVERLAY;
6092
6128
  var init_view = __esm({
@@ -7376,6 +7412,7 @@ __export(route_exports, {
7376
7412
  readAnswer: () => readAnswer,
7377
7413
  readJob: () => readJob,
7378
7414
  readStats: () => readStats,
7415
+ recentSections: () => recentSections,
7379
7416
  routeJob: () => routeJob,
7380
7417
  sweepRouter: () => sweepRouter,
7381
7418
  writeJob: () => writeJob
@@ -7526,8 +7563,12 @@ async function askRouter(store, v2, sessionId, model, kind) {
7526
7563
  const index = await routerIndex(store, v2, session.source ?? "");
7527
7564
  if (!/^[\w-]{1,64}$/.test(index.hash)) return { picks: { error: "the router index came back with a malformed hash" } };
7528
7565
  indexHash = index.hash;
7529
- const systemFile = path13.join(dir(v2), `system-${index.hash}.txt`);
7530
- if (!fs17.existsSync(systemFile)) fs17.writeFileSync(systemFile, index.system);
7566
+ const recent = recentSections(v2, store.config(), session, index.items);
7567
+ const system = withRecent(index.system, recent);
7568
+ const items = recent.length ? [...index.items, ...routerItems(recent)] : index.items;
7569
+ const name = recent.length ? `${index.hash}-${createHash5("sha256").update(system).digest("hex").slice(0, 12)}` : index.hash;
7570
+ const systemFile = path13.join(dir(v2), `system-${name}.txt`);
7571
+ if (!fs17.existsSync(systemFile)) fs17.writeFileSync(systemFile, system);
7531
7572
  const cwd = path13.join(dir(v2), "cwd");
7532
7573
  fs17.mkdirSync(cwd, { recursive: true });
7533
7574
  const inContext2 = session.inContext ?? [...session.loaded, ...session.pushed];
@@ -7539,13 +7580,22 @@ async function askRouter(store, v2, sessionId, model, kind) {
7539
7580
  const usage = { input: u.input_tokens ?? 0, cacheRead: u.cache_read_input_tokens ?? 0, cacheWrite: u.cache_creation_input_tokens ?? 0, output: u.output_tokens ?? 0, ...u.output_tokens_details?.thinking_tokens ? { thinking: u.output_tokens_details.thinking_tokens } : {} };
7540
7581
  const meta = { ...res.duration_ms ? { modelMs: res.duration_ms } : {}, usage, ...typeof res.total_cost_usd === "number" ? { costUsd: res.total_cost_usd } : {} };
7541
7582
  if (res.is_error) return { picks: { ...meta, error: `claude: ${(res.result ?? "error").slice(0, 300)}` }, indexHash };
7542
- const picks = parseRouterAnswer(res.result ?? "", index.items, inContext2);
7583
+ const picks = parseRouterAnswer(res.result ?? "", items, inContext2);
7543
7584
  if (!picks) return { picks: { ...meta, error: `not JSON: ${(res.result ?? "").slice(0, 120)}` }, indexHash };
7544
7585
  return { picks: { ...picks, ...meta }, indexHash };
7545
7586
  } catch (err) {
7546
7587
  return { picks: { error: (err instanceof Error ? err.message : String(err)).slice(0, 300) }, ...indexHash ? { indexHash } : {} };
7547
7588
  }
7548
7589
  }
7590
+ function recentSections(v2, config, session, known) {
7591
+ try {
7592
+ const have = new Set(known.map((i) => i.id));
7593
+ const view = localView(v2, config, session.cwd, { index: false, ...session.source !== void 0 ? { source: session.source } : {} });
7594
+ return recallable(view.sections, view.reader).filter((s) => !have.has(s.id) && (s.localTrial?.length ?? 0) > 0);
7595
+ } catch {
7596
+ return [];
7597
+ }
7598
+ }
7549
7599
  async function recordStats(v2, sessionId, a, model, indexHash) {
7550
7600
  let release = null;
7551
7601
  for (let i = 0; i < 40 && !(release = v2.tryLock("router-stats", 3e4)); i++) await new Promise((r) => setTimeout(r, 50));
@@ -7594,6 +7644,7 @@ var init_route = __esm({
7594
7644
  init_util();
7595
7645
  init_api();
7596
7646
  init_store2();
7647
+ init_view();
7597
7648
  ROUTER_MODEL = "claude-haiku-5-5";
7598
7649
  INDEX_TTL_MS = 10 * 6e4;
7599
7650
  CLAUDE_TIMEOUT_MS = 6e4;
@@ -9309,13 +9360,16 @@ var init_init = __esm({
9309
9360
  // src/setup.ts
9310
9361
  var setup_exports = {};
9311
9362
  __export(setup_exports, {
9363
+ HARNESS_NAMES: () => HARNESS_NAMES,
9312
9364
  HOSTED_API: () => HOSTED_API,
9313
9365
  apiAddress: () => apiAddress,
9314
9366
  askSources: () => askSources,
9315
9367
  autoConnect: () => autoConnect,
9368
+ chooseHarness: () => chooseHarness,
9316
9369
  connectionProfile: () => connectionProfile,
9317
9370
  executable: () => executable,
9318
9371
  hookBinary: () => hookBinary,
9372
+ installedHarnesses: () => installedHarnesses,
9319
9373
  readKey: () => readKey,
9320
9374
  repositoryRoot: () => repositoryRoot,
9321
9375
  setupEnvironment: () => setupEnvironment,
@@ -9338,6 +9392,31 @@ function executable(name) {
9338
9392
  }
9339
9393
  return void 0;
9340
9394
  }
9395
+ function installedHarnesses() {
9396
+ return ["claude-code", "codex", "pi"].filter((h) => executable(h === "claude-code" ? "claude" : h));
9397
+ }
9398
+ async function chooseHarness(out, interactive = !!process.stdin.isTTY) {
9399
+ const found = installedHarnesses();
9400
+ 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.");
9401
+ if (found.length === 1 || !interactive) {
9402
+ out(`Agent: ${HARNESS_NAMES[found[0]]}${found.length > 1 ? ` (also found ${found.slice(1).map((h) => HARNESS_NAMES[h]).join(", ")}: choose with --harness)` : ""}
9403
+ `);
9404
+ return found[0];
9405
+ }
9406
+ const readline2 = await import("node:readline/promises");
9407
+ const rl = readline2.createInterface({ input: process.stdin, output: process.stderr });
9408
+ try {
9409
+ found.forEach((h, i) => out(` ${i + 1}. ${HARNESS_NAMES[h]}
9410
+ `));
9411
+ const answer = (await rl.question(`Which agent should Bunshin connect? [1] `)).trim();
9412
+ const picked = found[(Number(answer) || 1) - 1] ?? found.find((h) => HARNESS_NAMES[h].toLowerCase().startsWith(answer.toLowerCase())) ?? found[0];
9413
+ out(`Agent: ${HARNESS_NAMES[picked]}
9414
+ `);
9415
+ return picked;
9416
+ } finally {
9417
+ rl.close();
9418
+ }
9419
+ }
9341
9420
  function hookBinary(harness) {
9342
9421
  const agent = executable(harness === "claude-code" ? "claude" : harness);
9343
9422
  const directories = [.../* @__PURE__ */ new Set([path19.dirname(process.execPath), path19.join(homeDir(), ".local/bin"), ...agent ? [path19.dirname(agent)] : []])];
@@ -9519,7 +9598,7 @@ async function autoConnect(cwd, env = process.env) {
9519
9598
  return { connected: false, reason: "failed", error: error instanceof Error ? error.message : String(error) };
9520
9599
  }
9521
9600
  }
9522
- var shellQuote;
9601
+ var shellQuote, HARNESS_NAMES;
9523
9602
  var init_setup = __esm({
9524
9603
  "src/setup.ts"() {
9525
9604
  "use strict";
@@ -9529,6 +9608,7 @@ var init_setup = __esm({
9529
9608
  init_util();
9530
9609
  init_trust();
9531
9610
  shellQuote = (value) => `'${value.replace(/'/g, `'"'"'`)}'`;
9611
+ HARNESS_NAMES = { "claude-code": "Claude Code", codex: "Codex", pi: "Pi" };
9532
9612
  }
9533
9613
  });
9534
9614
 
@@ -10157,6 +10237,168 @@ var init_commands = __esm({
10157
10237
  }
10158
10238
  });
10159
10239
 
10240
+ // src/login.ts
10241
+ var login_exports = {};
10242
+ __export(login_exports, {
10243
+ DeviceLoginUnavailable: () => DeviceLoginUnavailable,
10244
+ canOpenBrowser: () => canOpenBrowser,
10245
+ deviceLogin: () => deviceLogin,
10246
+ forgetLogin: () => forgetLogin,
10247
+ openBrowser: () => openBrowser,
10248
+ readLogin: () => readLogin,
10249
+ readPending: () => readPending,
10250
+ saveLogin: () => saveLogin
10251
+ });
10252
+ import fs26 from "node:fs";
10253
+ import os5 from "node:os";
10254
+ import path22 from "node:path";
10255
+ import { spawn as spawn5 } from "node:child_process";
10256
+ import { createHash as createHash8, randomBytes as randomBytes6 } from "node:crypto";
10257
+ function readLogin(apiUrl) {
10258
+ try {
10259
+ const saved = JSON.parse(fs26.readFileSync(loginFile(apiUrl), "utf8"));
10260
+ return saved.apiUrl === apiUrl && typeof saved.apiKey === "string" && saved.apiKey ? saved : void 0;
10261
+ } catch {
10262
+ return void 0;
10263
+ }
10264
+ }
10265
+ function saveLogin(login) {
10266
+ const directory = loginDirectory();
10267
+ fs26.mkdirSync(directory, { recursive: true, mode: 448 });
10268
+ const file2 = loginFile(login.apiUrl);
10269
+ const temporary = `${file2}.${randomBytes6(4).toString("hex")}.tmp`;
10270
+ fs26.writeFileSync(temporary, JSON.stringify({ ...login, savedAt: (/* @__PURE__ */ new Date()).toISOString() }) + "\n", { mode: 384, flag: "wx" });
10271
+ fs26.renameSync(temporary, file2);
10272
+ return file2;
10273
+ }
10274
+ function forgetLogin(apiUrl) {
10275
+ try {
10276
+ fs26.unlinkSync(loginFile(apiUrl));
10277
+ return true;
10278
+ } catch {
10279
+ return false;
10280
+ }
10281
+ }
10282
+ function canOpenBrowser(env = process.env) {
10283
+ if (env.BUNSHIN_NO_BROWSER === "1" || env.CI || env.CLAUDE_CODE_REMOTE === "true" || env.BUNSHIN_EPHEMERAL === "1") return false;
10284
+ if (env.SSH_CONNECTION || env.SSH_TTY) return false;
10285
+ if (process.platform === "darwin" || process.platform === "win32") return true;
10286
+ return !!(env.DISPLAY || env.WAYLAND_DISPLAY);
10287
+ }
10288
+ function openBrowser(url) {
10289
+ try {
10290
+ const [command, args] = process.platform === "darwin" ? ["open", [url]] : process.platform === "win32" ? ["cmd", ["/c", "start", "", url.replace(/&/g, "^&")]] : ["xdg-open", [url]];
10291
+ const child = spawn5(command, args, { stdio: "ignore", detached: true });
10292
+ child.on("error", () => {
10293
+ });
10294
+ child.unref();
10295
+ return true;
10296
+ } catch {
10297
+ return false;
10298
+ }
10299
+ }
10300
+ function readPending(apiUrl, now = Date.now()) {
10301
+ try {
10302
+ const p = JSON.parse(fs26.readFileSync(pendingFile(apiUrl), "utf8"));
10303
+ return p.apiUrl === apiUrl && p.deviceCode && p.expiresAt > now ? p : void 0;
10304
+ } catch {
10305
+ return void 0;
10306
+ }
10307
+ }
10308
+ function savePending(p) {
10309
+ fs26.mkdirSync(loginDirectory(), { recursive: true, mode: 448 });
10310
+ const file2 = pendingFile(p.apiUrl);
10311
+ const temporary = `${file2}.${randomBytes6(4).toString("hex")}.tmp`;
10312
+ fs26.writeFileSync(temporary, JSON.stringify(p) + "\n", { mode: 384, flag: "wx" });
10313
+ fs26.renameSync(temporary, file2);
10314
+ }
10315
+ function clearPending(apiUrl) {
10316
+ try {
10317
+ fs26.unlinkSync(pendingFile(apiUrl));
10318
+ } catch {
10319
+ }
10320
+ }
10321
+ function poster(opts) {
10322
+ const f = opts.fetchImpl ?? fetch;
10323
+ return async (p, body) => {
10324
+ let res;
10325
+ try {
10326
+ res = await f(`${opts.apiUrl}${p}`, { method: "POST", redirect: "error", signal: AbortSignal.timeout(15e3), headers: { "content-type": "application/json" }, body: JSON.stringify(body) });
10327
+ } catch {
10328
+ throw new Error("Could not reach Bunshin. Check your connection, then run setup again.");
10329
+ }
10330
+ if (res.status === 404 || res.status === 405) throw new DeviceLoginUnavailable("This Bunshin server cannot approve computers from the browser.");
10331
+ if (res.status === 429) return { status: "slow_down" };
10332
+ if (!res.ok) throw new Error(`Bunshin returned HTTP ${res.status}.`);
10333
+ return await res.json();
10334
+ };
10335
+ }
10336
+ async function deviceLogin(opts) {
10337
+ const post = poster(opts);
10338
+ const sleep = opts.sleep ?? ((ms) => new Promise((r) => setTimeout(r, ms)));
10339
+ let pending = opts.noWait ? void 0 : readPending(opts.apiUrl);
10340
+ if (pending) {
10341
+ opts.out(`Waiting for the approval started earlier (code ${pending.userCode}):
10342
+
10343
+ ${pending.url}
10344
+
10345
+ `);
10346
+ } else {
10347
+ const host = opts.host ?? os5.hostname().split(".")[0] ?? "";
10348
+ const start = await post("/saas/device/start", { client: opts.client, host });
10349
+ const deviceCode = String(start.deviceCode ?? "");
10350
+ const userCode = String(start.userCode ?? "");
10351
+ const url = String(start.verificationUriComplete ?? start.verificationUri ?? "");
10352
+ if (!deviceCode || !userCode || !url) throw new DeviceLoginUnavailable("This Bunshin server cannot approve computers from the browser.");
10353
+ 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 };
10354
+ if (opts.noWait) {
10355
+ savePending(pending);
10356
+ opts.out(`Open this link to approve this computer (it shows the code ${userCode}; check it matches, then click Approve):
10357
+
10358
+ ${url}
10359
+
10360
+ Then run bunshin setup: it finishes once the computer is approved. The link is valid for 10 minutes.
10361
+ `);
10362
+ return null;
10363
+ }
10364
+ const opened = opts.open !== false && canOpenBrowser() && openBrowser(url);
10365
+ opts.out(
10366
+ `${opened ? "Approve this computer in the browser window that just opened" : "Open this link to approve this computer"}:
10367
+
10368
+ ${url}
10369
+
10370
+ It shows the code ${userCode}; check it matches, then click Approve. Waiting\u2026
10371
+ `
10372
+ );
10373
+ }
10374
+ let interval = pending.interval * 1e3;
10375
+ try {
10376
+ while (Date.now() < pending.expiresAt) {
10377
+ await sleep(interval);
10378
+ const r = await post("/saas/device/token", { deviceCode: pending.deviceCode });
10379
+ if (r.status === "approved" && typeof r.key === "string") return { key: r.key };
10380
+ if (r.status === "denied") throw new Error("The request was declined in the browser. Run setup again to retry.");
10381
+ if (r.status === "expired") throw new Error("The request expired before it was approved. Run setup again for a new code.");
10382
+ if (r.status === "slow_down") interval += 1e3;
10383
+ }
10384
+ throw new Error("The request expired before it was approved. Run setup again for a new code.");
10385
+ } finally {
10386
+ clearPending(opts.apiUrl);
10387
+ }
10388
+ }
10389
+ var loginDirectory, loginFile, DeviceLoginUnavailable, pendingFile;
10390
+ var init_login = __esm({
10391
+ "src/login.ts"() {
10392
+ "use strict";
10393
+ init_util();
10394
+ loginDirectory = () => path22.join(homeDir(), ".config/bunshin");
10395
+ loginFile = (apiUrl) => path22.join(loginDirectory(), `login-${createHash8("sha256").update(apiUrl).digest("hex").slice(0, 16)}.json`);
10396
+ DeviceLoginUnavailable = class extends Error {
10397
+ };
10398
+ pendingFile = (apiUrl) => path22.join(loginDirectory(), `pending-${createHash8("sha256").update(apiUrl).digest("hex").slice(0, 16)}.json`);
10399
+ }
10400
+ });
10401
+
10160
10402
  // src/prompts.ts
10161
10403
  function renderLessonForInjection(l) {
10162
10404
  const head = `### ${l.title} \`${l.id}\` (${l.kind}${l.tags.length ? `; ${l.tags.join(", ")}` : ""})`;
@@ -10295,9 +10537,9 @@ __export(sync_exports2, {
10295
10537
  resolveConflict: () => resolveConflict,
10296
10538
  runSync: () => runSync
10297
10539
  });
10298
- import { createHash as createHash8 } from "node:crypto";
10299
- import path22 from "node:path";
10300
- import fs26 from "node:fs";
10540
+ import { createHash as createHash9 } from "node:crypto";
10541
+ import path23 from "node:path";
10542
+ import fs27 from "node:fs";
10301
10543
  async function api(config, method, route, body, timeoutMs = 1e4) {
10302
10544
  const ctrl = new AbortController();
10303
10545
  const timer = setTimeout(() => ctrl.abort(), timeoutMs);
@@ -10335,22 +10577,22 @@ async function mothershipLookup(config, ids, timeoutMs = 8e3) {
10335
10577
  }
10336
10578
  }
10337
10579
  async function runSync(store) {
10338
- const lock = path22.join(store.root, "sync.lock");
10580
+ const lock = path23.join(store.root, "sync.lock");
10339
10581
  const deadline = Date.now() + 12e4;
10340
10582
  for (; ; ) {
10341
10583
  try {
10342
- fs26.writeFileSync(lock, String(process.pid), { flag: "wx", mode: 384 });
10584
+ fs27.writeFileSync(lock, String(process.pid), { flag: "wx", mode: 384 });
10343
10585
  break;
10344
10586
  } catch (error) {
10345
10587
  if (error.code !== "EEXIST") throw error;
10346
10588
  try {
10347
- const owner = Number(fs26.readFileSync(lock, "utf8"));
10589
+ const owner = Number(fs27.readFileSync(lock, "utf8"));
10348
10590
  if (Number.isInteger(owner) && owner > 0) {
10349
10591
  try {
10350
10592
  process.kill(owner, 0);
10351
10593
  } catch (error2) {
10352
10594
  if (error2.code === "ESRCH") {
10353
- fs26.unlinkSync(lock);
10595
+ fs27.unlinkSync(lock);
10354
10596
  continue;
10355
10597
  }
10356
10598
  }
@@ -10369,7 +10611,7 @@ async function runSync(store) {
10369
10611
  return await syncStore(store);
10370
10612
  } finally {
10371
10613
  try {
10372
- fs26.unlinkSync(lock);
10614
+ fs27.unlinkSync(lock);
10373
10615
  } catch {
10374
10616
  }
10375
10617
  }
@@ -10397,9 +10639,9 @@ async function syncStore(store) {
10397
10639
  result.errors.push(String(e instanceof Error ? e.message : e));
10398
10640
  }
10399
10641
  }
10400
- const acknowledgementsFile = path22.join(store.root, "synced-traces.json");
10642
+ const acknowledgementsFile = path23.join(store.root, "synced-traces.json");
10401
10643
  const acknowledgements = readJson(acknowledgementsFile, {});
10402
- const fingerprint2 = (trace) => createHash8("sha256").update(JSON.stringify(trace)).digest("hex");
10644
+ const fingerprint2 = (trace) => createHash9("sha256").update(JSON.stringify(trace)).digest("hex");
10403
10645
  const traces = store.allTraces().filter((t) => acknowledgements[t.id] !== fingerprint2(t)).slice(0, 50);
10404
10646
  for (const t of traces) {
10405
10647
  try {
@@ -10491,7 +10733,7 @@ async function runRecall(store, opts) {
10491
10733
  };
10492
10734
  const connected = canSync(config) && config.recall.useMothership;
10493
10735
  const local = store.listLessons().filter((l) => !connected || l.provenance.userId === config.userId && l.provenance.orgId === config.orgId);
10494
- const byId = new Map(local.map((l) => [l.id, l]));
10736
+ const byId2 = new Map(local.map((l) => [l.id, l]));
10495
10737
  const rules = new Map(store.listRecallLessons().map((r) => [r.id, r]));
10496
10738
  let degraded;
10497
10739
  if (connected && !opts.offline) {
@@ -10514,12 +10756,12 @@ async function runRecall(store, opts) {
10514
10756
  const lookupOK = lookup && sameIdentity(lookup.profile);
10515
10757
  if (remoteOK || lookupOK) {
10516
10758
  profile = (remoteOK ? remote.profile : void 0) ?? (lookupOK ? lookup.profile : void 0) ?? profile;
10517
- byId.clear();
10759
+ byId2.clear();
10518
10760
  const refreshed = /* @__PURE__ */ new Map();
10519
10761
  if (lookupOK) {
10520
10762
  const unavailable = new Set(lookup.unavailableIds);
10521
10763
  for (const lesson of cached) {
10522
- if (unavailable.has(lesson.id) && lesson.version === 1 && (!config.lastSyncAt || lesson.provenance.createdAt > config.lastSyncAt)) byId.set(lesson.id, lesson);
10764
+ if (unavailable.has(lesson.id) && lesson.version === 1 && (!config.lastSyncAt || lesson.provenance.createdAt > config.lastSyncAt)) byId2.set(lesson.id, lesson);
10523
10765
  }
10524
10766
  for (const lesson of lookup.lessons) {
10525
10767
  if (cachedIds.has(lesson.id) && lesson.provenance.orgId === profile.orgId) refreshed.set(lesson.id, lesson);
@@ -10533,7 +10775,7 @@ async function runRecall(store, opts) {
10533
10775
  if (!checked || lesson.version > checked.version) refreshed.set(lesson.id, lesson);
10534
10776
  }
10535
10777
  for (const lesson of refreshed.values()) {
10536
- byId.set(lesson.id, lesson);
10778
+ byId2.set(lesson.id, lesson);
10537
10779
  if (!opts.dryRun) store.saveLesson(lesson, { reindex: false });
10538
10780
  }
10539
10781
  for (const rule of remoteOK ? remote.recallLessons : []) rules.set(rule.id, rule);
@@ -10548,7 +10790,7 @@ async function runRecall(store, opts) {
10548
10790
  }
10549
10791
  const fresh = new Set(Object.entries(state.servedAt).filter(([, turn]) => state.turn - turn < FRESH_TURNS).map(([id]) => id));
10550
10792
  const request = { task, userId: profile.userId, role: profile.role, orgUnit: profile.orgUnit, recentContext: history };
10551
- const prepared = prepareRecall([...byId.values()].map((lesson) => ({ lesson })), request, profile, [...rules.values()], { excludeIds: fresh });
10793
+ const prepared = prepareRecall([...byId2.values()].map((lesson) => ({ lesson })), request, profile, [...rules.values()], { excludeIds: fresh });
10552
10794
  const { candidates, recallLessons } = prepared;
10553
10795
  let selection;
10554
10796
  let selectedIds = fallbackRecall(candidates, config.recall.maxLessons);
@@ -10578,7 +10820,7 @@ async function runRecall(store, opts) {
10578
10820
  degraded = [degraded, response.error].filter(Boolean).join("; ");
10579
10821
  }
10580
10822
  }
10581
- const served = selectedIds.map((id) => byId.get(id));
10823
+ const served = selectedIds.map((id) => byId2.get(id));
10582
10824
  const trace = {
10583
10825
  id: newId("t"),
10584
10826
  sessionId: opts.sessionId,
@@ -10652,11 +10894,11 @@ __export(demo_exports, {
10652
10894
  runDemo: () => runDemo
10653
10895
  });
10654
10896
  import assert from "node:assert/strict";
10655
- import fs27 from "node:fs";
10656
- import os5 from "node:os";
10657
- import path23 from "node:path";
10897
+ import fs28 from "node:fs";
10898
+ import os6 from "node:os";
10899
+ import path24 from "node:path";
10658
10900
  async function runDemo(write) {
10659
- const root = fs27.mkdtempSync(path23.join(os5.tmpdir(), "bunshin-demo-"));
10901
+ const root = fs28.mkdtempSync(path24.join(os6.tmpdir(), "bunshin-demo-"));
10660
10902
  try {
10661
10903
  const store = Store.init(root, { ...DEMO_ENGINEER, apiUrl: "" });
10662
10904
  const { lessons, constraint, workflow } = demoScenario();
@@ -10673,7 +10915,7 @@ Task: ${DEMO_TASK}
10673
10915
  write(result.text);
10674
10916
  write("\nPASS: Legal hold constraint and deletion workflow recalled; C-suite, other-company, and superseded lessons excluded.\n");
10675
10917
  } finally {
10676
- fs27.rmSync(root, { recursive: true, force: true });
10918
+ fs28.rmSync(root, { recursive: true, force: true });
10677
10919
  }
10678
10920
  }
10679
10921
  var init_demo2 = __esm({
@@ -10686,21 +10928,21 @@ var init_demo2 = __esm({
10686
10928
  });
10687
10929
 
10688
10930
  // src/v2/gitremote.ts
10689
- import fs28 from "node:fs";
10690
- import path24 from "node:path";
10691
- import { createHash as createHash9 } from "node:crypto";
10931
+ import fs29 from "node:fs";
10932
+ import path25 from "node:path";
10933
+ import { createHash as createHash10 } from "node:crypto";
10692
10934
  function saveGitCredential(apiUrl, apiKey) {
10693
10935
  const file2 = gitCredentialFile();
10694
- fs28.mkdirSync(path24.dirname(file2), { recursive: true, mode: 448 });
10936
+ fs29.mkdirSync(path25.dirname(file2), { recursive: true, mode: 448 });
10695
10937
  let all = {};
10696
10938
  try {
10697
- all = JSON.parse(fs28.readFileSync(file2, "utf8"));
10939
+ all = JSON.parse(fs29.readFileSync(file2, "utf8"));
10698
10940
  } catch {
10699
10941
  }
10700
10942
  all[apiUrl.replace(/\/$/, "")] = apiKey;
10701
10943
  const tmp = `${file2}.${process.pid}.tmp`;
10702
- fs28.writeFileSync(tmp, JSON.stringify(all, null, 2) + "\n", { mode: 384 });
10703
- fs28.renameSync(tmp, file2);
10944
+ fs29.writeFileSync(tmp, JSON.stringify(all, null, 2) + "\n", { mode: 384 });
10945
+ fs29.renameSync(tmp, file2);
10704
10946
  }
10705
10947
  function resolveGitKey(apiUrl) {
10706
10948
  const base = apiUrl.replace(/\/$/, "");
@@ -10708,20 +10950,20 @@ function resolveGitKey(apiUrl) {
10708
10950
  const origin = urlOrigin(base);
10709
10951
  if (process.env.BUNSHIN_API_KEY && origin && trustedOrigins().has(origin)) return process.env.BUNSHIN_API_KEY;
10710
10952
  try {
10711
- const all = JSON.parse(fs28.readFileSync(gitCredentialFile(), "utf8"));
10953
+ const all = JSON.parse(fs29.readFileSync(gitCredentialFile(), "utf8"));
10712
10954
  if (all[base]) return all[base];
10713
10955
  } catch {
10714
10956
  }
10715
- const dir2 = path24.join(homeDir(), ".config/bunshin/credentials");
10957
+ const dir2 = path25.join(homeDir(), ".config/bunshin/credentials");
10716
10958
  let files = [];
10717
10959
  try {
10718
- files = fs28.readdirSync(dir2).filter((f) => f.endsWith(".json"));
10960
+ files = fs29.readdirSync(dir2).filter((f) => f.endsWith(".json"));
10719
10961
  } catch {
10720
10962
  return void 0;
10721
10963
  }
10722
10964
  for (const f of files.sort()) {
10723
10965
  try {
10724
- const c = JSON.parse(fs28.readFileSync(path24.join(dir2, f), "utf8"));
10966
+ const c = JSON.parse(fs29.readFileSync(path25.join(dir2, f), "utf8"));
10725
10967
  if (c.apiKey && c.apiUrl?.replace(/\/$/, "") === base) return c.apiKey;
10726
10968
  } catch {
10727
10969
  }
@@ -10729,7 +10971,7 @@ function resolveGitKey(apiUrl) {
10729
10971
  return void 0;
10730
10972
  }
10731
10973
  function refsDigest(refs) {
10732
- return createHash9("sha256").update(
10974
+ return createHash10("sha256").update(
10733
10975
  [...refs].sort((a, b) => a.ref.localeCompare(b.ref)).map((r) => `${r.sha} ${r.ref}`).join("\n")
10734
10976
  ).digest("hex").slice(0, 12);
10735
10977
  }
@@ -10742,7 +10984,7 @@ var init_gitremote = __esm({
10742
10984
  ZERO_SHA = "0".repeat(40);
10743
10985
  REMOTE_PATH = "/v1/git/repos/";
10744
10986
  remoteUrl = (apiUrl, repo) => `bunshin::${apiUrl.replace(/\/$/, "")}${REMOTE_PATH}${repo}`;
10745
- gitCredentialFile = () => path24.join(homeDir(), ".config/bunshin/git-credentials.json");
10987
+ gitCredentialFile = () => path25.join(homeDir(), ".config/bunshin/git-credentials.json");
10746
10988
  GitApiError = class extends Error {
10747
10989
  constructor(status, message, body = null) {
10748
10990
  super(message);
@@ -10834,8 +11076,8 @@ __export(gitrepo_exports, {
10834
11076
  githubReferences: () => githubReferences,
10835
11077
  repoFromUrl: () => repoFromUrl
10836
11078
  });
10837
- import fs29 from "node:fs";
10838
- import path25 from "node:path";
11079
+ import fs30 from "node:fs";
11080
+ import path26 from "node:path";
10839
11081
  import { spawnSync as spawnSync2 } from "node:child_process";
10840
11082
  function git3(cwd, args, opts = {}) {
10841
11083
  const r = spawnSync2("git", ["-C", cwd, ...args], { encoding: "utf8", stdio: opts.inherit ? ["ignore", "inherit", "inherit"] : ["ignore", "pipe", "pipe"], maxBuffer: 256 * 1024 * 1024 });
@@ -10844,9 +11086,9 @@ function git3(cwd, args, opts = {}) {
10844
11086
  return res;
10845
11087
  }
10846
11088
  function onPath(name) {
10847
- for (const dir2 of (process.env.PATH ?? "").split(path25.delimiter)) {
11089
+ for (const dir2 of (process.env.PATH ?? "").split(path26.delimiter)) {
10848
11090
  try {
10849
- fs29.accessSync(path25.join(dir2, name), fs29.constants.X_OK);
11091
+ fs30.accessSync(path26.join(dir2, name), fs30.constants.X_OK);
10850
11092
  return true;
10851
11093
  } catch {
10852
11094
  }
@@ -10930,11 +11172,11 @@ function switchOrigin(root, url, out) {
10930
11172
  }
10931
11173
  async function cmdImport(args, cwd, out, err) {
10932
11174
  requireHelper();
10933
- const root = toplevel(path25.resolve(str4(args.flags.path) ?? args._[1] ?? cwd));
11175
+ const root = toplevel(path26.resolve(str4(args.flags.path) ?? args._[1] ?? cwd));
10934
11176
  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
11177
  const rs = remotes(root);
10936
11178
  const originUrl = rs.get("origin");
10937
- const name = str4(args.flags.name) ?? (originUrl && !originUrl.startsWith("bunshin::") ? repoFromUrl(originUrl) : null) ?? `${path25.basename(path25.dirname(root))}/${path25.basename(root)}`;
11179
+ const name = str4(args.flags.name) ?? (originUrl && !originUrl.startsWith("bunshin::") ? repoFromUrl(originUrl) : null) ?? `${path26.basename(path26.dirname(root))}/${path26.basename(root)}`;
10938
11180
  const client = await connect(args, cwd);
10939
11181
  const url = remoteUrl(client.apiUrl, name);
10940
11182
  const fromOrigin = !!originUrl && !originUrl.startsWith("bunshin::") && !bool3(args.flags.local);
@@ -11010,7 +11252,7 @@ ${refsToGithub.length} line${refsToGithub.length === 1 ? "" : "s"} in the reposi
11010
11252
  if (refsToGithub.length > 40) out(` \u2026 and ${refsToGithub.length - 40} more (git grep for ${name})
11011
11253
  `);
11012
11254
  }
11013
- if (fs29.existsSync(path25.join(root, ".github"))) out(`
11255
+ if (fs30.existsSync(path26.join(root, ".github"))) out(`
11014
11256
  Note: .github/ (Actions, CODEOWNERS, templates) only works on GitHub; Bunshin does not run it.
11015
11257
  `);
11016
11258
  out(`
@@ -11021,7 +11263,7 @@ New machines clone with: bunshin repo clone ${name}
11021
11263
  }
11022
11264
  async function cmdAttach(args, cwd, out, err) {
11023
11265
  requireHelper();
11024
- const root = toplevel(path25.resolve(str4(args.flags.path) ?? cwd));
11266
+ const root = toplevel(path26.resolve(str4(args.flags.path) ?? cwd));
11025
11267
  const rs = remotes(root);
11026
11268
  const originUrl = rs.get("origin");
11027
11269
  const name = str4(args.flags.name) ?? args._[1] ?? (originUrl ? repoFromUrl(originUrl) : null);
@@ -11069,12 +11311,12 @@ async function cmdClone(args, cwd, out) {
11069
11311
  const dir2 = args._[2] ?? name.split("/")[1];
11070
11312
  const r = spawnSync2("git", ["clone", remoteUrl(client.apiUrl, name), dir2], { cwd, stdio: "inherit" });
11071
11313
  if (r.status !== 0) return r.status ?? 1;
11072
- out(`Cloned ${name} into ${path25.resolve(cwd, dir2)}
11314
+ out(`Cloned ${name} into ${path26.resolve(cwd, dir2)}
11073
11315
  `);
11074
11316
  return 0;
11075
11317
  }
11076
11318
  async function cmdVerify(args, cwd, out, err) {
11077
- const root = toplevel(path25.resolve(str4(args.flags.path) ?? cwd));
11319
+ const root = toplevel(path26.resolve(str4(args.flags.path) ?? cwd));
11078
11320
  const rs = remotes(root);
11079
11321
  const originUrl = rs.get("origin") ?? "";
11080
11322
  if (!originUrl.startsWith("bunshin::")) throw new Error("origin is not a Bunshin repository (run bunshin repo attach)");
@@ -11237,28 +11479,28 @@ __export(runner_exports, {
11237
11479
  setupText: () => setupText
11238
11480
  });
11239
11481
  import { spawnSync as spawnSync3 } from "node:child_process";
11240
- import fs30 from "node:fs";
11241
- import os6 from "node:os";
11242
- import path26 from "node:path";
11243
- function runnerHome(home = process.env.BUNSHIN_RUNNER_HOME || os6.homedir()) {
11244
- return path26.join(home, ".bunshin", "runner");
11482
+ import fs31 from "node:fs";
11483
+ import os7 from "node:os";
11484
+ import path27 from "node:path";
11485
+ function runnerHome(home = process.env.BUNSHIN_RUNNER_HOME || os7.homedir()) {
11486
+ return path27.join(home, ".bunshin", "runner");
11245
11487
  }
11246
11488
  function readInstalled(home) {
11247
11489
  try {
11248
- return JSON.parse(fs30.readFileSync(path26.join(runnerHome(home), "config.json"), "utf8"));
11490
+ return JSON.parse(fs31.readFileSync(path27.join(runnerHome(home), "config.json"), "utf8"));
11249
11491
  } catch {
11250
11492
  return null;
11251
11493
  }
11252
11494
  }
11253
11495
  function connection(args, cwd) {
11254
11496
  const saved = readInstalled();
11255
- const store = saved && path26.resolve(cwd).startsWith(runnerHome()) ? null : Store.discover(cwd);
11497
+ const store = saved && path27.resolve(cwd).startsWith(runnerHome()) ? null : Store.discover(cwd);
11256
11498
  const config = store?.config();
11257
11499
  const key = str5(args.flags.key) || process.env.BUNSHIN_RUNNER_KEY || process.env.BUNSHIN_API_KEY || config?.apiKey || saved?.key || "";
11258
11500
  const apiUrl = (str5(args.flags["api-url"]) || process.env.BUNSHIN_API_URL || config?.apiUrl || saved?.apiUrl || DEFAULT_API).replace(/\/$/, "");
11259
11501
  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
11502
  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 ?? `${os6.hostname().split(".")[0] || "runner"}`;
11503
+ const name = str5(args.flags.name) ?? process.env.BUNSHIN_RUNNER_NAME ?? saved?.name ?? `${os7.hostname().split(".")[0] || "runner"}`;
11262
11504
  return { apiUrl, key, name: name.replace(/[^\w.:@/-]/g, "-").slice(0, 80) };
11263
11505
  }
11264
11506
  async function call(c, method, route, body, timeoutMs = 6e4) {
@@ -11312,9 +11554,9 @@ async function runOnce(c, args, out, err) {
11312
11554
  const [job] = await lease(c, args);
11313
11555
  if (!job) break;
11314
11556
  const started = Date.now();
11315
- const scratch = fs30.mkdtempSync(path26.join(os6.tmpdir(), "bunshin-job-"));
11557
+ const scratch = fs31.mkdtempSync(path27.join(os7.tmpdir(), "bunshin-job-"));
11316
11558
  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
- () => fs30.rmSync(scratch, { recursive: true, force: true })
11559
+ () => fs31.rmSync(scratch, { recursive: true, force: true })
11318
11560
  );
11319
11561
  const model = config.backend === "codex-cli" ? config.codexModel ?? "codex default" : config.backend === "pi-cli" ? config.piModel ?? "pi default" : config.model;
11320
11562
  if (!res.ok) {
@@ -11404,24 +11646,24 @@ function renderCheck(id, c) {
11404
11646
  }
11405
11647
  function logAnswer(entry) {
11406
11648
  try {
11407
- fs30.mkdirSync(runnerHome(), { recursive: true });
11408
- fs30.appendFileSync(path26.join(runnerHome(), "log.jsonl"), `${JSON.stringify({ at: (/* @__PURE__ */ new Date()).toISOString(), ...entry })}
11649
+ fs31.mkdirSync(runnerHome(), { recursive: true });
11650
+ fs31.appendFileSync(path27.join(runnerHome(), "log.jsonl"), `${JSON.stringify({ at: (/* @__PURE__ */ new Date()).toISOString(), ...entry })}
11409
11651
  `);
11410
11652
  } catch {
11411
11653
  }
11412
11654
  }
11413
11655
  function which(name) {
11414
- for (const d of [...(process.env.PATH || "").split(path26.delimiter), path26.join(os6.homedir(), ".local", "bin")]) {
11415
- if (d && fs30.existsSync(path26.join(d, name))) return path26.join(d, name);
11656
+ for (const d of [...(process.env.PATH || "").split(path27.delimiter), path27.join(os7.homedir(), ".local", "bin")]) {
11657
+ if (d && fs31.existsSync(path27.join(d, name))) return path27.join(d, name);
11416
11658
  }
11417
11659
  return null;
11418
11660
  }
11419
11661
  function scheduledCommand(backend) {
11420
- const node = path26.dirname(process.execPath);
11421
- const npx = fs30.existsSync(path26.join(node, "npx")) ? path26.join(node, "npx") : which("npx") ?? "npx";
11662
+ const node = path27.dirname(process.execPath);
11663
+ const npx = fs31.existsSync(path27.join(node, "npx")) ? path27.join(node, "npx") : which("npx") ?? "npx";
11422
11664
  const bin = BIN_OF[backend] ? which(BIN_OF[backend]) : null;
11423
- 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"])];
11424
- return { argv: [npx, "-y", PKG2, "runner", "--once"], path: dirs.join(path26.delimiter) };
11665
+ 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"])];
11666
+ return { argv: [npx, "-y", PKG2, "runner", "--once"], path: dirs.join(path27.delimiter) };
11425
11667
  }
11426
11668
  function launchdPlist(backend, everyMinutes, home = runnerHome()) {
11427
11669
  const cmd = scheduledCommand(backend);
@@ -11436,8 +11678,8 @@ function launchdPlist(backend, everyMinutes, home = runnerHome()) {
11436
11678
  <dict><key>PATH</key><string>${xml(cmd.path)}</string></dict>
11437
11679
  <key>WorkingDirectory</key><string>${xml(home)}</string>
11438
11680
  <key>StartInterval</key><integer>${everyMinutes * 60}</integer>
11439
- <key>StandardOutPath</key><string>${xml(path26.join(home, "runner.log"))}</string>
11440
- <key>StandardErrorPath</key><string>${xml(path26.join(home, "runner.log"))}</string>
11681
+ <key>StandardOutPath</key><string>${xml(path27.join(home, "runner.log"))}</string>
11682
+ <key>StandardErrorPath</key><string>${xml(path27.join(home, "runner.log"))}</string>
11441
11683
  <key>ProcessType</key><string>Background</string>
11442
11684
  <key>LowPriorityIO</key><true/>
11443
11685
  </dict>
@@ -11448,19 +11690,19 @@ function cronLine(backend, everyMinutes, home = runnerHome()) {
11448
11690
  const cmd = scheduledCommand(backend);
11449
11691
  const when = everyMinutes >= 60 ? `17 */${Math.max(1, Math.round(everyMinutes / 60))} * * *` : `*/${everyMinutes} * * * *`;
11450
11692
  const q = (v) => `'${v.replace(/'/g, `'\\''`)}'`;
11451
- return `${when} cd ${q(home)} && PATH=${q(cmd.path)} ${cmd.argv.map(q).join(" ")} >> ${q(path26.join(home, "runner.log"))} 2>&1 ${CRON_MARK}`;
11693
+ 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
11694
  }
11453
11695
  function launchAgentsDir(opts) {
11454
- return opts.launchAgents ?? path26.join(process.env.BUNSHIN_RUNNER_HOME || os6.homedir(), "Library", "LaunchAgents");
11696
+ return opts.launchAgents ?? path27.join(process.env.BUNSHIN_RUNNER_HOME || os7.homedir(), "Library", "LaunchAgents");
11455
11697
  }
11456
11698
  function installSchedule(backend, everyMinutes, opts = {}) {
11457
11699
  const platform = opts.platform ?? process.platform;
11458
11700
  const run2 = opts.run ?? realRun;
11459
11701
  if (platform === "darwin") {
11460
11702
  const dir2 = launchAgentsDir(opts);
11461
- const plist = path26.join(dir2, `${LAUNCHD_LABEL}.plist`);
11462
- fs30.mkdirSync(dir2, { recursive: true });
11463
- fs30.writeFileSync(plist, launchdPlist(backend, everyMinutes));
11703
+ const plist = path27.join(dir2, `${LAUNCHD_LABEL}.plist`);
11704
+ fs31.mkdirSync(dir2, { recursive: true });
11705
+ fs31.writeFileSync(plist, launchdPlist(backend, everyMinutes));
11464
11706
  const domain = `gui/${process.getuid?.() ?? 501}`;
11465
11707
  run2("launchctl", ["bootout", `${domain}/${LAUNCHD_LABEL}`]);
11466
11708
  const r = run2("launchctl", ["bootstrap", domain, plist]);
@@ -11480,10 +11722,10 @@ function removeSchedule(opts = {}) {
11480
11722
  const platform = opts.platform ?? process.platform;
11481
11723
  const run2 = opts.run ?? realRun;
11482
11724
  if (platform === "darwin") {
11483
- const plist = path26.join(launchAgentsDir(opts), `${LAUNCHD_LABEL}.plist`);
11725
+ const plist = path27.join(launchAgentsDir(opts), `${LAUNCHD_LABEL}.plist`);
11484
11726
  run2("launchctl", ["bootout", `gui/${process.getuid?.() ?? 501}/${LAUNCHD_LABEL}`]);
11485
- if (!fs30.existsSync(plist)) return "no schedule";
11486
- fs30.rmSync(plist, { force: true });
11727
+ if (!fs31.existsSync(plist)) return "no schedule";
11728
+ fs31.rmSync(plist, { force: true });
11487
11729
  return `removed ${plist}`;
11488
11730
  }
11489
11731
  const current = run2("crontab", ["-l"]);
@@ -11510,10 +11752,10 @@ async function install(args, cwd, out, err, opts = {}) {
11510
11752
  }
11511
11753
  const every = Math.max(15, Number(str5(args.flags.every) ?? 60) || 60);
11512
11754
  const home = runnerHome();
11513
- fs30.mkdirSync(home, { recursive: true, mode: 448 });
11755
+ fs31.mkdirSync(home, { recursive: true, mode: 448 });
11514
11756
  const saved = { apiUrl: c.apiUrl, key: c.key, backend, ...config.model && str5(args.flags.model) ? { model: config.model } : {}, name: c.name, every };
11515
- fs30.writeFileSync(path26.join(home, "config.json"), JSON.stringify(saved, null, 2) + "\n", { mode: 384 });
11516
- fs30.chmodSync(path26.join(home, "config.json"), 384);
11757
+ fs31.writeFileSync(path27.join(home, "config.json"), JSON.stringify(saved, null, 2) + "\n", { mode: 384 });
11758
+ fs31.chmodSync(path27.join(home, "config.json"), 384);
11517
11759
  let schedule;
11518
11760
  try {
11519
11761
  schedule = installSchedule(backend, every, opts);
@@ -11526,7 +11768,7 @@ Run it yourself: npx -y ${PKG2} runner --once
11526
11768
  out(`\u2713 Runner "${c.name}" answers ${c.apiUrl}'s model jobs with ${BACKEND_NAME[backend] ?? backend} on this computer.
11527
11769
  `);
11528
11770
  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: ${path26.join(home, "runner.log")}
11771
+ ` : ` Every ${every} minutes while this computer is on (${schedule.kind}). Log: ${path27.join(home, "runner.log")}
11530
11772
  `);
11531
11773
  out(` Stop: npx -y ${PKG2} runner uninstall
11532
11774
  `);
@@ -11543,9 +11785,9 @@ Answering what waits now\u2026
11543
11785
  function uninstall(out, opts = {}) {
11544
11786
  out(`${removeSchedule(opts)}
11545
11787
  `);
11546
- const file2 = path26.join(runnerHome(), "config.json");
11547
- if (fs30.existsSync(file2)) {
11548
- fs30.rmSync(file2, { force: true });
11788
+ const file2 = path27.join(runnerHome(), "config.json");
11789
+ if (fs31.existsSync(file2)) {
11790
+ fs31.rmSync(file2, { force: true });
11549
11791
  out(`removed ${file2} (revoke the key in the console: Agent keys)
11550
11792
  `);
11551
11793
  }
@@ -11725,7 +11967,7 @@ async function cmdRunner(args, cwd, out, err, opts = {}) {
11725
11967
  out(text2);
11726
11968
  return 0;
11727
11969
  }
11728
- fs30.writeFileSync(file2, text2, { mode: 384 });
11970
+ fs31.writeFileSync(file2, text2, { mode: 384 });
11729
11971
  const left = Math.round((Date.parse(job.leaseUntil) - Date.now()) / 6e4);
11730
11972
  out(
11731
11973
  [
@@ -11743,7 +11985,7 @@ async function cmdRunner(args, cwd, out, err, opts = {}) {
11743
11985
  const id = args._[2];
11744
11986
  const file2 = args._[3] ?? "-";
11745
11987
  if (!id) throw new Error("usage: bunshin runner validate <job id> <file|->");
11746
- const text2 = file2 === "-" ? fs30.readFileSync(0, "utf8") : fs30.readFileSync(file2, "utf8");
11988
+ const text2 = file2 === "-" ? fs31.readFileSync(0, "utf8") : fs31.readFileSync(file2, "utf8");
11747
11989
  const r = await call(c, "POST", `/jobs/${id}/check`, { answer: text2, runner: c.name }, 12e4);
11748
11990
  out(renderCheck(id, r.body));
11749
11991
  return r.body.ok ? 0 : 1;
@@ -11752,7 +11994,7 @@ async function cmdRunner(args, cwd, out, err, opts = {}) {
11752
11994
  const id = args._[2];
11753
11995
  const file2 = args._[3] ?? "-";
11754
11996
  if (!id) throw new Error("usage: bunshin runner submit <job id> <file|-> [--force]");
11755
- const text2 = file2 === "-" ? fs30.readFileSync(0, "utf8") : fs30.readFileSync(file2, "utf8");
11997
+ const text2 = file2 === "-" ? fs31.readFileSync(0, "utf8") : fs31.readFileSync(file2, "utf8");
11756
11998
  const check = await call(c, "POST", `/jobs/${id}/check`, { answer: text2, runner: c.name }, 12e4).catch(() => null);
11757
11999
  if (check?.body && (check.status < 400 || check.body.problems)) {
11758
12000
  out(renderCheck(id, check.body));
@@ -11776,7 +12018,7 @@ async function cmdRunner(args, cwd, out, err, opts = {}) {
11776
12018
  const since = Date.parse(str5(args.flags.since) ?? "") || Date.now() - 12 * 36e5;
11777
12019
  const entries = (() => {
11778
12020
  try {
11779
- 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);
12021
+ 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
12022
  } catch {
11781
12023
  return [];
11782
12024
  }
@@ -11846,8 +12088,8 @@ var init_runner = __esm({
11846
12088
 
11847
12089
  // src/v2/importer.ts
11848
12090
  import { execFileSync as execFileSync7 } from "node:child_process";
11849
- import fs31 from "node:fs";
11850
- import path27 from "node:path";
12091
+ import fs32 from "node:fs";
12092
+ import path28 from "node:path";
11851
12093
  function rewriteRepoPaths(text2, repoName2, pack) {
11852
12094
  const re = new RegExp(`(?<=^|[\\s\`'"(=:])(?:~|\\$\\{?[A-Za-z_][A-Za-z0-9_]*\\}?)?(?:/[\\w.@+-]+)*/${escapeRe(repoName2)}(?=[/\\s\`'")\\]]|[.,;:](?:\\s|$)|$)`, "gm");
11853
12095
  return text2.replace(re, `~/.bunshin/library/${pack}`);
@@ -11886,7 +12128,7 @@ function buildDocs(files, opts) {
11886
12128
  const main2 = `${dir2}/SKILL.md`;
11887
12129
  const text2 = rw(files.get(main2).content);
11888
12130
  const fm = frontmatterDescription(text2);
11889
- const name = path27.posix.basename(dir2);
12131
+ const name = path28.posix.basename(dir2);
11890
12132
  const bundle = {};
11891
12133
  for (const p of all.filter((x) => x.startsWith(`${dir2}/`))) {
11892
12134
  claimed.add(p);
@@ -11984,22 +12226,22 @@ function isGitRepo(root) {
11984
12226
  function workingTreeFiles(root) {
11985
12227
  const out = /* @__PURE__ */ new Map();
11986
12228
  const list2 = isGitRepo(root) ? git4(root, ["ls-files", "-z"]).split("\0").filter(Boolean) : (function walk(dir2, base = "") {
11987
- return fs31.readdirSync(dir2, { withFileTypes: true }).flatMap((e) => {
12229
+ return fs32.readdirSync(dir2, { withFileTypes: true }).flatMap((e) => {
11988
12230
  if (e.name === ".git" || e.name === "node_modules") return [];
11989
12231
  const rel = base ? `${base}/${e.name}` : e.name;
11990
- return e.isDirectory() ? walk(path27.join(dir2, e.name), rel) : e.isFile() ? [rel] : [];
12232
+ return e.isDirectory() ? walk(path28.join(dir2, e.name), rel) : e.isFile() ? [rel] : [];
11991
12233
  });
11992
12234
  })(root);
11993
12235
  for (const rel of list2) {
11994
- const abs = path27.join(root, rel);
12236
+ const abs = path28.join(root, rel);
11995
12237
  let buf;
11996
12238
  try {
11997
- buf = fs31.readFileSync(abs);
12239
+ buf = fs32.readFileSync(abs);
11998
12240
  } catch {
11999
12241
  continue;
12000
12242
  }
12001
12243
  if (!isText(buf)) continue;
12002
- const exec = (fs31.statSync(abs).mode & 73) !== 0;
12244
+ const exec = (fs32.statSync(abs).mode & 73) !== 0;
12003
12245
  out.set(rel, { content: buf.toString("utf8"), ...exec ? { mode: "x" } : {} });
12004
12246
  }
12005
12247
  return out;
@@ -12033,7 +12275,7 @@ function diffDocs(prev, next) {
12033
12275
  return { docs: next.filter((d) => before.get(d.path) !== fingerprint(d)), removed: [...before.keys()].filter((p) => !after.has(p)) };
12034
12276
  }
12035
12277
  function readSkillSystem(root, opts) {
12036
- const repoName2 = path27.basename(path27.resolve(root));
12278
+ const repoName2 = path28.basename(path28.resolve(root));
12037
12279
  const build = (files2) => buildDocs(files2, { pack: opts.pack, repoName: repoName2, ...opts.rewrite === false ? { rewrite: false } : {} });
12038
12280
  const tree = build(workingTreeFiles(root));
12039
12281
  if (!opts.history || !isGitRepo(root)) return { versions: [{ summary: `import ${opts.pack}`, docs: tree, removed: [], complete: true }], docs: tree };
@@ -12110,7 +12352,7 @@ var init_importer = __esm({
12110
12352
  escapeRe = (s) => s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
12111
12353
  looksGenerated = (text2) => /generated by|do not edit( by hand)?/i.test(text2.slice(0, 600));
12112
12354
  isStopHook = (text2) => /"decision"\s*:\s*"block"|decision.{0,4}block/.test(text2) && /REASON=/.test(text2);
12113
- isUpdateHook = (p, text2) => /auto-?update/i.test(path27.basename(p)) || /git (pull|fetch)/.test(text2) && /SessionStart|session start/i.test(text2);
12355
+ isUpdateHook = (p, text2) => /auto-?update/i.test(path28.basename(p)) || /git (pull|fetch)/.test(text2) && /SessionStart|session start/i.test(text2);
12114
12356
  fingerprint = (d) => JSON.stringify(d);
12115
12357
  REWRITE_SYSTEM = `You adapt a company's skill documents after its skill system moved into Bunshin.
12116
12358
 
@@ -12146,8 +12388,8 @@ __export(skills_exports, {
12146
12388
  cmdSkill: () => cmdSkill,
12147
12389
  parsePin: () => parsePin
12148
12390
  });
12149
- import fs32 from "node:fs";
12150
- import path28 from "node:path";
12391
+ import fs33 from "node:fs";
12392
+ import path29 from "node:path";
12151
12393
  function requireOnline(store, what) {
12152
12394
  if (!canCall(store.config())) throw new Error(`${what} needs the hosted library: run \`bunshin setup\` first`);
12153
12395
  }
@@ -12156,9 +12398,9 @@ async function cmdImport2(store, args, cwd, out, err) {
12156
12398
  err("usage: bunshin import skills <dir> [--pack <name>] [--layer org|team:<unit>] [--owner-team <unit>] [--no-history] [--dry-run] [--propose-rewrites]\n");
12157
12399
  return 1;
12158
12400
  }
12159
- const root = path28.resolve(cwd, args._[2]);
12160
- if (!fs32.existsSync(root)) throw new Error(`${root} does not exist`);
12161
- const pack = str6(args.flags.pack) ?? path28.basename(root);
12401
+ const root = path29.resolve(cwd, args._[2]);
12402
+ if (!fs33.existsSync(root)) throw new Error(`${root} does not exist`);
12403
+ const pack = str6(args.flags.pack) ?? path29.basename(root);
12162
12404
  const history = args.flags.history !== false && !bool4(args.flags["no-history"]);
12163
12405
  const read = readSkillSystem(root, { pack, history, ...str6(args.flags.since) ? { since: str6(args.flags.since) } : {} });
12164
12406
  const kinds = /* @__PURE__ */ new Map();
@@ -12193,7 +12435,7 @@ async function cmdImport2(store, args, cwd, out, err) {
12193
12435
  const propose = args.flags["propose-rewrites"];
12194
12436
  if (propose) {
12195
12437
  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, path28.basename(root), out, err);
12438
+ await proposeRewrites(store, read.docs.filter((d) => !only.length || only.some((o) => d.path.includes(o))), pack, path29.basename(root), out, err);
12197
12439
  }
12198
12440
  out("Run `bunshin sync` on each machine (it runs at session start) to install the skills, instructions and files.\n");
12199
12441
  return 0;
@@ -12333,7 +12575,7 @@ ${report.skills} skills, ${report.references} references, ${report.errors.length
12333
12575
  }
12334
12576
  const graph = str6(args.flags.graph) ?? (bool4(args.flags.graph) ? "SKILLS-GRAPH.md" : void 0);
12335
12577
  if (graph) {
12336
- fs32.writeFileSync(path28.resolve(cwd, graph), renderSkillGraph(report));
12578
+ fs33.writeFileSync(path29.resolve(cwd, graph), renderSkillGraph(report));
12337
12579
  out(`graph written to ${graph}
12338
12580
  `);
12339
12581
  }
@@ -12403,8 +12645,8 @@ async function splitSkill(store, args, skill, name, out, err) {
12403
12645
  const files = splitPaths(v2, skill.skill.name);
12404
12646
  const sourceWords = words3(skill.body.slice(parseFrontmatter2(skill.body).bodyStart));
12405
12647
  if (bool4(args.flags.submit)) {
12406
- if (!fs32.existsSync(files.json)) throw new Error(`no split of ${skill.skill.name} yet: run \`bunshin skill split ${skill.skill.name}\` first`);
12407
- const f2 = JSON.parse(fs32.readFileSync(files.json, "utf8"));
12648
+ if (!fs33.existsSync(files.json)) throw new Error(`no split of ${skill.skill.name} yet: run \`bunshin skill split ${skill.skill.name}\` first`);
12649
+ const f2 = JSON.parse(fs33.readFileSync(files.json, "utf8"));
12408
12650
  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
12651
  const plan2 = parseSplit(f2.plan);
12410
12652
  if (!plan2) throw new Error(`${files.json} holds no spine`);
@@ -12415,7 +12657,7 @@ async function splitSkill(store, args, skill, name, out, err) {
12415
12657
  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
12658
  }
12417
12659
  const made = splitSuggestions(v2, config, skill, plan2);
12418
- fs32.rmSync(files.json, { force: true });
12660
+ fs33.rmSync(files.json, { force: true });
12419
12661
  if (!canCall(config)) {
12420
12662
  out(`${made} suggestions queued (${plan2.units.length} atoms and the spine); they leave with the next sync and wait for owner review.
12421
12663
  `);
@@ -12440,9 +12682,9 @@ async function splitSkill(store, args, skill, name, out, err) {
12440
12682
  if (!plan) throw new Error("the model's answer holds no spine");
12441
12683
  const coverage = splitCoverage(skill.body, [plan.spine, ...plan.units]);
12442
12684
  const f = { skill: skill.id, name: skill.skill.name, version: skill.version, at: (/* @__PURE__ */ new Date()).toISOString(), plan, coverage };
12443
- fs32.mkdirSync(path28.dirname(files.json), { recursive: true });
12444
- fs32.writeFileSync(files.json, JSON.stringify(f, null, 2));
12445
- fs32.writeFileSync(files.md, splitPreview(f, sourceWords));
12685
+ fs33.mkdirSync(path29.dirname(files.json), { recursive: true });
12686
+ fs33.writeFileSync(files.json, JSON.stringify(f, null, 2));
12687
+ fs33.writeFileSync(files.md, splitPreview(f, sourceWords));
12446
12688
  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
12689
  `);
12448
12690
  out(`Read ${files.md}; edit ${files.json} if needed; then send it with \`bunshin skill split ${skill.skill.name} --submit\`.
@@ -12549,9 +12791,9 @@ async function cmdLibrary(store, args, cwd, out, err) {
12549
12791
  `;
12550
12792
  const file2 = str6(args.flags.write) ?? (bool4(args.flags.write) ? ".claude/skills-version" : void 0);
12551
12793
  if (file2) {
12552
- const abs = path28.resolve(cwd, file2);
12553
- fs32.mkdirSync(path28.dirname(abs), { recursive: true });
12554
- fs32.writeFileSync(abs, line);
12794
+ const abs = path29.resolve(cwd, file2);
12795
+ fs33.mkdirSync(path29.dirname(abs), { recursive: true });
12796
+ fs33.writeFileSync(abs, line);
12555
12797
  out(`${file2}: ${line}`);
12556
12798
  } else out(line);
12557
12799
  return 0;
@@ -12561,12 +12803,12 @@ async function cmdLibrary(store, args, cwd, out, err) {
12561
12803
  const to = str6(args.flags.to);
12562
12804
  if (!to) throw new Error("--to <dir> is required");
12563
12805
  const pinFile = str6(args.flags.pin);
12564
- const pin = str6(args.flags.git) ? { git: str6(args.flags.git) } : pinFile ? parsePin(fs32.readFileSync(path28.resolve(cwd, pinFile), "utf8")) : parsePin(args._[2] ?? "");
12806
+ const pin = str6(args.flags.git) ? { git: str6(args.flags.git) } : pinFile ? parsePin(fs33.readFileSync(path29.resolve(cwd, pinFile), "utf8")) : parsePin(args._[2] ?? "");
12565
12807
  const q = pin.git ? `git=${pin.git}` : pin.version ? `version=${pin.version}` : "";
12566
12808
  if (!q) throw new Error("name a version: lib@N, --git <sha>, or --pin <file>");
12567
12809
  const snap = await v2api(config, "GET", `/library/snapshot?${q}`, void 0, { timeoutMs: 12e4 });
12568
- const dir2 = path28.resolve(cwd, to);
12569
- if (fs32.existsSync(dir2) && fs32.readdirSync(dir2).length && !bool4(args.flags.force)) throw new Error(`${dir2} is not empty (use --force)`);
12810
+ const dir2 = path29.resolve(cwd, to);
12811
+ if (fs33.existsSync(dir2) && fs33.readdirSync(dir2).length && !bool4(args.flags.force)) throw new Error(`${dir2} is not empty (use --force)`);
12570
12812
  const pack = str6(args.flags.pack);
12571
12813
  const docs = snap.sections.filter((s) => !pack || s.pack === pack);
12572
12814
  const res = materialize(docs, dir2);
@@ -12597,7 +12839,7 @@ var init_skills = __esm({
12597
12839
  skillsOf = (sections) => sections.filter((s) => s.skill && (s.status === "active" || s.status === "stale"));
12598
12840
  words3 = (t) => t.split(/\s+/).filter(Boolean).length;
12599
12841
  splitPaths = (v2, name) => {
12600
- const base = path28.join(v2.dir, "split", name.replace(/[^\w.-]/g, "_"));
12842
+ const base = path29.join(v2.dir, "split", name.replace(/[^\w.-]/g, "_"));
12601
12843
  return { json: `${base}.json`, md: `${base}.md` };
12602
12844
  };
12603
12845
  }
@@ -12610,27 +12852,27 @@ __export(reflect_exports, {
12610
12852
  buildLesson: () => buildLesson,
12611
12853
  runReflection: () => runReflection
12612
12854
  });
12613
- import fs33 from "node:fs";
12614
- import path29 from "node:path";
12615
- import { createHash as createHash10 } from "node:crypto";
12855
+ import fs34 from "node:fs";
12856
+ import path30 from "node:path";
12857
+ import { createHash as createHash11 } from "node:crypto";
12616
12858
  async function runReflection(store, opts) {
12617
12859
  const empty = { lessonIds: [], used: [], missed: [], attribution: [] };
12618
- const lock = path29.join(store.root, `reflect-${createHash10("sha256").update(opts.sessionId).digest("hex")}.lock`);
12860
+ const lock = path30.join(store.root, `reflect-${createHash11("sha256").update(opts.sessionId).digest("hex")}.lock`);
12619
12861
  const deadline = Date.now() + 66e4;
12620
12862
  for (; ; ) {
12621
12863
  try {
12622
- fs33.writeFileSync(lock, String(process.pid), { flag: "wx", mode: 384 });
12864
+ fs34.writeFileSync(lock, String(process.pid), { flag: "wx", mode: 384 });
12623
12865
  break;
12624
12866
  } catch (error) {
12625
12867
  if (error.code !== "EEXIST") throw error;
12626
12868
  try {
12627
- const owner = Number(fs33.readFileSync(lock, "utf8"));
12869
+ const owner = Number(fs34.readFileSync(lock, "utf8"));
12628
12870
  if (Number.isInteger(owner) && owner > 0) {
12629
12871
  try {
12630
12872
  process.kill(owner, 0);
12631
12873
  } catch (error2) {
12632
12874
  if (error2.code === "ESRCH") {
12633
- fs33.unlinkSync(lock);
12875
+ fs34.unlinkSync(lock);
12634
12876
  continue;
12635
12877
  }
12636
12878
  }
@@ -12645,7 +12887,7 @@ async function runReflection(store, opts) {
12645
12887
  return await reflectSession(store, opts);
12646
12888
  } finally {
12647
12889
  try {
12648
- fs33.unlinkSync(lock);
12890
+ fs34.unlinkSync(lock);
12649
12891
  } catch {
12650
12892
  }
12651
12893
  }
@@ -12988,8 +13230,8 @@ __export(cli_exports, {
12988
13230
  setupMod: () => setupMod,
12989
13231
  version: () => version
12990
13232
  });
12991
- import fs34 from "node:fs";
12992
- import path30 from "node:path";
13233
+ import fs35 from "node:fs";
13234
+ import path31 from "node:path";
12993
13235
  function parseArgs(argv) {
12994
13236
  const out = { _: [], flags: {} };
12995
13237
  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 +13340,7 @@ async function main(argv, opts = {}) {
13098
13340
  out(result.mcp.error ? `! bunshin MCP server not registered (${result.mcp.error}); sessions still learn and recall through the hooks.
13099
13341
  ` : "bunshin MCP server registered for this user.\n");
13100
13342
  for (const command of [result.learnCommand, result.borrowCommand]) {
13101
- if (command.error) err(`! ${path30.basename(command.file, ".md")} not installed at ${command.file}: ${command.error}
13343
+ if (command.error) err(`! ${path31.basename(command.file, ".md")} not installed at ${command.file}: ${command.error}
13102
13344
  `);
13103
13345
  }
13104
13346
  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 +13353,18 @@ async function main(argv, opts = {}) {
13111
13353
  }
13112
13354
  if (cmd === "setup") {
13113
13355
  try {
13114
- const { setupProject: setupProject2, executable: executable2, readKey: readKey2 } = await Promise.resolve().then(() => (init_setup(), setup_exports));
13115
- const harness = str7(args.flags.harness);
13116
- if (harness !== "codex" && harness !== "claude-code" && harness !== "pi") throw new Error("Choose your agent: bunshin setup --harness codex, claude-code, or pi.");
13356
+ const { setupProject: setupProject2, executable: executable2, chooseHarness: chooseHarness2, apiAddress: apiAddress2, HOSTED_API: HOSTED_API3 } = await Promise.resolve().then(() => (init_setup(), setup_exports));
13357
+ const flag = str7(args.flags.harness);
13358
+ 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).");
13359
+ const harness = flag ? flag : await chooseHarness2(out);
13117
13360
  const agent = harness === "claude-code" ? "claude" : harness;
13118
13361
  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(path30.join(cwd, ".bunshin"));
13362
+ const prior = new Store(path31.join(cwd, ".bunshin"));
13120
13363
  const existing = prior.trusted ? prior.config() : { apiUrl: "", apiKey: void 0 };
13121
13364
  const apiUrl = str7(args.flags["api-url"]);
13122
- const key = bool5(args.flags["key-stdin"]) ? await new Promise((resolve, reject) => {
13365
+ const address = apiAddress2(apiUrl ?? HOSTED_API3);
13366
+ const relogin = bool5(args.flags.login);
13367
+ const given = bool5(args.flags["key-stdin"]) ? await new Promise((resolve, reject) => {
13123
13368
  let value = "";
13124
13369
  process.stdin.setEncoding("utf8");
13125
13370
  process.stdin.on("data", (chunk) => {
@@ -13127,7 +13372,11 @@ async function main(argv, opts = {}) {
13127
13372
  });
13128
13373
  process.stdin.on("end", () => resolve(value.trim()));
13129
13374
  process.stdin.on("error", reject);
13130
- }) : process.env.BUNSHIN_API_KEY || (!apiUrl || apiUrl === existing.apiUrl) && existing.apiKey || await readKey2();
13375
+ }) : process.env.BUNSHIN_API_KEY || !relogin && (!apiUrl || apiUrl === existing.apiUrl) && existing.apiKey || void 0;
13376
+ const { readLogin: readLogin2, saveLogin: saveLogin2 } = await Promise.resolve().then(() => (init_login(), login_exports));
13377
+ const signedIn = given || relogin ? void 0 : readLogin2(address)?.apiKey;
13378
+ const fresh = given || signedIn ? void 0 : await signIn(address, harness, out);
13379
+ const key = given || signedIn || fresh;
13131
13380
  const hooksFlag = str7(args.flags.hooks);
13132
13381
  if (hooksFlag && hooksFlag !== "user" && hooksFlag !== "project") throw new Error("--hooks must be user (every session under this folder) or project (this folder only)");
13133
13382
  const only = str7(args.flags.only);
@@ -13145,8 +13394,9 @@ async function main(argv, opts = {}) {
13145
13394
  });
13146
13395
  if (result.config.hooks === "user" && !only && !exclude && !bool5(args.flags.all) && process.stdin.isTTY && !bool5(args.flags["key-stdin"])) {
13147
13396
  const { askSources: askSources2 } = await Promise.resolve().then(() => (init_setup(), setup_exports));
13148
- await askSources2(new Store(path30.join(cwd, ".bunshin")), out);
13397
+ await askSources2(new Store(path31.join(cwd, ".bunshin")), out);
13149
13398
  }
13399
+ if (fresh) saveLogin2({ apiUrl: address, apiKey: key, orgId: result.profile.orgId, userId: result.profile.userId });
13150
13400
  out(`Connected as ${result.profile.role}${result.profile.orgUnit ? ` in ${result.profile.orgUnit}` : " (company-wide)"}.
13151
13401
  `);
13152
13402
  out(result.config.hooks === "user" ? `Folder: ${cwd} (every session in it or below it uses this workspace)
@@ -13179,11 +13429,41 @@ Key saved privately outside the project.
13179
13429
  return 1;
13180
13430
  }
13181
13431
  }
13432
+ if (cmd === "login") {
13433
+ try {
13434
+ const { apiAddress: apiAddress2, connectionProfile: connectionProfile2, HOSTED_API: HOSTED_API3 } = await Promise.resolve().then(() => (init_setup(), setup_exports));
13435
+ const { saveLogin: saveLogin2 } = await Promise.resolve().then(() => (init_login(), login_exports));
13436
+ const address = apiAddress2(str7(args.flags["api-url"]) ?? HOSTED_API3);
13437
+ if (bool5(args.flags["no-wait"])) {
13438
+ const { deviceLogin: deviceLogin2 } = await Promise.resolve().then(() => (init_login(), login_exports));
13439
+ await deviceLogin2({ apiUrl: address, client: `bunshin ${version()} (login)`, out, noWait: true });
13440
+ return 0;
13441
+ }
13442
+ const key = await signIn(address, "login", out);
13443
+ const profile = await connectionProfile2(address, key);
13444
+ const file2 = saveLogin2({ apiUrl: address, apiKey: key, orgId: profile.orgId, userId: profile.userId });
13445
+ out(`Signed in as ${profile.role}${profile.orgUnit ? ` in ${profile.orgUnit}` : ""}. Saved privately in ${file2}.
13446
+ Run bunshin setup in any project to connect it; nothing more to paste.
13447
+ `);
13448
+ return 0;
13449
+ } catch (error) {
13450
+ err(`bunshin login: ${error instanceof Error ? error.message : String(error)}
13451
+ `);
13452
+ return 1;
13453
+ }
13454
+ }
13455
+ if (cmd === "logout") {
13456
+ const { apiAddress: apiAddress2, HOSTED_API: HOSTED_API3 } = await Promise.resolve().then(() => (init_setup(), setup_exports));
13457
+ const { forgetLogin: forgetLogin2 } = await Promise.resolve().then(() => (init_login(), login_exports));
13458
+ const forgot = forgetLogin2(apiAddress2(str7(args.flags["api-url"]) ?? HOSTED_API3));
13459
+ 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");
13460
+ return 0;
13461
+ }
13182
13462
  if (cmd === "init") return cmdInit(args, cwd, out, err);
13183
13463
  if (cmd === "mcp") {
13184
13464
  const { runMcpServer: runMcpServer2 } = await Promise.resolve().then(() => (init_mcp(), mcp_exports));
13185
13465
  const root = str7(args.flags.root);
13186
- await runMcpServer2({ cwd, ...root ? { store: new Store(path30.resolve(root)) } : {}, version: version() });
13466
+ await runMcpServer2({ cwd, ...root ? { store: new Store(path31.resolve(root)) } : {}, version: version() });
13187
13467
  return 0;
13188
13468
  }
13189
13469
  if (cmd === "demo") {
@@ -13297,7 +13577,7 @@ ${HELP2}`);
13297
13577
  function openStore(args, cwd) {
13298
13578
  const root = str7(args.flags.root);
13299
13579
  if (root) {
13300
- const store = new Store(path30.resolve(root));
13580
+ const store = new Store(path31.resolve(root));
13301
13581
  store.ensureLayout();
13302
13582
  return store;
13303
13583
  }
@@ -13313,7 +13593,7 @@ async function cmdInit(args, cwd, out, err) {
13313
13593
  orgId: str7(args.flags["org-id"]),
13314
13594
  userId: str7(args.flags["user-id"]),
13315
13595
  apiUrl: str7(args.flags["api-url"]),
13316
- apiKey: bool5(args.flags["key-stdin"]) ? fs34.readFileSync(0, "utf8").trim() || void 0 : str7(args.flags["api-key"]),
13596
+ apiKey: bool5(args.flags["key-stdin"]) ? fs35.readFileSync(0, "utf8").trim() || void 0 : str7(args.flags["api-key"]),
13317
13597
  scope: bool5(args.flags.global) ? "global" : str7(args.flags.scope),
13318
13598
  harness,
13319
13599
  noHooks: args.flags.hooks === false || bool5(args.flags["no-hooks"]),
@@ -13356,10 +13636,10 @@ function cmdStatus(store, args, out, v2) {
13356
13636
  const conflicts = store.listConflicts().filter((c) => c.status === "open");
13357
13637
  const metrics = store.readMetrics(void 0);
13358
13638
  const last50 = metrics?.windows?.find((w) => w.name === "last50");
13359
- 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")] : [];
13639
+ 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
13640
  const hooks = config.harness === "pi" ? hookFiles.filter((file2) => {
13361
13641
  try {
13362
- return fs34.readFileSync(file2, "utf8").startsWith("// Managed by Bunshin setup.");
13642
+ return fs35.readFileSync(file2, "utf8").startsWith("// Managed by Bunshin setup.");
13363
13643
  } catch {
13364
13644
  return false;
13365
13645
  }
@@ -13378,7 +13658,7 @@ function cmdStatus(store, args, out, v2) {
13378
13658
  llmBackend: resolveBackend(config) ?? "none (set ANTHROPIC_API_KEY or install the claude/codex CLI)",
13379
13659
  recallRouter: recallRouter(config),
13380
13660
  hooks: { [config.harness]: hooks },
13381
- hookFiles: hookFiles.filter((file2) => fs34.existsSync(file2)),
13661
+ hookFiles: hookFiles.filter((file2) => fs35.existsSync(file2)),
13382
13662
  recallQuality: last50 ? { precision: last50.precision, recall: last50.recall, f1: last50.f1, traces: last50.traces } : null,
13383
13663
  v2
13384
13664
  };
@@ -13431,7 +13711,7 @@ function cmdStatus(store, args, out, v2) {
13431
13711
  }
13432
13712
  function hookCount(file2) {
13433
13713
  try {
13434
- const raw = JSON.parse(fs34.readFileSync(file2, "utf8"));
13714
+ const raw = JSON.parse(fs35.readFileSync(file2, "utf8"));
13435
13715
  let n = 0;
13436
13716
  for (const groups of Object.values(raw.hooks ?? {})) {
13437
13717
  for (const g of groups ?? []) {
@@ -13551,7 +13831,7 @@ function cmdLessonAdd(store, args, out, err) {
13551
13831
  let content = str7(args.flags.content) ?? "";
13552
13832
  if (!content || content === "-" || args._.includes("-")) {
13553
13833
  try {
13554
- content = fs34.readFileSync(0, "utf8");
13834
+ content = fs35.readFileSync(0, "utf8");
13555
13835
  } catch {
13556
13836
  }
13557
13837
  }
@@ -13617,7 +13897,7 @@ async function cmdReflect(store, args, cwd, out, err) {
13617
13897
  }
13618
13898
  const { runReflection: runReflection2 } = await Promise.resolve().then(() => (init_reflect4(), reflect_exports));
13619
13899
  const result = await runReflection2(store, {
13620
- sessionId: str7(args.flags.session) ?? path30.basename(transcript).replace(/\.jsonl?$/, ""),
13900
+ sessionId: str7(args.flags.session) ?? path31.basename(transcript).replace(/\.jsonl?$/, ""),
13621
13901
  transcriptPath: transcript,
13622
13902
  cwd,
13623
13903
  force: bool5(args.flags.force)
@@ -13720,6 +14000,20 @@ async function cmdConflict(store, args, out, err) {
13720
14000
  }
13721
14001
  return 0;
13722
14002
  }
14003
+ async function signIn(apiUrl, harness, out) {
14004
+ const { deviceLogin: deviceLogin2, DeviceLoginUnavailable: DeviceLoginUnavailable2 } = await Promise.resolve().then(() => (init_login(), login_exports));
14005
+ try {
14006
+ const r = await deviceLogin2({ apiUrl, client: `bunshin ${version()} (${harness})`, out });
14007
+ if (!r) throw new Error("The computer was not approved.");
14008
+ return r.key;
14009
+ } catch (error) {
14010
+ if (!(error instanceof DeviceLoginUnavailable2)) throw error;
14011
+ out(`${error.message} Paste an agent key instead (Agent keys, in the console).
14012
+ `);
14013
+ const { readKey: readKey2 } = await Promise.resolve().then(() => (init_setup(), setup_exports));
14014
+ return readKey2();
14015
+ }
14016
+ }
13723
14017
  function store0HasKey(store) {
13724
14018
  return !!store.config().apiKey;
13725
14019
  }
@@ -13732,8 +14026,8 @@ async function setupMod(config) {
13732
14026
  if (installedModVersion2() === v) return `Bunshin UI: bunshin-ui ${v} is installed (a band above the prompt, /bunshin).
13733
14027
  `;
13734
14028
  try {
13735
- fs34.mkdirSync(modHome2(), { recursive: true });
13736
- fs34.writeFileSync(path30.join(modHome2(), `.attempted-${v}`), nowIso());
14029
+ fs35.mkdirSync(modHome2(), { recursive: true });
14030
+ fs35.writeFileSync(path31.join(modHome2(), `.attempted-${v}`), nowIso());
13737
14031
  const res = installMod2(v);
13738
14032
  if (res.steps.some((st) => st.ok && /plugin (install|update)/.test(st.command))) {
13739
14033
  return `Bunshin UI: bunshin-ui ${v} installed (a band above the prompt, /bunshin). It needs Claude Code mods on your account.
@@ -13763,9 +14057,13 @@ var init_cli = __esm({
13763
14057
 
13764
14058
  Usage: bunshin <command> [options]
13765
14059
 
13766
- setup --harness codex|claude-code|pi connect this project to your hosted workspace
13767
- --api-url <url> --no-hooks paste the key at the hidden prompt; profile is read from Bunshin
13768
- --key-stdin read the key from stdin (for automated setup)
14060
+ setup connect this project: finds your agent (Claude Code, Codex or Pi),
14061
+ and the first time on this computer opens the console to approve
14062
+ it (no key to copy); later projects connect without asking
14063
+ --harness codex|claude-code|pi pick the agent when several are installed
14064
+ --login approve again (another workspace: select it in the console first)
14065
+ --api-url <url> --no-hooks a self-hosted workspace; hooks off
14066
+ --key-stdin read an agent key from stdin (for automated setup)
13769
14067
  --hooks user a folder of projects: hooks in your user settings, so every
13770
14068
  session under this folder uses its workspace (default: project)
13771
14069
  --only a,b | --exclude c | --all
@@ -13777,6 +14075,9 @@ Usage: bunshin <command> [options]
13777
14075
  setup --robot --robot-id <id> --arm so101 --gripper <g> --mount <m> --cameras scene,wrist
13778
14076
  --domain <d> --site <s> --cell <c> [--depth] [--api-url <url>] [--harness claude-code]
13779
14077
  register this machine as a robot context (x-bunshin-context)
14078
+ login [--api-url <url>] approve this computer in the browser once; setup then needs no key
14079
+ --no-wait print the link and return (an agent running setup); setup then waits
14080
+ logout forget this computer's sign-in (revoke keys under Agent keys)
13780
14081
  init create a local store and configure the selected harness
13781
14082
  --role <r> --org-unit <u> --org-id <id> --user-id <id>
13782
14083
  --api-url <url> --api-key <key> (or --key-stdin) --scope repo|global (--global)
@@ -13853,7 +14154,7 @@ Global: --root <dir> (use this .bunshin store) --version --help
13853
14154
  Env: BUNSHIN_API_KEY, BUNSHIN_API_URL (setup --env), BUNSHIN_HARNESS, BUNSHIN_DISABLE, BUNSHIN_CHILD, BUNSHIN_CLAUDE_BIN,
13854
14155
  CLAUDE_CODE_SESSION_ID (learn / mcp session), ANTHROPIC_API_KEY (non-fork reflection)
13855
14156
  `;
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 ${path30.dirname(root)} to trust it.`;
14157
+ 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
14158
  }
13858
14159
  });
13859
14160