@bunshin-cc/bunshin 0.14.0 → 0.14.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 +108 -33
- package/package.json +1 -1
package/dist/bin.js
CHANGED
|
@@ -6956,9 +6956,34 @@ function transcriptIdleMs(transcriptPath, now = Date.now()) {
|
|
|
6956
6956
|
return void 0;
|
|
6957
6957
|
}
|
|
6958
6958
|
}
|
|
6959
|
-
function forkOwnCost(reported, before) {
|
|
6959
|
+
function forkOwnCost(reported, before, estimate) {
|
|
6960
|
+
const diff = reported !== void 0 && before !== void 0 ? reported - before : void 0;
|
|
6961
|
+
const near = (a, b) => a > 0 && b > 0 && a / b < 2 && b / a < 2;
|
|
6962
|
+
if (estimate !== void 0) {
|
|
6963
|
+
if (diff !== void 0 && near(diff, estimate)) return diff;
|
|
6964
|
+
if (reported !== void 0 && near(reported, estimate)) return reported;
|
|
6965
|
+
return estimate;
|
|
6966
|
+
}
|
|
6960
6967
|
if (reported === void 0) return void 0;
|
|
6961
|
-
|
|
6968
|
+
if (before === void 0) return reported;
|
|
6969
|
+
if (diff < 0) return reported;
|
|
6970
|
+
return diff > 0 ? diff : void 0;
|
|
6971
|
+
}
|
|
6972
|
+
function estimateForkCost(usage, modelUsage, model) {
|
|
6973
|
+
if (!usage || !modelUsage) return void 0;
|
|
6974
|
+
const base = (m) => m.replace(/\[.*\]$/, "");
|
|
6975
|
+
const entries = Object.entries(modelUsage);
|
|
6976
|
+
const entry = entries.find(([m]) => model && base(m) === base(model))?.[1] ?? entries.sort((a, b) => (b[1].costUSD ?? 0) - (a[1].costUSD ?? 0))[0]?.[1];
|
|
6977
|
+
if (!entry?.costUSD) return void 0;
|
|
6978
|
+
const w1h = entry.cacheCreationEphemeral1hInputTokens ?? 0;
|
|
6979
|
+
const w5m = entry.cacheCreationEphemeral5mInputTokens ?? Math.max(0, (entry.cacheCreationInputTokens ?? 0) - w1h);
|
|
6980
|
+
const weighted = (entry.inputTokens ?? 0) * TOKEN_WEIGHT.input + (entry.cacheReadInputTokens ?? 0) * TOKEN_WEIGHT.read + w5m * TOKEN_WEIGHT.write5m + w1h * TOKEN_WEIGHT.write1h + (entry.outputTokens ?? 0) * TOKEN_WEIGHT.output;
|
|
6981
|
+
if (weighted <= 0) return void 0;
|
|
6982
|
+
const own1h = usage.cache_creation?.ephemeral_1h_input_tokens;
|
|
6983
|
+
const ownWrite = usage.cache_creation_input_tokens ?? 0;
|
|
6984
|
+
const ownW = own1h !== void 0 ? own1h * TOKEN_WEIGHT.write1h + Math.max(0, ownWrite - own1h) * TOKEN_WEIGHT.write5m : ownWrite * TOKEN_WEIGHT.write1h;
|
|
6985
|
+
const own = (usage.input_tokens ?? 0) * TOKEN_WEIGHT.input + (usage.cache_read_input_tokens ?? 0) * TOKEN_WEIGHT.read + ownW + (usage.output_tokens ?? 0) * TOKEN_WEIGHT.output;
|
|
6986
|
+
return own > 0 ? own * entry.costUSD / weighted : void 0;
|
|
6962
6987
|
}
|
|
6963
6988
|
function cacheHitRate(u) {
|
|
6964
6989
|
if (!u) return void 0;
|
|
@@ -6966,6 +6991,9 @@ function cacheHitRate(u) {
|
|
|
6966
6991
|
const total = read + (u.cache_creation_input_tokens ?? 0) + (u.input_tokens ?? 0);
|
|
6967
6992
|
return total > 0 ? read / total : void 0;
|
|
6968
6993
|
}
|
|
6994
|
+
function cloudSession(env = process.env) {
|
|
6995
|
+
return env.CLAUDE_CODE_REMOTE === "true";
|
|
6996
|
+
}
|
|
6969
6997
|
function readForkCache(v2) {
|
|
6970
6998
|
try {
|
|
6971
6999
|
return JSON.parse(fs16.readFileSync(v2.p(FORK_CACHE_FILE), "utf8")).forks ?? [];
|
|
@@ -6979,10 +7007,28 @@ function recordForkCache(v2, rec) {
|
|
|
6979
7007
|
} catch {
|
|
6980
7008
|
}
|
|
6981
7009
|
}
|
|
7010
|
+
async function forkRecords(v2, config, fromServer) {
|
|
7011
|
+
const local = readForkCache(v2);
|
|
7012
|
+
if (!fromServer || !canCall(config)) return local;
|
|
7013
|
+
const recent = local.some((r) => r.cloud && !r.cold && Date.now() - Date.parse(r.at) < MISS_HOLD_MS);
|
|
7014
|
+
if (recent) return local;
|
|
7015
|
+
try {
|
|
7016
|
+
const res = await v2api(config, "GET", "/reflections/forks", void 0, { timeoutMs: 4e3 });
|
|
7017
|
+
const remote = (res.forks ?? []).filter((r) => typeof r.at === "string" && typeof r.hitRate === "number").map((r) => ({ ...r, cloud: true }));
|
|
7018
|
+
return [...remote, ...local].sort((a, b) => Date.parse(a.at) - Date.parse(b.at));
|
|
7019
|
+
} catch {
|
|
7020
|
+
return local;
|
|
7021
|
+
}
|
|
7022
|
+
}
|
|
6982
7023
|
function forkDecision(records, o) {
|
|
6983
7024
|
if (o.learn) return { fork: true, reason: "asked for (/learn)" };
|
|
6984
|
-
if (o.tokens <= o.limit) return { fork: true, reason: "short session" };
|
|
6985
7025
|
const now = o.now ?? Date.now();
|
|
7026
|
+
if (o.cloud) {
|
|
7027
|
+
const latest2 = [...records].reverse().find((r) => r.cloud && r.mode === "faithful" && !r.cold && now - Date.parse(r.at) < MISS_HOLD_MS);
|
|
7028
|
+
if (latest2 && latest2.hitRate < CACHE_MISS) return { fork: false, reason: `forks of your cloud sessions missed their cache (${Math.round(latest2.hitRate * 100)}% read from cache): ${CLOUD_MISS_WHY}. Digest of the new turns` };
|
|
7029
|
+
if (latest2) return { fork: true, reason: `forks of your cloud sessions read ${Math.round(latest2.hitRate * 100)}% from the session's cache` };
|
|
7030
|
+
}
|
|
7031
|
+
if (o.tokens <= o.limit) return { fork: true, reason: "short session" };
|
|
6986
7032
|
const latest = [...records].reverse().find((r) => r.mode === "faithful" && !r.cold && r.tokens > o.limit && now - Date.parse(r.at) < MISS_HOLD_MS);
|
|
6987
7033
|
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` };
|
|
6988
7034
|
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" };
|
|
@@ -7040,7 +7086,7 @@ function runClaudeFork(sessionId, prompt, { cwd, model, mode = "faithful", timeo
|
|
|
7040
7086
|
env = parseJsonLoose(out);
|
|
7041
7087
|
}
|
|
7042
7088
|
if (!env || typeof env !== "object") return finish({ ok: false, error: `fork exited ${code2}: ${(err || out).slice(0, 300)}` });
|
|
7043
|
-
const base = { usage: env.usage, costUsd: env.total_cost_usd, forkSessionId: env.session_id };
|
|
7089
|
+
const base = { usage: env.usage, costUsd: env.total_cost_usd, forkSessionId: env.session_id, ...env.modelUsage && typeof env.modelUsage === "object" ? { modelUsage: env.modelUsage } : {} };
|
|
7044
7090
|
if (env.is_error || typeof env.result !== "string") return finish({ ok: false, ...base, error: `fork error: ${String(env.result ?? err).slice(0, 300)}` });
|
|
7045
7091
|
finish({ ok: true, text: env.result, ...base });
|
|
7046
7092
|
});
|
|
@@ -7161,7 +7207,8 @@ async function runReflectionV2(store, opts) {
|
|
|
7161
7207
|
const call2 = {};
|
|
7162
7208
|
const sessionTokens = estimateSessionTokens(session.transcriptPath);
|
|
7163
7209
|
const limit = config.reflect.forkMaxTokens ?? 6e4;
|
|
7164
|
-
const
|
|
7210
|
+
const cloud = cloudSession();
|
|
7211
|
+
const decision = forkDecision(await forkRecords(v2, config, cloud && origin !== "learn"), { learn: origin === "learn", tokens: sessionTokens, limit, cloud });
|
|
7165
7212
|
const useFork = harness === "claude-code" && decision.fork;
|
|
7166
7213
|
if (harness === "claude-code") call2.cacheNote = decision.reason;
|
|
7167
7214
|
if (useFork) {
|
|
@@ -7174,7 +7221,7 @@ async function runReflectionV2(store, opts) {
|
|
|
7174
7221
|
const idleMs = transcriptIdleMs(session.transcriptPath);
|
|
7175
7222
|
const cold = idleMs !== void 0 && idleMs > Math.max(config.reflect.cacheTtlMs, 5 * 6e4);
|
|
7176
7223
|
const fork = await runClaudeFork(opts.sessionId, prompt, { cwd: session.cwd, model, mode });
|
|
7177
|
-
fork.costUsd = forkOwnCost(fork.costUsd, before);
|
|
7224
|
+
fork.costUsd = forkOwnCost(fork.costUsd, before, estimateForkCost(fork.usage, fork.modelUsage, model));
|
|
7178
7225
|
const hitRate = cacheHitRate(fork.usage);
|
|
7179
7226
|
call2.cacheMode = mode;
|
|
7180
7227
|
if (hitRate !== void 0) {
|
|
@@ -7183,12 +7230,14 @@ async function runReflectionV2(store, opts) {
|
|
|
7183
7230
|
if (coldMiss) {
|
|
7184
7231
|
call2.cacheCold = true;
|
|
7185
7232
|
call2.cacheNote = `the session's prompt cache had expired (idle ${Math.round(idleMs / 6e4)} min before this fork): not counted as a miss`;
|
|
7233
|
+
} else if (cloud && mode === "faithful" && hitRate < CACHE_MISS) {
|
|
7234
|
+
call2.cacheNote = `missed: ${CLOUD_MISS_WHY}. Your cloud sessions reflect from a digest of their new turns for a week`;
|
|
7186
7235
|
}
|
|
7187
|
-
recordForkCache(v2, { at: (/* @__PURE__ */ new Date()).toISOString(), sessionId: opts.sessionId, mode, tokens: sessionTokens, hitRate, ...fork.costUsd !== void 0 ? { costUsd: fork.costUsd } : {}, ...coldMiss ? { cold: true } : {} });
|
|
7188
|
-
if (mode === "faithful" && hitRate < CACHE_MISS && sessionTokens > limit && !coldMiss) {
|
|
7236
|
+
recordForkCache(v2, { at: (/* @__PURE__ */ new Date()).toISOString(), sessionId: opts.sessionId, mode, tokens: sessionTokens, hitRate, ...fork.costUsd !== void 0 ? { costUsd: fork.costUsd } : {}, ...coldMiss ? { cold: true } : {}, ...cloud ? { cloud: true } : {} });
|
|
7237
|
+
if (mode === "faithful" && hitRate < CACHE_MISS && (sessionTokens > limit || cloud) && !coldMiss) {
|
|
7189
7238
|
const cost = fork.costUsd !== void 0 ? ` ($${fork.costUsd.toFixed(2)})` : "";
|
|
7190
7239
|
v2.log("v2-reflect-cache-miss", { session: opts.sessionId, hitRate, tokens: sessionTokens, costUsd: fork.costUsd ?? null });
|
|
7191
|
-
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`));
|
|
7240
|
+
updateFeed(v2, opts.sessionId, (f) => addEvent(f, "warning", `reflection did not reuse this session's prompt cache${cost}: ${cloud ? "your cloud sessions" : "large sessions here"} reflect from a digest of their new turns for now`));
|
|
7192
7241
|
}
|
|
7193
7242
|
}
|
|
7194
7243
|
Object.assign(call2, {
|
|
@@ -7315,7 +7364,7 @@ async function runReflectionV2(store, opts) {
|
|
|
7315
7364
|
nothingNew: result.nothingNew,
|
|
7316
7365
|
...call2.usage ? { usage: call2.usage } : {},
|
|
7317
7366
|
...call2.costUsd !== void 0 ? { costUsd: call2.costUsd } : {},
|
|
7318
|
-
...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 } : {} } } : {},
|
|
7367
|
+
...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 } : {}, ...cloudSession() ? { cloud: true } : {} } } : {},
|
|
7319
7368
|
durationMs: Date.now() - Date.parse(startedAt),
|
|
7320
7369
|
...result.error ? { error: result.error } : {},
|
|
7321
7370
|
startedAt,
|
|
@@ -7382,7 +7431,7 @@ function learnLines(result, view) {
|
|
|
7382
7431
|
return applied ? `captured: ${s.summary ?? summarize(s.op)} \u2192 ${target}` : `proposed (not applied): ${s.summary ?? summarize(s.op)} \u2192 ${target}`;
|
|
7383
7432
|
});
|
|
7384
7433
|
}
|
|
7385
|
-
var FORK_TIMEOUT_MS, FORK_DENIED_TOOLS, FORK_GUARD_SETTINGS, readSettings, FORK_CACHE_FILE, CACHE_MISS, MISS_HOLD_MS;
|
|
7434
|
+
var FORK_TIMEOUT_MS, FORK_DENIED_TOOLS, FORK_GUARD_SETTINGS, readSettings, TOKEN_WEIGHT, CLOUD_MISS_WHY, FORK_CACHE_FILE, CACHE_MISS, MISS_HOLD_MS;
|
|
7386
7435
|
var init_reflect3 = __esm({
|
|
7387
7436
|
"src/v2/reflect.ts"() {
|
|
7388
7437
|
"use strict";
|
|
@@ -7407,6 +7456,8 @@ var init_reflect3 = __esm({
|
|
|
7407
7456
|
return {};
|
|
7408
7457
|
}
|
|
7409
7458
|
};
|
|
7459
|
+
TOKEN_WEIGHT = { input: 1, read: 0.1, write5m: 1.25, write1h: 2, output: 5 };
|
|
7460
|
+
CLOUD_MISS_WHY = "in claude.ai cloud sessions the host adds instructions to the session's system prompt (an organisation's, for one) that a fork cannot reproduce, so a fork reuses only the tools and the start of the system prompt";
|
|
7410
7461
|
FORK_CACHE_FILE = "fork-cache.json";
|
|
7411
7462
|
CACHE_MISS = 0.5;
|
|
7412
7463
|
MISS_HOLD_MS = 7 * 24 * 36e5;
|
|
@@ -8662,7 +8713,7 @@ async function onSessionEnd(ctx) {
|
|
|
8662
8713
|
}
|
|
8663
8714
|
let action = "none";
|
|
8664
8715
|
const ephemeral = ephemeralHost();
|
|
8665
|
-
if (gate.reflect && config.reflect.enabled && !ephemeral) {
|
|
8716
|
+
if (gate.reflect && config.reflect.enabled && (!ephemeral || config.upload === "header-only")) {
|
|
8666
8717
|
episode.reflected = "edge";
|
|
8667
8718
|
action = "fork";
|
|
8668
8719
|
} else if (gate.worth) action = "cloud";
|
|
@@ -9060,13 +9111,13 @@ function removeBunshinHooks(settings) {
|
|
|
9060
9111
|
else delete out.hooks;
|
|
9061
9112
|
return out;
|
|
9062
9113
|
}
|
|
9063
|
-
function mergeClaudeSettings(settings, { bin = "bunshin", harness = "claude-code", user = false, allTools = false, autoConnect: autoConnect2 = false } = {}) {
|
|
9114
|
+
function mergeClaudeSettings(settings, { bin = "bunshin", harness = "claude-code", user = false, allTools = false, autoConnect: autoConnect2 = false, upload } = {}) {
|
|
9064
9115
|
const base = removeBunshinHooks(settings);
|
|
9065
9116
|
const hooks = { ...base.hooks ?? {} };
|
|
9066
9117
|
for (const { event, arg, timeout, matcher } of harness === "codex" ? CODEX_HOOK_EVENTS : HOOK_EVENTS) {
|
|
9067
9118
|
const groups = Array.isArray(hooks[event]) ? [...hooks[event]] : [];
|
|
9068
9119
|
const hook = bunshinHookEntry(arg, autoConnect2 && arg === "session-start" ? AUTO_CONNECT_SESSION_START_TIMEOUT : timeout, bin);
|
|
9069
|
-
hook.command = `${user ? "BUNSHIN_HOOK_SCOPE=user " : ""}${user && autoConnect2 ? "BUNSHIN_AUTO_CONNECT=1 " : ""}BUNSHIN_HARNESS=${harness} ${hook.command}`;
|
|
9120
|
+
hook.command = `${user ? "BUNSHIN_HOOK_SCOPE=user " : ""}${user && autoConnect2 ? "BUNSHIN_AUTO_CONNECT=1 " : ""}${user && autoConnect2 && upload ? `BUNSHIN_UPLOAD=${upload} ` : ""}BUNSHIN_HARNESS=${harness} ${hook.command}`;
|
|
9070
9121
|
if (harness === "codex") delete hook._bunshin;
|
|
9071
9122
|
const m = matcher && allTools && event === "PreToolUse" ? ALL_TOOLS_MATCHER : matcher;
|
|
9072
9123
|
groups.push(m ? { matcher: m, hooks: [hook] } : { hooks: [hook] });
|
|
@@ -9107,10 +9158,10 @@ export { default } from ${JSON.stringify(pathToFileURL(extension).href)};
|
|
|
9107
9158
|
return { file: file2, installed: 0, changed: false, error: error instanceof Error ? error.message : String(error) };
|
|
9108
9159
|
}
|
|
9109
9160
|
}
|
|
9110
|
-
function installClaudeHooks({ file: file2 = claudeSettingsPath(), bin = "bunshin", remove = false, harness = "claude-code", user = false, allTools = false, autoConnect: autoConnect2 = false } = {}) {
|
|
9161
|
+
function installClaudeHooks({ file: file2 = claudeSettingsPath(), bin = "bunshin", remove = false, harness = "claude-code", user = false, allTools = false, autoConnect: autoConnect2 = false, upload } = {}) {
|
|
9111
9162
|
try {
|
|
9112
9163
|
const before = fileExists(file2) ? JSON.parse(fs22.readFileSync(file2, "utf8")) : {};
|
|
9113
|
-
const after = remove ? removeBunshinHooks(before) : mergeClaudeSettings(before, { bin, harness, user, allTools, autoConnect: autoConnect2 });
|
|
9164
|
+
const after = remove ? removeBunshinHooks(before) : mergeClaudeSettings(before, { bin, harness, user, allTools, autoConnect: autoConnect2, ...upload ? { upload } : {} });
|
|
9114
9165
|
const changed = JSON.stringify(before) !== JSON.stringify(after);
|
|
9115
9166
|
if (changed) {
|
|
9116
9167
|
ensureDir(path18.dirname(file2));
|
|
@@ -9373,6 +9424,7 @@ var setup_exports = {};
|
|
|
9373
9424
|
__export(setup_exports, {
|
|
9374
9425
|
HARNESS_NAMES: () => HARNESS_NAMES,
|
|
9375
9426
|
HOSTED_API: () => HOSTED_API,
|
|
9427
|
+
UPLOAD_MODES: () => UPLOAD_MODES,
|
|
9376
9428
|
apiAddress: () => apiAddress,
|
|
9377
9429
|
askSources: () => askSources,
|
|
9378
9430
|
autoConnect: () => autoConnect,
|
|
@@ -9532,6 +9584,7 @@ ${profile.userId}`).digest("hex");
|
|
|
9532
9584
|
store.saveConfig({
|
|
9533
9585
|
...base,
|
|
9534
9586
|
...sources ? { sources } : {},
|
|
9587
|
+
...opts.upload ? { upload: opts.upload } : {},
|
|
9535
9588
|
...profile,
|
|
9536
9589
|
apiKey: void 0,
|
|
9537
9590
|
credentialFile,
|
|
@@ -9579,7 +9632,7 @@ function setupEnvironment(opts) {
|
|
|
9579
9632
|
const bin = opts.bin ?? hookBinary(opts.harness);
|
|
9580
9633
|
const claudeDir = path19.dirname(claudeSettingsPath());
|
|
9581
9634
|
return {
|
|
9582
|
-
hooks: installClaudeHooks({ bin, harness: opts.harness, user: true, autoConnect: true }),
|
|
9635
|
+
hooks: installClaudeHooks({ bin, harness: opts.harness, user: true, autoConnect: true, ...opts.upload ? { upload: opts.upload } : {} }),
|
|
9583
9636
|
permissions: installClaudePermissions(),
|
|
9584
9637
|
mcp: installUserMcp({ launcher: mcpLauncher(bin), ...opts.claude ? { claude: opts.claude } : {} }),
|
|
9585
9638
|
learnCommand: installLearnCommand({ file: path19.join(claudeDir, "commands", "learn.md") }),
|
|
@@ -9603,13 +9656,14 @@ async function autoConnect(cwd, env = process.env) {
|
|
|
9603
9656
|
const root = repositoryRoot(cwd);
|
|
9604
9657
|
if (!root || root === path19.resolve(homeDir()) || root === path19.parse(root).root) return { connected: false, reason: "not-a-repository" };
|
|
9605
9658
|
try {
|
|
9606
|
-
const
|
|
9659
|
+
const upload = UPLOAD_MODES.find((m) => m === env.BUNSHIN_UPLOAD);
|
|
9660
|
+
const result = await setupProject({ cwd: root, apiKey, harness, noHooks: true, hooks: "user", ...env.BUNSHIN_API_URL ? { apiUrl: env.BUNSHIN_API_URL } : {}, ...upload ? { upload } : {} });
|
|
9607
9661
|
return { connected: true, root, profile: result.profile };
|
|
9608
9662
|
} catch (error) {
|
|
9609
9663
|
return { connected: false, reason: "failed", error: error instanceof Error ? error.message : String(error) };
|
|
9610
9664
|
}
|
|
9611
9665
|
}
|
|
9612
|
-
var shellQuote, HARNESS_NAMES;
|
|
9666
|
+
var shellQuote, HARNESS_NAMES, UPLOAD_MODES;
|
|
9613
9667
|
var init_setup = __esm({
|
|
9614
9668
|
"src/setup.ts"() {
|
|
9615
9669
|
"use strict";
|
|
@@ -9620,6 +9674,7 @@ var init_setup = __esm({
|
|
|
9620
9674
|
init_trust();
|
|
9621
9675
|
shellQuote = (value) => `'${value.replace(/'/g, `'"'"'`)}'`;
|
|
9622
9676
|
HARNESS_NAMES = { "claude-code": "Claude Code", codex: "Codex", pi: "Pi" };
|
|
9677
|
+
UPLOAD_MODES = ["redacted", "header-only", "full"];
|
|
9623
9678
|
}
|
|
9624
9679
|
});
|
|
9625
9680
|
|
|
@@ -9667,8 +9722,13 @@ async function handleHook(rawEvent, input, opts = {}) {
|
|
|
9667
9722
|
if (isChild()) return {};
|
|
9668
9723
|
const cwd = opts.cwd ?? input.cwd ?? process.cwd();
|
|
9669
9724
|
let store = opts.store !== void 0 ? opts.store : Store.discover(cwd);
|
|
9725
|
+
let connected;
|
|
9670
9726
|
if (!store && opts.store === void 0 && event === "session-start" && process.env.BUNSHIN_AUTO_CONNECT === "1" && !deferToProject(cwd)) {
|
|
9671
|
-
|
|
9727
|
+
const r = await connectHere(cwd);
|
|
9728
|
+
if ("problem" in r) return r.problem ? { systemMessage: `\u25C6 Bunshin: ${r.problem}`, hookSpecificOutput: { hookEventName: "SessionStart", additionalContext: `## Bunshin
|
|
9729
|
+
Bunshin is installed in this environment but did not connect: ${r.problem} If the person asks about Bunshin, tell them this.` } } : {};
|
|
9730
|
+
store = r.store;
|
|
9731
|
+
connected = r.connected;
|
|
9672
9732
|
}
|
|
9673
9733
|
if (!store) return {};
|
|
9674
9734
|
const config = store.config();
|
|
@@ -9683,9 +9743,11 @@ async function handleHook(rawEvent, input, opts = {}) {
|
|
|
9683
9743
|
timer = setTimeout(() => resolve({}), Math.max(1, deadline - Date.now()) + 250);
|
|
9684
9744
|
timer.unref?.();
|
|
9685
9745
|
});
|
|
9686
|
-
const out = await Promise.race([work, late]);
|
|
9746
|
+
const out = await Promise.race([work, late]) ?? {};
|
|
9687
9747
|
if (timer) clearTimeout(timer);
|
|
9688
|
-
|
|
9748
|
+
if (connected) out.systemMessage = out.systemMessage ? `\u25C6 Bunshin: ${connected}
|
|
9749
|
+
${out.systemMessage}` : `\u25C6 Bunshin: ${connected}`;
|
|
9750
|
+
return out;
|
|
9689
9751
|
} catch (err) {
|
|
9690
9752
|
try {
|
|
9691
9753
|
store.log("hook-error", { event, session: input.session_id, error: err instanceof Error ? err.message : String(err) });
|
|
@@ -9694,21 +9756,22 @@ async function handleHook(rawEvent, input, opts = {}) {
|
|
|
9694
9756
|
return {};
|
|
9695
9757
|
}
|
|
9696
9758
|
}
|
|
9697
|
-
async function connectHere(cwd) {
|
|
9759
|
+
async function connectHere(cwd, env = process.env) {
|
|
9698
9760
|
try {
|
|
9699
9761
|
const { autoConnect: autoConnect2 } = await Promise.resolve().then(() => (init_setup(), setup_exports));
|
|
9700
|
-
const result = await autoConnect2(cwd);
|
|
9762
|
+
const result = await autoConnect2(cwd, env);
|
|
9701
9763
|
if (!result.connected) {
|
|
9702
|
-
|
|
9703
|
-
if (
|
|
9764
|
+
const problem = result.reason === "no-key" ? "it has no key yet. Add the secret BUNSHIN_API_KEY to this environment (create it in the Bunshin console: Overview \u2192 A cloud environment); new sessions then connect on their own." : result.reason === "failed" ? `it could not connect this repository: ${result.error ?? "unknown error"}` : result.reason === "no-harness" ? "its hooks were installed without an agent. Run bunshin setup --env again in the environment's setup script." : "";
|
|
9765
|
+
if (problem) process.stderr.write(`bunshin: ${problem}
|
|
9704
9766
|
`);
|
|
9705
|
-
return
|
|
9767
|
+
return { problem };
|
|
9706
9768
|
}
|
|
9707
9769
|
const store = Store.discover(cwd);
|
|
9708
|
-
store
|
|
9709
|
-
|
|
9710
|
-
|
|
9711
|
-
|
|
9770
|
+
if (!store) return { problem: "it connected this repository but could not open its store." };
|
|
9771
|
+
store.log("auto-connect", { root: result.root, role: result.profile.role, orgUnit: result.profile.orgUnit });
|
|
9772
|
+
return { store, connected: `connected ${path20.basename(result.root)} to your workspace as ${result.profile.role}${result.profile.orgUnit ? ` (${result.profile.orgUnit})` : ""}. It learns from this session and recalls what the workspace knows.` };
|
|
9773
|
+
} catch (err) {
|
|
9774
|
+
return { problem: `it could not connect this repository: ${err instanceof Error ? err.message : String(err)}` };
|
|
9712
9775
|
}
|
|
9713
9776
|
}
|
|
9714
9777
|
function deferToProject(cwd, env = process.env) {
|
|
@@ -13341,7 +13404,8 @@ async function main(argv, opts = {}) {
|
|
|
13341
13404
|
const harness = str7(args.flags.harness) ?? "claude-code";
|
|
13342
13405
|
if (harness !== "claude-code") throw new Error("--env supports --harness claude-code for now.");
|
|
13343
13406
|
const { setupEnvironment: setupEnvironment2 } = await Promise.resolve().then(() => (init_setup(), setup_exports));
|
|
13344
|
-
const
|
|
13407
|
+
const upload = transcriptsFlag(args);
|
|
13408
|
+
const result = setupEnvironment2({ harness, ...upload ? { upload } : {} });
|
|
13345
13409
|
if (result.hooks.error) throw new Error(`hooks could not be configured in ${result.hooks.file}: ${result.hooks.error}`);
|
|
13346
13410
|
out(`${result.hooks.installed} hooks configured in ${result.hooks.file}: each git repository connects on its first session.
|
|
13347
13411
|
`);
|
|
@@ -13355,6 +13419,7 @@ async function main(argv, opts = {}) {
|
|
|
13355
13419
|
if (command.error) err(`! ${path31.basename(command.file, ".md")} not installed at ${command.file}: ${command.error}
|
|
13356
13420
|
`);
|
|
13357
13421
|
}
|
|
13422
|
+
if (upload === "header-only") out("Transcripts stay in the container: sessions upload what they learned and a header, and reflect here.\n");
|
|
13358
13423
|
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");
|
|
13359
13424
|
return 0;
|
|
13360
13425
|
} catch (error) {
|
|
@@ -13395,12 +13460,14 @@ async function main(argv, opts = {}) {
|
|
|
13395
13460
|
const exclude = str7(args.flags.exclude);
|
|
13396
13461
|
const listed = (v) => v.split(",").map((x) => x.trim().replace(/\/+$/, "")).filter(Boolean);
|
|
13397
13462
|
out("Connecting to Bunshin\u2026\n");
|
|
13463
|
+
const upload = transcriptsFlag(args);
|
|
13398
13464
|
const result = await setupProject2({
|
|
13399
13465
|
cwd,
|
|
13400
13466
|
harness,
|
|
13401
13467
|
apiKey: key,
|
|
13402
13468
|
apiUrl,
|
|
13403
13469
|
noHooks: bool5(args.flags["no-hooks"]),
|
|
13470
|
+
...upload ? { upload } : {},
|
|
13404
13471
|
...hooksFlag ? { hooks: hooksFlag } : {},
|
|
13405
13472
|
...bool5(args.flags.all) ? { sources: null } : only || exclude ? { sources: { ...only ? { only: listed(only) } : {}, ...exclude ? { exclude: listed(exclude) } : {} } } : {}
|
|
13406
13473
|
});
|
|
@@ -14012,6 +14079,13 @@ async function cmdConflict(store, args, out, err) {
|
|
|
14012
14079
|
}
|
|
14013
14080
|
return 0;
|
|
14014
14081
|
}
|
|
14082
|
+
function transcriptsFlag(args) {
|
|
14083
|
+
const v = str7(args.flags.transcripts);
|
|
14084
|
+
if (v === void 0) return void 0;
|
|
14085
|
+
if (v === "local" || v === "header-only") return "header-only";
|
|
14086
|
+
if (v === "redacted" || v === "full") return v;
|
|
14087
|
+
throw new Error("--transcripts must be local (keep them on this machine), redacted (the default) or full");
|
|
14088
|
+
}
|
|
14015
14089
|
async function signIn(apiUrl, harness, out) {
|
|
14016
14090
|
const { deviceLogin: deviceLogin2, DeviceLoginUnavailable: DeviceLoginUnavailable2 } = await Promise.resolve().then(() => (init_login(), login_exports));
|
|
14017
14091
|
try {
|
|
@@ -14074,13 +14148,14 @@ Usage: bunshin <command> [options]
|
|
|
14074
14148
|
it (no key to copy); later projects connect without asking
|
|
14075
14149
|
--harness codex|claude-code|pi pick the agent when several are installed
|
|
14076
14150
|
--login approve again (another workspace: select it in the console first)
|
|
14151
|
+
--transcripts local keep session transcripts on this machine (upload only what was learned)
|
|
14077
14152
|
--api-url <url> --no-hooks a self-hosted workspace; hooks off
|
|
14078
14153
|
--key-stdin read an agent key from stdin (for automated setup)
|
|
14079
14154
|
--hooks user a folder of projects: hooks in your user settings, so every
|
|
14080
14155
|
session under this folder uses its workspace (default: project)
|
|
14081
14156
|
--only a,b | --exclude c | --all
|
|
14082
14157
|
which of the folder's projects take part (asked when omitted)
|
|
14083
|
-
setup --env [--harness claude-code]
|
|
14158
|
+
setup --env [--harness claude-code] [--transcripts local]
|
|
14084
14159
|
an environment's setup script (a cloud container): no key now;
|
|
14085
14160
|
user hooks connect each git repository on its first session,
|
|
14086
14161
|
with BUNSHIN_API_KEY from the environment
|