@bunshin-cc/bunshin 0.12.0 → 0.12.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.
- package/dist/bin.js +225 -39
- package/package.json +1 -1
package/dist/bin.js
CHANGED
|
@@ -148,6 +148,10 @@ async function askClaudeCli(opts) {
|
|
|
148
148
|
];
|
|
149
149
|
const raw = await run("claude", args, { stdin: opts.user, cwd: opts.cwd, timeoutMs: opts.timeoutMs ?? 3e5, backend: "claude-cli" });
|
|
150
150
|
const envelope = parseJsonLoose(raw);
|
|
151
|
+
if (envelope?.usage || envelope?.total_cost_usd !== void 0) {
|
|
152
|
+
const u = envelope.usage ?? {};
|
|
153
|
+
opts.onUsage?.({ input: u.input_tokens, cacheRead: u.cache_read_input_tokens, cacheWrite: u.cache_creation_input_tokens, output: u.output_tokens, ...envelope.total_cost_usd !== void 0 ? { costUsd: envelope.total_cost_usd } : {} });
|
|
154
|
+
}
|
|
151
155
|
if (envelope && typeof envelope.result === "string") {
|
|
152
156
|
if (envelope.is_error) throw new Error(`claude: ${envelope.result.slice(0, 300)}`);
|
|
153
157
|
return envelope.result;
|
|
@@ -566,7 +570,7 @@ var init_store = __esm({
|
|
|
566
570
|
gateModel: "claude-haiku-4-5-20251001",
|
|
567
571
|
backend: "auto",
|
|
568
572
|
recall: { enabled: true, maxLessons: 4, hookBudgetMs: 3500, useMothership: true },
|
|
569
|
-
reflect: { enabled: true, cooldownMinutes: 10, minToolCalls: 3, minUserTurns: 2, nudge: true, autoApply: "all", cacheTtlMs: 5 * 6e4 },
|
|
573
|
+
reflect: { enabled: true, cooldownMinutes: 10, minToolCalls: 3, minUserTurns: 2, nudge: true, autoApply: "all", cacheTtlMs: 5 * 6e4, forkMaxTokens: 6e4 },
|
|
570
574
|
upload: "redacted"
|
|
571
575
|
};
|
|
572
576
|
EMPTY_SESSION = { turn: 0, served: [], servedAt: {}, reflectedMessages: 0, conflictsAsked: [] };
|
|
@@ -3134,7 +3138,13 @@ At most ${max} suggestions. Schema:
|
|
|
3134
3138
|
| {"op": "param", "key": string, "value": string|number|boolean}
|
|
3135
3139
|
| {"op": "situation", "text": string},
|
|
3136
3140
|
"rationale": string, "urgency": "normal"|"urgent",
|
|
3137
|
-
"signal": "steering"|"environment"|"knowledge"|"capability"|"approach"}]
|
|
3141
|
+
"signal": "steering"|"environment"|"knowledge"|"capability"|"approach"}],
|
|
3142
|
+
"considered": [{"moment": string, "decision": "lesson"|"skip", "why": string}]}
|
|
3143
|
+
|
|
3144
|
+
In "considered", list the moments you weighed (a correction, a failure recovered from, something
|
|
3145
|
+
learned about the code or the company), at most 6, most important first: name each in a few words,
|
|
3146
|
+
say whether it became a lesson or was skipped, and why in one sentence. People read this to see
|
|
3147
|
+
what reflection noticed and to steer it; list them even when nothing is new.`;
|
|
3138
3148
|
}
|
|
3139
3149
|
function feedbackSection(f) {
|
|
3140
3150
|
return `
|
|
@@ -3185,6 +3195,12 @@ and name what you correct in the rationale (e.g. "contradicts g_ab12: uploads wo
|
|
|
3185
3195
|
|
|
3186
3196
|
${body}`;
|
|
3187
3197
|
}
|
|
3198
|
+
function parseConsidered(raw) {
|
|
3199
|
+
const value = typeof raw === "string" ? extractJson(raw) : raw;
|
|
3200
|
+
const list2 = value && typeof value === "object" ? value.considered : void 0;
|
|
3201
|
+
if (!Array.isArray(list2)) return [];
|
|
3202
|
+
return list2.filter((x) => !!x && typeof x === "object").map((x) => ({ moment: clean(x.moment).slice(0, 300), decision: x.decision === "lesson" ? "lesson" : "skip", why: clean(x.why).slice(0, 600) })).filter((x) => x.moment).slice(0, 8);
|
|
3203
|
+
}
|
|
3188
3204
|
function extractJson(text2) {
|
|
3189
3205
|
try {
|
|
3190
3206
|
const whole = JSON.parse(text2.trim());
|
|
@@ -3368,6 +3384,14 @@ var init_reflect = __esm({
|
|
|
3368
3384
|
signal: { type: "string", enum: ["steering", "environment", "knowledge", "capability", "approach"] }
|
|
3369
3385
|
}
|
|
3370
3386
|
}
|
|
3387
|
+
},
|
|
3388
|
+
considered: {
|
|
3389
|
+
type: "array",
|
|
3390
|
+
items: {
|
|
3391
|
+
type: "object",
|
|
3392
|
+
required: ["moment", "decision", "why"],
|
|
3393
|
+
properties: { moment: { type: "string" }, decision: { type: "string", enum: ["lesson", "skip"] }, why: { type: "string" } }
|
|
3394
|
+
}
|
|
3371
3395
|
}
|
|
3372
3396
|
}
|
|
3373
3397
|
};
|
|
@@ -6767,6 +6791,7 @@ var init_sync = __esm({
|
|
|
6767
6791
|
|
|
6768
6792
|
// src/v2/reflect.ts
|
|
6769
6793
|
import { spawn as spawn3 } from "node:child_process";
|
|
6794
|
+
import os3 from "node:os";
|
|
6770
6795
|
import { createHash as createHash4 } from "node:crypto";
|
|
6771
6796
|
import fs16 from "node:fs";
|
|
6772
6797
|
import path12 from "node:path";
|
|
@@ -6774,24 +6799,127 @@ function episodeIdFor(contextId, sessionId) {
|
|
|
6774
6799
|
return `e_${createHash4("sha256").update(`${contextId}
|
|
6775
6800
|
${sessionId}`).digest("hex").slice(0, 16)}`;
|
|
6776
6801
|
}
|
|
6777
|
-
function
|
|
6778
|
-
const
|
|
6779
|
-
|
|
6780
|
-
|
|
6781
|
-
|
|
6782
|
-
|
|
6783
|
-
|
|
6784
|
-
"
|
|
6785
|
-
"json",
|
|
6786
|
-
|
|
6787
|
-
|
|
6788
|
-
"--strict-mcp-config",
|
|
6789
|
-
"--disallowedTools",
|
|
6790
|
-
FORK_DENIED_TOOLS,
|
|
6791
|
-
"--max-turns",
|
|
6792
|
-
"1",
|
|
6793
|
-
prompt
|
|
6802
|
+
function forkArgs(sessionId, prompt, mode, model) {
|
|
6803
|
+
const head = ["-p", "--resume", sessionId, "--fork-session", "--output-format", "json", ...model ? ["--model", model] : []];
|
|
6804
|
+
if (mode === "isolated") return [...head, "--strict-mcp-config", "--disallowedTools", FORK_DENIED_TOOLS, "--max-turns", "1", prompt];
|
|
6805
|
+
return [...head, "--settings", FORK_GUARD_SETTINGS, "--permission-prompts", "none", "--max-turns", "3", prompt];
|
|
6806
|
+
}
|
|
6807
|
+
function forkGuardAvailable(cwd, home = os3.homedir()) {
|
|
6808
|
+
const files = [
|
|
6809
|
+
path12.join(home, ".claude", "settings.json"),
|
|
6810
|
+
...cwd ? [path12.join(cwd, ".claude", "settings.json"), path12.join(cwd, ".claude", "settings.local.json")] : [],
|
|
6811
|
+
"/etc/claude-code/managed-settings.json",
|
|
6812
|
+
"/Library/Application Support/ClaudeCode/managed-settings.json"
|
|
6794
6813
|
];
|
|
6814
|
+
return !files.some((f) => {
|
|
6815
|
+
const s = readSettings(f);
|
|
6816
|
+
return s.disableAllHooks === true || s.allowManagedHooksOnly === true;
|
|
6817
|
+
});
|
|
6818
|
+
}
|
|
6819
|
+
function sessionModel(transcriptPath) {
|
|
6820
|
+
if (!transcriptPath) return void 0;
|
|
6821
|
+
try {
|
|
6822
|
+
const fd = fs16.openSync(transcriptPath, "r");
|
|
6823
|
+
try {
|
|
6824
|
+
const size = fs16.fstatSync(fd).size;
|
|
6825
|
+
const len = Math.min(size, 4 * 1024 * 1024);
|
|
6826
|
+
const buf = Buffer.alloc(len);
|
|
6827
|
+
fs16.readSync(fd, buf, 0, len, size - len);
|
|
6828
|
+
const lines = buf.toString("utf8").split("\n").reverse();
|
|
6829
|
+
for (const l of lines) {
|
|
6830
|
+
if (!l.includes('"assistant"')) continue;
|
|
6831
|
+
try {
|
|
6832
|
+
const d = JSON.parse(l);
|
|
6833
|
+
if (d.type === "assistant" && d.message?.model && d.message.model !== "<synthetic>") return d.message.model;
|
|
6834
|
+
} catch {
|
|
6835
|
+
}
|
|
6836
|
+
}
|
|
6837
|
+
} finally {
|
|
6838
|
+
fs16.closeSync(fd);
|
|
6839
|
+
}
|
|
6840
|
+
} catch {
|
|
6841
|
+
}
|
|
6842
|
+
return void 0;
|
|
6843
|
+
}
|
|
6844
|
+
function lastLineWith(file2, needle, tail = 4 * 1024 * 1024) {
|
|
6845
|
+
try {
|
|
6846
|
+
const fd = fs16.openSync(file2, "r");
|
|
6847
|
+
try {
|
|
6848
|
+
const size = fs16.fstatSync(fd).size;
|
|
6849
|
+
const len = Math.min(size, tail);
|
|
6850
|
+
const buf = Buffer.alloc(len);
|
|
6851
|
+
fs16.readSync(fd, buf, 0, len, size - len);
|
|
6852
|
+
return buf.toString("utf8").split("\n").reverse().find((l) => l.includes(needle));
|
|
6853
|
+
} finally {
|
|
6854
|
+
fs16.closeSync(fd);
|
|
6855
|
+
}
|
|
6856
|
+
} catch {
|
|
6857
|
+
return void 0;
|
|
6858
|
+
}
|
|
6859
|
+
}
|
|
6860
|
+
function sessionCostSoFar(transcriptPath) {
|
|
6861
|
+
if (!transcriptPath) return void 0;
|
|
6862
|
+
const line = lastLineWith(transcriptPath, '"cost-state"');
|
|
6863
|
+
if (!line) return void 0;
|
|
6864
|
+
try {
|
|
6865
|
+
const v = JSON.parse(line).totalCostUSD;
|
|
6866
|
+
return typeof v === "number" ? v : void 0;
|
|
6867
|
+
} catch {
|
|
6868
|
+
return void 0;
|
|
6869
|
+
}
|
|
6870
|
+
}
|
|
6871
|
+
function forkOwnCost(reported, before) {
|
|
6872
|
+
if (reported === void 0) return void 0;
|
|
6873
|
+
return before === void 0 ? reported : Math.max(0, reported - before);
|
|
6874
|
+
}
|
|
6875
|
+
function cacheHitRate(u) {
|
|
6876
|
+
if (!u) return void 0;
|
|
6877
|
+
const read = u.cache_read_input_tokens ?? 0;
|
|
6878
|
+
const total = read + (u.cache_creation_input_tokens ?? 0) + (u.input_tokens ?? 0);
|
|
6879
|
+
return total > 0 ? read / total : void 0;
|
|
6880
|
+
}
|
|
6881
|
+
function readForkCache(v2) {
|
|
6882
|
+
try {
|
|
6883
|
+
return JSON.parse(fs16.readFileSync(v2.p(FORK_CACHE_FILE), "utf8")).forks ?? [];
|
|
6884
|
+
} catch {
|
|
6885
|
+
return [];
|
|
6886
|
+
}
|
|
6887
|
+
}
|
|
6888
|
+
function recordForkCache(v2, rec) {
|
|
6889
|
+
try {
|
|
6890
|
+
fs16.writeFileSync(v2.p(FORK_CACHE_FILE), JSON.stringify({ forks: [...readForkCache(v2), rec].slice(-50) }, null, 2));
|
|
6891
|
+
} catch {
|
|
6892
|
+
}
|
|
6893
|
+
}
|
|
6894
|
+
function forkDecision(records, o) {
|
|
6895
|
+
if (o.learn) return { fork: true, reason: "asked for (/learn)" };
|
|
6896
|
+
if (o.tokens <= o.limit) return { fork: true, reason: "short session" };
|
|
6897
|
+
const now = o.now ?? Date.now();
|
|
6898
|
+
const latest = [...records].reverse().find((r) => r.mode === "faithful" && r.tokens > o.limit && now - Date.parse(r.at) < MISS_HOLD_MS);
|
|
6899
|
+
if (latest && latest.hitRate < CACHE_MISS) return { fork: false, reason: `the last fork here missed the session's cache (${Math.round(latest.hitRate * 100)}% read from cache): digest of the new turns` };
|
|
6900
|
+
return { fork: true, reason: latest ? `forks here read ${Math.round(latest.hitRate * 100)}% from the session's cache` : "first fork of a large session here" };
|
|
6901
|
+
}
|
|
6902
|
+
function reflectionSummary(v2, days = 7, now = Date.now()) {
|
|
6903
|
+
const since = now - days * 864e5;
|
|
6904
|
+
const traces = v2.listReflections().filter((t) => Date.parse(t.startedAt) >= since);
|
|
6905
|
+
let read = 0;
|
|
6906
|
+
let paid = 0;
|
|
6907
|
+
let misses = 0;
|
|
6908
|
+
let forks = 0;
|
|
6909
|
+
for (const t of traces) {
|
|
6910
|
+
if (t.method !== "fork" || !t.usage) continue;
|
|
6911
|
+
forks++;
|
|
6912
|
+
read += t.usage.cacheRead ?? 0;
|
|
6913
|
+
paid += (t.usage.cacheWrite ?? 0) + (t.usage.input ?? 0);
|
|
6914
|
+
const rate = t.cache?.hitRate;
|
|
6915
|
+
if (rate !== void 0 && rate < CACHE_MISS) misses++;
|
|
6916
|
+
}
|
|
6917
|
+
const latest = [...readForkCache(v2)].reverse()[0];
|
|
6918
|
+
return { runs: traces.length, costUsd: traces.reduce((a, t) => a + (t.costUsd ?? 0), 0), forks, hitRate: read + paid > 0 ? read / (read + paid) : null, misses, mode: latest?.mode ?? null };
|
|
6919
|
+
}
|
|
6920
|
+
function runClaudeFork(sessionId, prompt, { cwd, model, mode = "faithful", timeoutMs = FORK_TIMEOUT_MS } = {}) {
|
|
6921
|
+
const bin = process.env.BUNSHIN_CLAUDE_BIN || "claude";
|
|
6922
|
+
const args = forkArgs(sessionId, prompt, mode, model);
|
|
6795
6923
|
return new Promise((resolve) => {
|
|
6796
6924
|
let out = "";
|
|
6797
6925
|
let err = "";
|
|
@@ -6931,13 +7059,35 @@ async function runReflectionV2(store, opts) {
|
|
|
6931
7059
|
const promptBase = { contextKind: view.ctx.kind, layers: view.layers, index, captured, guidelines, scopes: scopeChoices(view.bundle?.scopes, view.source), ...opts.focus ? { focus: opts.focus } : {}, ...earlier ? { earlier } : {}, ...profile ? { profileId: profile.id } : {} };
|
|
6932
7060
|
let raw = null;
|
|
6933
7061
|
const call2 = {};
|
|
6934
|
-
|
|
7062
|
+
const sessionTokens = estimateSessionTokens(session.transcriptPath);
|
|
7063
|
+
const limit = config.reflect.forkMaxTokens ?? 6e4;
|
|
7064
|
+
const decision = forkDecision(readForkCache(v2), { learn: origin === "learn", tokens: sessionTokens, limit });
|
|
7065
|
+
const useFork = harness === "claude-code" && decision.fork;
|
|
7066
|
+
if (harness === "claude-code") call2.cacheNote = decision.reason;
|
|
7067
|
+
if (useFork) {
|
|
6935
7068
|
const prompt = buildReflectPrompt(promptBase);
|
|
6936
|
-
const
|
|
7069
|
+
const guard = forkGuardAvailable(session.cwd);
|
|
7070
|
+
const mode = config.reflect.forkMode === "isolated" || !guard ? "isolated" : "faithful";
|
|
7071
|
+
if (mode === "isolated") call2.cacheNote = guard ? "reflect.forkMode is isolated in this machine's config" : "hooks are turned off on this machine (disableAllHooks or allowManagedHooksOnly), so the guard that stops a fork acting cannot run";
|
|
7072
|
+
const model = mode === "faithful" ? sessionModel(session.transcriptPath) ?? config.model : config.model;
|
|
7073
|
+
const before = sessionCostSoFar(session.transcriptPath);
|
|
7074
|
+
const fork = await runClaudeFork(opts.sessionId, prompt, { cwd: session.cwd, model, mode });
|
|
7075
|
+
fork.costUsd = forkOwnCost(fork.costUsd, before);
|
|
7076
|
+
const hitRate = cacheHitRate(fork.usage);
|
|
7077
|
+
call2.cacheMode = mode;
|
|
7078
|
+
if (hitRate !== void 0) {
|
|
7079
|
+
call2.hitRate = hitRate;
|
|
7080
|
+
recordForkCache(v2, { at: (/* @__PURE__ */ new Date()).toISOString(), sessionId: opts.sessionId, mode, tokens: sessionTokens, hitRate, ...fork.costUsd !== void 0 ? { costUsd: fork.costUsd } : {} });
|
|
7081
|
+
if (mode === "faithful" && hitRate < CACHE_MISS && sessionTokens > limit) {
|
|
7082
|
+
const cost = fork.costUsd !== void 0 ? ` ($${fork.costUsd.toFixed(2)})` : "";
|
|
7083
|
+
v2.log("v2-reflect-cache-miss", { session: opts.sessionId, hitRate, tokens: sessionTokens, costUsd: fork.costUsd ?? null });
|
|
7084
|
+
updateFeed(v2, opts.sessionId, (f) => addEvent(f, "warning", `reflection did not reuse this session's prompt cache${cost}: large sessions here reflect from a digest of their new turns for now`));
|
|
7085
|
+
}
|
|
7086
|
+
}
|
|
6937
7087
|
Object.assign(call2, {
|
|
6938
7088
|
prompt,
|
|
6939
7089
|
executor: "edge:claude-cli",
|
|
6940
|
-
model
|
|
7090
|
+
model,
|
|
6941
7091
|
...fork.usage ? { usage: { input: fork.usage.input_tokens, cacheRead: fork.usage.cache_read_input_tokens, cacheWrite: fork.usage.cache_creation_input_tokens, output: fork.usage.output_tokens } } : {},
|
|
6942
7092
|
...fork.costUsd !== void 0 ? { costUsd: fork.costUsd } : {}
|
|
6943
7093
|
});
|
|
@@ -6946,8 +7096,10 @@ async function runReflectionV2(store, opts) {
|
|
|
6946
7096
|
v2.log("v2-reflect-fork", {
|
|
6947
7097
|
session: opts.sessionId,
|
|
6948
7098
|
ok: fork.ok,
|
|
6949
|
-
model
|
|
7099
|
+
model,
|
|
7100
|
+
mode,
|
|
6950
7101
|
cache: true,
|
|
7102
|
+
hit_rate: hitRate ?? null,
|
|
6951
7103
|
cache_read_input_tokens: fork.usage?.cache_read_input_tokens ?? null,
|
|
6952
7104
|
cache_creation_input_tokens: fork.usage?.cache_creation_input_tokens ?? null,
|
|
6953
7105
|
total_cost_usd: fork.costUsd ?? null,
|
|
@@ -6961,9 +7113,11 @@ async function runReflectionV2(store, opts) {
|
|
|
6961
7113
|
if (result.method === "none" && session.transcriptPath && fs16.existsSync(session.transcriptPath)) {
|
|
6962
7114
|
const transcriptDigest = digest(facts ?? parseTranscript(session.transcriptPath), { from, maxChars: 4e4 });
|
|
6963
7115
|
const digestPrompt = buildReflectPrompt({ ...promptBase, transcriptDigest });
|
|
7116
|
+
const digestUsage = {};
|
|
6964
7117
|
const res = await askJson(config, {
|
|
6965
7118
|
system: "You are Bunshin's reflection pass. Follow the instructions in the user message and reply with one JSON object only.",
|
|
6966
7119
|
user: digestPrompt,
|
|
7120
|
+
onUsage: ({ costUsd, ...usage }) => Object.assign(digestUsage, { usage, ...costUsd !== void 0 ? { costUsd } : {} }),
|
|
6967
7121
|
schema: REFLECT_SCHEMA,
|
|
6968
7122
|
timeoutMs: FORK_TIMEOUT_MS,
|
|
6969
7123
|
cwd: session.cwd
|
|
@@ -6973,7 +7127,7 @@ async function runReflectionV2(store, opts) {
|
|
|
6973
7127
|
raw = res.value;
|
|
6974
7128
|
result.method = "digest";
|
|
6975
7129
|
result.error = void 0;
|
|
6976
|
-
Object.assign(call2, { prompt: digestPrompt, executor: `edge:${res.backend}`, model: config.model, thinking: void 0, usage:
|
|
7130
|
+
Object.assign(call2, { prompt: digestPrompt, executor: `edge:${res.backend}`, model: config.model, thinking: void 0, usage: digestUsage.usage, costUsd: digestUsage.costUsd });
|
|
6977
7131
|
} else result.error = [result.error, res.error].filter(Boolean).join("; ");
|
|
6978
7132
|
}
|
|
6979
7133
|
const known = /* @__PURE__ */ new Set([...view.byId.keys(), ...index.map((s) => s.id)]);
|
|
@@ -7050,9 +7204,11 @@ async function runReflectionV2(store, opts) {
|
|
|
7050
7204
|
...call2.thinking ? { thinking: call2.thinking } : {},
|
|
7051
7205
|
...raw !== null ? { output: typeof raw === "string" ? raw : JSON.stringify(raw, null, 2) } : {},
|
|
7052
7206
|
proposals: [...kept, ...refused].sort((a, b) => a.index - b.index),
|
|
7207
|
+
...raw !== null && parseConsidered(raw).length ? { considered: parseConsidered(raw) } : {},
|
|
7053
7208
|
nothingNew: result.nothingNew,
|
|
7054
7209
|
...call2.usage ? { usage: call2.usage } : {},
|
|
7055
7210
|
...call2.costUsd !== void 0 ? { costUsd: call2.costUsd } : {},
|
|
7211
|
+
...call2.cacheNote || call2.hitRate !== void 0 ? { cache: { ...call2.cacheMode ? { mode: call2.cacheMode } : {}, ...call2.hitRate !== void 0 ? { hitRate: Math.round(call2.hitRate * 1e3) / 1e3 } : {}, ...call2.cacheNote ? { note: call2.cacheNote } : {} } } : {},
|
|
7056
7212
|
durationMs: Date.now() - Date.parse(startedAt),
|
|
7057
7213
|
...result.error ? { error: result.error } : {},
|
|
7058
7214
|
startedAt,
|
|
@@ -7090,6 +7246,14 @@ async function runReflectionV2(store, opts) {
|
|
|
7090
7246
|
}
|
|
7091
7247
|
return result;
|
|
7092
7248
|
}
|
|
7249
|
+
function estimateSessionTokens(transcriptPath) {
|
|
7250
|
+
if (!transcriptPath) return 0;
|
|
7251
|
+
try {
|
|
7252
|
+
return Math.round(fs16.statSync(transcriptPath).size / 7);
|
|
7253
|
+
} catch {
|
|
7254
|
+
return 0;
|
|
7255
|
+
}
|
|
7256
|
+
}
|
|
7093
7257
|
function proposalSummary(item) {
|
|
7094
7258
|
const it = item && typeof item === "object" ? item : {};
|
|
7095
7259
|
const op = it.op && typeof it.op === "object" ? it.op : void 0;
|
|
@@ -7111,7 +7275,7 @@ function learnLines(result, view) {
|
|
|
7111
7275
|
return applied ? `captured: ${s.summary ?? summarize(s.op)} \u2192 ${target}` : `proposed (not applied): ${s.summary ?? summarize(s.op)} \u2192 ${target}`;
|
|
7112
7276
|
});
|
|
7113
7277
|
}
|
|
7114
|
-
var FORK_TIMEOUT_MS, FORK_DENIED_TOOLS;
|
|
7278
|
+
var FORK_TIMEOUT_MS, FORK_DENIED_TOOLS, FORK_GUARD_SETTINGS, readSettings, FORK_CACHE_FILE, CACHE_MISS, MISS_HOLD_MS;
|
|
7115
7279
|
var init_reflect3 = __esm({
|
|
7116
7280
|
"src/v2/reflect.ts"() {
|
|
7117
7281
|
"use strict";
|
|
@@ -7126,6 +7290,19 @@ var init_reflect3 = __esm({
|
|
|
7126
7290
|
init_view();
|
|
7127
7291
|
FORK_TIMEOUT_MS = 12e4;
|
|
7128
7292
|
FORK_DENIED_TOOLS = "Bash,Edit,Write,MultiEdit,NotebookEdit,WebFetch,WebSearch,Task,Agent,Skill,SlashCommand";
|
|
7293
|
+
FORK_GUARD_SETTINGS = JSON.stringify({
|
|
7294
|
+
hooks: { PreToolUse: [{ matcher: "*", hooks: [{ type: "command", command: "echo 'Bunshin reflection: tools are disabled here; answer with the JSON only.' >&2; exit 2" }] }] }
|
|
7295
|
+
});
|
|
7296
|
+
readSettings = (file2) => {
|
|
7297
|
+
try {
|
|
7298
|
+
return JSON.parse(fs16.readFileSync(file2, "utf8"));
|
|
7299
|
+
} catch {
|
|
7300
|
+
return {};
|
|
7301
|
+
}
|
|
7302
|
+
};
|
|
7303
|
+
FORK_CACHE_FILE = "fork-cache.json";
|
|
7304
|
+
CACHE_MISS = 0.5;
|
|
7305
|
+
MISS_HOLD_MS = 7 * 24 * 36e5;
|
|
7129
7306
|
}
|
|
7130
7307
|
});
|
|
7131
7308
|
|
|
@@ -7386,10 +7563,10 @@ __export(uicmd_exports, {
|
|
|
7386
7563
|
});
|
|
7387
7564
|
import { spawnSync } from "node:child_process";
|
|
7388
7565
|
import fs18 from "node:fs";
|
|
7389
|
-
import
|
|
7566
|
+
import os4 from "node:os";
|
|
7390
7567
|
import path14 from "node:path";
|
|
7391
7568
|
import { fileURLToPath } from "node:url";
|
|
7392
|
-
function modHome(home = process.env.BUNSHIN_DEPLOY_HOME ||
|
|
7569
|
+
function modHome(home = process.env.BUNSHIN_DEPLOY_HOME || os4.homedir()) {
|
|
7393
7570
|
return path14.join(home, ".bunshin", "claude-code-ui");
|
|
7394
7571
|
}
|
|
7395
7572
|
function modSource() {
|
|
@@ -8190,10 +8367,10 @@ function onStop(ctx) {
|
|
|
8190
8367
|
function autoReflect(ctx, v2, config, session, scan, now) {
|
|
8191
8368
|
if (!config.reflect.enabled) return false;
|
|
8192
8369
|
const last = Date.parse(session.autoReflectAt ?? session.reflectedAt ?? "");
|
|
8193
|
-
if (Number.isFinite(last) && now.getTime() - last < Math.max(0, config.reflect.
|
|
8370
|
+
if (Number.isFinite(last) && now.getTime() - last < Math.max(0, config.reflect.continualMinutes ?? 20) * 6e4) return false;
|
|
8194
8371
|
const from = reflectCursor(session, scan.facts.turns.length);
|
|
8195
8372
|
const signals = sessionSignals({ scan: sinceTurn(scan, from), startedAt: session.startedAt, lastActivityAt: now.toISOString(), partial: from > 0 });
|
|
8196
|
-
const gate = sessionGate(signals, { now: now.toISOString(), cacheTtlMs: config.reflect.cacheTtlMs });
|
|
8373
|
+
const gate = sessionGate(signals, { now: now.toISOString(), cacheTtlMs: config.reflect.cacheTtlMs, minToolCalls: config.reflect.continualMinToolCalls ?? 30 });
|
|
8197
8374
|
if (!gate.reflect) return false;
|
|
8198
8375
|
v2.updateSession(session.sessionId, ctx.cwd, (s) => {
|
|
8199
8376
|
s.autoReflectAt = now.toISOString();
|
|
@@ -9843,6 +10020,7 @@ function v2Status(store, cwd) {
|
|
|
9843
10020
|
const sync = v2.readSyncState();
|
|
9844
10021
|
const pooled = cwdInPool(config, cwd, store.root);
|
|
9845
10022
|
return {
|
|
10023
|
+
reflection: reflectionSummary(v2),
|
|
9846
10024
|
context: { id: view.ctx.id, kind: view.ctx.kind, layers: view.layers },
|
|
9847
10025
|
source: { id: pooled ? sourceFor(cwd, store.root, view.ctx) ?? null : null, inPool: pooled, folder: topFolder(cwd, store.root) || null },
|
|
9848
10026
|
bundle: bundle ? { sections: bundle.sections.length, generatedAt: bundle.generatedAt, release: bundle.release?.version ?? null } : null,
|
|
@@ -10415,10 +10593,10 @@ __export(demo_exports, {
|
|
|
10415
10593
|
});
|
|
10416
10594
|
import assert from "node:assert/strict";
|
|
10417
10595
|
import fs27 from "node:fs";
|
|
10418
|
-
import
|
|
10596
|
+
import os5 from "node:os";
|
|
10419
10597
|
import path23 from "node:path";
|
|
10420
10598
|
async function runDemo(write) {
|
|
10421
|
-
const root = fs27.mkdtempSync(path23.join(
|
|
10599
|
+
const root = fs27.mkdtempSync(path23.join(os5.tmpdir(), "bunshin-demo-"));
|
|
10422
10600
|
try {
|
|
10423
10601
|
const store = Store.init(root, { ...DEMO_ENGINEER, apiUrl: "" });
|
|
10424
10602
|
const { lessons, constraint, workflow } = demoScenario();
|
|
@@ -11000,9 +11178,9 @@ __export(runner_exports, {
|
|
|
11000
11178
|
});
|
|
11001
11179
|
import { spawnSync as spawnSync3 } from "node:child_process";
|
|
11002
11180
|
import fs30 from "node:fs";
|
|
11003
|
-
import
|
|
11181
|
+
import os6 from "node:os";
|
|
11004
11182
|
import path26 from "node:path";
|
|
11005
|
-
function runnerHome(home = process.env.BUNSHIN_RUNNER_HOME ||
|
|
11183
|
+
function runnerHome(home = process.env.BUNSHIN_RUNNER_HOME || os6.homedir()) {
|
|
11006
11184
|
return path26.join(home, ".bunshin", "runner");
|
|
11007
11185
|
}
|
|
11008
11186
|
function readInstalled(home) {
|
|
@@ -11020,7 +11198,7 @@ function connection(args, cwd) {
|
|
|
11020
11198
|
const apiUrl = (str5(args.flags["api-url"]) || process.env.BUNSHIN_API_URL || config?.apiUrl || saved?.apiUrl || DEFAULT_API).replace(/\/$/, "");
|
|
11021
11199
|
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");
|
|
11022
11200
|
if (!secureUrl(apiUrl)) throw new Error(`refusing ${apiUrl}: the runner's key travels only over https (http only on localhost)`);
|
|
11023
|
-
const name = str5(args.flags.name) ?? process.env.BUNSHIN_RUNNER_NAME ?? saved?.name ?? `${
|
|
11201
|
+
const name = str5(args.flags.name) ?? process.env.BUNSHIN_RUNNER_NAME ?? saved?.name ?? `${os6.hostname().split(".")[0] || "runner"}`;
|
|
11024
11202
|
return { apiUrl, key, name: name.replace(/[^\w.:@/-]/g, "-").slice(0, 80) };
|
|
11025
11203
|
}
|
|
11026
11204
|
async function call(c, method, route, body, timeoutMs = 6e4) {
|
|
@@ -11074,7 +11252,7 @@ async function runOnce(c, args, out, err) {
|
|
|
11074
11252
|
const [job] = await lease(c, args);
|
|
11075
11253
|
if (!job) break;
|
|
11076
11254
|
const started = Date.now();
|
|
11077
|
-
const scratch = fs30.mkdtempSync(path26.join(
|
|
11255
|
+
const scratch = fs30.mkdtempSync(path26.join(os6.tmpdir(), "bunshin-job-"));
|
|
11078
11256
|
const res = await askJson(config, { system: job.system, user: job.prompt, schema: job.schema, enforceSchema: false, timeoutMs: 15 * 6e4, maxTokens: 16e3, cwd: scratch }).finally(
|
|
11079
11257
|
() => fs30.rmSync(scratch, { recursive: true, force: true })
|
|
11080
11258
|
);
|
|
@@ -11173,7 +11351,7 @@ function logAnswer(entry) {
|
|
|
11173
11351
|
}
|
|
11174
11352
|
}
|
|
11175
11353
|
function which(name) {
|
|
11176
|
-
for (const d of [...(process.env.PATH || "").split(path26.delimiter), path26.join(
|
|
11354
|
+
for (const d of [...(process.env.PATH || "").split(path26.delimiter), path26.join(os6.homedir(), ".local", "bin")]) {
|
|
11177
11355
|
if (d && fs30.existsSync(path26.join(d, name))) return path26.join(d, name);
|
|
11178
11356
|
}
|
|
11179
11357
|
return null;
|
|
@@ -11182,7 +11360,7 @@ function scheduledCommand(backend) {
|
|
|
11182
11360
|
const node = path26.dirname(process.execPath);
|
|
11183
11361
|
const npx = fs30.existsSync(path26.join(node, "npx")) ? path26.join(node, "npx") : which("npx") ?? "npx";
|
|
11184
11362
|
const bin = BIN_OF[backend] ? which(BIN_OF[backend]) : null;
|
|
11185
|
-
const dirs = [.../* @__PURE__ */ new Set([node, ...bin ? [path26.dirname(bin)] : [], path26.join(
|
|
11363
|
+
const dirs = [.../* @__PURE__ */ new Set([node, ...bin ? [path26.dirname(bin)] : [], path26.join(os6.homedir(), ".local", "bin"), "/opt/homebrew/bin", "/usr/local/bin", "/usr/bin", "/bin", "/usr/sbin", "/sbin"])];
|
|
11186
11364
|
return { argv: [npx, "-y", PKG2, "runner", "--once"], path: dirs.join(path26.delimiter) };
|
|
11187
11365
|
}
|
|
11188
11366
|
function launchdPlist(backend, everyMinutes, home = runnerHome()) {
|
|
@@ -11213,7 +11391,7 @@ function cronLine(backend, everyMinutes, home = runnerHome()) {
|
|
|
11213
11391
|
return `${when} cd ${q(home)} && PATH=${q(cmd.path)} ${cmd.argv.map(q).join(" ")} >> ${q(path26.join(home, "runner.log"))} 2>&1 ${CRON_MARK}`;
|
|
11214
11392
|
}
|
|
11215
11393
|
function launchAgentsDir(opts) {
|
|
11216
|
-
return opts.launchAgents ?? path26.join(process.env.BUNSHIN_RUNNER_HOME ||
|
|
11394
|
+
return opts.launchAgents ?? path26.join(process.env.BUNSHIN_RUNNER_HOME || os6.homedir(), "Library", "LaunchAgents");
|
|
11217
11395
|
}
|
|
11218
11396
|
function installSchedule(backend, everyMinutes, opts = {}) {
|
|
11219
11397
|
const platform = opts.platform ?? process.platform;
|
|
@@ -13114,7 +13292,7 @@ function cmdStatus(store, args, out, v2) {
|
|
|
13114
13292
|
const config = store.config();
|
|
13115
13293
|
const lessons = store.listLessons();
|
|
13116
13294
|
const byKind = (k) => lessons.filter((l) => l.kind === k && l.status !== "retired").length;
|
|
13117
|
-
const recallLessons = store.listRecallLessons().filter((
|
|
13295
|
+
const recallLessons = store.listRecallLessons().filter((r2) => r2.status === "active");
|
|
13118
13296
|
const conflicts = store.listConflicts().filter((c) => c.status === "open");
|
|
13119
13297
|
const metrics = store.readMetrics(void 0);
|
|
13120
13298
|
const last50 = metrics?.windows?.find((w) => w.name === "last50");
|
|
@@ -13181,6 +13359,14 @@ function cmdStatus(store, args, out, v2) {
|
|
|
13181
13359
|
`);
|
|
13182
13360
|
if (last50) out(`recall F1 precision ${pct2(last50.precision)}, recall ${pct2(last50.recall)}, F1 ${pct2(last50.f1)} over ${last50.traces} traces
|
|
13183
13361
|
`);
|
|
13362
|
+
const r = v2.reflection;
|
|
13363
|
+
{
|
|
13364
|
+
if (r?.runs) {
|
|
13365
|
+
const cache = r.hitRate === null ? "no forks" : `forks read ${pct2(r.hitRate)} from the session's cache${r.mode ? ` (${r.mode})` : ""}${r.misses ? ` \u2014 ${r.misses} MISSED: see their reflection traces` : ""}`;
|
|
13366
|
+
out(`reflection 7 days: ${r.runs} run${r.runs === 1 ? "" : "s"}, $${r.costUsd.toFixed(2)}; ${cache}
|
|
13367
|
+
`);
|
|
13368
|
+
}
|
|
13369
|
+
}
|
|
13184
13370
|
return 0;
|
|
13185
13371
|
}
|
|
13186
13372
|
function hookCount(file2) {
|