@bunshin-cc/bunshin 0.12.0 → 0.12.2
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 +286 -40
- 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: [] };
|
|
@@ -2402,7 +2406,7 @@ anchor "${GUIDELINES_ANCHOR}", one general rule in the imperative, with the reas
|
|
|
2402
2406
|
|
|
2403
2407
|
${rules}${route}`;
|
|
2404
2408
|
}
|
|
2405
|
-
var GUIDELINES_ANCHOR, generality;
|
|
2409
|
+
var GUIDELINES_ID, GUIDELINES_ANCHOR, generality;
|
|
2406
2410
|
var init_guidelines = __esm({
|
|
2407
2411
|
"../core/src/v2/guidelines.ts"() {
|
|
2408
2412
|
"use strict";
|
|
@@ -2410,6 +2414,7 @@ var init_guidelines = __esm({
|
|
|
2410
2414
|
init_layers();
|
|
2411
2415
|
init_engine();
|
|
2412
2416
|
init_scopes();
|
|
2417
|
+
GUIDELINES_ID = "reflection:guidelines";
|
|
2413
2418
|
GUIDELINES_ANCHOR = "rules";
|
|
2414
2419
|
generality = (l) => ({ org: 0, group: 1, source: 2, robot: 3, user: 3 })[layerKind(l)] ?? 4;
|
|
2415
2420
|
}
|
|
@@ -3134,7 +3139,37 @@ At most ${max} suggestions. Schema:
|
|
|
3134
3139
|
| {"op": "param", "key": string, "value": string|number|boolean}
|
|
3135
3140
|
| {"op": "situation", "text": string},
|
|
3136
3141
|
"rationale": string, "urgency": "normal"|"urgent",
|
|
3137
|
-
"signal": "steering"|"environment"|"knowledge"|"capability"|"approach"}]
|
|
3142
|
+
"signal": "steering"|"environment"|"knowledge"|"capability"|"approach"}],
|
|
3143
|
+
"considered": [{"moment": string, "decision": "lesson"|"skip", "why": string}]}
|
|
3144
|
+
|
|
3145
|
+
In "considered", list the moments you weighed (a correction, a failure recovered from, something
|
|
3146
|
+
learned about the code or the company), at most 6, most important first: name each in a few words,
|
|
3147
|
+
say whether it became a lesson or was skipped, and why in one sentence. People read this to see
|
|
3148
|
+
what reflection noticed and to steer it; list them even when nothing is new.`;
|
|
3149
|
+
}
|
|
3150
|
+
function runSection(r) {
|
|
3151
|
+
const list2 = (xs) => xs.length ? xs.map((x) => `- ${x}`).join("\n") : "- (none)";
|
|
3152
|
+
return `
|
|
3153
|
+
The feedback is about one earlier reflection run on this session (${r.at}${r.turns ? `, turns ${r.turns.from + 1}\u2013${r.turns.to}` : ""}). This is what it did:
|
|
3154
|
+
|
|
3155
|
+
What it considered:
|
|
3156
|
+
${list2(r.considered.map((c) => `${c.decision === "lesson" ? "took as a lesson" : "skipped"}: ${c.moment} (${c.why})`))}
|
|
3157
|
+
|
|
3158
|
+
What it kept:
|
|
3159
|
+
${list2(r.kept)}
|
|
3160
|
+
${r.dropped.length ? `
|
|
3161
|
+
What it proposed that was refused:
|
|
3162
|
+
${list2(r.dropped.map((d) => `${d.summary} (${d.reason})`))}
|
|
3163
|
+
` : ""}${r.nothingNew ? "\nIt answered that the turns taught nothing new.\n" : ""}
|
|
3164
|
+
That run did not take what the person expected. Before proposing anything, work out from the
|
|
3165
|
+
above why it missed it: it never noticed the moment (not in what it considered), it noticed and
|
|
3166
|
+
skipped it (on what reasoning), or it took a weaker or wrong lesson. Then propose:
|
|
3167
|
+
1. the lesson it should have taken, written as the guidelines ask; and
|
|
3168
|
+
2. a rule for the reflection guidelines (op "append" to ${GUIDELINES_ID}, anchor "rules") that would
|
|
3169
|
+
make a future reflection take that kind of lesson: general, about how to reflect, never about
|
|
3170
|
+
this session's topic, and not a repeat of a rule already there.
|
|
3171
|
+
In "considered", say why that run missed it, in one sentence.
|
|
3172
|
+
`;
|
|
3138
3173
|
}
|
|
3139
3174
|
function feedbackSection(f) {
|
|
3140
3175
|
return `
|
|
@@ -3152,6 +3187,7 @@ The lesson it is about:
|
|
|
3152
3187
|
${f.lesson.trim()}
|
|
3153
3188
|
</lesson>
|
|
3154
3189
|
` : ""}
|
|
3190
|
+
${f.run ? runSection(f.run) : ""}
|
|
3155
3191
|
Treat it as a correction from a person (signal "steering"): the strongest evidence there is. Act on it:
|
|
3156
3192
|
- If it says the session taught something that was missed, capture that lesson in the right
|
|
3157
3193
|
document, written as the guidelines below ask. ${f.transcript ? "Find it in the session below." : "The session's trace is no longer available: work from the feedback itself (the person's own account), the lessons already taken and the documents."}
|
|
@@ -3185,6 +3221,12 @@ and name what you correct in the rationale (e.g. "contradicts g_ab12: uploads wo
|
|
|
3185
3221
|
|
|
3186
3222
|
${body}`;
|
|
3187
3223
|
}
|
|
3224
|
+
function parseConsidered(raw) {
|
|
3225
|
+
const value = typeof raw === "string" ? extractJson(raw) : raw;
|
|
3226
|
+
const list2 = value && typeof value === "object" ? value.considered : void 0;
|
|
3227
|
+
if (!Array.isArray(list2)) return [];
|
|
3228
|
+
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);
|
|
3229
|
+
}
|
|
3188
3230
|
function extractJson(text2) {
|
|
3189
3231
|
try {
|
|
3190
3232
|
const whole = JSON.parse(text2.trim());
|
|
@@ -3368,6 +3410,14 @@ var init_reflect = __esm({
|
|
|
3368
3410
|
signal: { type: "string", enum: ["steering", "environment", "knowledge", "capability", "approach"] }
|
|
3369
3411
|
}
|
|
3370
3412
|
}
|
|
3413
|
+
},
|
|
3414
|
+
considered: {
|
|
3415
|
+
type: "array",
|
|
3416
|
+
items: {
|
|
3417
|
+
type: "object",
|
|
3418
|
+
required: ["moment", "decision", "why"],
|
|
3419
|
+
properties: { moment: { type: "string" }, decision: { type: "string", enum: ["lesson", "skip"] }, why: { type: "string" } }
|
|
3420
|
+
}
|
|
3371
3421
|
}
|
|
3372
3422
|
}
|
|
3373
3423
|
};
|
|
@@ -6767,6 +6817,7 @@ var init_sync = __esm({
|
|
|
6767
6817
|
|
|
6768
6818
|
// src/v2/reflect.ts
|
|
6769
6819
|
import { spawn as spawn3 } from "node:child_process";
|
|
6820
|
+
import os3 from "node:os";
|
|
6770
6821
|
import { createHash as createHash4 } from "node:crypto";
|
|
6771
6822
|
import fs16 from "node:fs";
|
|
6772
6823
|
import path12 from "node:path";
|
|
@@ -6774,24 +6825,142 @@ function episodeIdFor(contextId, sessionId) {
|
|
|
6774
6825
|
return `e_${createHash4("sha256").update(`${contextId}
|
|
6775
6826
|
${sessionId}`).digest("hex").slice(0, 16)}`;
|
|
6776
6827
|
}
|
|
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
|
|
6828
|
+
function forkArgs(sessionId, prompt, mode, model) {
|
|
6829
|
+
const head = ["-p", "--resume", sessionId, "--fork-session", "--output-format", "json", ...model ? ["--model", model] : []];
|
|
6830
|
+
if (mode === "isolated") return [...head, "--strict-mcp-config", "--disallowedTools", FORK_DENIED_TOOLS, "--max-turns", "1", prompt];
|
|
6831
|
+
return [...head, "--settings", FORK_GUARD_SETTINGS, "--permission-prompts", "none", "--max-turns", "3", prompt];
|
|
6832
|
+
}
|
|
6833
|
+
function forkGuardAvailable(cwd, home = os3.homedir()) {
|
|
6834
|
+
const files = [
|
|
6835
|
+
path12.join(home, ".claude", "settings.json"),
|
|
6836
|
+
...cwd ? [path12.join(cwd, ".claude", "settings.json"), path12.join(cwd, ".claude", "settings.local.json")] : [],
|
|
6837
|
+
"/etc/claude-code/managed-settings.json",
|
|
6838
|
+
"/Library/Application Support/ClaudeCode/managed-settings.json"
|
|
6794
6839
|
];
|
|
6840
|
+
return !files.some((f) => {
|
|
6841
|
+
const s = readSettings(f);
|
|
6842
|
+
return s.disableAllHooks === true || s.allowManagedHooksOnly === true;
|
|
6843
|
+
});
|
|
6844
|
+
}
|
|
6845
|
+
function sessionModel(transcriptPath) {
|
|
6846
|
+
if (!transcriptPath) return void 0;
|
|
6847
|
+
try {
|
|
6848
|
+
const fd = fs16.openSync(transcriptPath, "r");
|
|
6849
|
+
try {
|
|
6850
|
+
const size = fs16.fstatSync(fd).size;
|
|
6851
|
+
const len = Math.min(size, 4 * 1024 * 1024);
|
|
6852
|
+
const buf = Buffer.alloc(len);
|
|
6853
|
+
fs16.readSync(fd, buf, 0, len, size - len);
|
|
6854
|
+
const lines = buf.toString("utf8").split("\n").reverse();
|
|
6855
|
+
for (const l of lines) {
|
|
6856
|
+
if (!l.includes('"assistant"')) continue;
|
|
6857
|
+
try {
|
|
6858
|
+
const d = JSON.parse(l);
|
|
6859
|
+
if (d.type === "assistant" && d.message?.model && d.message.model !== "<synthetic>") return d.message.model;
|
|
6860
|
+
} catch {
|
|
6861
|
+
}
|
|
6862
|
+
}
|
|
6863
|
+
} finally {
|
|
6864
|
+
fs16.closeSync(fd);
|
|
6865
|
+
}
|
|
6866
|
+
} catch {
|
|
6867
|
+
}
|
|
6868
|
+
return void 0;
|
|
6869
|
+
}
|
|
6870
|
+
function lastLineWith(file2, needle, chunk = 1024 * 1024) {
|
|
6871
|
+
let fd;
|
|
6872
|
+
try {
|
|
6873
|
+
fd = fs16.openSync(file2, "r");
|
|
6874
|
+
let pos = fs16.fstatSync(fd).size;
|
|
6875
|
+
let carry = "";
|
|
6876
|
+
while (pos > 0) {
|
|
6877
|
+
const len = Math.min(chunk, pos);
|
|
6878
|
+
pos -= len;
|
|
6879
|
+
const buf = Buffer.alloc(len);
|
|
6880
|
+
fs16.readSync(fd, buf, 0, len, pos);
|
|
6881
|
+
const text2 = buf.toString("utf8") + carry;
|
|
6882
|
+
const lines = text2.split("\n");
|
|
6883
|
+
carry = pos > 0 ? lines.shift() ?? "" : "";
|
|
6884
|
+
for (let i = lines.length - 1; i >= 0; i--) if (lines[i].includes(needle)) return lines[i];
|
|
6885
|
+
}
|
|
6886
|
+
return void 0;
|
|
6887
|
+
} catch {
|
|
6888
|
+
return void 0;
|
|
6889
|
+
} finally {
|
|
6890
|
+
if (fd !== void 0) fs16.closeSync(fd);
|
|
6891
|
+
}
|
|
6892
|
+
}
|
|
6893
|
+
function sessionCostSoFar(transcriptPath) {
|
|
6894
|
+
if (!transcriptPath) return void 0;
|
|
6895
|
+
const line = lastLineWith(transcriptPath, '"cost-state"');
|
|
6896
|
+
if (!line) return void 0;
|
|
6897
|
+
try {
|
|
6898
|
+
const v = JSON.parse(line).totalCostUSD;
|
|
6899
|
+
return typeof v === "number" ? v : void 0;
|
|
6900
|
+
} catch {
|
|
6901
|
+
return void 0;
|
|
6902
|
+
}
|
|
6903
|
+
}
|
|
6904
|
+
function transcriptIdleMs(transcriptPath, now = Date.now()) {
|
|
6905
|
+
if (!transcriptPath) return void 0;
|
|
6906
|
+
try {
|
|
6907
|
+
return Math.max(0, now - fs16.statSync(transcriptPath).mtimeMs);
|
|
6908
|
+
} catch {
|
|
6909
|
+
return void 0;
|
|
6910
|
+
}
|
|
6911
|
+
}
|
|
6912
|
+
function forkOwnCost(reported, before) {
|
|
6913
|
+
if (reported === void 0) return void 0;
|
|
6914
|
+
return before === void 0 ? reported : Math.max(0, reported - before);
|
|
6915
|
+
}
|
|
6916
|
+
function cacheHitRate(u) {
|
|
6917
|
+
if (!u) return void 0;
|
|
6918
|
+
const read = u.cache_read_input_tokens ?? 0;
|
|
6919
|
+
const total = read + (u.cache_creation_input_tokens ?? 0) + (u.input_tokens ?? 0);
|
|
6920
|
+
return total > 0 ? read / total : void 0;
|
|
6921
|
+
}
|
|
6922
|
+
function readForkCache(v2) {
|
|
6923
|
+
try {
|
|
6924
|
+
return JSON.parse(fs16.readFileSync(v2.p(FORK_CACHE_FILE), "utf8")).forks ?? [];
|
|
6925
|
+
} catch {
|
|
6926
|
+
return [];
|
|
6927
|
+
}
|
|
6928
|
+
}
|
|
6929
|
+
function recordForkCache(v2, rec) {
|
|
6930
|
+
try {
|
|
6931
|
+
fs16.writeFileSync(v2.p(FORK_CACHE_FILE), JSON.stringify({ forks: [...readForkCache(v2), rec].slice(-50) }, null, 2));
|
|
6932
|
+
} catch {
|
|
6933
|
+
}
|
|
6934
|
+
}
|
|
6935
|
+
function forkDecision(records, o) {
|
|
6936
|
+
if (o.learn) return { fork: true, reason: "asked for (/learn)" };
|
|
6937
|
+
if (o.tokens <= o.limit) return { fork: true, reason: "short session" };
|
|
6938
|
+
const now = o.now ?? Date.now();
|
|
6939
|
+
const latest = [...records].reverse().find((r) => r.mode === "faithful" && !r.cold && r.tokens > o.limit && now - Date.parse(r.at) < MISS_HOLD_MS);
|
|
6940
|
+
if (latest && latest.hitRate < CACHE_MISS) return { fork: false, reason: `the last fork here missed the session's cache (${Math.round(latest.hitRate * 100)}% read from cache): digest of the new turns` };
|
|
6941
|
+
return { fork: true, reason: latest ? `forks here read ${Math.round(latest.hitRate * 100)}% from the session's cache` : "first fork of a large session here" };
|
|
6942
|
+
}
|
|
6943
|
+
function reflectionSummary(v2, days = 7, now = Date.now()) {
|
|
6944
|
+
const since = now - days * 864e5;
|
|
6945
|
+
const traces = v2.listReflections().filter((t) => Date.parse(t.startedAt) >= since);
|
|
6946
|
+
let read = 0;
|
|
6947
|
+
let paid = 0;
|
|
6948
|
+
let misses = 0;
|
|
6949
|
+
let forks = 0;
|
|
6950
|
+
for (const t of traces) {
|
|
6951
|
+
if (t.method !== "fork" || !t.usage) continue;
|
|
6952
|
+
forks++;
|
|
6953
|
+
read += t.usage.cacheRead ?? 0;
|
|
6954
|
+
paid += (t.usage.cacheWrite ?? 0) + (t.usage.input ?? 0);
|
|
6955
|
+
const rate = t.cache?.hitRate;
|
|
6956
|
+
if (rate !== void 0 && rate < CACHE_MISS && !t.cache?.cold) misses++;
|
|
6957
|
+
}
|
|
6958
|
+
const latest = [...readForkCache(v2)].reverse()[0];
|
|
6959
|
+
return { runs: traces.length, costUsd: traces.reduce((a, t) => a + (t.costUsd ?? 0), 0), forks, hitRate: read + paid > 0 ? read / (read + paid) : null, misses, mode: latest?.mode ?? null };
|
|
6960
|
+
}
|
|
6961
|
+
function runClaudeFork(sessionId, prompt, { cwd, model, mode = "faithful", timeoutMs = FORK_TIMEOUT_MS } = {}) {
|
|
6962
|
+
const bin = process.env.BUNSHIN_CLAUDE_BIN || "claude";
|
|
6963
|
+
const args = forkArgs(sessionId, prompt, mode, model);
|
|
6795
6964
|
return new Promise((resolve) => {
|
|
6796
6965
|
let out = "";
|
|
6797
6966
|
let err = "";
|
|
@@ -6922,6 +7091,18 @@ async function runReflectionV2(store, opts) {
|
|
|
6922
7091
|
...reflectionIndex(view, [...session.loaded, ...session.pushed, ...session.served], session.task, opts.focus, humanTurnsOf(session.transcriptPath)).filter((s) => s.id !== profile?.id)
|
|
6923
7092
|
];
|
|
6924
7093
|
const harness = session.harness ?? config.harness;
|
|
7094
|
+
if (session.serverReflectedTurns === void 0 && canCall(config)) {
|
|
7095
|
+
try {
|
|
7096
|
+
const cur = await v2api(config, "GET", `/episodes/${encodeURIComponent(episodeId)}/cursor`, void 0, { timeoutMs: 5e3 });
|
|
7097
|
+
v2.updateSession(opts.sessionId, session.cwd, (s) => {
|
|
7098
|
+
s.serverReflectedTurns = Math.max(s.serverReflectedTurns ?? 0, typeof cur.reflectedTurns === "number" ? cur.reflectedTurns : 0);
|
|
7099
|
+
if (Array.isArray(cur.lessons)) s.serverLessons = cur.lessons.filter((l) => typeof l === "string").slice(0, 40);
|
|
7100
|
+
});
|
|
7101
|
+
} catch (err) {
|
|
7102
|
+
if (err instanceof ApiError && err.status === 404) v2.updateSession(opts.sessionId, session.cwd, (s) => void (s.serverReflectedTurns ??= 0));
|
|
7103
|
+
}
|
|
7104
|
+
Object.assign(session, v2.readSession(opts.sessionId) ?? {});
|
|
7105
|
+
}
|
|
6925
7106
|
const facts = readFacts(session.transcriptPath);
|
|
6926
7107
|
const turns = facts?.turns.length ?? 0;
|
|
6927
7108
|
const from = reflectCursor(session, turns);
|
|
@@ -6931,13 +7112,42 @@ async function runReflectionV2(store, opts) {
|
|
|
6931
7112
|
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
7113
|
let raw = null;
|
|
6933
7114
|
const call2 = {};
|
|
6934
|
-
|
|
7115
|
+
const sessionTokens = estimateSessionTokens(session.transcriptPath);
|
|
7116
|
+
const limit = config.reflect.forkMaxTokens ?? 6e4;
|
|
7117
|
+
const decision = forkDecision(readForkCache(v2), { learn: origin === "learn", tokens: sessionTokens, limit });
|
|
7118
|
+
const useFork = harness === "claude-code" && decision.fork;
|
|
7119
|
+
if (harness === "claude-code") call2.cacheNote = decision.reason;
|
|
7120
|
+
if (useFork) {
|
|
6935
7121
|
const prompt = buildReflectPrompt(promptBase);
|
|
6936
|
-
const
|
|
7122
|
+
const guard = forkGuardAvailable(session.cwd);
|
|
7123
|
+
const mode = config.reflect.forkMode === "isolated" || !guard ? "isolated" : "faithful";
|
|
7124
|
+
if (mode === "isolated") call2.cacheNote = guard ? "reflect.forkMode is isolated in this machine's config" : "hooks are turned off on this machine (disableAllHooks or allowManagedHooksOnly), so the guard that stops a fork acting cannot run";
|
|
7125
|
+
const model = mode === "faithful" ? sessionModel(session.transcriptPath) ?? config.model : config.model;
|
|
7126
|
+
const before = sessionCostSoFar(session.transcriptPath);
|
|
7127
|
+
const idleMs = transcriptIdleMs(session.transcriptPath);
|
|
7128
|
+
const cold = idleMs !== void 0 && idleMs > Math.max(config.reflect.cacheTtlMs, 5 * 6e4);
|
|
7129
|
+
const fork = await runClaudeFork(opts.sessionId, prompt, { cwd: session.cwd, model, mode });
|
|
7130
|
+
fork.costUsd = forkOwnCost(fork.costUsd, before);
|
|
7131
|
+
const hitRate = cacheHitRate(fork.usage);
|
|
7132
|
+
call2.cacheMode = mode;
|
|
7133
|
+
if (hitRate !== void 0) {
|
|
7134
|
+
call2.hitRate = hitRate;
|
|
7135
|
+
const coldMiss = cold && hitRate < CACHE_MISS;
|
|
7136
|
+
if (coldMiss) {
|
|
7137
|
+
call2.cacheCold = true;
|
|
7138
|
+
call2.cacheNote = `the session's prompt cache had expired (idle ${Math.round(idleMs / 6e4)} min before this fork): not counted as a miss`;
|
|
7139
|
+
}
|
|
7140
|
+
recordForkCache(v2, { at: (/* @__PURE__ */ new Date()).toISOString(), sessionId: opts.sessionId, mode, tokens: sessionTokens, hitRate, ...fork.costUsd !== void 0 ? { costUsd: fork.costUsd } : {}, ...coldMiss ? { cold: true } : {} });
|
|
7141
|
+
if (mode === "faithful" && hitRate < CACHE_MISS && sessionTokens > limit && !coldMiss) {
|
|
7142
|
+
const cost = fork.costUsd !== void 0 ? ` ($${fork.costUsd.toFixed(2)})` : "";
|
|
7143
|
+
v2.log("v2-reflect-cache-miss", { session: opts.sessionId, hitRate, tokens: sessionTokens, costUsd: fork.costUsd ?? null });
|
|
7144
|
+
updateFeed(v2, opts.sessionId, (f) => addEvent(f, "warning", `reflection did not reuse this session's prompt cache${cost}: large sessions here reflect from a digest of their new turns for now`));
|
|
7145
|
+
}
|
|
7146
|
+
}
|
|
6937
7147
|
Object.assign(call2, {
|
|
6938
7148
|
prompt,
|
|
6939
7149
|
executor: "edge:claude-cli",
|
|
6940
|
-
model
|
|
7150
|
+
model,
|
|
6941
7151
|
...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
7152
|
...fork.costUsd !== void 0 ? { costUsd: fork.costUsd } : {}
|
|
6943
7153
|
});
|
|
@@ -6946,8 +7156,10 @@ async function runReflectionV2(store, opts) {
|
|
|
6946
7156
|
v2.log("v2-reflect-fork", {
|
|
6947
7157
|
session: opts.sessionId,
|
|
6948
7158
|
ok: fork.ok,
|
|
6949
|
-
model
|
|
7159
|
+
model,
|
|
7160
|
+
mode,
|
|
6950
7161
|
cache: true,
|
|
7162
|
+
hit_rate: hitRate ?? null,
|
|
6951
7163
|
cache_read_input_tokens: fork.usage?.cache_read_input_tokens ?? null,
|
|
6952
7164
|
cache_creation_input_tokens: fork.usage?.cache_creation_input_tokens ?? null,
|
|
6953
7165
|
total_cost_usd: fork.costUsd ?? null,
|
|
@@ -6961,9 +7173,11 @@ async function runReflectionV2(store, opts) {
|
|
|
6961
7173
|
if (result.method === "none" && session.transcriptPath && fs16.existsSync(session.transcriptPath)) {
|
|
6962
7174
|
const transcriptDigest = digest(facts ?? parseTranscript(session.transcriptPath), { from, maxChars: 4e4 });
|
|
6963
7175
|
const digestPrompt = buildReflectPrompt({ ...promptBase, transcriptDigest });
|
|
7176
|
+
const digestUsage = {};
|
|
6964
7177
|
const res = await askJson(config, {
|
|
6965
7178
|
system: "You are Bunshin's reflection pass. Follow the instructions in the user message and reply with one JSON object only.",
|
|
6966
7179
|
user: digestPrompt,
|
|
7180
|
+
onUsage: ({ costUsd, ...usage }) => Object.assign(digestUsage, { usage, ...costUsd !== void 0 ? { costUsd } : {} }),
|
|
6967
7181
|
schema: REFLECT_SCHEMA,
|
|
6968
7182
|
timeoutMs: FORK_TIMEOUT_MS,
|
|
6969
7183
|
cwd: session.cwd
|
|
@@ -6973,7 +7187,7 @@ async function runReflectionV2(store, opts) {
|
|
|
6973
7187
|
raw = res.value;
|
|
6974
7188
|
result.method = "digest";
|
|
6975
7189
|
result.error = void 0;
|
|
6976
|
-
Object.assign(call2, { prompt: digestPrompt, executor: `edge:${res.backend}`, model: config.model, thinking: void 0, usage:
|
|
7190
|
+
Object.assign(call2, { prompt: digestPrompt, executor: `edge:${res.backend}`, model: config.model, thinking: void 0, usage: digestUsage.usage, costUsd: digestUsage.costUsd });
|
|
6977
7191
|
} else result.error = [result.error, res.error].filter(Boolean).join("; ");
|
|
6978
7192
|
}
|
|
6979
7193
|
const known = /* @__PURE__ */ new Set([...view.byId.keys(), ...index.map((s) => s.id)]);
|
|
@@ -7050,9 +7264,11 @@ async function runReflectionV2(store, opts) {
|
|
|
7050
7264
|
...call2.thinking ? { thinking: call2.thinking } : {},
|
|
7051
7265
|
...raw !== null ? { output: typeof raw === "string" ? raw : JSON.stringify(raw, null, 2) } : {},
|
|
7052
7266
|
proposals: [...kept, ...refused].sort((a, b) => a.index - b.index),
|
|
7267
|
+
...raw !== null && parseConsidered(raw).length ? { considered: parseConsidered(raw) } : {},
|
|
7053
7268
|
nothingNew: result.nothingNew,
|
|
7054
7269
|
...call2.usage ? { usage: call2.usage } : {},
|
|
7055
7270
|
...call2.costUsd !== void 0 ? { costUsd: call2.costUsd } : {},
|
|
7271
|
+
...call2.cacheNote || call2.hitRate !== void 0 ? { cache: { ...call2.cacheMode ? { mode: call2.cacheMode } : {}, ...call2.hitRate !== void 0 ? { hitRate: Math.round(call2.hitRate * 1e3) / 1e3 } : {}, ...call2.cacheNote ? { note: call2.cacheNote } : {}, ...call2.cacheCold ? { cold: true } : {} } } : {},
|
|
7056
7272
|
durationMs: Date.now() - Date.parse(startedAt),
|
|
7057
7273
|
...result.error ? { error: result.error } : {},
|
|
7058
7274
|
startedAt,
|
|
@@ -7090,6 +7306,14 @@ async function runReflectionV2(store, opts) {
|
|
|
7090
7306
|
}
|
|
7091
7307
|
return result;
|
|
7092
7308
|
}
|
|
7309
|
+
function estimateSessionTokens(transcriptPath) {
|
|
7310
|
+
if (!transcriptPath) return 0;
|
|
7311
|
+
try {
|
|
7312
|
+
return Math.round(fs16.statSync(transcriptPath).size / 7);
|
|
7313
|
+
} catch {
|
|
7314
|
+
return 0;
|
|
7315
|
+
}
|
|
7316
|
+
}
|
|
7093
7317
|
function proposalSummary(item) {
|
|
7094
7318
|
const it = item && typeof item === "object" ? item : {};
|
|
7095
7319
|
const op = it.op && typeof it.op === "object" ? it.op : void 0;
|
|
@@ -7111,7 +7335,7 @@ function learnLines(result, view) {
|
|
|
7111
7335
|
return applied ? `captured: ${s.summary ?? summarize(s.op)} \u2192 ${target}` : `proposed (not applied): ${s.summary ?? summarize(s.op)} \u2192 ${target}`;
|
|
7112
7336
|
});
|
|
7113
7337
|
}
|
|
7114
|
-
var FORK_TIMEOUT_MS, FORK_DENIED_TOOLS;
|
|
7338
|
+
var FORK_TIMEOUT_MS, FORK_DENIED_TOOLS, FORK_GUARD_SETTINGS, readSettings, FORK_CACHE_FILE, CACHE_MISS, MISS_HOLD_MS;
|
|
7115
7339
|
var init_reflect3 = __esm({
|
|
7116
7340
|
"src/v2/reflect.ts"() {
|
|
7117
7341
|
"use strict";
|
|
@@ -7126,6 +7350,19 @@ var init_reflect3 = __esm({
|
|
|
7126
7350
|
init_view();
|
|
7127
7351
|
FORK_TIMEOUT_MS = 12e4;
|
|
7128
7352
|
FORK_DENIED_TOOLS = "Bash,Edit,Write,MultiEdit,NotebookEdit,WebFetch,WebSearch,Task,Agent,Skill,SlashCommand";
|
|
7353
|
+
FORK_GUARD_SETTINGS = JSON.stringify({
|
|
7354
|
+
hooks: { PreToolUse: [{ matcher: "*", hooks: [{ type: "command", command: "echo 'Bunshin reflection: tools are disabled here; answer with the JSON only.' >&2; exit 2" }] }] }
|
|
7355
|
+
});
|
|
7356
|
+
readSettings = (file2) => {
|
|
7357
|
+
try {
|
|
7358
|
+
return JSON.parse(fs16.readFileSync(file2, "utf8"));
|
|
7359
|
+
} catch {
|
|
7360
|
+
return {};
|
|
7361
|
+
}
|
|
7362
|
+
};
|
|
7363
|
+
FORK_CACHE_FILE = "fork-cache.json";
|
|
7364
|
+
CACHE_MISS = 0.5;
|
|
7365
|
+
MISS_HOLD_MS = 7 * 24 * 36e5;
|
|
7129
7366
|
}
|
|
7130
7367
|
});
|
|
7131
7368
|
|
|
@@ -7386,10 +7623,10 @@ __export(uicmd_exports, {
|
|
|
7386
7623
|
});
|
|
7387
7624
|
import { spawnSync } from "node:child_process";
|
|
7388
7625
|
import fs18 from "node:fs";
|
|
7389
|
-
import
|
|
7626
|
+
import os4 from "node:os";
|
|
7390
7627
|
import path14 from "node:path";
|
|
7391
7628
|
import { fileURLToPath } from "node:url";
|
|
7392
|
-
function modHome(home = process.env.BUNSHIN_DEPLOY_HOME ||
|
|
7629
|
+
function modHome(home = process.env.BUNSHIN_DEPLOY_HOME || os4.homedir()) {
|
|
7393
7630
|
return path14.join(home, ".bunshin", "claude-code-ui");
|
|
7394
7631
|
}
|
|
7395
7632
|
function modSource() {
|
|
@@ -8190,10 +8427,10 @@ function onStop(ctx) {
|
|
|
8190
8427
|
function autoReflect(ctx, v2, config, session, scan, now) {
|
|
8191
8428
|
if (!config.reflect.enabled) return false;
|
|
8192
8429
|
const last = Date.parse(session.autoReflectAt ?? session.reflectedAt ?? "");
|
|
8193
|
-
if (Number.isFinite(last) && now.getTime() - last < Math.max(0, config.reflect.
|
|
8430
|
+
if (Number.isFinite(last) && now.getTime() - last < Math.max(0, config.reflect.continualMinutes ?? 20) * 6e4) return false;
|
|
8194
8431
|
const from = reflectCursor(session, scan.facts.turns.length);
|
|
8195
8432
|
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 });
|
|
8433
|
+
const gate = sessionGate(signals, { now: now.toISOString(), cacheTtlMs: config.reflect.cacheTtlMs, minToolCalls: config.reflect.continualMinToolCalls ?? 30 });
|
|
8197
8434
|
if (!gate.reflect) return false;
|
|
8198
8435
|
v2.updateSession(session.sessionId, ctx.cwd, (s) => {
|
|
8199
8436
|
s.autoReflectAt = now.toISOString();
|
|
@@ -9843,6 +10080,7 @@ function v2Status(store, cwd) {
|
|
|
9843
10080
|
const sync = v2.readSyncState();
|
|
9844
10081
|
const pooled = cwdInPool(config, cwd, store.root);
|
|
9845
10082
|
return {
|
|
10083
|
+
reflection: reflectionSummary(v2),
|
|
9846
10084
|
context: { id: view.ctx.id, kind: view.ctx.kind, layers: view.layers },
|
|
9847
10085
|
source: { id: pooled ? sourceFor(cwd, store.root, view.ctx) ?? null : null, inPool: pooled, folder: topFolder(cwd, store.root) || null },
|
|
9848
10086
|
bundle: bundle ? { sections: bundle.sections.length, generatedAt: bundle.generatedAt, release: bundle.release?.version ?? null } : null,
|
|
@@ -10415,10 +10653,10 @@ __export(demo_exports, {
|
|
|
10415
10653
|
});
|
|
10416
10654
|
import assert from "node:assert/strict";
|
|
10417
10655
|
import fs27 from "node:fs";
|
|
10418
|
-
import
|
|
10656
|
+
import os5 from "node:os";
|
|
10419
10657
|
import path23 from "node:path";
|
|
10420
10658
|
async function runDemo(write) {
|
|
10421
|
-
const root = fs27.mkdtempSync(path23.join(
|
|
10659
|
+
const root = fs27.mkdtempSync(path23.join(os5.tmpdir(), "bunshin-demo-"));
|
|
10422
10660
|
try {
|
|
10423
10661
|
const store = Store.init(root, { ...DEMO_ENGINEER, apiUrl: "" });
|
|
10424
10662
|
const { lessons, constraint, workflow } = demoScenario();
|
|
@@ -11000,9 +11238,9 @@ __export(runner_exports, {
|
|
|
11000
11238
|
});
|
|
11001
11239
|
import { spawnSync as spawnSync3 } from "node:child_process";
|
|
11002
11240
|
import fs30 from "node:fs";
|
|
11003
|
-
import
|
|
11241
|
+
import os6 from "node:os";
|
|
11004
11242
|
import path26 from "node:path";
|
|
11005
|
-
function runnerHome(home = process.env.BUNSHIN_RUNNER_HOME ||
|
|
11243
|
+
function runnerHome(home = process.env.BUNSHIN_RUNNER_HOME || os6.homedir()) {
|
|
11006
11244
|
return path26.join(home, ".bunshin", "runner");
|
|
11007
11245
|
}
|
|
11008
11246
|
function readInstalled(home) {
|
|
@@ -11020,7 +11258,7 @@ function connection(args, cwd) {
|
|
|
11020
11258
|
const apiUrl = (str5(args.flags["api-url"]) || process.env.BUNSHIN_API_URL || config?.apiUrl || saved?.apiUrl || DEFAULT_API).replace(/\/$/, "");
|
|
11021
11259
|
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
11260
|
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 ?? `${
|
|
11261
|
+
const name = str5(args.flags.name) ?? process.env.BUNSHIN_RUNNER_NAME ?? saved?.name ?? `${os6.hostname().split(".")[0] || "runner"}`;
|
|
11024
11262
|
return { apiUrl, key, name: name.replace(/[^\w.:@/-]/g, "-").slice(0, 80) };
|
|
11025
11263
|
}
|
|
11026
11264
|
async function call(c, method, route, body, timeoutMs = 6e4) {
|
|
@@ -11074,7 +11312,7 @@ async function runOnce(c, args, out, err) {
|
|
|
11074
11312
|
const [job] = await lease(c, args);
|
|
11075
11313
|
if (!job) break;
|
|
11076
11314
|
const started = Date.now();
|
|
11077
|
-
const scratch = fs30.mkdtempSync(path26.join(
|
|
11315
|
+
const scratch = fs30.mkdtempSync(path26.join(os6.tmpdir(), "bunshin-job-"));
|
|
11078
11316
|
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
11317
|
() => fs30.rmSync(scratch, { recursive: true, force: true })
|
|
11080
11318
|
);
|
|
@@ -11173,7 +11411,7 @@ function logAnswer(entry) {
|
|
|
11173
11411
|
}
|
|
11174
11412
|
}
|
|
11175
11413
|
function which(name) {
|
|
11176
|
-
for (const d of [...(process.env.PATH || "").split(path26.delimiter), path26.join(
|
|
11414
|
+
for (const d of [...(process.env.PATH || "").split(path26.delimiter), path26.join(os6.homedir(), ".local", "bin")]) {
|
|
11177
11415
|
if (d && fs30.existsSync(path26.join(d, name))) return path26.join(d, name);
|
|
11178
11416
|
}
|
|
11179
11417
|
return null;
|
|
@@ -11182,7 +11420,7 @@ function scheduledCommand(backend) {
|
|
|
11182
11420
|
const node = path26.dirname(process.execPath);
|
|
11183
11421
|
const npx = fs30.existsSync(path26.join(node, "npx")) ? path26.join(node, "npx") : which("npx") ?? "npx";
|
|
11184
11422
|
const bin = BIN_OF[backend] ? which(BIN_OF[backend]) : null;
|
|
11185
|
-
const dirs = [.../* @__PURE__ */ new Set([node, ...bin ? [path26.dirname(bin)] : [], path26.join(
|
|
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"])];
|
|
11186
11424
|
return { argv: [npx, "-y", PKG2, "runner", "--once"], path: dirs.join(path26.delimiter) };
|
|
11187
11425
|
}
|
|
11188
11426
|
function launchdPlist(backend, everyMinutes, home = runnerHome()) {
|
|
@@ -11213,7 +11451,7 @@ function cronLine(backend, everyMinutes, home = runnerHome()) {
|
|
|
11213
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}`;
|
|
11214
11452
|
}
|
|
11215
11453
|
function launchAgentsDir(opts) {
|
|
11216
|
-
return opts.launchAgents ?? path26.join(process.env.BUNSHIN_RUNNER_HOME ||
|
|
11454
|
+
return opts.launchAgents ?? path26.join(process.env.BUNSHIN_RUNNER_HOME || os6.homedir(), "Library", "LaunchAgents");
|
|
11217
11455
|
}
|
|
11218
11456
|
function installSchedule(backend, everyMinutes, opts = {}) {
|
|
11219
11457
|
const platform = opts.platform ?? process.platform;
|
|
@@ -13114,7 +13352,7 @@ function cmdStatus(store, args, out, v2) {
|
|
|
13114
13352
|
const config = store.config();
|
|
13115
13353
|
const lessons = store.listLessons();
|
|
13116
13354
|
const byKind = (k) => lessons.filter((l) => l.kind === k && l.status !== "retired").length;
|
|
13117
|
-
const recallLessons = store.listRecallLessons().filter((
|
|
13355
|
+
const recallLessons = store.listRecallLessons().filter((r2) => r2.status === "active");
|
|
13118
13356
|
const conflicts = store.listConflicts().filter((c) => c.status === "open");
|
|
13119
13357
|
const metrics = store.readMetrics(void 0);
|
|
13120
13358
|
const last50 = metrics?.windows?.find((w) => w.name === "last50");
|
|
@@ -13181,6 +13419,14 @@ function cmdStatus(store, args, out, v2) {
|
|
|
13181
13419
|
`);
|
|
13182
13420
|
if (last50) out(`recall F1 precision ${pct2(last50.precision)}, recall ${pct2(last50.recall)}, F1 ${pct2(last50.f1)} over ${last50.traces} traces
|
|
13183
13421
|
`);
|
|
13422
|
+
const r = v2.reflection;
|
|
13423
|
+
{
|
|
13424
|
+
if (r?.runs) {
|
|
13425
|
+
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` : ""}`;
|
|
13426
|
+
out(`reflection 7 days: ${r.runs} run${r.runs === 1 ? "" : "s"}, $${r.costUsd.toFixed(2)}; ${cache}
|
|
13427
|
+
`);
|
|
13428
|
+
}
|
|
13429
|
+
}
|
|
13184
13430
|
return 0;
|
|
13185
13431
|
}
|
|
13186
13432
|
function hookCount(file2) {
|