@bunshin-cc/bunshin 0.13.0 → 0.14.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/dist/bin.js +102 -39
  2. 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
  }
@@ -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);
@@ -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
 
@@ -3539,6 +3575,16 @@ var init_adopt = __esm({
3539
3575
  }
3540
3576
  });
3541
3577
 
3578
+ // ../core/src/v2/dream.ts
3579
+ var init_dream = __esm({
3580
+ "../core/src/v2/dream.ts"() {
3581
+ "use strict";
3582
+ init_merge();
3583
+ init_guidelines();
3584
+ init_reconcile();
3585
+ }
3586
+ });
3587
+
3542
3588
  // ../core/src/v2/index.ts
3543
3589
  var init_v2 = __esm({
3544
3590
  "../core/src/v2/index.ts"() {
@@ -3566,6 +3612,7 @@ var init_v2 = __esm({
3566
3612
  init_scopes();
3567
3613
  init_generalize();
3568
3614
  init_adopt();
3615
+ init_dream();
3569
3616
  }
3570
3617
  });
3571
3618
 
@@ -3858,7 +3905,7 @@ function matchingRecallLessons(task, rules) {
3858
3905
  }
3859
3906
  function prepareRecall(inputs, request, profile, rules = [], opts = {}) {
3860
3907
  const recallLessons = matchingRecallLessons(request.task, rules);
3861
- const byId = /* @__PURE__ */ new Map();
3908
+ const byId2 = /* @__PURE__ */ new Map();
3862
3909
  for (const { lesson, relevance } of inputs) {
3863
3910
  if (!canSee(lesson, profile) || !["active", "stale", "conflicted"].includes(lesson.status) || opts.excludeIds?.has(lesson.id)) continue;
3864
3911
  const lexical = lexicalRelevance(lesson, request.task);
@@ -3875,10 +3922,10 @@ function prepareRecall(inputs, request, profile, rules = [], opts = {}) {
3875
3922
  if (Math.max(taskRelevance, expanded) <= 0) continue;
3876
3923
  const result = score(lesson, request, profile, Math.max(taskRelevance, expanded), opts);
3877
3924
  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);
3925
+ const previous = byId2.get(lesson.id);
3926
+ if (!previous || previous.lesson.version < lesson.version || previous.lesson.version === lesson.version && previous.score < candidate.score) byId2.set(lesson.id, candidate);
3880
3927
  }
3881
- const candidates = [...byId.values()].sort((a, b) => b.score - a.score || a.lessonId.localeCompare(b.lessonId)).slice(0, opts.poolSize ?? 30);
3928
+ const candidates = [...byId2.values()].sort((a, b) => b.score - a.score || a.lessonId.localeCompare(b.lessonId)).slice(0, opts.poolSize ?? 30);
3882
3929
  return { candidates, recallLessons };
3883
3930
  }
3884
3931
  function fallbackRecall(candidates, limit) {
@@ -6064,8 +6111,8 @@ function localView(v2, config, cwd, opts = {}) {
6064
6111
  source = void 0;
6065
6112
  }
6066
6113
  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);
6114
+ const byId2 = /* @__PURE__ */ new Map();
6115
+ for (const s of bundle?.sections ?? []) byId2.set(s.id, s);
6069
6116
  let root = cwd;
6070
6117
  let repo = "";
6071
6118
  if (opts.index !== false) {
@@ -6074,8 +6121,8 @@ function localView(v2, config, cwd, opts = {}) {
6074
6121
  root = idx.root;
6075
6122
  repo = idx.index.repo;
6076
6123
  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);
6124
+ const upstream = byId2.get(s.id);
6125
+ byId2.set(s.id, upstream ? { ...upstream, ...s, stats: upstream.stats, situations: upstream.situations, experience: upstream.experience } : s);
6079
6126
  }
6080
6127
  } catch {
6081
6128
  }
@@ -6083,10 +6130,10 @@ function localView(v2, config, cwd, opts = {}) {
6083
6130
  const overlays = v2.readOverlays();
6084
6131
  if (bundle?.pending?.length) {
6085
6132
  const local = /* @__PURE__ */ new Set([...overlays.map((o) => o.suggestionId), ...v2.listSuggestions().map((s) => s.id)]);
6086
- applyPending(byId, bundle.pending, local);
6133
+ applyPending(byId2, bundle.pending, local);
6087
6134
  }
6088
- applyOverlays(byId, overlays, ctx);
6089
- return { ctx, reader, ...source ? { source } : {}, layers: reader.layers, bundle, sections: [...byId.values()], byId, root, repo };
6135
+ applyOverlays(byId2, overlays, ctx);
6136
+ return { ctx, reader, ...source ? { source } : {}, layers: reader.layers, bundle, sections: [...byId2.values()], byId: byId2, root, repo };
6090
6137
  }
6091
6138
  var ACTIVE_OVERLAY;
6092
6139
  var init_view = __esm({
@@ -7376,6 +7423,7 @@ __export(route_exports, {
7376
7423
  readAnswer: () => readAnswer,
7377
7424
  readJob: () => readJob,
7378
7425
  readStats: () => readStats,
7426
+ recentSections: () => recentSections,
7379
7427
  routeJob: () => routeJob,
7380
7428
  sweepRouter: () => sweepRouter,
7381
7429
  writeJob: () => writeJob
@@ -7526,8 +7574,12 @@ async function askRouter(store, v2, sessionId, model, kind) {
7526
7574
  const index = await routerIndex(store, v2, session.source ?? "");
7527
7575
  if (!/^[\w-]{1,64}$/.test(index.hash)) return { picks: { error: "the router index came back with a malformed hash" } };
7528
7576
  indexHash = index.hash;
7529
- const systemFile = path13.join(dir(v2), `system-${index.hash}.txt`);
7530
- if (!fs17.existsSync(systemFile)) fs17.writeFileSync(systemFile, index.system);
7577
+ const recent = recentSections(v2, store.config(), session, index.items);
7578
+ const system = withRecent(index.system, recent);
7579
+ const items = recent.length ? [...index.items, ...routerItems(recent)] : index.items;
7580
+ const name = recent.length ? `${index.hash}-${createHash5("sha256").update(system).digest("hex").slice(0, 12)}` : index.hash;
7581
+ const systemFile = path13.join(dir(v2), `system-${name}.txt`);
7582
+ if (!fs17.existsSync(systemFile)) fs17.writeFileSync(systemFile, system);
7531
7583
  const cwd = path13.join(dir(v2), "cwd");
7532
7584
  fs17.mkdirSync(cwd, { recursive: true });
7533
7585
  const inContext2 = session.inContext ?? [...session.loaded, ...session.pushed];
@@ -7539,13 +7591,22 @@ async function askRouter(store, v2, sessionId, model, kind) {
7539
7591
  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
7592
  const meta = { ...res.duration_ms ? { modelMs: res.duration_ms } : {}, usage, ...typeof res.total_cost_usd === "number" ? { costUsd: res.total_cost_usd } : {} };
7541
7593
  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);
7594
+ const picks = parseRouterAnswer(res.result ?? "", items, inContext2);
7543
7595
  if (!picks) return { picks: { ...meta, error: `not JSON: ${(res.result ?? "").slice(0, 120)}` }, indexHash };
7544
7596
  return { picks: { ...picks, ...meta }, indexHash };
7545
7597
  } catch (err) {
7546
7598
  return { picks: { error: (err instanceof Error ? err.message : String(err)).slice(0, 300) }, ...indexHash ? { indexHash } : {} };
7547
7599
  }
7548
7600
  }
7601
+ function recentSections(v2, config, session, known) {
7602
+ try {
7603
+ const have = new Set(known.map((i) => i.id));
7604
+ const view = localView(v2, config, session.cwd, { index: false, ...session.source !== void 0 ? { source: session.source } : {} });
7605
+ return recallable(view.sections, view.reader).filter((s) => !have.has(s.id) && (s.localTrial?.length ?? 0) > 0);
7606
+ } catch {
7607
+ return [];
7608
+ }
7609
+ }
7549
7610
  async function recordStats(v2, sessionId, a, model, indexHash) {
7550
7611
  let release = null;
7551
7612
  for (let i = 0; i < 40 && !(release = v2.tryLock("router-stats", 3e4)); i++) await new Promise((r) => setTimeout(r, 50));
@@ -7594,6 +7655,7 @@ var init_route = __esm({
7594
7655
  init_util();
7595
7656
  init_api();
7596
7657
  init_store2();
7658
+ init_view();
7597
7659
  ROUTER_MODEL = "claude-haiku-5-5";
7598
7660
  INDEX_TTL_MS = 10 * 6e4;
7599
7661
  CLAUDE_TIMEOUT_MS = 6e4;
@@ -10682,7 +10744,7 @@ async function runRecall(store, opts) {
10682
10744
  };
10683
10745
  const connected = canSync(config) && config.recall.useMothership;
10684
10746
  const local = store.listLessons().filter((l) => !connected || l.provenance.userId === config.userId && l.provenance.orgId === config.orgId);
10685
- const byId = new Map(local.map((l) => [l.id, l]));
10747
+ const byId2 = new Map(local.map((l) => [l.id, l]));
10686
10748
  const rules = new Map(store.listRecallLessons().map((r) => [r.id, r]));
10687
10749
  let degraded;
10688
10750
  if (connected && !opts.offline) {
@@ -10705,12 +10767,12 @@ async function runRecall(store, opts) {
10705
10767
  const lookupOK = lookup && sameIdentity(lookup.profile);
10706
10768
  if (remoteOK || lookupOK) {
10707
10769
  profile = (remoteOK ? remote.profile : void 0) ?? (lookupOK ? lookup.profile : void 0) ?? profile;
10708
- byId.clear();
10770
+ byId2.clear();
10709
10771
  const refreshed = /* @__PURE__ */ new Map();
10710
10772
  if (lookupOK) {
10711
10773
  const unavailable = new Set(lookup.unavailableIds);
10712
10774
  for (const lesson of cached) {
10713
- if (unavailable.has(lesson.id) && lesson.version === 1 && (!config.lastSyncAt || lesson.provenance.createdAt > config.lastSyncAt)) byId.set(lesson.id, lesson);
10775
+ if (unavailable.has(lesson.id) && lesson.version === 1 && (!config.lastSyncAt || lesson.provenance.createdAt > config.lastSyncAt)) byId2.set(lesson.id, lesson);
10714
10776
  }
10715
10777
  for (const lesson of lookup.lessons) {
10716
10778
  if (cachedIds.has(lesson.id) && lesson.provenance.orgId === profile.orgId) refreshed.set(lesson.id, lesson);
@@ -10724,7 +10786,7 @@ async function runRecall(store, opts) {
10724
10786
  if (!checked || lesson.version > checked.version) refreshed.set(lesson.id, lesson);
10725
10787
  }
10726
10788
  for (const lesson of refreshed.values()) {
10727
- byId.set(lesson.id, lesson);
10789
+ byId2.set(lesson.id, lesson);
10728
10790
  if (!opts.dryRun) store.saveLesson(lesson, { reindex: false });
10729
10791
  }
10730
10792
  for (const rule of remoteOK ? remote.recallLessons : []) rules.set(rule.id, rule);
@@ -10739,7 +10801,7 @@ async function runRecall(store, opts) {
10739
10801
  }
10740
10802
  const fresh = new Set(Object.entries(state.servedAt).filter(([, turn]) => state.turn - turn < FRESH_TURNS).map(([id]) => id));
10741
10803
  const request = { task, userId: profile.userId, role: profile.role, orgUnit: profile.orgUnit, recentContext: history };
10742
- const prepared = prepareRecall([...byId.values()].map((lesson) => ({ lesson })), request, profile, [...rules.values()], { excludeIds: fresh });
10804
+ const prepared = prepareRecall([...byId2.values()].map((lesson) => ({ lesson })), request, profile, [...rules.values()], { excludeIds: fresh });
10743
10805
  const { candidates, recallLessons } = prepared;
10744
10806
  let selection;
10745
10807
  let selectedIds = fallbackRecall(candidates, config.recall.maxLessons);
@@ -10769,7 +10831,7 @@ async function runRecall(store, opts) {
10769
10831
  degraded = [degraded, response.error].filter(Boolean).join("; ");
10770
10832
  }
10771
10833
  }
10772
- const served = selectedIds.map((id) => byId.get(id));
10834
+ const served = selectedIds.map((id) => byId2.get(id));
10773
10835
  const trace = {
10774
10836
  id: newId("t"),
10775
10837
  sessionId: opts.sessionId,
@@ -11504,7 +11566,8 @@ async function runOnce(c, args, out, err) {
11504
11566
  if (!job) break;
11505
11567
  const started = Date.now();
11506
11568
  const scratch = fs31.mkdtempSync(path27.join(os7.tmpdir(), "bunshin-job-"));
11507
- const res = await askJson(config, { system: job.system, user: job.prompt, schema: job.schema, enforceSchema: false, timeoutMs: 15 * 6e4, maxTokens: 16e3, cwd: scratch }).finally(
11569
+ let usage;
11570
+ const res = await askJson(config, { system: job.system, user: job.prompt, schema: job.schema, enforceSchema: false, timeoutMs: 15 * 6e4, maxTokens: 16e3, cwd: scratch, onUsage: (u) => usage = u }).finally(
11508
11571
  () => fs31.rmSync(scratch, { recursive: true, force: true })
11509
11572
  );
11510
11573
  const model = config.backend === "codex-cli" ? config.codexModel ?? "codex default" : config.backend === "pi-cli" ? config.piModel ?? "pi default" : config.model;
@@ -11516,7 +11579,7 @@ async function runOnce(c, args, out, err) {
11516
11579
  if (r2.body.status === "retry" && /no LLM backend|not found|ENOENT/.test(res.error)) break;
11517
11580
  continue;
11518
11581
  }
11519
- const r = await call(c, "POST", `/jobs/${job.id}/answer`, { answer: res.value, model, runner: c.name }, 12e4);
11582
+ const r = await call(c, "POST", `/jobs/${job.id}/answer`, { answer: res.value, model, runner: c.name, ...usage ? { usage } : {} }, 12e4);
11520
11583
  out(`${job.id} ${job.kind}: ${r.body.status}${r.body.error ? ` (${r.body.error})` : ""} in ${Math.round((Date.now() - started) / 1e3)}s via ${res.backend}
11521
11584
  `);
11522
11585
  if (r.body.status === "done" || r.body.status === "stale") done++;
@@ -11532,7 +11595,7 @@ function effortOf(job) {
11532
11595
  const tokens = Math.round(chars / 4);
11533
11596
  const minutes = Math.max(2, Math.round(2 + tokens / 15e3));
11534
11597
  const proposals = (job.prompt.match(/^### g_\w+/gm) ?? []).length;
11535
- const what = job.kind === "reflect" ? "read every [USER] message and each failed or denied result first; most sessions teach nothing new, and at most 4 lessons are kept" : job.kind === "merge" ? `${proposals} proposal${proposals === 1 ? "" : "s"} against one document: decide each, edit only what the applied ones need` : job.kind === "generalize" ? `${(job.prompt.match(/^<document /gm) ?? []).length} documents from sibling scopes: write once at the parent what at least two of them share, and trim it out of them; "nothing_shared" is a normal answer` : `${proposals} proposed new document${proposals === 1 ? "" : "s"}: combine, fold into existing ones, or reject`;
11598
+ const what = job.kind === "reflect" ? "read every [USER] message and each failed or denied result first; most sessions teach nothing new, and at most 4 lessons are kept" : job.kind === "merge" ? `${proposals} proposal${proposals === 1 ? "" : "s"} against one document: decide each, edit only what the applied ones need` : job.kind === "dream" ? `${proposals} proposal${proposals === 1 ? "" : "s"} that would wait for a person: integrate (as is, reworded, or into the document it belongs in), reject, or leave it for a person; check each against its session, and add rather than overwrite` : job.kind === "generalize" ? `${(job.prompt.match(/^<document /gm) ?? []).length} documents from sibling scopes: write once at the parent what at least two of them share, and trim it out of them; "nothing_shared" is a normal answer` : `${proposals} proposed new document${proposals === 1 ? "" : "s"}: combine, fold into existing ones, or reject`;
11536
11599
  return `${chars.toLocaleString("en")} chars (~${tokens.toLocaleString("en")} tokens); about ${minutes} min. ${what}.`;
11537
11600
  }
11538
11601
  function jobIndex(text2) {
@@ -12020,7 +12083,7 @@ var init_runner = __esm({
12020
12083
  init_trust();
12021
12084
  init_version();
12022
12085
  DEFAULT_API = "https://api.bunshin.cc";
12023
- KINDS2 = ["reflect", "merge", "create", "generalize"];
12086
+ KINDS2 = ["reflect", "merge", "create", "generalize", "dream"];
12024
12087
  str5 = (v) => typeof v === "string" && v.trim() ? v.trim() : void 0;
12025
12088
  LAUNCHD_LABEL = "cc.bunshin.runner";
12026
12089
  CRON_MARK = "# bunshin-runner";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@bunshin-cc/bunshin",
3
- "version": "0.13.0",
3
+ "version": "0.14.0",
4
4
  "description": "Shared memory for company AI agents. Connect Codex, Claude Code, or Pi to Bunshin.",
5
5
  "type": "module",
6
6
  "bin": {