@vectorize-io/hindsight-coding-agents 0.6.1 → 0.8.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 (56) hide show
  1. package/README.md +314 -51
  2. package/dist/antigravity-hook.js +1039 -198
  3. package/dist/antigravity-statusline.js +185 -11
  4. package/dist/antigravity-stop-hook.js +1026 -163
  5. package/dist/claude-hook.js +1039 -198
  6. package/dist/claude-sessionstart-hook.js +1123 -190
  7. package/dist/claude-stop-hook.js +1026 -163
  8. package/dist/cline.js +749 -209
  9. package/dist/codex-hook.js +1039 -198
  10. package/dist/codex-sessionstart-hook.js +1123 -190
  11. package/dist/codex-stop-hook.js +1026 -163
  12. package/dist/copilot-hook.js +1039 -198
  13. package/dist/copilot-sessionstart-hook.js +1123 -190
  14. package/dist/copilot-stop-hook.js +1026 -163
  15. package/dist/cursor-hook.js +1039 -198
  16. package/dist/cursor-sessionstart-hook.js +1123 -190
  17. package/dist/cursor-stop-hook.js +1026 -163
  18. package/dist/daemon-start.js +154 -5
  19. package/dist/dcode-hook.js +1039 -198
  20. package/dist/dcode-sessionstart-hook.js +1123 -190
  21. package/dist/dcode-stop-hook.js +1026 -163
  22. package/dist/deepen.js +437 -105
  23. package/dist/devin-hook.js +1039 -198
  24. package/dist/devin-sessionstart-hook.js +1123 -190
  25. package/dist/devin-stop-hook.js +1026 -163
  26. package/dist/droid-hook.js +1039 -198
  27. package/dist/droid-sessionstart-hook.js +1123 -190
  28. package/dist/droid-stop-hook.js +1026 -163
  29. package/dist/dsh.js +750 -210
  30. package/dist/grok-hook.js +1039 -198
  31. package/dist/grok-sessionstart-hook.js +1123 -190
  32. package/dist/grok-stop-hook.js +1026 -163
  33. package/dist/hindsight-seed.js +157 -8
  34. package/dist/index.js +749 -209
  35. package/dist/installer.js +1233 -366
  36. package/dist/kilo.js +749 -209
  37. package/dist/kimi-hook.js +3909 -0
  38. package/dist/kimi-sessionstart-hook.js +4650 -0
  39. package/dist/kimi-stop-hook.js +4218 -0
  40. package/dist/mcp-server.js +373 -71
  41. package/dist/opencode2.js +778 -209
  42. package/dist/pi.js +754 -211
  43. package/dist/prime-agent.js +754 -211
  44. package/dist/qwen-hook.js +1039 -198
  45. package/dist/qwen-sessionstart-hook.js +1123 -190
  46. package/dist/qwen-stop-hook.js +1026 -163
  47. package/dist/status.js +333 -59
  48. package/dist/traecode-hook.js +3909 -0
  49. package/dist/traecode-sessionstart-hook.js +4650 -0
  50. package/dist/traecode-stop-hook.js +4218 -0
  51. package/dist/zcode-hook.js +1039 -198
  52. package/dist/zcode-sessionstart-hook.js +1123 -190
  53. package/dist/zcode-stop-hook.js +1026 -163
  54. package/package.json +15 -11
  55. package/plugin.json +1 -1
  56. package/skill/SKILL.md +241 -48
@@ -0,0 +1,4218 @@
1
+ #!/usr/bin/env node
2
+
3
+ // src/core/hook.ts
4
+ import { existsSync as existsSync2, readFileSync as readFileSync5 } from "fs";
5
+
6
+ // src/core/bank.ts
7
+ import { existsSync } from "fs";
8
+ import { homedir as homedir2 } from "os";
9
+ import { basename, dirname as dirname3, join as join4, normalize, sep } from "path";
10
+
11
+ // src/core/diag.ts
12
+ import { join as join2 } from "path";
13
+
14
+ // src/core/log.ts
15
+ import { appendFileSync, mkdirSync, renameSync, statSync } from "fs";
16
+ import { homedir } from "os";
17
+ import { dirname, join } from "path";
18
+ function logsDir() {
19
+ return join(homedir(), ".hindsight", "coding-agents-logs");
20
+ }
21
+ var LOG_MAX_BYTES = 10 * 1024 * 1024;
22
+ function appendLogLine(file, text) {
23
+ mkdirSync(dirname(file), { recursive: true, mode: 448 });
24
+ try {
25
+ if (statSync(file).size >= LOG_MAX_BYTES) renameSync(file, `${file}.1`);
26
+ } catch {
27
+ }
28
+ appendFileSync(file, text, { mode: 384 });
29
+ }
30
+ var WEIGHT = { debug: 10, info: 20, warn: 30, error: 40 };
31
+ var current = ["debug", "info", "warn", "error"].find(
32
+ (l) => l === process.env.HINDSIGHT_LOG_LEVEL
33
+ ) ?? "info";
34
+ function setLogLevel(level) {
35
+ if (!process.env.HINDSIGHT_LOG_LEVEL) current = level;
36
+ }
37
+ function logFilePath() {
38
+ return process.env.HINDSIGHT_LOG_FILE || join(logsDir(), "plugin.log");
39
+ }
40
+ function write(level, scope, msg, extra) {
41
+ if (WEIGHT[level] < WEIGHT[current]) return;
42
+ try {
43
+ appendLogLine(
44
+ logFilePath(),
45
+ `${(/* @__PURE__ */ new Date()).toISOString()} ${level.toUpperCase().padEnd(5)} [${scope}] ${msg}` + (extra && Object.keys(extra).length ? ` ${JSON.stringify(extra)}` : "") + "\n"
46
+ );
47
+ } catch {
48
+ }
49
+ }
50
+ var log = {
51
+ debug: (scope, msg, extra) => write("debug", scope, msg, extra),
52
+ info: (scope, msg, extra) => write("info", scope, msg, extra),
53
+ warn: (scope, msg, extra) => write("warn", scope, msg, extra),
54
+ error: (scope, msg, extra) => write("error", scope, msg, extra)
55
+ };
56
+ function describeError(value, maxChars = 200) {
57
+ const parts = [];
58
+ const seen = /* @__PURE__ */ new Set();
59
+ let current2 = value;
60
+ while (current2 && !seen.has(current2)) {
61
+ seen.add(current2);
62
+ const error = current2;
63
+ const text = typeof error.message === "string" ? error.message : String(current2);
64
+ const withCode = error.code ? `${text} (${String(error.code)})` : text;
65
+ if (withCode && parts.at(-1) !== withCode) parts.push(withCode);
66
+ current2 = error.cause;
67
+ }
68
+ return (parts.join(": ") || String(value)).slice(0, maxChars);
69
+ }
70
+
71
+ // src/core/diag.ts
72
+ function diagFilePath() {
73
+ return process.env.HINDSIGHT_DIAG_FILE || join2(logsDir(), "diag.jsonl");
74
+ }
75
+ function diag(harness, event, extra = {}) {
76
+ log.debug(harness, `diag:${event}`, extra);
77
+ try {
78
+ appendLogLine(
79
+ diagFilePath(),
80
+ JSON.stringify({ ts: (/* @__PURE__ */ new Date()).toISOString(), harness, event, ...extra }) + "\n"
81
+ );
82
+ } catch {
83
+ }
84
+ }
85
+
86
+ // src/core/git-layout.ts
87
+ import { lstatSync, readFileSync, realpathSync } from "fs";
88
+ import { dirname as dirname2, isAbsolute, join as join3, resolve } from "path";
89
+ var TRANSIENT = /* @__PURE__ */ new Set(["EAGAIN", "EMFILE", "ENFILE", "EBUSY", "EINTR", "EIO", "ETIMEDOUT"]);
90
+ var ATTEMPTS = 3;
91
+ var BACKOFF_MS = 20;
92
+ function errorCode(error) {
93
+ return error?.code ?? "";
94
+ }
95
+ function sleepSync(ms) {
96
+ Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms);
97
+ }
98
+ var TransientProbeError = class extends Error {
99
+ };
100
+ function entryKind(path) {
101
+ try {
102
+ const st = lstatSync(path);
103
+ return st.isDirectory() ? "dir" : "file";
104
+ } catch (error) {
105
+ if (TRANSIENT.has(errorCode(error))) throw new TransientProbeError(errorCode(error));
106
+ return "none";
107
+ }
108
+ }
109
+ function readTextOrNull(path) {
110
+ try {
111
+ return readFileSync(path, "utf8");
112
+ } catch (error) {
113
+ if (TRANSIENT.has(errorCode(error))) throw new TransientProbeError(errorCode(error));
114
+ return null;
115
+ }
116
+ }
117
+ function gitDirFromPointer(text, holder) {
118
+ const match = /^\s*gitdir:\s*(.+?)\s*$/m.exec(text);
119
+ if (!match) return null;
120
+ const target = match[1];
121
+ return isAbsolute(target) ? target : resolve(holder, target);
122
+ }
123
+ function commonDirOf(gitDir) {
124
+ const pointer = entryKind(join3(gitDir, "commondir")) === "file" ? readTextOrNull(join3(gitDir, "commondir"))?.trim() : null;
125
+ if (!pointer) return gitDir;
126
+ return isAbsolute(pointer) ? pointer : resolve(gitDir, pointer);
127
+ }
128
+ function isBare(commonDir) {
129
+ const config = readTextOrNull(join3(commonDir, "config"));
130
+ return config !== null && /^\s*bare\s*=\s*true\s*$/im.test(config);
131
+ }
132
+ function looksLikeBareRepository(directory) {
133
+ return entryKind(join3(directory, "HEAD")) === "file" && entryKind(join3(directory, "objects")) === "dir" && entryKind(join3(directory, "refs")) === "dir";
134
+ }
135
+ function canonical(path) {
136
+ try {
137
+ return realpathSync(path);
138
+ } catch {
139
+ return path;
140
+ }
141
+ }
142
+ function resolved(commonDir) {
143
+ if (entryKind(commonDir) !== "dir") return null;
144
+ const canonicalDir = canonical(commonDir);
145
+ return { status: "resolved", commonDir: canonicalDir, bare: isBare(canonicalDir) };
146
+ }
147
+ function probeOnce(directory) {
148
+ let current2 = resolve(directory);
149
+ for (; ; ) {
150
+ const dotGit = join3(current2, ".git");
151
+ const kind = entryKind(dotGit);
152
+ if (kind === "dir") {
153
+ const layout = resolved(commonDirOf(dotGit));
154
+ if (layout) return layout;
155
+ } else if (kind === "file") {
156
+ const text = readTextOrNull(dotGit);
157
+ const gitDir = text ? gitDirFromPointer(text, current2) : null;
158
+ const layout = gitDir ? resolved(commonDirOf(gitDir)) : null;
159
+ if (layout) return layout;
160
+ }
161
+ if (looksLikeBareRepository(current2)) {
162
+ const layout = resolved(current2);
163
+ if (layout) return layout;
164
+ }
165
+ const parent = dirname2(current2);
166
+ if (parent === current2) return { status: "absent" };
167
+ current2 = parent;
168
+ }
169
+ }
170
+ function probeGitLayout(directory) {
171
+ if (!directory) return { status: "absent" };
172
+ let last = "";
173
+ for (let attempt = 0; attempt < ATTEMPTS; attempt++) {
174
+ if (attempt) sleepSync(BACKOFF_MS * attempt);
175
+ try {
176
+ return probeOnce(directory);
177
+ } catch (error) {
178
+ last = error instanceof TransientProbeError ? error.message : errorCode(error) || "unknown";
179
+ }
180
+ }
181
+ return { status: "failed", reason: last };
182
+ }
183
+
184
+ // src/core/template.ts
185
+ var PLACEHOLDER = /\{([a-zA-Z_]+)\}/g;
186
+ function applyTemplate(template, resolvers, what) {
187
+ return template.replace(PLACEHOLDER, (_, name) => {
188
+ const resolve3 = resolvers[name];
189
+ if (!resolve3) {
190
+ console.error(
191
+ `hindsight: unknown ${what} placeholder "{${name}}" \u2014 valid: ` + Object.keys(resolvers).sort().map((k) => `{${k}}`).join(", ")
192
+ );
193
+ return "unknown";
194
+ }
195
+ return resolve3();
196
+ });
197
+ }
198
+
199
+ // src/core/bank.ts
200
+ var DEFAULT_BANK_NAME = "coding";
201
+ var DEFAULT_TEMPLATE = "coding-agent::{gitProject}";
202
+ var BankResolutionError = class extends Error {
203
+ constructor(message) {
204
+ super(message);
205
+ this.name = "BankResolutionError";
206
+ }
207
+ };
208
+ function resolveProjectRoot(directory) {
209
+ if (!directory) return { status: "absent" };
210
+ const layout = probeGitLayout(directory);
211
+ if (layout.status !== "resolved") return layout;
212
+ const commonDir = layout.commonDir;
213
+ if (basename(commonDir) === ".git") return { status: "resolved", root: dirname3(commonDir) };
214
+ if (basename(commonDir).startsWith(".") && layout.bare) {
215
+ return { status: "resolved", root: dirname3(commonDir) };
216
+ }
217
+ return { status: "resolved", root: commonDir };
218
+ }
219
+ function projectNameOf(directory, sessionRoot) {
220
+ return gitProjectName(directory, true, sessionRoot);
221
+ }
222
+ var PROJECT_ROOT_ENV = ["CLAUDE_PROJECT_DIR"];
223
+ function nearestExistingDir(directory) {
224
+ let current2 = directory;
225
+ while (current2) {
226
+ if (existsSync(current2)) return current2;
227
+ const parent = dirname3(current2);
228
+ if (parent === current2) return "";
229
+ current2 = parent;
230
+ }
231
+ return "";
232
+ }
233
+ function dirName(directory) {
234
+ return directory && basename(directory) || "unknown";
235
+ }
236
+ function mainWorktreeRoot(directory, sessionRoot = "") {
237
+ const candidates = [
238
+ nearestExistingDir(directory),
239
+ sessionRoot,
240
+ ...PROJECT_ROOT_ENV.map((v) => process.env[v] || "")
241
+ ];
242
+ let failure = null;
243
+ for (const candidate of candidates) {
244
+ if (!candidate) continue;
245
+ const projectRoot = resolveProjectRoot(candidate);
246
+ if (projectRoot.status === "resolved") return projectRoot;
247
+ if (projectRoot.status === "failed") failure = projectRoot;
248
+ }
249
+ return failure ?? { status: "absent" };
250
+ }
251
+ function gitProjectName(directory, resolveWorktrees, sessionRoot = "") {
252
+ if (resolveWorktrees) {
253
+ const projectRoot = mainWorktreeRoot(directory, sessionRoot);
254
+ if (projectRoot.status === "resolved") return basename(projectRoot.root);
255
+ if (projectRoot.status === "failed") {
256
+ throw new BankResolutionError(
257
+ `git probe failed for ${directory} (${projectRoot.reason}) \u2014 refusing to guess a bank id`
258
+ );
259
+ }
260
+ }
261
+ return dirName(sessionRoot || directory);
262
+ }
263
+ function configuredDir(dir) {
264
+ const expanded = dir === "~" || dir.startsWith("~/") ? join4(homedir2(), dir.slice(1)) : dir;
265
+ return normalize(expanded).replace(new RegExp(`\\${sep}+$`), "");
266
+ }
267
+ function isWithin(directory, configured) {
268
+ return directory === configured || directory.startsWith(configured + sep);
269
+ }
270
+ function mapLookup(map, directory) {
271
+ const cwd = normalize(directory);
272
+ let best;
273
+ for (const [dir, value] of Object.entries(map)) {
274
+ const p = configuredDir(dir);
275
+ if (isWithin(cwd, p)) {
276
+ if (!best || p.length > best.len) best = { len: p.length, value };
277
+ }
278
+ }
279
+ return best?.value;
280
+ }
281
+ function lookupDirectories(config, directory, sessionRoot = "") {
282
+ const directories = [normalize(directory)];
283
+ if (config.resolveWorktrees ?? true) {
284
+ const projectRoot = mainWorktreeRoot(directory, sessionRoot);
285
+ const normalizedRoot = projectRoot.status === "resolved" ? normalize(projectRoot.root) : "";
286
+ if (normalizedRoot && normalizedRoot !== directories[0]) directories.push(normalizedRoot);
287
+ }
288
+ return directories;
289
+ }
290
+ function isOptedIn(config, directory) {
291
+ if (!config.optInOnly) return true;
292
+ if (!directory) return false;
293
+ const directories = lookupDirectories(config, directory);
294
+ if (directories.some(
295
+ (candidate) => (config.optInPaths ?? []).some(
296
+ (configured) => configured && isWithin(candidate, configuredDir(configured))
297
+ )
298
+ ))
299
+ return true;
300
+ const pathMap = config.mapPathToBank;
301
+ return Boolean(pathMap && directories.some((candidate) => mapLookup(pathMap, candidate)));
302
+ }
303
+ function pathSection(config, paths, directory) {
304
+ if (!directory || !paths) return void 0;
305
+ return lookupDirectories(config, directory).map((candidate) => mapLookup(paths, candidate)).find((section) => section !== void 0);
306
+ }
307
+ function mappedBank(config, directory, sessionRoot) {
308
+ const pathMap = config.mapPathToBank;
309
+ if (!directory || !pathMap) return void 0;
310
+ return lookupDirectories(config, directory, sessionRoot).map((candidate) => mapLookup(pathMap, candidate)).find((bank) => bank !== void 0);
311
+ }
312
+ function deriveBankId(config, directory, harness = "coding", sessionRoot) {
313
+ const mapped = mappedBank(config, directory, sessionRoot);
314
+ if (mapped) return mapped;
315
+ const dynamic = config.dynamicBankId ?? !config.bankId;
316
+ if (!dynamic) return config.bankId || DEFAULT_BANK_NAME;
317
+ const resolvers = {
318
+ harness: () => harness,
319
+ project: () => dirName(directory),
320
+ gitProject: () => gitProjectName(directory, config.resolveWorktrees ?? true, sessionRoot),
321
+ channel: () => process.env.HINDSIGHT_CHANNEL_ID || "default",
322
+ user: () => process.env.HINDSIGHT_USER_ID || "anonymous"
323
+ };
324
+ return applyTemplate(config.bankIdTemplate || DEFAULT_TEMPLATE, resolvers, "bankIdTemplate");
325
+ }
326
+ function deriveBankIdOrSkip(config, directory, harness = "coding", sessionRoot) {
327
+ try {
328
+ return deriveBankId(config, directory, harness, sessionRoot);
329
+ } catch (error) {
330
+ if (!(error instanceof BankResolutionError)) throw error;
331
+ log.warn(harness, "bank unresolved: skipping (repository could not be identified)", {
332
+ directory,
333
+ error: error.message
334
+ });
335
+ diag(harness, "bank_unresolved", { directory, error: error.message });
336
+ return null;
337
+ }
338
+ }
339
+
340
+ // src/core/config.ts
341
+ import { readFileSync as readFileSync2 } from "fs";
342
+ import { homedir as homedir3 } from "os";
343
+ import { join as join7 } from "path";
344
+
345
+ // src/core/seed.ts
346
+ import { spawn as realSpawn } from "child_process";
347
+ import { dirname as dirname4, join as join5 } from "path";
348
+ import { fileURLToPath } from "url";
349
+ var DEFAULT_SEED_LIMIT = 300;
350
+
351
+ // src/core/missions.ts
352
+ import { createHash } from "crypto";
353
+ var GIT_MISSION = "You are ingesting a single git commit: its message and its full diff. Extract the concrete technical DECISION and the CAUSE/INVARIANT it encodes, bound to the specific code entities (functions, methods, files) and behaviors it changes. Preserve exact identifiers, paths, and literal values verbatim. Preserve the 'REF-ID: <token>' marker verbatim in every fact. Capture both WHAT changed and WHY. Issue/PR references (#123, GH-123, PROJ-123) are load-bearing: keep them VERBATIM in the fact text and emit each as an ENTITY, so a later question about that issue or PR retrieves this decision.";
354
+ var GITLOG_MISSION = "You are ingesting an aggregated block of git commit MESSAGES ONLY (no diffs) \u2014 the project's recent commit-message history, newest first. Extract the project's INITIATIVES, FEATURES, ENHANCEMENTS, and notable changes or THEMES over time \u2014 what the project has been working on and how it has evolved. Do NOT extract per-line code detail (there is no diff to draw it from). Group related commits into a coherent initiative/theme where the messages make that clear; preserve exact identifiers and literal values verbatim when quoting a subject line. Keep issue/PR references (#123, GH-123) VERBATIM and emit each as an ENTITY \u2014 they are how future sessions will ask about this work.";
355
+ var CONVERSATION_MISSION = `You are ingesting a developer conversation as a JSONL transcript (one {role, content} turn per line): the user's requests, the assistant's narration, and compact 'action' turns naming each tool use and its target (e.g. "Edit boltons/strutils.py") with no arguments or outputs. It may be a SHORT decision chat or a LONG working session \u2014 scale the facts to the substance, never to the message count. Extract the FEWEST facts that capture the OUTCOME: the settled DECISIONS and their exact rules/values (quote literals VERBATIM); concrete CHANGES to specific code entities; problems and how they were resolved; conventions or invariants established; at most one fact for a notable REJECTED alternative ('initially proposed X, changed to Y because Z'). A short decision chat usually yields 1-2 facts; a substantial working session several. CRITICAL: a conversation REVISES itself \u2014 record ONLY the FINAL state as what is in effect; a superseded proposal appears ONLY inside the rejected fact, NEVER as its own 'decided' fact; if the same setting changes several times keep only the LAST, and make unmistakably clear which choice WON. Do NOT emit one fact per message, per intermediate proposal, or per action turn. Keep issue/PR references (#123, GH-123) VERBATIM and emit each as an ENTITY. Preserve the 'REF-ID: <token>' marker verbatim in every fact. Do not invent; capture only what was actually settled.`;
356
+ var REFLECT_MISSION = "You are a debugging assistant with the project's past decisions in memory (git rationale and developer chats). Given a bug's SYMPTOM, find the past decision whose rationale explains the ROOT CAUSE \u2014 not one that merely shares vocabulary. Answer with the PRECISE fix: state the EXACT rule and the LITERAL values, identifiers, strings, numbers, or set members that were decided \u2014 quote them VERBATIM, never paraphrase, generalize, or omit them (give the actual decided value, not 'the project standard'). If memories CONFLICT on the same rule, the LATEST decision wins \u2014 prefer facts that explicitly amend or supersede an earlier one, state the superseded rule as no longer in effect, and never present it as the fix. Name the function/file to change and cite the REF-ID(s). If NOTHING in memory genuinely explains THIS symptom, say exactly that in one short sentence \u2014 a wrong-but-confident nearest match is worse than an honest miss; never stretch an unrelated decision to fit.";
357
+ var DOCUMENT_MISSION = "You are ingesting a standalone document (notes, docs, or structural findings). Extract the concrete facts, concepts, and structure it describes.";
358
+ var OBSERVATIONS_MISSION = "Consolidate durable knowledge about THIS codebase \u2014 recurring patterns, conventions, module responsibilities, and how components relate \u2014 from the ingested commits and conversations. Favor stable structural understanding over one-off details. When a new fact contradicts or supersedes an existing observation, UPDATE that observation to reflect the current state rather than creating a sibling alongside it; note that the rule was revised and when, so the superseded version is visible as history rather than as a competing claim.";
359
+ var RETAIN_EXTRACTION_MODES = ["concise", "verbose", "verbatim", "chunks"];
360
+ var DEFAULT_RETAIN_EXTRACTION_MODE = "concise";
361
+ var RETAIN_STRATEGIES = {
362
+ git: { retain_mission: GIT_MISSION, retain_extraction_mode: DEFAULT_RETAIN_EXTRACTION_MODE },
363
+ // ONE big aggregated document (last N commit messages, no diffs) -> a larger chunk size so it stays
364
+ // in as few chunks as possible and the extractor sees the whole history arc at once.
365
+ gitlog: {
366
+ retain_mission: GITLOG_MISSION,
367
+ retain_extraction_mode: DEFAULT_RETAIN_EXTRACTION_MODE,
368
+ retain_chunk_size: 12e3
369
+ },
370
+ // ONE strategy for ALL developer conversations — backfilled decision chats and live working
371
+ // sessions alike (they are the same content type in the same JSON transcript format; the mission
372
+ // scales extraction to the substance, final-state-wins). Chunk big enough to hold a whole typical
373
+ // conversation in ONE chunk so the extractor sees the full proposal→revision arc (the 3000
374
+ // default SPLIT them into per-chunk fragments); very long sessions still split and fall back to
375
+ // the consolidation layer.
376
+ conversation: {
377
+ retain_mission: CONVERSATION_MISSION,
378
+ retain_extraction_mode: DEFAULT_RETAIN_EXTRACTION_MODE,
379
+ retain_chunk_size: 12e3
380
+ },
381
+ // Structural documents (e.g. the codebase survey's ingested findings) aren't dialogue — the
382
+ // chat strategy's "final decision vs rejected proposal" extraction doesn't apply. A bigger chunk
383
+ // size (documents can run long) keeps the concrete facts/structure together instead.
384
+ document: {
385
+ retain_mission: DOCUMENT_MISSION,
386
+ retain_extraction_mode: DEFAULT_RETAIN_EXTRACTION_MODE,
387
+ retain_chunk_size: 12e3
388
+ },
389
+ // Codebase-SURVEY lifecycle documents, ONE strategy with conditional rules: the survey's
390
+ // internal status markers ("researching…"/"completed" baselines) must yield ZERO memories,
391
+ // while any actual survey findings routed here extract as concrete structural facts.
392
+ survey: {
393
+ retain_extraction_mode: "custom",
394
+ retain_custom_instructions: "This document belongs to the Hindsight codebase-survey lifecycle. Apply ONE of two rules: (1) If the content is an internal status marker \u2014 it says it is an internal marker, or merely announces that a survey started/completed at some commit \u2014 extract NOTHING: return an empty list of facts. (2) Otherwise the content is survey FINDINGS about the codebase: extract the concrete structural facts it states (components and their responsibilities, key concepts, conventions, tech stack), preserving identifiers verbatim.",
395
+ retain_chunk_size: 12e3
396
+ }
397
+ };
398
+ var KNOWLEDGE_LABELS = {
399
+ key: "knowledge",
400
+ type: "multi-values",
401
+ // 0, 1, or several — empty is normal
402
+ optional: true,
403
+ tag: true,
404
+ // emits knowledge:<value> onto the fact's tags
405
+ description: "Routing labels for this project's Hindsight KNOWLEDGE PAGES \u2014 curated, human-readable summaries of the repo's DURABLE engineering knowledge (architecture, key decisions, conventions, ongoing initiatives), each page rebuilt automatically from the facts labeled for it. Mark a fact only when it is durable, reusable knowledge a developer would still want surfaced in future sessions. IMPORTANT: leave this EMPTY for routine, transient, or operational facts \u2014 a passing test, a one-off command, a status update, a debugging dead-end. MOST facts should get no label here. Assign more than one value only when the fact genuinely fits several.",
406
+ values: [
407
+ {
408
+ value: "feature-work",
409
+ description: "A new feature, initiative, or enhancement being planned or built \u2014 the capability being added and the intent behind it. Not routine bug-fixes or chores."
410
+ },
411
+ {
412
+ value: "decision",
413
+ description: "A technical decision that will constrain future work, with its rationale \u2014 why this approach was chosen over alternatives, or a rule deliberately adopted."
414
+ },
415
+ {
416
+ value: "convention",
417
+ description: "An established way this project does things \u2014 naming, structure, testing, error handling, or another recurring pattern a contributor is expected to follow."
418
+ },
419
+ {
420
+ value: "component",
421
+ description: "What a specific module, file, service, or subsystem is responsible for, or how components depend on and connect to one another."
422
+ },
423
+ {
424
+ value: "concept",
425
+ description: "A domain concept, key abstraction, or piece of project vocabulary a new contributor must understand to work effectively."
426
+ }
427
+ ]
428
+ };
429
+ function pageScopeRule(project) {
430
+ return ` Scope this page to ${project} ITSELF: the bank also holds facts about external tools, libraries and services that ${project} merely uses, configures, deploys or discusses, and those belong to somebody else's codebase. Include something only when its subject is ${project}'s own code, configuration or process; when it is about a dependency, leave it out however well-evidenced it looks \u2014 including any commit SHA or identifier that belongs to that dependency's repository rather than this one.`;
431
+ }
432
+ var PAGE_TAXONOMY = [
433
+ {
434
+ name: "Component map",
435
+ source_query: "From this project's commit history and past discussions, what are the main components/modules/subsystems, what is each responsible for, and how do they relate to or depend on one another? Describe the structure and responsibilities.",
436
+ tags: ["knowledge:component"]
437
+ },
438
+ {
439
+ name: "Core concepts",
440
+ source_query: "What are the core concepts, domain abstractions, and key entities in this project \u2014 the vocabulary a developer must understand? For each, explain what it represents and its role, drawn from how they are introduced and discussed across the history and conversations.",
441
+ tags: ["knowledge:concept"]
442
+ },
443
+ {
444
+ name: "Conventions and patterns",
445
+ source_query: "What conventions, idioms, and recurring patterns does this project follow \u2014 its approach to testing, error handling, naming, structure, and how changes are typically made? Describe how THIS project does things, as evidenced across its history and discussions.",
446
+ tags: ["knowledge:convention"]
447
+ },
448
+ {
449
+ name: "Key decisions and rationale",
450
+ source_query: "What are the significant technical decisions made in this project and the rationale behind them \u2014 the durable 'why we do it this way' a developer should know? Summarize the decisions and their reasoning from the commit rationales and past conversations.",
451
+ tags: ["knowledge:decision"]
452
+ },
453
+ {
454
+ name: "Initiatives and enhancements",
455
+ source_query: "Based on this repository's commit history, what are the major initiatives, features, and enhancements the project has worked on? Summarize the themes and notable changes over time. When a source memory's context carries a `[[page:<id>]]` link, repeat that link in the summary of what it describes, so each initiative links to its detailed page.",
456
+ tags: ["knowledge:feature-work"]
457
+ }
458
+ ];
459
+ var PAGE_NAMES = PAGE_TAXONOMY.map((page) => page.name);
460
+ function pagesFor(project, pages = {}, customPages = {}) {
461
+ const scope = pageScopeRule(project);
462
+ const byName = new Map(
463
+ Object.entries(pages).map(([name, override]) => [name.trim().toLowerCase(), override])
464
+ );
465
+ const out = [];
466
+ for (const page of PAGE_TAXONOMY) {
467
+ const override = byName.get(page.name.toLowerCase());
468
+ if (override === false) continue;
469
+ out.push({ ...page, source_query: (override?.source_query || page.source_query) + scope });
470
+ }
471
+ for (const [name, page] of Object.entries(customPages)) {
472
+ out.push({ name: name.trim(), source_query: page.source_query + scope, tags: page.tags ?? [] });
473
+ }
474
+ return out;
475
+ }
476
+ var PAGE_MAX_TOKENS = 4096;
477
+ var PAGE_TAGS_MATCH = "all";
478
+ var PAGE_FACT_TYPES = ["world", "experience", "observation"];
479
+ var DEFAULT_PAGE_TRIGGER_CRON = "H * * * *";
480
+ var CRON_FIELD_RANGES = [
481
+ [0, 59],
482
+ // minute
483
+ [0, 23],
484
+ // hour
485
+ [1, 31],
486
+ // day of month
487
+ [1, 12],
488
+ // month
489
+ [0, 6]
490
+ // day of week
491
+ ];
492
+ var HASHED_FIELD = /^H(?:\((\d+)-(\d+)\))?$/;
493
+ function isHashedCron(cron) {
494
+ return /(^|\s)H/.test(cron);
495
+ }
496
+ function parseHashedCron(cron) {
497
+ const fields = cron.trim().split(/\s+/);
498
+ if (fields.length !== CRON_FIELD_RANGES.length) return void 0;
499
+ for (const [i, field] of fields.entries()) {
500
+ if (!field.startsWith("H")) continue;
501
+ const m = HASHED_FIELD.exec(field);
502
+ if (!m) return void 0;
503
+ if (m[1] === void 0) continue;
504
+ const [lo, hi] = [Number(m[1]), Number(m[2])];
505
+ const [min, max] = CRON_FIELD_RANGES[i];
506
+ if (lo > hi || lo < min || hi > max) return void 0;
507
+ }
508
+ return fields;
509
+ }
510
+ function hashedValue(seed, field, lo, hi) {
511
+ const digest = createHash("sha256").update(`${seed}\0${field}`).digest();
512
+ return lo + digest.readUInt32BE(0) % (hi - lo + 1);
513
+ }
514
+ function expandCronHash(cron, seed) {
515
+ if (!isHashedCron(cron)) return cron;
516
+ const fields = parseHashedCron(cron);
517
+ if (!fields) return cron;
518
+ return fields.map((field, i) => {
519
+ const m = HASHED_FIELD.exec(field);
520
+ if (!m) return field;
521
+ const [lo, hi] = m[1] === void 0 ? CRON_FIELD_RANGES[i] : [Number(m[1]), Number(m[2])];
522
+ return String(hashedValue(seed, i, lo, hi));
523
+ }).join(" ");
524
+ }
525
+ function pageTriggerFor(trigger, bank, page) {
526
+ const cron = trigger.refresh_cron;
527
+ if (!cron || !isHashedCron(cron)) return trigger;
528
+ return { ...trigger, refresh_cron: expandCronHash(cron, `${bank}\0${page}`) };
529
+ }
530
+ function buildPageTrigger(cfg = {}) {
531
+ const base = { fact_types: PAGE_FACT_TYPES, tags_match: PAGE_TAGS_MATCH };
532
+ switch (cfg.pageTriggerType) {
533
+ case "auto-refresh":
534
+ return { ...base, refresh_after_consolidation: true };
535
+ case "manual":
536
+ return { ...base, refresh_after_consolidation: false };
537
+ // "cron" and an unset type alike: the default schedule stands in for a missing expression, so
538
+ // a trigger built from a partial config is never a cron trigger with nothing to fire on.
539
+ default:
540
+ return { ...base, refresh_cron: cfg.pageTriggerCron || DEFAULT_PAGE_TRIGGER_CRON };
541
+ }
542
+ }
543
+ function pageTriggerDrifted(current2, desired) {
544
+ return current2.tags_match !== desired.tags_match || (current2.refresh_cron ?? null) !== (desired.refresh_cron ?? null) || Boolean(current2.refresh_after_consolidation) !== Boolean(desired.refresh_after_consolidation);
545
+ }
546
+ function pageTriggerPatch(desired) {
547
+ if (desired.refresh_after_consolidation === false) return { ...desired, refresh_cron: null };
548
+ return desired;
549
+ }
550
+ var CODING_BANK_TEMPLATE = {
551
+ version: "1",
552
+ bank: {
553
+ reflect_mission: REFLECT_MISSION,
554
+ enable_observations: true,
555
+ observations_mission: OBSERVATIONS_MISSION,
556
+ retain_mission: GIT_MISSION,
557
+ retain_extraction_mode: DEFAULT_RETAIN_EXTRACTION_MODE,
558
+ retain_default_strategy: "git",
559
+ retain_strategies: RETAIN_STRATEGIES,
560
+ entity_labels: [KNOWLEDGE_LABELS],
561
+ entities_allow_free_form: true
562
+ }
563
+ };
564
+ var MISSION_FIELDS = ["reflect_mission", "retain_mission", "observations_mission"];
565
+ var PLUGIN_GOVERNED_BANK_FIELDS = [
566
+ "retain_strategies",
567
+ "entity_labels",
568
+ "retain_extraction_mode"
569
+ ];
570
+ function isSet(v) {
571
+ if (v === null || v === void 0) return false;
572
+ if (typeof v === "string") return v.trim() !== "";
573
+ return true;
574
+ }
575
+ function codingBankManifest(overrides, mode = DEFAULT_RETAIN_EXTRACTION_MODE, defaults = {}) {
576
+ const current2 = overrides ?? {};
577
+ const template = CODING_BANK_TEMPLATE.bank;
578
+ const bank = {};
579
+ if (!MISSION_FIELDS.some((f) => isSet(current2[f]))) {
580
+ bank.reflect_mission = template.reflect_mission;
581
+ bank.enable_observations = template.enable_observations;
582
+ bank.observations_mission = template.observations_mission;
583
+ bank.retain_mission = template.retain_mission;
584
+ bank.retain_extraction_mode = mode;
585
+ }
586
+ if (!isSet(current2.retain_default_strategy))
587
+ bank.retain_default_strategy = template.retain_default_strategy;
588
+ if (!isSet(current2.entities_allow_free_form))
589
+ bank.entities_allow_free_form = template.entities_allow_free_form;
590
+ const strategies = current2.retain_strategies && typeof current2.retain_strategies === "object" ? current2.retain_strategies : {};
591
+ const updates = {};
592
+ for (const [name, def] of Object.entries(template.retain_strategies)) {
593
+ const synced = def.retain_extraction_mode === "custom" ? {} : { retain_extraction_mode: mode };
594
+ const have = strategies[name];
595
+ if (!have || typeof have !== "object") updates[name] = { ...def, ...synced };
596
+ else if ("retain_extraction_mode" in synced && have.retain_extraction_mode !== mode)
597
+ updates[name] = { ...have, ...synced };
598
+ }
599
+ if (Object.keys(updates).length > 0) bank.retain_strategies = { ...strategies, ...updates };
600
+ const labels = Array.isArray(current2.entity_labels) ? current2.entity_labels : [];
601
+ const [knowledgeGroup] = template.entity_labels;
602
+ if (!labels.some((g) => g?.key === knowledgeGroup.key))
603
+ bank.entity_labels = [...labels, knowledgeGroup];
604
+ for (const [key, value] of Object.entries(defaults)) {
605
+ if (PLUGIN_GOVERNED_BANK_FIELDS.includes(key) || !isSet(value) || isSet(current2[key])) continue;
606
+ bank[key] = value;
607
+ }
608
+ return Object.keys(bank).length > 0 ? { version: "1", bank } : void 0;
609
+ }
610
+
611
+ // src/core/util.ts
612
+ import { accessSync, constants } from "fs";
613
+ import { delimiter, join as join6 } from "path";
614
+ var sleep = (ms) => new Promise((r) => setTimeout(r, ms));
615
+ function semverGte(version, min) {
616
+ const parts = (v) => {
617
+ const m = v.trim().match(/^(\d+)\.(\d+)(?:\.(\d+))?/);
618
+ return m ? [Number(m[1]), Number(m[2]), Number(m[3] ?? 0)] : void 0;
619
+ };
620
+ const a = version ? parts(version) : void 0;
621
+ const b = parts(min);
622
+ if (!a || !b) return false;
623
+ for (let i = 0; i < 3; i++) {
624
+ if (a[i] !== b[i]) return a[i] > b[i];
625
+ }
626
+ return true;
627
+ }
628
+ async function pool(items, n, fn, onError, onProgress) {
629
+ let i = 0, done = 0;
630
+ async function worker() {
631
+ while (i < items.length) {
632
+ const idx = i++;
633
+ try {
634
+ await fn(items[idx], idx);
635
+ } catch (e) {
636
+ onError?.(idx, e);
637
+ }
638
+ onProgress?.(++done, items.length);
639
+ }
640
+ }
641
+ await Promise.all(Array.from({ length: Math.min(n, items.length) }, worker));
642
+ }
643
+ function isOurMcpEntry(entry) {
644
+ if (!entry || typeof entry !== "object") return false;
645
+ const candidate = entry;
646
+ if (candidate.command !== "node" || !Array.isArray(candidate.args)) return false;
647
+ const script = candidate.args[0];
648
+ if (typeof script !== "string") return false;
649
+ const parts = script.replaceAll("\\", "/").split("/").filter(Boolean);
650
+ return parts.at(-1) === "mcp-server.js" && parts.at(-2) === "dist" && (parts.at(-3) === "coding-agents" || parts.at(-3) === "hindsight-coding-agents");
651
+ }
652
+
653
+ // src/core/hindsight.ts
654
+ function resolveRetainScopes(tags, configured) {
655
+ if (configured !== "per_source") return configured;
656
+ const sources = [...new Set((tags ?? []).filter((t) => t.startsWith("source:")))].sort();
657
+ return [[], ...sources.map((s) => [s])];
658
+ }
659
+ var DEFAULT_OBSERVATION_SCOPES = "shared";
660
+ var MIN_IDEMPOTENT_RETAIN_VERSION = "0.8.6";
661
+ var RateLimitedError = class extends Error {
662
+ constructor(retryAfterMs2) {
663
+ super(`rate limited; retry after ${Math.round(retryAfterMs2 / 1e3)}s`);
664
+ this.retryAfterMs = retryAfterMs2;
665
+ this.name = "RateLimitedError";
666
+ }
667
+ retryAfterMs;
668
+ code = "rate_limited";
669
+ };
670
+ function retryAfterMs(header) {
671
+ if (!header) return 0;
672
+ const secs = Number(header.trim());
673
+ if (Number.isFinite(secs) && secs >= 0) return secs * 1e3;
674
+ const at = Date.parse(header);
675
+ return Number.isNaN(at) ? 0 : Math.max(0, at - Date.now());
676
+ }
677
+ var KnowledgePagesUnavailableError = class extends Error {
678
+ code = "knowledge_pages_unavailable";
679
+ constructor() {
680
+ super("Hindsight server does not support knowledge pages");
681
+ this.name = "KnowledgePagesUnavailableError";
682
+ }
683
+ };
684
+ async function isEndpointMissing(r) {
685
+ try {
686
+ const j = await r.json();
687
+ return String(j?.detail ?? "").trim().toLowerCase() === "not found";
688
+ } catch {
689
+ return true;
690
+ }
691
+ }
692
+ var TERMINAL = /* @__PURE__ */ new Set(["completed", "failed", "cancelled", "error"]);
693
+ var ReflectError = class extends Error {
694
+ constructor(message, status, timedOut, options) {
695
+ super(message, options);
696
+ this.status = status;
697
+ this.timedOut = timedOut;
698
+ this.name = "ReflectError";
699
+ }
700
+ status;
701
+ timedOut;
702
+ /** A timeout or a 5xx means reflect's synthesis (the slow LLM path) broke, while the cheap
703
+ * retrieval endpoints may still answer — worth falling back. A 4xx will fail the same way on
704
+ * every endpoint (auth, missing bank), so it is not. */
705
+ get fallbackEligible() {
706
+ return this.timedOut || this.status !== void 0 && this.status >= 500;
707
+ }
708
+ };
709
+ var DEFAULT_MAX_PARALLEL_RETAINS = 10;
710
+ var DEFAULT_PAGE_SEARCH_LIMIT = 10;
711
+ var DEFAULT_RECALL_OPTIONS = {
712
+ types: ["observation"],
713
+ budget: "low",
714
+ max_tokens: 2e3,
715
+ include: { entities: null }
716
+ };
717
+ var POLL_CYCLE_MS = 5e3;
718
+ var RETRY_AFTER_FLOOR_MS = 10 * 1e3;
719
+ var RETRY_AFTER_CEILING_MS = 60 * 1e3;
720
+ function shapePage(page) {
721
+ const p = page ?? {};
722
+ const body = typeof p.body === "string" && p.body.trim() ? p.body : p.markdown;
723
+ return {
724
+ id: p.id,
725
+ name: p.name,
726
+ ...p.description ? { description: p.description } : {},
727
+ ...Array.isArray(p.tags) && p.tags.length ? { tags: p.tags } : {},
728
+ ...p.timestamp ? { last_updated_at: p.timestamp } : {},
729
+ body
730
+ };
731
+ }
732
+ var HindsightClient = class {
733
+ apiUrl;
734
+ /** The credential the NEXT request will sign with — NOT the one the config file holds. The two
735
+ * diverge exactly when #3600 bites, which is why `hindsight_diagnose` reports both. */
736
+ token;
737
+ tokenProvider;
738
+ bank;
739
+ project;
740
+ opIds = [];
741
+ // async operation ids collected by retain(), for drain()
742
+ /** Tri-state capability probe: unknown until the first page request, then cached. */
743
+ knowledgePagesSupported;
744
+ /** Tri-state capability probe: unknown until the first append-mode retain, then cached. */
745
+ idempotentRetain;
746
+ log;
747
+ maxParallelRetains;
748
+ observationScopes;
749
+ pageSearchLimit;
750
+ recallOptions;
751
+ constructor(o) {
752
+ this.apiUrl = o.apiUrl.replace(/\/$/, "");
753
+ this.token = o.apiToken;
754
+ this.tokenProvider = o.tokenProvider;
755
+ this.bank = o.bank;
756
+ this.project = o.project;
757
+ this.log = o.log ?? (() => {
758
+ });
759
+ this.maxParallelRetains = o.maxParallelRetains || DEFAULT_MAX_PARALLEL_RETAINS;
760
+ this.observationScopes = o.observationScopes ?? DEFAULT_OBSERVATION_SCOPES;
761
+ this.pageSearchLimit = o.pageSearchLimit || DEFAULT_PAGE_SEARCH_LIMIT;
762
+ this.recallOptions = { ...DEFAULT_RECALL_OPTIONS, ...o.recallOptions };
763
+ }
764
+ /** The credential in use, for diagnostics. Never log or report the VALUE — booleans only. */
765
+ get apiToken() {
766
+ return this.token;
767
+ }
768
+ headers() {
769
+ const h = {
770
+ "Content-Type": "application/json",
771
+ "Accept-Encoding": "identity"
772
+ };
773
+ if (this.token) h["Authorization"] = `Bearer ${this.token}`;
774
+ return h;
775
+ }
776
+ /** Re-read the credential from the live config. Returns whether it actually CHANGED — a retry is
777
+ * only worth sending if it did, so a genuinely wrong key still surfaces as one 401 rather than
778
+ * doubling every failing request. */
779
+ refreshToken() {
780
+ if (!this.tokenProvider) return false;
781
+ let next;
782
+ try {
783
+ next = this.tokenProvider();
784
+ } catch {
785
+ return false;
786
+ }
787
+ if (next === this.token) return false;
788
+ this.token = next;
789
+ return true;
790
+ }
791
+ /**
792
+ * The ONE place a request is signed. Every fetch goes through it — the generic `req`, the drain
793
+ * poll and `reflect` — because a 401 recovery wired into only one of them leaves the others
794
+ * failing forever, which is how #3600 read from the outside: hooks worked, in-session tools did
795
+ * not.
796
+ *
797
+ * On a 401 the credential is re-resolved and the request replayed ONCE (its body is already a
798
+ * string, so replay is exact). A 401 means the server did nothing, so replaying is side-effect
799
+ * free even for retain. The retry shares the caller's `signal`, deliberately: one deadline still
800
+ * bounds the whole call.
801
+ */
802
+ async fetchWithAuth(url, init) {
803
+ const send = () => fetch(url, { ...init, headers: this.headers() });
804
+ const r = await send();
805
+ if (r.status !== 401 || !this.refreshToken()) return r;
806
+ return send();
807
+ }
808
+ /** A 401 with no `Authorization` header is a different failure from a rejected key, and the
809
+ * server answers identically for both — only the client knows which it sent. */
810
+ authHint(status) {
811
+ if (status !== 401) return "";
812
+ return this.token ? " (the configured apiToken was rejected \u2014 check ~/.hindsight/coding-agent.json)" : " (no apiToken is configured, so no Authorization header was sent)";
813
+ }
814
+ bankUrl(suffix = "") {
815
+ return `${this.apiUrl}/v1/default/banks/${encodeURIComponent(this.bank)}${suffix}`;
816
+ }
817
+ /** `tolerate` adds statuses that are returned to the caller instead of thrown (404 always is). */
818
+ async req(method, url, body, tolerate = [], timeoutMs = 15e3) {
819
+ const r = await this.fetchWithAuth(url, {
820
+ method,
821
+ body: body ? JSON.stringify(body) : void 0,
822
+ signal: AbortSignal.timeout(timeoutMs)
823
+ });
824
+ if (r.status === 429 && !tolerate.includes(429))
825
+ throw new RateLimitedError(retryAfterMs(r.headers.get("retry-after")));
826
+ if (!r.ok && r.status !== 404 && !tolerate.includes(r.status))
827
+ throw new Error(
828
+ `${method} ${url} -> ${r.status} ${await r.text()}${this.authHint(r.status)}`
829
+ );
830
+ return r;
831
+ }
832
+ /** Retain one memory. ALWAYS async: enqueue extraction server-side and collect its op-id for
833
+ * drain(). Nothing in this plugin can afford to block a coding agent's hook on extraction. */
834
+ async retain(content, context, documentId, tags, strategy, opts = {}) {
835
+ const item = {
836
+ content,
837
+ context,
838
+ document_id: documentId,
839
+ tags,
840
+ strategy,
841
+ // Sent on EVERY retain, including the server default `combined`, so the scoping a bank's
842
+ // observations were built under is a property of the write rather than of whichever server
843
+ // version happened to process it. Servers older than 0.4.15 ignore the field.
844
+ observation_scopes: resolveRetainScopes(tags, this.observationScopes)
845
+ };
846
+ if (opts.timestamp) item.timestamp = opts.timestamp;
847
+ if (opts.metadata) item.metadata = opts.metadata;
848
+ if (opts.updateMode) item.update_mode = opts.updateMode;
849
+ const body = { items: [item], async: true };
850
+ if (opts.operationId) body.operation_id = opts.operationId;
851
+ const r = await this.req("POST", this.bankUrl("/memories"), body);
852
+ try {
853
+ const j = await r.json();
854
+ if (j.operation_id) this.opIds.push(j.operation_id);
855
+ } catch {
856
+ }
857
+ }
858
+ /**
859
+ * Whether this server honours `operation_id` on an async retain, and can therefore be appended to
860
+ * safely (see MIN_IDEMPOTENT_RETAIN_VERSION). Probed once per client via GET /version; anything
861
+ * unreachable, unparseable or older answers "no", which costs efficiency, never correctness.
862
+ */
863
+ async supportsIdempotentRetain() {
864
+ if (this.idempotentRetain === void 0) {
865
+ this.idempotentRetain = await this.probeIdempotentRetain();
866
+ this.log(`server retain idempotency: ${this.idempotentRetain ? "supported" : "unavailable"}`);
867
+ }
868
+ return this.idempotentRetain;
869
+ }
870
+ async probeIdempotentRetain() {
871
+ try {
872
+ const r = await this.req("GET", `${this.apiUrl}/version`);
873
+ if (!r.ok) return false;
874
+ const j = await r.json();
875
+ return semverGte(j.api_version, MIN_IDEMPOTENT_RETAIN_VERSION);
876
+ } catch {
877
+ return false;
878
+ }
879
+ }
880
+ /**
881
+ * Whether a session write-back may use `update_mode="append"`: the server must dedupe by
882
+ * `operation_id` AND the bank must keep document text, or the server rejects the append in the
883
+ * background (#4613). Only an explicit `store_document_text: false` answers "no" — an unreachable
884
+ * or unparseable config assumes the default (stored), so a flaky probe never downgrades appends.
885
+ */
886
+ async supportsAppendRetain() {
887
+ if (!await this.supportsIdempotentRetain()) return false;
888
+ try {
889
+ const r = await this.req("GET", this.bankUrl("/config"));
890
+ if (!r.ok) return true;
891
+ const j = await r.json();
892
+ return j.config?.store_document_text !== false;
893
+ } catch {
894
+ return true;
895
+ }
896
+ }
897
+ /**
898
+ * Every document_id currently in the bank under a strategy tag (e.g. `source:git`), paginated into a
899
+ * Set. Powers the incremental git-sync's "what's already ingested?" check — since git commits are stored
900
+ * with document_id `git:<sha>`, the returned Set lets a caller diff a ref's commits against memory.
901
+ */
902
+ async listDocumentIds(tag, tagsMatch = "all") {
903
+ const ids = /* @__PURE__ */ new Set();
904
+ const limit = 500;
905
+ for (let offset = 0; ; offset += limit) {
906
+ const q = `?tags=${encodeURIComponent(tag)}&tags_match=${tagsMatch}&limit=${limit}&offset=${offset}`;
907
+ const r = await this.req("GET", this.bankUrl(`/documents${q}`));
908
+ let items = [];
909
+ let total = 0;
910
+ try {
911
+ const j = await r.json();
912
+ items = j.items || [];
913
+ total = j.total ?? 0;
914
+ } catch {
915
+ break;
916
+ }
917
+ for (const it of items) if (it.id) ids.add(it.id);
918
+ if (items.length < limit || ids.size >= total) break;
919
+ }
920
+ return ids;
921
+ }
922
+ /**
923
+ * The tags on one document, or undefined when the bank holds none with that id. Read from the
924
+ * document LISTING narrowed by `q` (a substring match on the id, so the exact id is picked out of
925
+ * the page) rather than GET /documents/{id}, which also sends the document's full text: the
926
+ * caller, the git-log freshness check on SessionStart, reads a ~100k-character document for one tag.
927
+ */
928
+ async documentTags(documentId) {
929
+ const limit = 100;
930
+ for (let offset = 0; ; offset += limit) {
931
+ const q = `?q=${encodeURIComponent(documentId)}&limit=${limit}&offset=${offset}`;
932
+ const r = await this.req("GET", this.bankUrl(`/documents${q}`));
933
+ const j = await r.json();
934
+ const items = j.items ?? [];
935
+ const hit = items.find((it) => it.id === documentId);
936
+ if (hit) return hit.tags ?? [];
937
+ if (items.length < limit || offset + limit >= (j.total ?? 0)) return void 0;
938
+ }
939
+ }
940
+ /** Configure the bank: POST the coding bank manifest to /import (missions, retain strategies,
941
+ * entity labels), then seed knowledge pages when the server supports them. Both halves are
942
+ * idempotent and ADDITIVE — nothing the bank already says is overwritten (#3927), bar the
943
+ * extraction mode of the plugin's own strategies, which follows its config (#4560) — so
944
+ * the deepen engine can re-run this every pass. Creates the bank if missing; legacy servers
945
+ * continue with the template-only path.
946
+ *
947
+ * `manage: false` skips the config half entirely, for a bank whose owner shapes it themselves.
948
+ * That bank should then define the strategies this plugin writes under (`git`, `gitlog`,
949
+ * `conversation`, `document`, `survey`): an unknown strategy name is not an error server-side,
950
+ * it just falls back to the bank's own config, so the miss is silent. */
951
+ async configureBank(opts = {}) {
952
+ if (opts.reset) {
953
+ await this.req("DELETE", this.bankUrl());
954
+ this.log(`[bank] reset ${this.bank}`);
955
+ }
956
+ if (opts.manage === false) {
957
+ this.log(`[bank] manageBankConfig: false \u2014 leaving ${this.bank}'s configuration alone`);
958
+ } else {
959
+ const manifest = codingBankManifest(
960
+ opts.reset ? void 0 : await this.readBankOverrides(),
961
+ opts.extractionMode,
962
+ opts.defaults
963
+ );
964
+ if (!manifest) {
965
+ this.log(`[bank] ${this.bank} already carries the coding structure \u2014 nothing to apply`);
966
+ } else {
967
+ await this.req("POST", this.bankUrl("/import"), manifest);
968
+ this.log(`[bank] applied to ${this.bank}: ${Object.keys(manifest.bank).sort().join(", ")}`);
969
+ }
970
+ }
971
+ await this.seedPages(opts.pageTrigger, opts.pages, opts.customPages);
972
+ }
973
+ /**
974
+ * This bank's own config OVERRIDES, or undefined when there are none to read.
975
+ *
976
+ * Deliberately the overrides and not the resolved config: an inherited global default is not
977
+ * something this bank's owner chose, so it must not read as "already set". `undefined` means the
978
+ * bank does not exist yet, or the deployment has the bank-config API switched off — in neither
979
+ * case can anything have been customised, so the caller seeds the full template.
980
+ */
981
+ async readBankOverrides() {
982
+ try {
983
+ const r = await this.req("GET", this.bankUrl("/config"));
984
+ if (!r.ok) return void 0;
985
+ const j = await r.json();
986
+ return j.overrides ?? {};
987
+ } catch {
988
+ return void 0;
989
+ }
990
+ }
991
+ /** Explicitly delete one document (and its cascaded memory units/links). Background sync must
992
+ * never use this as a cleanup primitive: a document id alone does not prove repository ownership. */
993
+ async deleteDocument(documentId) {
994
+ await this.req("DELETE", this.bankUrl(`/documents/${encodeURIComponent(documentId)}`));
995
+ }
996
+ /** Count of operations still ACTIVE on this bank — the list includes terminal ops (completed/
997
+ * failed/cancelled), so filter by status. Powers syncStatus's "extractions drained" check. */
998
+ async activeOperations() {
999
+ const r = await this.req("GET", this.bankUrl("/operations"));
1000
+ try {
1001
+ const j = await r.json();
1002
+ const ops = j.operations ?? j.items ?? [];
1003
+ return ops.filter((o) => !TERMINAL.has((o?.status || "").toLowerCase())).length;
1004
+ } catch {
1005
+ return 0;
1006
+ }
1007
+ }
1008
+ /**
1009
+ * Poll each enqueued operation by id until terminal. LIST only shows active ops, so per-id GET is reliable.
1010
+ *
1011
+ * Concurrency is capped at `maxParallelRetains` (the API rate-limits bursts, not single
1012
+ * requests — a 200 to a lone GET with 429s under `Promise.all` over every pending op). A 429
1013
+ * leaves the op pending and backs the next cycle off by its `Retry-After` (10s floor) instead
1014
+ * of hammering the next cycle 5s later.
1015
+ */
1016
+ async drain(ids, label, maxMs = 60 * 60 * 1e3) {
1017
+ if (!ids.length) return;
1018
+ this.log(`[wait] draining ${ids.length} ${label} operations \u2026`);
1019
+ const start = Date.now();
1020
+ const pending = new Set(ids);
1021
+ let failed = 0;
1022
+ while (pending.size && Date.now() - start < maxMs) {
1023
+ let backoffMs = POLL_CYCLE_MS;
1024
+ await pool([...pending], this.maxParallelRetains, async (id) => {
1025
+ try {
1026
+ const r = await this.fetchWithAuth(this.bankUrl(`/operations/${id}`), { method: "GET" });
1027
+ if (r.status === 429) {
1028
+ backoffMs = Math.min(
1029
+ RETRY_AFTER_CEILING_MS,
1030
+ Math.max(backoffMs, RETRY_AFTER_FLOOR_MS, retryAfterMs(r.headers.get("retry-after")))
1031
+ );
1032
+ return;
1033
+ }
1034
+ if (!r.ok) return;
1035
+ const st = ((await r.json()).status || "").toLowerCase();
1036
+ if (TERMINAL.has(st)) {
1037
+ pending.delete(id);
1038
+ if (st !== "completed") failed++;
1039
+ }
1040
+ } catch {
1041
+ }
1042
+ });
1043
+ if (pending.size) {
1044
+ this.log(` \u2026 ${pending.size}/${ids.length} ${label} ops pending`);
1045
+ await sleep(backoffMs);
1046
+ }
1047
+ }
1048
+ this.log(
1049
+ `[wait] ${label} drained \u2014 ${ids.length - pending.size} done, ${failed} failed` + (pending.size ? `, ${pending.size} still pending at timeout` : "")
1050
+ );
1051
+ }
1052
+ /**
1053
+ * Reflect: synthesized, root-cause answer over the bank. Bounded so a slow server never hangs a
1054
+ * caller — but `timeoutMs` is REQUIRED, deliberately: the right deadline differs by an order of
1055
+ * magnitude between the automatic hook (20s, to fit the host's window) and the agent-invoked
1056
+ * tool (minutes, on a populated bank). This used to default to 120s, which silently overrode the
1057
+ * tool's configured window and aborted every high-budget synthesis mid-flight (#3590).
1058
+ */
1059
+ async reflect(query, opts) {
1060
+ const ctrl = new AbortController();
1061
+ const timer = setTimeout(() => ctrl.abort(), opts.timeoutMs);
1062
+ try {
1063
+ const resp = await this.fetchWithAuth(this.bankUrl("/reflect"), {
1064
+ method: "POST",
1065
+ body: JSON.stringify({ query, budget: opts.budget ?? "high" }),
1066
+ signal: ctrl.signal
1067
+ });
1068
+ if (!resp.ok)
1069
+ throw new ReflectError(
1070
+ `reflect ${resp.status} ${(await resp.text()).slice(0, 1e3)}${this.authHint(resp.status)}`,
1071
+ resp.status,
1072
+ false
1073
+ );
1074
+ const data = await resp.json();
1075
+ return (data.text || "").trim();
1076
+ } catch (e) {
1077
+ if (ctrl.signal.aborted)
1078
+ throw new ReflectError(`reflect timed out after ${opts.timeoutMs}ms`, void 0, true, {
1079
+ cause: e
1080
+ });
1081
+ throw e;
1082
+ } finally {
1083
+ clearTimeout(timer);
1084
+ }
1085
+ }
1086
+ /**
1087
+ * Raw recall with no LLM in the loop, so it still answers when reflect's synthesis times out or
1088
+ * 5xxs. The body is `recallOptions` (consolidated observations by default) — a bank that grows
1089
+ * no observations widens it rather than getting nothing back. Returns the texts in rank order.
1090
+ *
1091
+ * The name predates `recallOptions` (the observation type used to be hardcoded here) and is
1092
+ * kept deliberately: this is the client's published surface, so renaming it would break
1093
+ * importers for a cosmetic gain. The doc above is the contract, not the name.
1094
+ */
1095
+ async recallObservations(query, opts) {
1096
+ const r = await this.req(
1097
+ "POST",
1098
+ this.bankUrl("/memories/recall"),
1099
+ // `query` is applied AFTER the spread: everything else is the caller's to override, but a
1100
+ // config that could replace the goal with a fixed string would silently recall for the
1101
+ // wrong question on every turn.
1102
+ { ...this.recallOptions, query },
1103
+ [],
1104
+ opts.timeoutMs
1105
+ );
1106
+ if (r.status === 404) return [];
1107
+ const j = await r.json();
1108
+ return (j.results ?? []).map((x) => (x.text ?? "").trim()).filter(Boolean);
1109
+ }
1110
+ /**
1111
+ * Latch `knowledgePagesSupported = false` iff this response really means the endpoint is absent.
1112
+ * Returns whether it latched. A bank-not-found 404 is NOT a capability verdict — it is the
1113
+ * expected answer before the bank's first retain — so it must never cache a negative (#4607).
1114
+ *
1115
+ * Only 404 is tested: `req` throws on every other non-ok status it was not told to tolerate, so
1116
+ * the 405/501 this used to check for never reach a caller in the first place.
1117
+ */
1118
+ async pagesUnsupported(r) {
1119
+ if (r.status !== 404 || !await isEndpointMissing(r)) return false;
1120
+ this.knowledgePagesSupported = false;
1121
+ return true;
1122
+ }
1123
+ /**
1124
+ * The bank's knowledge-base tree (folders + pages, nested). The tree carries names, source
1125
+ * queries and staleness but NOT synthesized content, so it is cheap enough to poll.
1126
+ */
1127
+ async tree() {
1128
+ if (this.knowledgePagesSupported === false) throw new KnowledgePagesUnavailableError();
1129
+ const r = await this.req("GET", this.bankUrl("/knowledge-base/tree"));
1130
+ if (await this.pagesUnsupported(r)) throw new KnowledgePagesUnavailableError();
1131
+ if (r.status === 404) return [];
1132
+ this.knowledgePagesSupported = true;
1133
+ try {
1134
+ return (await r.json()).roots ?? [];
1135
+ } catch {
1136
+ return [];
1137
+ }
1138
+ }
1139
+ /**
1140
+ * List knowledge pages (ids + names only — no synthesized content), flattened out of the tree
1141
+ * and shaped as `{items:[…]}` for `parsePageList`. Folders are dropped: they carry no content
1142
+ * to read, and a caller enumerating pages wants leaves, not structure.
1143
+ *
1144
+ * NOTE the ids are knowledge-base node ids (`kp-…`), NOT the backing mental-model ids. Every
1145
+ * page read/update in this client goes through the same knowledge-base ids, so a page id from
1146
+ * here, from `searchKnowledgePages`, or from a `[[page:<id>]]` link all resolve identically.
1147
+ */
1148
+ async listPages() {
1149
+ const items = [];
1150
+ const walk = (nodes, folder) => {
1151
+ for (const n of nodes) {
1152
+ if (!n?.id || !n?.name) continue;
1153
+ if (n.kind === "page") {
1154
+ items.push({
1155
+ id: n.id,
1156
+ name: n.name,
1157
+ ...n.description ? { description: n.description } : {},
1158
+ ...folder ? { folder } : {}
1159
+ });
1160
+ }
1161
+ if (n.children?.length) walk(n.children, n.kind === "folder" ? n.name : folder);
1162
+ }
1163
+ };
1164
+ walk(await this.tree());
1165
+ return { items };
1166
+ }
1167
+ /**
1168
+ * Read one knowledge page's synthesized content by knowledge-base id, shaped by `shapePage` so
1169
+ * the body arrives once. The endpoint omits the internal reflect trace that built
1170
+ * the page — that is 70-95% of the raw bytes and can blow past an MCP host's per-tool-result
1171
+ * token cap.
1172
+ */
1173
+ async getPage(pageId) {
1174
+ if (this.knowledgePagesSupported === false) throw new KnowledgePagesUnavailableError();
1175
+ const r = await this.req(
1176
+ "GET",
1177
+ this.bankUrl(`/knowledge-base/pages/${encodeURIComponent(pageId)}`)
1178
+ );
1179
+ if (r.status === 404) throw new Error(`knowledge page not found: ${pageId}`);
1180
+ return shapePage(await r.json());
1181
+ }
1182
+ /** Hybrid (BM25 + vector, RRF-fused) server-side search over the bank's knowledge pages.
1183
+ * Returns page-level hits with a relevance snippet — the real search behind
1184
+ * hindsight_search_knowledge_pages. */
1185
+ async searchKnowledgePages(query, opts = {}) {
1186
+ if (this.knowledgePagesSupported === false) throw new KnowledgePagesUnavailableError();
1187
+ const q = `?q=${encodeURIComponent(query)}&limit=${opts.limit ?? this.pageSearchLimit}`;
1188
+ const r = await this.req(
1189
+ "GET",
1190
+ this.bankUrl(`/knowledge-base/search${q}`),
1191
+ void 0,
1192
+ [],
1193
+ opts.timeoutMs
1194
+ );
1195
+ if (await this.pagesUnsupported(r)) throw new KnowledgePagesUnavailableError();
1196
+ if (r.status === 404) return [];
1197
+ const j = await r.json();
1198
+ return (j.results ?? []).map((x) => ({
1199
+ id: x.id,
1200
+ name: x.name,
1201
+ ...x.source_query ? { source_query: x.source_query } : {},
1202
+ snippet: x.snippet ?? "",
1203
+ score: x.score ?? 0
1204
+ }));
1205
+ }
1206
+ /**
1207
+ * Seed the fixed page taxonomy as knowledge-base pages at the tree root, idempotently.
1208
+ *
1209
+ * Matched by NAME, not id: `/knowledge-base/pages` mints its own `kp-…` id, so a stable
1210
+ * client-chosen id isn't available to match on (unlike the old mental-model path, which keyed
1211
+ * off a slug). Names are unique per folder server-side, which makes them a sound key.
1212
+ *
1213
+ * An existing page is PATCHed rather than recreated so a plugin upgrade that rewords a
1214
+ * `source_query` re-syncs onto the live page instead of orphaning its synthesized content —
1215
+ * which is how `pageScopeRule`'s repo name reaches banks seeded by an earlier version.
1216
+ */
1217
+ async seedPages(pageTrigger = buildPageTrigger(), pagesConfig = {}, customPages = {}) {
1218
+ const pages = pagesFor(this.project ?? this.bank, pagesConfig, customPages);
1219
+ const existing = /* @__PURE__ */ new Map();
1220
+ let roots;
1221
+ try {
1222
+ roots = await this.tree();
1223
+ } catch (e) {
1224
+ if (e instanceof KnowledgePagesUnavailableError) {
1225
+ this.log(`[bank] knowledge pages unavailable on ${this.apiUrl}; continuing without pages`);
1226
+ return;
1227
+ }
1228
+ throw e;
1229
+ }
1230
+ for (const n of roots) {
1231
+ if (n.kind === "page" && n.name) existing.set(n.name.toLowerCase(), n);
1232
+ }
1233
+ let created = 0;
1234
+ let updated = 0;
1235
+ let vanished = 0;
1236
+ for (const page of pages) {
1237
+ const hit = existing.get(page.name.toLowerCase());
1238
+ const body = {
1239
+ name: page.name,
1240
+ source_query: page.source_query,
1241
+ tags: page.tags,
1242
+ max_tokens: PAGE_MAX_TOKENS,
1243
+ // Resolved HERE, not in `buildPageTrigger`: a hashed cron (`H`) needs the page's identity,
1244
+ // and one trigger is built per session for all of them.
1245
+ trigger: pageTriggerFor(pageTrigger, this.bank, page.name)
1246
+ };
1247
+ if (!hit) {
1248
+ const r = await this.req("POST", this.bankUrl("/knowledge-base/pages"), body, [409]);
1249
+ if (await this.pagesUnsupported(r)) {
1250
+ this.log(
1251
+ `[bank] knowledge pages unavailable on ${this.apiUrl}; continuing without pages`
1252
+ );
1253
+ return;
1254
+ }
1255
+ if (r.status === 404) {
1256
+ this.log(`[bank] ${this.bank} does not exist yet; pages seed on the next session`);
1257
+ return;
1258
+ }
1259
+ if (r.status !== 409) created++;
1260
+ } else {
1261
+ const sourceDrift = hit.description !== page.source_query;
1262
+ const triggerDrift = hit.trigger != null && pageTriggerDrifted(hit.trigger, body.trigger);
1263
+ if (!sourceDrift && !triggerDrift) continue;
1264
+ const patch = {};
1265
+ if (sourceDrift) {
1266
+ patch.source_query = page.source_query;
1267
+ patch.tags = page.tags;
1268
+ this.log(
1269
+ `[bank] re-syncing "${page.name}" to its configured source_query \u2014 set pages[${JSON.stringify(page.name)}].source_query to keep your own wording`
1270
+ );
1271
+ }
1272
+ if (triggerDrift) patch.trigger = pageTriggerPatch(body.trigger);
1273
+ const r = await this.req(
1274
+ "PATCH",
1275
+ this.bankUrl(`/knowledge-base/nodes/${encodeURIComponent(hit.id)}`),
1276
+ patch
1277
+ );
1278
+ if (await this.pagesUnsupported(r)) {
1279
+ this.log(
1280
+ `[bank] knowledge pages unavailable on ${this.apiUrl}; continuing without pages`
1281
+ );
1282
+ return;
1283
+ }
1284
+ if (r.status === 404) {
1285
+ vanished++;
1286
+ continue;
1287
+ }
1288
+ updated++;
1289
+ }
1290
+ }
1291
+ const initiatives = await this.resyncInitiativeTriggers(roots, pageTrigger);
1292
+ this.log(
1293
+ `[bank] knowledge pages seeded on ${this.bank} (scoped to ${this.project ?? this.bank}): ${created} created, ${updated} re-synced, ${pages.length - created - updated - vanished} unchanged` + (vanished ? `, ${vanished} deleted under us` : "") + (initiatives ? `, ${initiatives} initiative pages re-synced` : "")
1294
+ );
1295
+ }
1296
+ /**
1297
+ * Bring the captured initiative pages onto the same refresh policy as the seeded taxonomy.
1298
+ *
1299
+ * `captureInitiative` stamps this very trigger when it creates a page, so on a bank seeded under
1300
+ * an older default they are the same drift as the taxonomy — and on a real repo they are most of
1301
+ * it: five taxonomy pages against one page per initiative, each an LLM synthesis per
1302
+ * consolidation under the auto-refresh that used to be the default (#3506).
1303
+ *
1304
+ * Only the trigger is touched. Their `name` and `source_query` are written once, from the
1305
+ * initiative's own title, and re-stating either would rebuild a page whose question never
1306
+ * changed. The tree read above is reused rather than re-fetched.
1307
+ */
1308
+ async resyncInitiativeTriggers(roots, pageTrigger) {
1309
+ const folder = roots.find(
1310
+ (n) => n.kind === "folder" && (n.name || "").toLowerCase() === "initiatives"
1311
+ );
1312
+ let updated = 0;
1313
+ for (const page of folder?.children ?? []) {
1314
+ if (page.kind !== "page" || page.trigger == null) continue;
1315
+ const desired = pageTriggerFor(pageTrigger, this.bank, page.name);
1316
+ if (!pageTriggerDrifted(page.trigger, desired)) continue;
1317
+ const r = await this.req(
1318
+ "PATCH",
1319
+ this.bankUrl(`/knowledge-base/nodes/${encodeURIComponent(page.id)}`),
1320
+ { trigger: pageTriggerPatch(desired) }
1321
+ );
1322
+ if (r.status === 404) continue;
1323
+ updated++;
1324
+ }
1325
+ return updated;
1326
+ }
1327
+ /** URL/id-safe slug: lowercase, non-alphanumerics → "-", trim dashes, cap length; fallback "initiative". */
1328
+ slugify(s) {
1329
+ return s.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "").slice(0, 60) || "initiative";
1330
+ }
1331
+ /**
1332
+ * Active-path capture: register a major feature as a per-initiative page + a marker memory.
1333
+ * New initiative → creates a page under the Initiatives folder.
1334
+ * Update (relatesToPageId) → no new page; only a marker accruing to the existing page, so an
1335
+ * enhancement or a mid-work plan change lands on the initiative it belongs to.
1336
+ *
1337
+ * The marker carries its page id in two places, neither of them a tag (#3641):
1338
+ * `metadata.relatedPageId` for provenance (visible on the document, and to a reflect loop that
1339
+ * expands one), and a `[[page:<id>]]` link in the retain CONTEXT, which is the only one of the
1340
+ * three channels a page synthesis actually reads — reflect's search results keep `context` and
1341
+ * `tags` but strip `metadata` (`_UNREAD_RESULT_FIELDS`), and the id has no business in a tag
1342
+ * vocabulary that exists to be matched with exact set-ops.
1343
+ */
1344
+ async captureInitiative(args) {
1345
+ let pageId = args.relatesToPageId;
1346
+ if (!pageId) {
1347
+ const folderId = await this.ensureFolder("Initiatives");
1348
+ const subject = this.project ?? this.bank;
1349
+ const r = await this.req("POST", this.bankUrl("/knowledge-base/pages"), {
1350
+ name: args.title,
1351
+ source_query: `Summarize the "${args.title}" initiative: what is being built or changed and why, and its current state \u2014 drawn from the project's memory.` + pageScopeRule(subject),
1352
+ parent_id: folderId,
1353
+ tags: ["knowledge:feature-work"],
1354
+ max_tokens: PAGE_MAX_TOKENS,
1355
+ trigger: pageTriggerFor(args.pageTrigger ?? buildPageTrigger(), this.bank, args.title)
1356
+ });
1357
+ try {
1358
+ const j = await r.json();
1359
+ pageId = j.page_id ?? j.id;
1360
+ } catch {
1361
+ }
1362
+ pageId ||= `initiative-${this.slugify(args.title)}`;
1363
+ }
1364
+ const verb = args.relatesToPageId ? "Update to an existing initiative" : "New initiative";
1365
+ const content = `${verb}: ${args.title}. ${args.summary}`;
1366
+ const markerId = `initiative-marker-${this.slugify(args.title)}-${Date.now()}`;
1367
+ const tags = [.../* @__PURE__ */ new Set([...args.stamp?.tags ?? [], "knowledge:feature-work"])];
1368
+ const context = `initiative marker for [[page:${pageId}]]`;
1369
+ await this.retain(content, context, markerId, tags, "document", {
1370
+ metadata: { ...args.stamp?.metadata ?? {}, relatedPageId: pageId }
1371
+ });
1372
+ return { page_id: pageId };
1373
+ }
1374
+ /** Find a root folder by name (case-insensitive) or create it; returns its id. Fail-open to undefined. */
1375
+ async ensureFolder(name) {
1376
+ try {
1377
+ const tree = await (await this.req("GET", this.bankUrl("/knowledge-base/tree"))).json();
1378
+ const hit = (tree.roots || []).find(
1379
+ (n) => n.kind === "folder" && (n.name || "").toLowerCase() === name.toLowerCase()
1380
+ );
1381
+ if (hit?.id) return hit.id;
1382
+ } catch {
1383
+ }
1384
+ try {
1385
+ const r = await this.req("POST", this.bankUrl("/knowledge-base/folders"), { name });
1386
+ return (await r.json()).id;
1387
+ } catch {
1388
+ return void 0;
1389
+ }
1390
+ }
1391
+ };
1392
+
1393
+ // src/core/config.ts
1394
+ var CONFIG_PATH = process.env.HINDSIGHT_CONFIG || join7(homedir3(), ".hindsight", "coding-agent.json");
1395
+ var DEFAULT_DAEMON_PORT = 9077;
1396
+ var DEFAULT_DAEMON_PROFILE = "coding-agent";
1397
+ function resolvePageTrigger(raw) {
1398
+ if (raw.pageTriggerType === "manual") return { type: "manual" };
1399
+ if (raw.pageTriggerType === "auto-refresh") return { type: "auto-refresh" };
1400
+ if (raw.pageTriggerType !== void 0 && raw.pageTriggerType !== "cron")
1401
+ log.warn(
1402
+ "config",
1403
+ `ignoring pageTriggerType=${JSON.stringify(raw.pageTriggerType)} \u2014 expected cron|auto-refresh|manual`
1404
+ );
1405
+ const cron = raw.pageTriggerCron?.trim();
1406
+ if (!cron) return { type: "cron", cron: DEFAULT_PAGE_TRIGGER_CRON };
1407
+ if (!isHashedCron(cron) || parseHashedCron(cron)) return { type: "cron", cron };
1408
+ log.warn(
1409
+ "config",
1410
+ `pageTriggerCron ${JSON.stringify(cron)} has a malformed hashed field \u2014 write \`H\` or \`H(<lo>-<hi>)\` within the field's own range, e.g. "H H(0-5) * * *" \u2014 falling back to ${JSON.stringify(DEFAULT_PAGE_TRIGGER_CRON)}`
1411
+ );
1412
+ return { type: "cron", cron: DEFAULT_PAGE_TRIGGER_CRON };
1413
+ }
1414
+ function resolvePages(raw) {
1415
+ const value = raw;
1416
+ if (!value || typeof value !== "object" || Array.isArray(value)) return {};
1417
+ const out = {};
1418
+ for (const [name, entry] of Object.entries(value)) {
1419
+ if (!PAGE_NAMES.some((known) => known.toLowerCase() === name.trim().toLowerCase())) {
1420
+ log.warn(
1421
+ "config",
1422
+ `ignoring pages[${JSON.stringify(name)}] \u2014 no seeded page has that name; expected one of: ${PAGE_NAMES.join(", ")}`
1423
+ );
1424
+ continue;
1425
+ }
1426
+ if (entry === false) {
1427
+ out[name] = false;
1428
+ continue;
1429
+ }
1430
+ const query = entry && typeof entry === "object" && !Array.isArray(entry) ? entry.source_query : void 0;
1431
+ if (typeof query === "string" && query.trim()) {
1432
+ out[name] = { source_query: query };
1433
+ continue;
1434
+ }
1435
+ log.warn(
1436
+ "config",
1437
+ `ignoring pages[${JSON.stringify(name)}]=${JSON.stringify(entry)} \u2014 expected false, or {"source_query": "<your question>"}`
1438
+ );
1439
+ }
1440
+ return out;
1441
+ }
1442
+ function resolveCustomPages(raw) {
1443
+ const value = raw;
1444
+ if (!value || typeof value !== "object" || Array.isArray(value)) return {};
1445
+ const out = {};
1446
+ for (const [rawName, entry] of Object.entries(value)) {
1447
+ const name = rawName.trim();
1448
+ if (!name) continue;
1449
+ if (PAGE_NAMES.some((known) => known.toLowerCase() === name.toLowerCase())) {
1450
+ log.warn(
1451
+ "config",
1452
+ `ignoring customPages[${JSON.stringify(rawName)}] \u2014 that is a seeded page; reword it under \`pages\` instead`
1453
+ );
1454
+ continue;
1455
+ }
1456
+ const query = entry && typeof entry === "object" && !Array.isArray(entry) ? entry.source_query : void 0;
1457
+ if (typeof query !== "string" || !query.trim()) {
1458
+ log.warn(
1459
+ "config",
1460
+ `ignoring customPages[${JSON.stringify(rawName)}]=${JSON.stringify(entry)} \u2014 expected {"source_query": "<your question>"}`
1461
+ );
1462
+ continue;
1463
+ }
1464
+ const rawTags = entry.tags;
1465
+ const tags = Array.isArray(rawTags) ? rawTags.filter((t) => typeof t === "string" && t.trim() !== "") : [];
1466
+ out[name] = tags.length ? { source_query: query, tags } : { source_query: query };
1467
+ }
1468
+ return out;
1469
+ }
1470
+ var DEFAULT_REFLECT_TIMEOUT_MS = 2e4;
1471
+ var DEFAULT_REFLECT_TOOL_TIMEOUT_MS = 33e4;
1472
+ var DEFAULT_INJECT_TIMEOUT_MS = 7e3;
1473
+ var REFLECT_BUDGETS = ["low", "mid", "high"];
1474
+ function resolveReflectBudget(raw) {
1475
+ const value = raw.reflectBudget;
1476
+ if (value === void 0) return "high";
1477
+ if (typeof value === "string" && REFLECT_BUDGETS.includes(value))
1478
+ return value;
1479
+ log.warn("config", `ignoring reflectBudget=${JSON.stringify(value)} \u2014 expected low|mid|high`);
1480
+ return "high";
1481
+ }
1482
+ var OBSERVATION_SCOPE_MODES = [
1483
+ "shared",
1484
+ "combined",
1485
+ "per_tag",
1486
+ "all_combinations",
1487
+ "per_source"
1488
+ ];
1489
+ function resolveObservationScopes(raw) {
1490
+ const value = raw;
1491
+ if (typeof value === "string")
1492
+ return OBSERVATION_SCOPE_MODES.includes(value) ? value : DEFAULT_OBSERVATION_SCOPES;
1493
+ if (Array.isArray(value)) {
1494
+ const scopes = value.filter((scope) => Array.isArray(scope)).map((scope) => scope.filter((t) => typeof t === "string" && t.trim() !== ""));
1495
+ if (scopes.length) return scopes;
1496
+ }
1497
+ return DEFAULT_OBSERVATION_SCOPES;
1498
+ }
1499
+ function resolveDefaultBankConfig(raw) {
1500
+ const value = raw;
1501
+ if (!value || typeof value !== "object" || Array.isArray(value)) return {};
1502
+ const out = {};
1503
+ for (const [key, v] of Object.entries(value)) {
1504
+ if (PLUGIN_GOVERNED_BANK_FIELDS.includes(key)) {
1505
+ log.warn(
1506
+ "config",
1507
+ `ignoring defaultBankConfig.${key} \u2014 the plugin manages this field itself` + (key === "retain_extraction_mode" ? " (set retainExtractionMode instead)" : "")
1508
+ );
1509
+ continue;
1510
+ }
1511
+ out[key] = v;
1512
+ }
1513
+ return out;
1514
+ }
1515
+ var AUTO_INJECT_MODES = ["reflect", "pages", "recall", "none"];
1516
+ function resolveAutoInject(raw) {
1517
+ if (raw.autoReflect !== void 0) {
1518
+ const replacement = raw.autoReflect === false ? "none" : "reflect";
1519
+ log.warn("config", `autoReflect is deprecated \u2014 use autoInject: "${replacement}" instead`);
1520
+ }
1521
+ if (AUTO_INJECT_MODES.includes(raw.autoInject)) return raw.autoInject;
1522
+ return raw.autoReflect === false ? "none" : "reflect";
1523
+ }
1524
+ function resolveConfig(raw = {}) {
1525
+ const serverMode = ["cloud", "self-hosted", "daemon"].includes(raw.serverMode) ? raw.serverMode : "cloud";
1526
+ const apiPort = raw.apiPort || DEFAULT_DAEMON_PORT;
1527
+ const pageTrigger = resolvePageTrigger(raw);
1528
+ return {
1529
+ serverMode,
1530
+ // Daemon mode resolves the URL HERE rather than at each call site: every entry point already
1531
+ // builds its client from cfg.apiUrl, so collapsing the mode into that one field means the
1532
+ // daemon needs no plumbing through eight separate constructors.
1533
+ apiUrl: serverMode === "daemon" ? `http://127.0.0.1:${apiPort}` : raw.apiUrl ?? "https://api.hindsight.vectorize.io",
1534
+ apiToken: raw.apiToken || void 0,
1535
+ apiPort,
1536
+ daemonIdleTimeout: raw.daemonIdleTimeout,
1537
+ daemonProfile: raw.daemonProfile || DEFAULT_DAEMON_PROFILE,
1538
+ embedVersion: raw.embedVersion || void 0,
1539
+ embedPackagePath: raw.embedPackagePath || void 0,
1540
+ bankId: raw.bankId,
1541
+ dynamicBankId: raw.dynamicBankId,
1542
+ bankIdTemplate: raw.bankIdTemplate,
1543
+ mapPathToBank: raw.mapPathToBank,
1544
+ resolveWorktrees: raw.resolveWorktrees,
1545
+ optInOnly: raw.optInOnly ?? false,
1546
+ // Same shape as retainTags: a config typo must not become a path that silently approves nothing.
1547
+ optInPaths: Array.isArray(raw.optInPaths) ? raw.optInPaths.filter((p) => typeof p === "string" && p.trim() !== "") : [],
1548
+ harness: raw.harness ?? "opencode",
1549
+ disabled: raw.disabled ?? false,
1550
+ retainSessions: raw.retainSessions ?? true,
1551
+ // write sessions back by default, every harness
1552
+ manageBankConfig: raw.manageBankConfig ?? true,
1553
+ retainExtractionMode: RETAIN_EXTRACTION_MODES.includes(raw.retainExtractionMode) ? raw.retainExtractionMode : DEFAULT_RETAIN_EXTRACTION_MODE,
1554
+ defaultBankConfig: resolveDefaultBankConfig(raw.defaultBankConfig),
1555
+ maxParallelRetains: raw.maxParallelRetains || 10,
1556
+ reflectTimeoutMs: raw.reflectTimeoutMs || DEFAULT_REFLECT_TIMEOUT_MS,
1557
+ // Inherit an explicitly-raised reflectTimeoutMs (that is what users reaching for a longer
1558
+ // reflect already set), but never let it LOWER the tool below the default — a short window is
1559
+ // set to bound the automatic hook, not to cut off a call the agent is waiting on.
1560
+ reflectToolTimeoutMs: raw.reflectToolTimeoutMs || Math.max(raw.reflectTimeoutMs || 0, DEFAULT_REFLECT_TOOL_TIMEOUT_MS),
1561
+ injectTimeoutMs: raw.injectTimeoutMs || DEFAULT_INJECT_TIMEOUT_MS,
1562
+ reflectBudget: resolveReflectBudget(raw),
1563
+ autoInject: resolveAutoInject(raw),
1564
+ pageSearchLimit: raw.pageSearchLimit || DEFAULT_PAGE_SEARCH_LIMIT,
1565
+ // Same shape as retainMetadata: an object, or nothing. An array would spread into numeric
1566
+ // keys and reach the API as garbage, so it is rejected like any other non-object.
1567
+ recallOptions: raw.recallOptions && typeof raw.recallOptions === "object" && !Array.isArray(raw.recallOptions) ? { ...raw.recallOptions } : {},
1568
+ toolGuideExtra: typeof raw.toolGuideExtra === "string" && raw.toolGuideExtra.trim() ? raw.toolGuideExtra : void 0,
1569
+ // Every turn, not every tenth. The guide is what tells the agent WHEN to reach for memory, and
1570
+ // at a cadence of 10 a normal session is told once, on turn 1, and never again. Measured over
1571
+ // 40 real Claude Code turns, moving this from 10 to 1 took searches from 15% of turns to 32.5%
1572
+ // with no wording change at all. The cost is the guide's ~2KB re-sent per turn, which caches.
1573
+ pageRefreshEveryTurns: raw.pageRefreshEveryTurns || 1,
1574
+ pageTriggerType: pageTrigger.type,
1575
+ pageTriggerCron: pageTrigger.cron,
1576
+ pages: resolvePages(raw.pages),
1577
+ customPages: resolveCustomPages(raw.customPages),
1578
+ autoSeed: raw.autoSeed ?? true,
1579
+ seedLimit: raw.seedLimit || DEFAULT_SEED_LIMIT,
1580
+ codebaseSurvey: raw.codebaseSurvey ?? true,
1581
+ surveyModel: raw.surveyModel || "haiku",
1582
+ surveyBudgetUsd: raw.surveyBudgetUsd || 2,
1583
+ surveyRefreshCommits: raw.surveyRefreshCommits ?? 20,
1584
+ gitIngest: ["message", "full", "none"].includes(raw.gitIngest) ? raw.gitIngest : "message",
1585
+ // Hostile input is a config typo, not an attack: keep only string entries so a stray number or
1586
+ // nested object cannot reach the API as a tag and fail the whole retain.
1587
+ retainTags: Array.isArray(raw.retainTags) ? raw.retainTags.filter((t) => typeof t === "string" && t.trim() !== "") : [],
1588
+ // Undefined, not "", when unset or blank: the retain call distinguishes "not configured" (use
1589
+ // the built-in default) from a configured value, and an empty context would strip the default.
1590
+ retainContext: typeof raw.retainContext === "string" && raw.retainContext.trim() !== "" ? raw.retainContext : void 0,
1591
+ retainMetadata: raw.retainMetadata && typeof raw.retainMetadata === "object" ? Object.fromEntries(
1592
+ Object.entries(raw.retainMetadata).filter(([, v]) => typeof v === "string")
1593
+ ) : {},
1594
+ observationScopes: resolveObservationScopes(raw.observationScopes),
1595
+ banks: raw.banks && typeof raw.banks === "object" ? raw.banks : {},
1596
+ paths: raw.paths && typeof raw.paths === "object" ? raw.paths : {},
1597
+ logLevel: ["debug", "info", "warn", "error"].includes(raw.logLevel) ? raw.logLevel : "info",
1598
+ autoUpdate: raw.autoUpdate ?? true
1599
+ };
1600
+ }
1601
+ function readRaw(path) {
1602
+ try {
1603
+ return JSON.parse(readFileSync2(path, "utf8"));
1604
+ } catch (e) {
1605
+ if (e?.code !== "ENOENT") {
1606
+ console.error(`hindsight: ignoring invalid config at ${path}: ${e?.message || e}`);
1607
+ }
1608
+ return {};
1609
+ }
1610
+ }
1611
+ function mergeRaw(a, b) {
1612
+ const { harnesses: _drop, ...flat } = b;
1613
+ return {
1614
+ ...a,
1615
+ ...flat,
1616
+ banks: { ...a.banks ?? {}, ...b.banks ?? {} },
1617
+ paths: { ...a.paths ?? {}, ...b.paths ?? {} }
1618
+ };
1619
+ }
1620
+ function applyLayer(raw, layer, harness) {
1621
+ let out = mergeRaw(raw, layer);
1622
+ const perHarness = harness ? layer.harnesses?.[harness] : void 0;
1623
+ if (perHarness) out = mergeRaw(out, perHarness);
1624
+ return out;
1625
+ }
1626
+ var ENV_KEYS = {
1627
+ serverMode: "HINDSIGHT_SERVER_MODE",
1628
+ apiUrl: "HINDSIGHT_API_URL",
1629
+ apiToken: "HINDSIGHT_API_TOKEN",
1630
+ // These four keep the names the old per-agent Claude Code plugin used, so a user migrating from
1631
+ // it can carry their existing environment over unchanged.
1632
+ apiPort: "HINDSIGHT_API_PORT",
1633
+ daemonIdleTimeout: "HINDSIGHT_DAEMON_IDLE_TIMEOUT",
1634
+ embedVersion: "HINDSIGHT_EMBED_VERSION",
1635
+ embedPackagePath: "HINDSIGHT_EMBED_PACKAGE_PATH",
1636
+ daemonProfile: "HINDSIGHT_DAEMON_PROFILE",
1637
+ bankId: "HINDSIGHT_BANK_ID",
1638
+ dynamicBankId: "HINDSIGHT_DYNAMIC_BANK_ID",
1639
+ bankIdTemplate: "HINDSIGHT_BANK_ID_TEMPLATE",
1640
+ resolveWorktrees: "HINDSIGHT_RESOLVE_WORKTREES",
1641
+ optInOnly: "HINDSIGHT_OPT_IN_ONLY",
1642
+ optInPaths: "HINDSIGHT_OPT_IN_PATHS",
1643
+ harness: "HINDSIGHT_HARNESS",
1644
+ disabled: "HINDSIGHT_DISABLED",
1645
+ retainSessions: "HINDSIGHT_RETAIN_SESSIONS",
1646
+ maxParallelRetains: "HINDSIGHT_MAX_PARALLEL_RETAINS",
1647
+ reflectTimeoutMs: "HINDSIGHT_REFLECT_TIMEOUT_MS",
1648
+ reflectToolTimeoutMs: "HINDSIGHT_REFLECT_TOOL_TIMEOUT_MS",
1649
+ injectTimeoutMs: "HINDSIGHT_INJECT_TIMEOUT_MS",
1650
+ reflectBudget: "HINDSIGHT_REFLECT_BUDGET",
1651
+ autoInject: "HINDSIGHT_AUTO_INJECT",
1652
+ pageSearchLimit: "HINDSIGHT_PAGE_SEARCH_LIMIT",
1653
+ toolGuideExtra: "HINDSIGHT_TOOL_GUIDE_EXTRA",
1654
+ autoReflect: "HINDSIGHT_AUTO_REFLECT",
1655
+ pageRefreshEveryTurns: "HINDSIGHT_PAGE_REFRESH_EVERY_TURNS",
1656
+ pageTriggerType: "HINDSIGHT_PAGE_TRIGGER_TYPE",
1657
+ pageTriggerCron: "HINDSIGHT_PAGE_TRIGGER_CRON",
1658
+ autoSeed: "HINDSIGHT_AUTO_SEED",
1659
+ seedLimit: "HINDSIGHT_SEED_LIMIT",
1660
+ codebaseSurvey: "HINDSIGHT_CODEBASE_SURVEY",
1661
+ surveyModel: "HINDSIGHT_SURVEY_MODEL",
1662
+ surveyBudgetUsd: "HINDSIGHT_SURVEY_BUDGET_USD",
1663
+ surveyRefreshCommits: "HINDSIGHT_SURVEY_REFRESH_COMMITS",
1664
+ logLevel: "HINDSIGHT_LOG_LEVEL",
1665
+ autoUpdate: "HINDSIGHT_AUTO_UPDATE",
1666
+ gitIngest: "HINDSIGHT_GIT_INGEST",
1667
+ // Scalar modes only ("shared", "combined", "per_tag", "all_combinations"). An explicit scope
1668
+ // list is a list OF lists, which does not survive flattening into one variable — file-only.
1669
+ observationScopes: "HINDSIGHT_OBSERVATION_SCOPES",
1670
+ // Comma-separated, e.g. HINDSIGHT_RETAIN_TAGS="project:{gitProject},env:work". A LIST rather than
1671
+ // a map, so it flattens cleanly; its sibling retainMetadata stays file-only for the reason above.
1672
+ retainTags: "HINDSIGHT_RETAIN_TAGS",
1673
+ manageBankConfig: "HINDSIGHT_MANAGE_BANK_CONFIG",
1674
+ retainExtractionMode: "HINDSIGHT_RETAIN_EXTRACTION_MODE"
1675
+ };
1676
+ var ENV_BOOLEANS = /* @__PURE__ */ new Set([
1677
+ "dynamicBankId",
1678
+ "resolveWorktrees",
1679
+ "optInOnly",
1680
+ "disabled",
1681
+ "retainSessions",
1682
+ "autoReflect",
1683
+ "autoSeed",
1684
+ "codebaseSurvey",
1685
+ "autoUpdate",
1686
+ "manageBankConfig"
1687
+ ]);
1688
+ var ENV_LISTS = /* @__PURE__ */ new Set(["retainTags", "optInPaths"]);
1689
+ var ENV_NUMBERS = /* @__PURE__ */ new Set([
1690
+ "apiPort",
1691
+ "daemonIdleTimeout",
1692
+ "maxParallelRetains",
1693
+ "reflectTimeoutMs",
1694
+ "reflectToolTimeoutMs",
1695
+ "injectTimeoutMs",
1696
+ "pageSearchLimit",
1697
+ "pageRefreshEveryTurns",
1698
+ "seedLimit",
1699
+ "surveyBudgetUsd",
1700
+ "surveyRefreshCommits"
1701
+ ]);
1702
+ function readEnvConfig(env = process.env) {
1703
+ const out = {};
1704
+ for (const [key, name] of Object.entries(ENV_KEYS)) {
1705
+ const value = env[name];
1706
+ if (value === void 0 || value.trim() === "") continue;
1707
+ if (ENV_BOOLEANS.has(key)) {
1708
+ out[key] = ["1", "true", "yes", "on"].includes(value.trim().toLowerCase());
1709
+ } else if (ENV_LISTS.has(key)) {
1710
+ const items = value.split(",").map((v) => v.trim()).filter(Boolean);
1711
+ if (items.length) out[key] = items;
1712
+ } else if (ENV_NUMBERS.has(key)) {
1713
+ const n = Number(value);
1714
+ if (Number.isFinite(n)) out[key] = n;
1715
+ else console.error(`hindsight: ignoring ${name}=${value} \u2014 not a number`);
1716
+ } else {
1717
+ out[key] = value;
1718
+ }
1719
+ }
1720
+ return out;
1721
+ }
1722
+ function loadConfig(opts = {}) {
1723
+ const o = typeof opts === "string" ? { path: opts } : opts;
1724
+ const withEnv = applyLayer({}, readEnvConfig(), o.harness);
1725
+ const raw = applyLayer(withEnv, readRaw(o.path ?? CONFIG_PATH), o.harness);
1726
+ if (!raw.harness && o.harness) raw.harness = o.harness;
1727
+ return resolveConfig(raw);
1728
+ }
1729
+ var BANK_OVERRIDE_EXCLUDED = [
1730
+ "bankId",
1731
+ "bankIdTemplate",
1732
+ "mapPathToBank",
1733
+ "dynamicBankId",
1734
+ "resolveWorktrees",
1735
+ // Approval is decided BEFORE the bank is resolved, so a `banks.<id>` section naming these could
1736
+ // only ever arrive too late to matter — strip them rather than let them read as effective.
1737
+ "optInOnly",
1738
+ "optInPaths",
1739
+ "harness"
1740
+ ];
1741
+ function applyBankConfig(cfg, resolvedId, directory) {
1742
+ if (directory !== void 0 && !isOptedIn(cfg, directory))
1743
+ return { cfg: { ...cfg, disabled: true }, bankId: resolvedId };
1744
+ const byPath = directory === void 0 ? void 0 : pathSection(cfg, cfg.paths, directory);
1745
+ if (byPath) {
1746
+ const { bank: _rename, ...rest } = overrideFields(byPath);
1747
+ cfg = { ...cfg, ...resolvePartial(cfg, rest) };
1748
+ }
1749
+ const section = cfg.banks[resolvedId];
1750
+ if (!section) return { cfg, bankId: resolvedId };
1751
+ const safe = overrideFields(section);
1752
+ const bankId = typeof safe.bank === "string" && safe.bank ? safe.bank : resolvedId;
1753
+ delete safe.bank;
1754
+ return { cfg: { ...cfg, ...resolvePartial(cfg, safe) }, bankId };
1755
+ }
1756
+ function overrideFields(section) {
1757
+ const safe = { ...section };
1758
+ for (const k of BANK_OVERRIDE_EXCLUDED) delete safe[k];
1759
+ delete safe.banks;
1760
+ delete safe.paths;
1761
+ return safe;
1762
+ }
1763
+ function resolvePartial(cfg, patch) {
1764
+ const full = resolveConfig(patch);
1765
+ const out = {};
1766
+ for (const key of Object.keys(patch)) {
1767
+ if (key in full)
1768
+ out[key] = full[key];
1769
+ }
1770
+ if ("autoReflect" in patch && !("autoInject" in patch)) out.autoInject = full.autoInject;
1771
+ if ("serverMode" in patch || "apiUrl" in patch || "apiPort" in patch) {
1772
+ const conn = resolveConfig({
1773
+ serverMode: patch.serverMode ?? cfg.serverMode,
1774
+ apiPort: patch.apiPort ?? cfg.apiPort,
1775
+ apiUrl: patch.apiUrl ?? (cfg.serverMode === "daemon" ? void 0 : cfg.apiUrl)
1776
+ });
1777
+ out.serverMode = conn.serverMode;
1778
+ out.apiUrl = conn.apiUrl;
1779
+ out.apiPort = conn.apiPort;
1780
+ }
1781
+ return out;
1782
+ }
1783
+
1784
+ // src/core/session-cache.ts
1785
+ import { mkdirSync as mkdirSync2, readFileSync as readFileSync3, renameSync as renameSync2, rmSync, writeFileSync } from "fs";
1786
+ import { tmpdir } from "os";
1787
+ import { dirname as dirname5, join as join8 } from "path";
1788
+ function writeFileAtomic(path, body) {
1789
+ mkdirSync2(dirname5(path), { recursive: true });
1790
+ const tmp = `${path}.${process.pid}.tmp`;
1791
+ try {
1792
+ writeFileSync(tmp, body);
1793
+ renameSync2(tmp, path);
1794
+ } catch (e) {
1795
+ try {
1796
+ rmSync(tmp, { force: true });
1797
+ } catch {
1798
+ }
1799
+ throw e;
1800
+ }
1801
+ }
1802
+ function sessionRootFile(harness, sessionId) {
1803
+ return join8(tmpdir(), `hindsight-${harness}`, `${sessionId}.root`);
1804
+ }
1805
+ function sessionRootDir(harness, sessionId, cwd) {
1806
+ if (!sessionId || !cwd) return cwd;
1807
+ const file = sessionRootFile(harness, sessionId);
1808
+ try {
1809
+ const recorded = readFileSync3(file, "utf8").trim();
1810
+ if (recorded) return recorded;
1811
+ } catch {
1812
+ }
1813
+ try {
1814
+ writeFileAtomic(file, cwd);
1815
+ } catch {
1816
+ }
1817
+ return cwd;
1818
+ }
1819
+ function fileUsageCursorStore(harness) {
1820
+ const file = (sessionId) => join8(tmpdir(), `hindsight-${harness}`, `${sessionId}.usage.json`);
1821
+ return {
1822
+ read: (sessionId) => {
1823
+ try {
1824
+ const turns = JSON.parse(readFileSync3(file(sessionId), "utf8")).turns;
1825
+ return typeof turns === "number" ? turns : void 0;
1826
+ } catch {
1827
+ return void 0;
1828
+ }
1829
+ },
1830
+ write: (sessionId, turns) => {
1831
+ try {
1832
+ writeFileAtomic(file(sessionId), JSON.stringify({ turns }));
1833
+ } catch {
1834
+ }
1835
+ }
1836
+ };
1837
+ }
1838
+ function cursorFile(harness, sessionId) {
1839
+ return join8(tmpdir(), `hindsight-${harness}`, `${sessionId}.retain.json`);
1840
+ }
1841
+ function fileCursorStore(harness) {
1842
+ return {
1843
+ read: (sessionId) => {
1844
+ try {
1845
+ return JSON.parse(readFileSync3(cursorFile(harness, sessionId), "utf8"));
1846
+ } catch {
1847
+ return void 0;
1848
+ }
1849
+ },
1850
+ write: (sessionId, cursor) => {
1851
+ try {
1852
+ writeFileAtomic(cursorFile(harness, sessionId), JSON.stringify(cursor));
1853
+ } catch {
1854
+ }
1855
+ }
1856
+ };
1857
+ }
1858
+
1859
+ // src/core/turn-journal.ts
1860
+ import { appendFileSync as appendFileSync2, mkdirSync as mkdirSync3, readFileSync as readFileSync4, statSync as statSync2 } from "fs";
1861
+ import { tmpdir as tmpdir2 } from "os";
1862
+ import { dirname as dirname6, join as join9 } from "path";
1863
+
1864
+ // src/core/transcript-util.ts
1865
+ var MEMORY_TAG_RE = /<(hook_prompt|task-notification|system-reminder|hindsight_memory|hindsight_memories|hindsight_bank|relevant_memories|user_feedback|hindsight_knowledge|hindsight_knowledge_refresh)\b[\s\S]*?<\/\1>/g;
1866
+ function stripInjectedMemory(s) {
1867
+ return s.replace(MEMORY_TAG_RE, "");
1868
+ }
1869
+ var TARGET_KEYS = [
1870
+ "file_path",
1871
+ "path",
1872
+ "notebook_path",
1873
+ "command",
1874
+ "pattern",
1875
+ "query",
1876
+ "url",
1877
+ "name",
1878
+ "id"
1879
+ ];
1880
+ var ACTION_TARGET_CAP = 100;
1881
+ function actionLine(tool, input) {
1882
+ let target = "";
1883
+ if (input && typeof input === "object") {
1884
+ const rec = input;
1885
+ for (const k of TARGET_KEYS) {
1886
+ const v = rec[k];
1887
+ if (typeof v === "string" && v.trim()) {
1888
+ target = v.trim().split("\n")[0];
1889
+ break;
1890
+ }
1891
+ }
1892
+ } else if (typeof input === "string") {
1893
+ target = input.trim().split("\n")[0];
1894
+ }
1895
+ if (target.length > ACTION_TARGET_CAP) target = `${target.slice(0, ACTION_TARGET_CAP)}\u2026`;
1896
+ return target ? `${tool} ${target}` : tool;
1897
+ }
1898
+
1899
+ // src/core/turn-journal.ts
1900
+ var JOURNAL_MAX_BYTES = 8 * 1024 * 1024;
1901
+ function journalPath(harness, sessionId) {
1902
+ return join9(tmpdir2(), `hindsight-${harness}`, `${sessionId || "no-session"}.journal.jsonl`);
1903
+ }
1904
+ function appendJournalTurn(path, turn) {
1905
+ const content = stripInjectedMemory(turn.content ?? "").trim();
1906
+ if (!content) return;
1907
+ try {
1908
+ if (statSync2(path).size >= JOURNAL_MAX_BYTES) return;
1909
+ } catch {
1910
+ }
1911
+ const last = readJournalTranscript(path).at(-1);
1912
+ if (last && last.role === turn.role && last.content === content) return;
1913
+ try {
1914
+ mkdirSync3(dirname6(path), { recursive: true });
1915
+ appendFileSync2(
1916
+ path,
1917
+ JSON.stringify({
1918
+ role: turn.role,
1919
+ content,
1920
+ timestamp: turn.timestamp ?? (/* @__PURE__ */ new Date()).toISOString()
1921
+ }) + "\n"
1922
+ );
1923
+ } catch {
1924
+ }
1925
+ }
1926
+ function readJournalTranscript(path) {
1927
+ let body;
1928
+ try {
1929
+ body = readFileSync4(path, "utf8");
1930
+ } catch {
1931
+ return [];
1932
+ }
1933
+ const turns = [];
1934
+ for (const line of body.split("\n")) {
1935
+ const trimmed = line.trim();
1936
+ if (!trimmed) continue;
1937
+ let parsed;
1938
+ try {
1939
+ parsed = JSON.parse(trimmed);
1940
+ } catch {
1941
+ continue;
1942
+ }
1943
+ if (typeof parsed !== "object" || parsed === null) continue;
1944
+ const { role, content, timestamp } = parsed;
1945
+ if (typeof role !== "string" || typeof content !== "string" || !content) continue;
1946
+ turns.push({
1947
+ role,
1948
+ content,
1949
+ ...typeof timestamp === "string" ? { timestamp } : {}
1950
+ });
1951
+ }
1952
+ return turns;
1953
+ }
1954
+
1955
+ // src/core/retain-hook.ts
1956
+ import { readFileSync as readFileSync7 } from "fs";
1957
+
1958
+ // src/core/retain-cursor.ts
1959
+ import { createHash as createHash2 } from "crypto";
1960
+ var PENDING_MAX_AGE_MS = 12 * 60 * 60 * 1e3;
1961
+ var PENDING_MAX_BYTES = 256 * 1024;
1962
+ var MAX_CURSOR_PATHS = 16;
1963
+ function advancePaths(seen, path) {
1964
+ if (!path) return seen;
1965
+ return [...(seen ?? []).filter((p) => p !== path), path].slice(-MAX_CURSOR_PATHS);
1966
+ }
1967
+ function pendingReplayable(cursor, now) {
1968
+ const pending = cursor.pending ?? [];
1969
+ if (!pending.length) return true;
1970
+ if (pending.some((p) => now - p.at > PENDING_MAX_AGE_MS)) return false;
1971
+ return pending.reduce((n, p) => n + p.content.length, 0) <= PENDING_MAX_BYTES;
1972
+ }
1973
+ function fingerprintTurns(turns, count) {
1974
+ const h = createHash2("sha1").update(String(count));
1975
+ for (let i = 0; i < count; i++) h.update("\n" + JSON.stringify(turns[i]));
1976
+ return h.digest("hex");
1977
+ }
1978
+ function planRetain(turns, cursor, opts) {
1979
+ if (!turns.length) return { mode: "skip" };
1980
+ if (!opts.appendSupported || !cursor || cursor.dirty) return { mode: "replace" };
1981
+ if (!pendingReplayable(cursor, opts.now ?? Date.now())) return { mode: "replace" };
1982
+ if (cursor.bank !== opts.bank) return { mode: "replace" };
1983
+ const seen = cursor.paths ?? [];
1984
+ const newFile = Boolean(opts.path && seen.length && !seen.includes(opts.path));
1985
+ const continues = cursor.turns <= turns.length && fingerprintTurns(turns, cursor.turns) === cursor.fingerprint;
1986
+ if (!continues) return newFile ? { mode: "append", fromTurn: 0 } : { mode: "replace" };
1987
+ if (cursor.turns === turns.length) return { mode: "skip" };
1988
+ return { mode: "append", fromTurn: cursor.turns };
1989
+ }
1990
+
1991
+ // src/core/uuid.ts
1992
+ import { createHash as createHash3 } from "crypto";
1993
+ var HINDSIGHT_NAMESPACE = "e75686a4-e923-4326-a0d1-358f1c6c3eb4";
1994
+ function uuidV5(name, namespace = HINDSIGHT_NAMESPACE) {
1995
+ const ns = Buffer.from(namespace.replace(/-/g, ""), "hex");
1996
+ if (ns.length !== 16) throw new Error(`invalid UUID namespace: ${namespace}`);
1997
+ const bytes = Buffer.from(
1998
+ createHash3("sha1").update(ns).update(Buffer.from(name, "utf8")).digest().subarray(0, 16)
1999
+ );
2000
+ bytes[6] = bytes[6] & 15 | 80;
2001
+ bytes[8] = bytes[8] & 63 | 128;
2002
+ const hex = bytes.toString("hex");
2003
+ return [
2004
+ hex.slice(0, 8),
2005
+ hex.slice(8, 12),
2006
+ hex.slice(12, 16),
2007
+ hex.slice(16, 20),
2008
+ hex.slice(20)
2009
+ ].join("-");
2010
+ }
2011
+
2012
+ // src/core/chat.ts
2013
+ function withRefId(refId, turns, baseTs) {
2014
+ return [{ role: "system", content: `REF-ID: ${refId}`, timestamp: baseTs }, ...turns];
2015
+ }
2016
+ function renderSessionJsonl(refId, turns, baseTs) {
2017
+ return withRefId(refId, turns, baseTs).map((t) => JSON.stringify(t)).join("\n");
2018
+ }
2019
+ async function supportsAppend(client) {
2020
+ try {
2021
+ return await client.supportsAppendRetain();
2022
+ } catch {
2023
+ return false;
2024
+ }
2025
+ }
2026
+ var DEFAULT_RETRY_WINDOW_MS = 6e4;
2027
+ var RETAIN_RETRY_ATTEMPTS = 2;
2028
+ var REQUEST_BUDGET_MS = 15e3;
2029
+ async function submitWithRetry(send, isStillNewest, retryUntil) {
2030
+ for (let attempt = 0; ; attempt++) {
2031
+ try {
2032
+ return await send();
2033
+ } catch (e) {
2034
+ const limited = e instanceof RateLimitedError;
2035
+ if (!limited || attempt >= RETAIN_RETRY_ATTEMPTS || !isStillNewest()) throw e;
2036
+ const wait = e.retryAfterMs || 1e3;
2037
+ if (Date.now() + wait + REQUEST_BUDGET_MS > retryUntil) throw e;
2038
+ await sleep(wait);
2039
+ }
2040
+ }
2041
+ }
2042
+ var writeBacks = /* @__PURE__ */ new WeakMap();
2043
+ function serialize(cursors, sessionId, write2) {
2044
+ const perSession = writeBacks.get(cursors) ?? /* @__PURE__ */ new Map();
2045
+ writeBacks.set(cursors, perSession);
2046
+ const next = (perSession.get(sessionId) ?? Promise.resolve()).then(write2, write2);
2047
+ const tail = next.catch(() => {
2048
+ });
2049
+ perSession.set(sessionId, tail);
2050
+ void tail.then(() => {
2051
+ if (perSession.get(sessionId) === tail) perSession.delete(sessionId);
2052
+ });
2053
+ return next;
2054
+ }
2055
+ var DEFAULT_RETAIN_CONTEXT = `conversation between the user and you (the coding agent): user turns are the user's words and decisions, assistant turns are yours. When an assistant turn says something is fixed, passes or works, record it as the agent's claim ("the agent reported X fixed"), not as an established fact.`;
2056
+ async function retainLiveSession(client, sessionId, turns, startTs, harness, opts = {}) {
2057
+ const cursors = opts.cursors;
2058
+ if (!cursors)
2059
+ return writeSession(
2060
+ client,
2061
+ sessionId,
2062
+ turns,
2063
+ startTs,
2064
+ harness,
2065
+ opts.stamp,
2066
+ void 0,
2067
+ opts.retryUntil,
2068
+ opts.transcriptPath
2069
+ );
2070
+ return serialize(
2071
+ cursors,
2072
+ sessionId,
2073
+ () => writeSession(
2074
+ client,
2075
+ sessionId,
2076
+ turns,
2077
+ startTs,
2078
+ harness,
2079
+ opts.stamp,
2080
+ cursors,
2081
+ opts.retryUntil,
2082
+ opts.transcriptPath
2083
+ )
2084
+ );
2085
+ }
2086
+ async function writeSession(client, sessionId, turns, startTs, harness, stamp, cursors, retryUntil = Date.now() + DEFAULT_RETRY_WINDOW_MS, transcriptPath) {
2087
+ if (!turns.length) return;
2088
+ const refId = `conversation:${sessionId}`;
2089
+ const cursor = cursors?.read(sessionId);
2090
+ const appendSupported = Boolean(cursors) && (cursor?.appendSupported === true || await supportsAppend(client));
2091
+ const plan = planRetain(turns, cursor, {
2092
+ appendSupported,
2093
+ bank: client.bank,
2094
+ path: transcriptPath
2095
+ });
2096
+ const paths = plan.mode === "replace" ? transcriptPath ? [transcriptPath] : void 0 : advancePaths(cursor?.paths, transcriptPath);
2097
+ const outbox = plan.mode === "replace" ? [] : cursor?.pending ?? [];
2098
+ if (plan.mode === "skip" && !outbox.length) return;
2099
+ const opId = (mode, content) => uuidV5(`${client.bank}
2100
+ ${refId}
2101
+ ${mode}
2102
+ ${content}`);
2103
+ const submit = (content, operationId, append) => client.retain(
2104
+ content,
2105
+ // Configured context wins. Extraction reads this to decide whose claim a sentence is, so the
2106
+ // default names both speakers: the previous "coding agent session" said nothing about
2107
+ // authorship and let an assistant's proposal be recorded as the user's decision.
2108
+ stamp?.context ?? DEFAULT_RETAIN_CONTEXT,
2109
+ refId,
2110
+ // Configured tags first, built-ins last and deduped: `source:chat` and `harness:<id>` are what
2111
+ // the documents list filters and draws its agent logo from, so a template cannot displace them.
2112
+ [
2113
+ .../* @__PURE__ */ new Set([
2114
+ ...stamp?.tags ?? [],
2115
+ "source:chat",
2116
+ ...harness ? [`harness:${harness}`] : []
2117
+ ])
2118
+ ],
2119
+ "conversation",
2120
+ {
2121
+ timestamp: startTs,
2122
+ updateMode: append ? "append" : void 0,
2123
+ operationId,
2124
+ metadata: {
2125
+ ...stamp?.metadata,
2126
+ // configured first: the built-ins below win on any key collision
2127
+ source: "chat",
2128
+ session_id: sessionId,
2129
+ ref_id: refId,
2130
+ ...harness ? { harness } : {}
2131
+ }
2132
+ }
2133
+ );
2134
+ const next = {
2135
+ turns: turns.length,
2136
+ fingerprint: fingerprintTurns(turns, turns.length),
2137
+ bank: client.bank,
2138
+ ...paths ? { paths } : {},
2139
+ ...appendSupported ? { appendSupported: true } : {}
2140
+ };
2141
+ const stillOurs = () => {
2142
+ if (!cursors) return true;
2143
+ const now = cursors.read(sessionId);
2144
+ return now?.turns === next.turns && now?.fingerprint === next.fingerprint;
2145
+ };
2146
+ if (plan.mode === "replace") {
2147
+ const content = renderSessionJsonl(refId, turns, startTs);
2148
+ cursors?.write(sessionId, { ...next, dirty: true });
2149
+ await submitWithRetry(
2150
+ () => submit(content, opId("replace", content), false),
2151
+ stillOurs,
2152
+ retryUntil
2153
+ );
2154
+ cursors?.write(sessionId, next);
2155
+ return;
2156
+ }
2157
+ const queue = [...outbox];
2158
+ if (plan.mode === "append") {
2159
+ const content = turns.slice(plan.fromTurn).map((t) => JSON.stringify(t)).join("\n");
2160
+ queue.push({ content, operationId: opId("append", content), at: Date.now() });
2161
+ }
2162
+ cursors?.write(sessionId, { ...next, pending: queue });
2163
+ for (let i = 0; i < queue.length; i++) {
2164
+ if (i > 0 && Date.now() + REQUEST_BUDGET_MS > retryUntil) return;
2165
+ const entry = queue[i];
2166
+ await submitWithRetry(
2167
+ () => submit(entry.content, entry.operationId, true),
2168
+ stillOurs,
2169
+ retryUntil
2170
+ );
2171
+ const remaining = queue.slice(i + 1);
2172
+ cursors?.write(sessionId, remaining.length ? { ...next, pending: remaining } : next);
2173
+ }
2174
+ }
2175
+
2176
+ // src/core/daemon.ts
2177
+ import { execFileSync, spawn as realSpawn2 } from "child_process";
2178
+ import { dirname as dirname7, join as join10 } from "path";
2179
+ import { fileURLToPath as fileURLToPath2 } from "url";
2180
+ var DAEMON_WAIT_RETAIN_MS = 4e4;
2181
+ async function isServerHealthy(baseUrl, timeoutMs = 2e3) {
2182
+ try {
2183
+ const res = await fetch(`${baseUrl}/health`, { signal: AbortSignal.timeout(timeoutMs) });
2184
+ return res.ok;
2185
+ } catch {
2186
+ return false;
2187
+ }
2188
+ }
2189
+ function hasRustToolchain() {
2190
+ if (process.platform !== "darwin") return true;
2191
+ try {
2192
+ execFileSync("cargo", ["--version"], {
2193
+ stdio: "pipe",
2194
+ timeout: 1e4,
2195
+ windowsHide: true
2196
+ });
2197
+ return true;
2198
+ } catch {
2199
+ return false;
2200
+ }
2201
+ }
2202
+ function hasUvx() {
2203
+ try {
2204
+ execFileSync("uvx", ["--version"], {
2205
+ stdio: "pipe",
2206
+ timeout: 1e4,
2207
+ windowsHide: true
2208
+ });
2209
+ return true;
2210
+ } catch {
2211
+ return false;
2212
+ }
2213
+ }
2214
+ var PROVIDER_PROBES = [
2215
+ { provider: "openai", keyEnv: "OPENAI_API_KEY" },
2216
+ { provider: "anthropic", keyEnv: "ANTHROPIC_API_KEY" },
2217
+ { provider: "gemini", keyEnv: "GEMINI_API_KEY" },
2218
+ { provider: "groq", keyEnv: "GROQ_API_KEY" }
2219
+ ];
2220
+ function detectLlm(env = process.env) {
2221
+ const explicit = env.HINDSIGHT_API_LLM_PROVIDER?.trim();
2222
+ if (explicit) {
2223
+ return {
2224
+ provider: explicit,
2225
+ apiKey: env.HINDSIGHT_API_LLM_API_KEY?.trim() || void 0,
2226
+ source: "HINDSIGHT_API_LLM_PROVIDER"
2227
+ };
2228
+ }
2229
+ for (const probe of PROVIDER_PROBES) {
2230
+ const key = env[probe.keyEnv]?.trim();
2231
+ if (key) return { provider: probe.provider, apiKey: key, source: probe.keyEnv };
2232
+ }
2233
+ if (onPath("claude")) {
2234
+ return { provider: "claude-code", source: "the Claude Code CLI on PATH (no API key needed)" };
2235
+ }
2236
+ return void 0;
2237
+ }
2238
+ function onPath(bin) {
2239
+ try {
2240
+ execFileSync("which", [bin], {
2241
+ stdio: "pipe",
2242
+ timeout: 5e3,
2243
+ windowsHide: true
2244
+ });
2245
+ return true;
2246
+ } catch {
2247
+ return false;
2248
+ }
2249
+ }
2250
+ function startDaemonDetached(cfg, harness, spawnFn = realSpawn2) {
2251
+ try {
2252
+ const starter = join10(dirname7(fileURLToPath2(import.meta.url)), "daemon-start.js");
2253
+ const child = spawnFn("node", [starter, "--harness", harness], {
2254
+ detached: true,
2255
+ stdio: "ignore",
2256
+ windowsHide: true
2257
+ });
2258
+ child.on("error", () => {
2259
+ });
2260
+ child.unref();
2261
+ diag(harness, "daemon_start_spawned", { apiUrl: cfg.apiUrl });
2262
+ } catch {
2263
+ }
2264
+ }
2265
+ var coldStarts = /* @__PURE__ */ new Map();
2266
+ async function waitBounded(p, ms) {
2267
+ let timer;
2268
+ try {
2269
+ await Promise.race([
2270
+ p,
2271
+ new Promise((resolve3) => {
2272
+ timer = setTimeout(resolve3, Math.max(ms, 0));
2273
+ })
2274
+ ]);
2275
+ } finally {
2276
+ clearTimeout(timer);
2277
+ }
2278
+ }
2279
+ async function ensureDaemon(cfg, harness, opts = {}) {
2280
+ if (cfg.serverMode !== "daemon") return;
2281
+ if (await isServerHealthy(cfg.apiUrl)) return;
2282
+ if (!preflightDaemon(cfg, harness)) return;
2283
+ const waitMs = opts.waitMs ?? 0;
2284
+ const running = coldStarts.get(cfg.apiUrl);
2285
+ if (running) {
2286
+ const startedAt = Date.now();
2287
+ await waitBounded(
2288
+ running.catch(() => void 0),
2289
+ waitMs
2290
+ );
2291
+ const remaining = waitMs - (Date.now() - startedAt);
2292
+ if (remaining > 0) await waitForHealth(cfg.apiUrl, remaining);
2293
+ return;
2294
+ }
2295
+ const attempt = (async () => {
2296
+ startDaemonDetached(cfg, harness, opts.spawnFn);
2297
+ await waitForHealth(cfg.apiUrl, waitMs);
2298
+ })();
2299
+ coldStarts.set(cfg.apiUrl, attempt);
2300
+ try {
2301
+ await attempt;
2302
+ } finally {
2303
+ if (coldStarts.get(cfg.apiUrl) === attempt) coldStarts.delete(cfg.apiUrl);
2304
+ }
2305
+ }
2306
+ async function waitForHealth(baseUrl, budgetMs, pollMs = 1e3) {
2307
+ const deadline = Date.now() + budgetMs;
2308
+ while (Date.now() < deadline) {
2309
+ await new Promise((r) => setTimeout(r, pollMs));
2310
+ if (await isServerHealthy(baseUrl)) return true;
2311
+ }
2312
+ return false;
2313
+ }
2314
+ function preflightDaemon(cfg, harness) {
2315
+ if (!hasUvx()) {
2316
+ diag(harness, "daemon_uvx_missing", { apiUrl: cfg.apiUrl });
2317
+ log.warn(harness, "daemon mode needs `uv` on PATH \u2014 see https://docs.astral.sh/uv/");
2318
+ return false;
2319
+ }
2320
+ if (!hasRustToolchain()) {
2321
+ diag(harness, "daemon_rust_missing", { platform: process.platform });
2322
+ log.warn(
2323
+ harness,
2324
+ "daemon mode on macOS needs a current Rust toolchain (litellm ships no macOS wheel) \u2014 install from https://rustup.rs, then `rustup default stable && rustup update`"
2325
+ );
2326
+ return false;
2327
+ }
2328
+ if (!detectLlm()) {
2329
+ diag(harness, "daemon_no_llm", {});
2330
+ log.warn(
2331
+ harness,
2332
+ "daemon mode needs an LLM for fact extraction \u2014 set OPENAI_API_KEY (or ANTHROPIC_API_KEY / GEMINI_API_KEY / HINDSIGHT_API_LLM_PROVIDER), or install the Claude Code CLI"
2333
+ );
2334
+ return false;
2335
+ }
2336
+ return true;
2337
+ }
2338
+
2339
+ // src/core/retain-stamp.ts
2340
+ import { basename as basename2 } from "path";
2341
+ var RESERVED_TAG_PREFIX = /^(source|harness):/;
2342
+ function resolversFor(ctx) {
2343
+ return {
2344
+ // Worktree-aware like the bank id, so every linked worktree of a repo stamps the SAME name —
2345
+ // otherwise a shared bank ends up with `project:app` and `project:app-wt2` for one repository.
2346
+ gitProject: () => projectNameOf(ctx.directory, ctx.sessionRoot),
2347
+ project: () => ctx.directory ? basename2(ctx.directory) : "unknown",
2348
+ harness: () => ctx.harness,
2349
+ bankId: () => ctx.bankId,
2350
+ sessionId: () => ctx.sessionId ?? "unknown",
2351
+ timestamp: () => (/* @__PURE__ */ new Date()).toISOString(),
2352
+ channel: () => process.env.HINDSIGHT_CHANNEL_ID || "default",
2353
+ user: () => process.env.HINDSIGHT_USER_ID || "anonymous"
2354
+ };
2355
+ }
2356
+ function buildRetainStamp(cfg, ctx) {
2357
+ const hasTags = Boolean(cfg.retainTags?.length);
2358
+ const hasMetadata = Boolean(cfg.retainMetadata && Object.keys(cfg.retainMetadata).length);
2359
+ const hasContext = Boolean(cfg.retainContext?.trim());
2360
+ if (!hasTags && !hasMetadata && !hasContext) return { tags: [], metadata: {} };
2361
+ const base = resolversFor(ctx);
2362
+ const cache = /* @__PURE__ */ new Map();
2363
+ const resolvers = Object.fromEntries(
2364
+ Object.entries(base).map(([name, resolve3]) => [
2365
+ name,
2366
+ () => {
2367
+ const hit = cache.get(name);
2368
+ if (hit !== void 0) return hit;
2369
+ const value = resolve3();
2370
+ cache.set(name, value);
2371
+ return value;
2372
+ }
2373
+ ])
2374
+ );
2375
+ const tags = (cfg.retainTags ?? []).map((t) => applyTemplate(t, resolvers, "retainTags").trim()).filter(Boolean).filter((t) => {
2376
+ if (!RESERVED_TAG_PREFIX.test(t)) return true;
2377
+ log.warn("retain-stamp", "ignoring reserved retainTags entry", { tag: t });
2378
+ return false;
2379
+ });
2380
+ const metadata = {};
2381
+ for (const [key, value] of Object.entries(cfg.retainMetadata ?? {})) {
2382
+ metadata[key] = applyTemplate(value, resolvers, "retainMetadata");
2383
+ }
2384
+ const context = hasContext ? applyTemplate(cfg.retainContext, resolvers, "retainContext").trim() || void 0 : void 0;
2385
+ return { tags, metadata, context };
2386
+ }
2387
+
2388
+ // src/core/jsonl.ts
2389
+ import { closeSync, openSync, readSync } from "fs";
2390
+ import { StringDecoder } from "string_decoder";
2391
+ var CHUNK_BYTES = 64 * 1024;
2392
+ function* readJsonl(path) {
2393
+ let fd;
2394
+ try {
2395
+ fd = openSync(path, "r");
2396
+ } catch {
2397
+ return;
2398
+ }
2399
+ try {
2400
+ const buffer = Buffer.allocUnsafe(CHUNK_BYTES);
2401
+ const decoder = new StringDecoder("utf8");
2402
+ let pending = "";
2403
+ let position = 0;
2404
+ for (; ; ) {
2405
+ const bytesRead = readSync(fd, buffer, 0, buffer.length, position);
2406
+ if (bytesRead <= 0) break;
2407
+ position += bytesRead;
2408
+ pending += decoder.write(buffer.subarray(0, bytesRead));
2409
+ let newline;
2410
+ while ((newline = pending.indexOf("\n")) !== -1) {
2411
+ yield pending.slice(0, newline);
2412
+ pending = pending.slice(newline + 1);
2413
+ }
2414
+ }
2415
+ pending += decoder.end();
2416
+ if (pending) yield pending;
2417
+ } finally {
2418
+ closeSync(fd);
2419
+ }
2420
+ }
2421
+
2422
+ // src/core/transcript.ts
2423
+ function renderLine(content, type) {
2424
+ if (typeof content === "string") {
2425
+ const text = stripInjectedMemory(content).trim();
2426
+ return text ? [{ role: type, content: text }] : [];
2427
+ }
2428
+ if (!Array.isArray(content)) return [];
2429
+ const texts = [];
2430
+ const actions = [];
2431
+ for (const b of content) {
2432
+ if (!b || typeof b !== "object") continue;
2433
+ if (b.type === "text" && typeof b.text === "string") {
2434
+ const t = stripInjectedMemory(b.text).trim();
2435
+ if (t) texts.push(t);
2436
+ } else if (b.type === "tool_use" && typeof b.name === "string") {
2437
+ actions.push({ role: "action", content: actionLine(b.name, b.input) });
2438
+ }
2439
+ }
2440
+ const out = [];
2441
+ const joined = texts.join("\n").trim();
2442
+ if (joined) out.push({ role: type, content: joined });
2443
+ out.push(...actions);
2444
+ return out;
2445
+ }
2446
+ function readClaudeTranscript(path) {
2447
+ const turns = [];
2448
+ for (const rawLine of readJsonl(path)) {
2449
+ const trimmed = rawLine.trim();
2450
+ if (!trimmed) continue;
2451
+ let parsed;
2452
+ try {
2453
+ parsed = JSON.parse(trimmed);
2454
+ } catch {
2455
+ continue;
2456
+ }
2457
+ if (typeof parsed !== "object" || parsed === null) continue;
2458
+ const line = parsed;
2459
+ if (line.type !== "user" && line.type !== "assistant") continue;
2460
+ if (line.isMeta === true) continue;
2461
+ if (line.isSidechain === true) continue;
2462
+ if (line.isCompactSummary === true) continue;
2463
+ if (typeof line.message !== "object" || line.message === null) continue;
2464
+ for (const rendered of renderLine(line.message.content, line.type)) {
2465
+ const turn = { role: rendered.role, content: rendered.content };
2466
+ if (typeof line.timestamp === "string") turn.timestamp = line.timestamp;
2467
+ turns.push(turn);
2468
+ }
2469
+ }
2470
+ return turns;
2471
+ }
2472
+
2473
+ // src/core/usage.ts
2474
+ import { readFileSync as readFileSync6 } from "fs";
2475
+ import { join as join11 } from "path";
2476
+ function usageFilePath() {
2477
+ return process.env.HINDSIGHT_USAGE_FILE || join11(logsDir(), "usage.jsonl");
2478
+ }
2479
+ var HINDSIGHT_TOOL_RE = /hindsight_(?:[a-z]+_)*[a-z]+$/;
2480
+ var CREDIT_RE = /from hindsight memory/i;
2481
+ var ASSISTANT_ROLES = /* @__PURE__ */ new Set(["assistant", "model"]);
2482
+ function summarizeTurns(turns) {
2483
+ const out = [];
2484
+ for (const t of turns) {
2485
+ if (t.role === "user") {
2486
+ out.push({ turn: out.length + 1, calls: [], credited: false });
2487
+ continue;
2488
+ }
2489
+ const current2 = out.at(-1);
2490
+ if (!current2) continue;
2491
+ if (t.role === "action") {
2492
+ const tool = t.content.split(" ", 1)[0].match(HINDSIGHT_TOOL_RE)?.[0];
2493
+ if (tool) current2.calls.push(tool);
2494
+ } else if (ASSISTANT_ROLES.has(t.role) && CREDIT_RE.test(t.content)) {
2495
+ current2.credited = true;
2496
+ }
2497
+ }
2498
+ return out;
2499
+ }
2500
+ function recordUsage(args) {
2501
+ const summary = summarizeTurns(args.turns);
2502
+ const finished = args.lastTurnComplete ? summary : summary.slice(0, -1);
2503
+ const recorded = args.cursors.read(args.sessionId) ?? 0;
2504
+ const from = args.reviseLastTurn ? Math.max(0, recorded - 1) : recorded;
2505
+ if (finished.length <= from) return;
2506
+ const ts = (/* @__PURE__ */ new Date()).toISOString();
2507
+ const lines = finished.slice(from).map(
2508
+ (u) => JSON.stringify({
2509
+ ts,
2510
+ harness: args.harness,
2511
+ session: args.sessionId,
2512
+ bank: args.bankId,
2513
+ turn: u.turn,
2514
+ calls: u.calls,
2515
+ credited: u.credited
2516
+ }) + "\n"
2517
+ ).join("");
2518
+ try {
2519
+ appendLogLine(usageFilePath(), lines);
2520
+ args.cursors.write(args.sessionId, finished.length);
2521
+ } catch {
2522
+ }
2523
+ }
2524
+
2525
+ // src/core/retain-hook.ts
2526
+ var HOST_DEADLINE_MARGIN_MS = 2e3;
2527
+ async function buildRetain(args) {
2528
+ const { harness, sessionId, transcriptPath, client } = args;
2529
+ const readTranscript = args.readTranscript ?? readClaudeTranscript;
2530
+ const turns = readTranscript(transcriptPath);
2531
+ const decoded = args.lastAssistantMessage ? (args.readLastMessage ?? ((raw) => raw))(args.lastAssistantMessage) : "";
2532
+ const lastAssistantMessage = stripInjectedMemory(decoded).trim();
2533
+ if (lastAssistantMessage && turns.at(-1)?.content !== lastAssistantMessage) {
2534
+ turns.push({
2535
+ role: "assistant",
2536
+ content: lastAssistantMessage,
2537
+ timestamp: (/* @__PURE__ */ new Date()).toISOString()
2538
+ });
2539
+ }
2540
+ if (turns.length === 0) return;
2541
+ recordUsage({
2542
+ harness,
2543
+ sessionId,
2544
+ bankId: args.bankId ?? "",
2545
+ turns,
2546
+ cursors: args.usageCursors ?? fileUsageCursorStore(harness),
2547
+ lastTurnComplete: true,
2548
+ // The host has usually not flushed this turn's final reply yet — and that is
2549
+ // the message carrying the credit line. Re-emit the previous turn so the next
2550
+ // Stop, reading a complete transcript, corrects it. See recordUsage.
2551
+ reviseLastTurn: true
2552
+ });
2553
+ const startTs = turns[0]?.timestamp ?? (/* @__PURE__ */ new Date()).toISOString();
2554
+ const t0 = Date.now();
2555
+ try {
2556
+ await retainLiveSession(client, sessionId, turns, startTs, harness, {
2557
+ cursors: args.cursors ?? fileCursorStore(harness),
2558
+ stamp: args.stamp,
2559
+ retryUntil: args.retryUntil,
2560
+ transcriptPath
2561
+ });
2562
+ diag(harness, "retain_ok", { ms: Date.now() - t0, turns: turns.length, session: sessionId });
2563
+ } catch (e) {
2564
+ log.warn(harness, "session write-back failed", {
2565
+ error: describeError(e)
2566
+ });
2567
+ diag(harness, "retain_failed", {
2568
+ ms: Date.now() - t0,
2569
+ error: describeError(e),
2570
+ session: sessionId
2571
+ });
2572
+ }
2573
+ }
2574
+ async function runRetainHook(spec, makeClient = (o) => new HindsightClient(o)) {
2575
+ if (process.env.HINDSIGHT_DISABLE_HOOKS) return;
2576
+ const hostDeadline = Date.now() + spec.hostTimeoutSec * 1e3 - HOST_DEADLINE_MARGIN_MS;
2577
+ let ev = {};
2578
+ try {
2579
+ ev = JSON.parse(readFileSync7(0, "utf8"));
2580
+ } catch {
2581
+ return;
2582
+ }
2583
+ if (spec.accept && !spec.accept(ev)) return;
2584
+ const parsed = spec.parse(ev);
2585
+ const { sessionId, cwd: rawCwd, lastAssistantMessage } = parsed;
2586
+ const cwd = rawCwd || process.cwd();
2587
+ let transcriptPath = parsed.transcriptPath;
2588
+ let readTranscript = spec.readTranscript;
2589
+ let cfg = loadConfig({ harness: spec.harness });
2590
+ setLogLevel(cfg.logLevel);
2591
+ if (cfg.disabled) return;
2592
+ if (spec.journal) {
2593
+ transcriptPath = journalPath(spec.harness, sessionId);
2594
+ readTranscript = readJournalTranscript;
2595
+ appendJournalTurn(transcriptPath, {
2596
+ role: "assistant",
2597
+ content: spec.journal.assistantText(ev)
2598
+ });
2599
+ }
2600
+ if (!transcriptPath) return;
2601
+ const sessionRoot = sessionRootDir(spec.harness, sessionId, cwd);
2602
+ const derived = deriveBankIdOrSkip(cfg, cwd, spec.harness, sessionRoot);
2603
+ if (derived === null) return;
2604
+ const resolved2 = applyBankConfig(cfg, derived, cwd);
2605
+ cfg = resolved2.cfg;
2606
+ const bankId = resolved2.bankId;
2607
+ if (cfg.disabled) return;
2608
+ if (!cfg.retainSessions) {
2609
+ diag(spec.harness, "retain_disabled", { bank: bankId, session: sessionId });
2610
+ return;
2611
+ }
2612
+ await ensureDaemon(cfg, spec.harness, { waitMs: DAEMON_WAIT_RETAIN_MS });
2613
+ const client = makeClient({
2614
+ apiUrl: cfg.apiUrl,
2615
+ apiToken: cfg.apiToken,
2616
+ bank: bankId,
2617
+ maxParallelRetains: cfg.maxParallelRetains,
2618
+ observationScopes: cfg.observationScopes
2619
+ });
2620
+ await buildRetain({
2621
+ harness: spec.harness,
2622
+ sessionId: sessionId || "no-session",
2623
+ transcriptPath,
2624
+ client,
2625
+ readTranscript,
2626
+ lastAssistantMessage,
2627
+ readLastMessage: spec.readLastMessage,
2628
+ retryUntil: hostDeadline,
2629
+ bankId,
2630
+ stamp: buildRetainStamp(cfg, {
2631
+ directory: cwd,
2632
+ sessionRoot,
2633
+ harness: spec.harness,
2634
+ bankId,
2635
+ sessionId: sessionId || "no-session"
2636
+ })
2637
+ });
2638
+ }
2639
+
2640
+ // src/core/session-start.ts
2641
+ import { readFileSync as readFileSync11 } from "fs";
2642
+
2643
+ // src/core/git.ts
2644
+ import { execFileSync as execFileSync2 } from "child_process";
2645
+ import { resolve as resolve2 } from "path";
2646
+
2647
+ // src/core/status.ts
2648
+ import { execFileSync as execFileSync3 } from "child_process";
2649
+
2650
+ // src/core/survey.ts
2651
+ import { spawn as realSpawn4 } from "child_process";
2652
+ import { createHash as createHash4 } from "crypto";
2653
+ import { existsSync as existsSync3 } from "fs";
2654
+ import { homedir as homedir4, tmpdir as tmpdir3 } from "os";
2655
+ import { dirname as dirname8, join as join13 } from "path";
2656
+ import { fileURLToPath as fileURLToPath3 } from "url";
2657
+
2658
+ // src/core/survey-lease.ts
2659
+ import { spawn as realSpawn3 } from "child_process";
2660
+ import { randomUUID } from "crypto";
2661
+ import {
2662
+ mkdirSync as mkdirSync4,
2663
+ mkdtempSync,
2664
+ readdirSync,
2665
+ renameSync as renameSync3,
2666
+ rmdirSync,
2667
+ rmSync as rmSync2,
2668
+ statSync as statSync3,
2669
+ unlinkSync,
2670
+ utimesSync,
2671
+ writeFileSync as writeFileSync2
2672
+ } from "fs";
2673
+ import { join as join12 } from "path";
2674
+
2675
+ // src/core/auto-update.ts
2676
+ import { spawn as realSpawn5 } from "child_process";
2677
+ import {
2678
+ existsSync as existsSync4,
2679
+ mkdirSync as mkdirSync5,
2680
+ readFileSync as readFileSync8,
2681
+ realpathSync as realpathSync2,
2682
+ unlinkSync as unlinkSync2,
2683
+ writeFileSync as writeFileSync3
2684
+ } from "fs";
2685
+ import { homedir as homedir5, tmpdir as tmpdir4 } from "os";
2686
+ import { dirname as dirname9, join as join14 } from "path";
2687
+ import { fileURLToPath as fileURLToPath4 } from "url";
2688
+ var CHECK_INTERVAL_MS = 24 * 60 * 60 * 1e3;
2689
+ var NPM_VIEW_TIMEOUT_MS = 5e3;
2690
+ var NPM_VIEW_HARD_DEADLINE_MS = NPM_VIEW_TIMEOUT_MS + 1e3;
2691
+ var LOCK_STALE_MS = 10 * 60 * 1e3;
2692
+
2693
+ // src/core/skill-sync.ts
2694
+ import { cpSync, existsSync as existsSync6, readFileSync as readFileSync9 } from "fs";
2695
+ import { homedir as homedir6 } from "os";
2696
+ import { dirname as dirname10, join as join16 } from "path";
2697
+ import { fileURLToPath as fileURLToPath5 } from "url";
2698
+
2699
+ // src/core/skill-dirs.ts
2700
+ import { existsSync as existsSync5 } from "fs";
2701
+ import { join as join15 } from "path";
2702
+
2703
+ // src/core/legacy.ts
2704
+ import { existsSync as existsSync7, readFileSync as readFileSync10 } from "fs";
2705
+ import { homedir as homedir7 } from "os";
2706
+ import { join as join17, relative, isAbsolute as isAbsolute2 } from "path";
2707
+
2708
+ // src/core/traecode-mcp.ts
2709
+ import { execFileSync as execFileSync4 } from "child_process";
2710
+ import { existsSync as existsSync8, mkdirSync as mkdirSync6, readFileSync as readFileSync12, readdirSync as readdirSync2, rmSync as rmSync3, writeFileSync as writeFileSync4 } from "fs";
2711
+ import { homedir as homedir8 } from "os";
2712
+ import { dirname as dirname11, isAbsolute as isAbsolute3, join as join18 } from "path";
2713
+ import { fileURLToPath as fileURLToPath6 } from "url";
2714
+ var MCP_SERVER_NAME = "hindsight";
2715
+ var MCP_FILE_REL = join18(".trae", "mcp.json");
2716
+ function bundledDistDir() {
2717
+ const here = dirname11(fileURLToPath6(import.meta.url));
2718
+ return existsSync8(join18(here, "mcp-server.js")) ? here : join18(here, "..", "..", "dist");
2719
+ }
2720
+ function canon(value) {
2721
+ if (Array.isArray(value)) return `[${value.map(canon).join(",")}]`;
2722
+ if (value && typeof value === "object") {
2723
+ const entries = Object.entries(value).sort(
2724
+ ([a], [b]) => a < b ? -1 : a > b ? 1 : 0
2725
+ );
2726
+ return `{${entries.map(([k, v]) => `${JSON.stringify(k)}:${canon(v)}`).join(",")}}`;
2727
+ }
2728
+ return JSON.stringify(value);
2729
+ }
2730
+ var WORKSPACE_MCP_KEY = "trae.mcp.enableWorkspaceMcp";
2731
+ var HINT_MIN_INTERVAL_MS = 24 * 60 * 60 * 1e3;
2732
+ function traecodeUserDataDir(home) {
2733
+ const root = process.platform === "darwin" ? join18(home, "Library", "Application Support") : process.platform === "win32" ? process.env.APPDATA ?? join18(home, "AppData", "Roaming") : process.env.XDG_CONFIG_HOME ?? join18(home, ".config");
2734
+ for (const brand of ["Trae CN", "Trae"]) {
2735
+ const dir = join18(root, brand);
2736
+ if (existsSync8(dir)) return dir;
2737
+ }
2738
+ return join18(root, "Trae CN");
2739
+ }
2740
+ var traecodeUserSettingsPath = (home) => join18(traecodeUserDataDir(home), "User", "settings.json");
2741
+ var gateStateFileFor = (dist) => join18(dirname11(dist), ".workspace-mcp.json");
2742
+ function gateStateFile() {
2743
+ return gateStateFileFor(bundledDistDir());
2744
+ }
2745
+ function readGateState(opts = {}) {
2746
+ try {
2747
+ return JSON.parse(readFileSync12(opts.stateFile ?? gateStateFile(), "utf8"));
2748
+ } catch {
2749
+ return {};
2750
+ }
2751
+ }
2752
+ function workspaceMcpGateState(settingsPath) {
2753
+ let raw;
2754
+ try {
2755
+ raw = readFileSync12(settingsPath, "utf8");
2756
+ } catch {
2757
+ return "unknown";
2758
+ }
2759
+ try {
2760
+ const doc = JSON.parse(raw);
2761
+ return doc[WORKSPACE_MCP_KEY] === true ? "on" : "off";
2762
+ } catch {
2763
+ const hit = raw.match(new RegExp(`"${WORKSPACE_MCP_KEY}"\\s*:\\s*(true|false)`));
2764
+ return hit ? hit[1] === "true" ? "on" : "off" : "unknown";
2765
+ }
2766
+ }
2767
+ function workspaceMcpHint(opts = {}) {
2768
+ try {
2769
+ const settingsPath = traecodeUserSettingsPath(opts.home ?? homedir8());
2770
+ if (workspaceMcpGateState(settingsPath) === "on") return void 0;
2771
+ const now = opts.now ?? Date.now();
2772
+ const state = readGateState(opts);
2773
+ if (state.workspaceMcpEnabled) return void 0;
2774
+ if (typeof state.lastHint === "number" && now - state.lastHint < HINT_MIN_INTERVAL_MS) {
2775
+ return void 0;
2776
+ }
2777
+ writeFileSync4(
2778
+ opts.stateFile ?? gateStateFile(),
2779
+ JSON.stringify({ ...state, lastHint: now }, null, 2) + "\n"
2780
+ );
2781
+ return 'Hindsight MCP tools are hidden: TraeCode does not read per-repo MCP configs until workspace MCP is enabled. Turn it on once in Trae settings (search "enableWorkspaceMcp") or re-run `hindsight-coding-agents install traecode` \u2014 then reload this window.';
2782
+ } catch {
2783
+ return void 0;
2784
+ }
2785
+ }
2786
+ function gitignoreCovers(lines) {
2787
+ return lines.some((l) => {
2788
+ const t = l.trim();
2789
+ return t.includes(".trae");
2790
+ });
2791
+ }
2792
+ function ensureGitignored(repo) {
2793
+ const gitignore = join18(repo, ".gitignore");
2794
+ if (!existsSync8(gitignore)) return;
2795
+ const current2 = readFileSync12(gitignore, "utf8");
2796
+ if (gitignoreCovers(current2.split("\n"))) return;
2797
+ const addition = (current2.endsWith("\n") || current2 === "" ? "" : "\n") + "# hindsight MCP registration (machine-specific)\n.trae/mcp.json\n";
2798
+ writeFileSync4(gitignore, current2 + addition);
2799
+ }
2800
+ function ensureTraecodeWorkspaceMcp(cwd, opts = {}) {
2801
+ registerTraecodeWorkspaceMcp(cwd, opts);
2802
+ const seeded = ensureWorkspaceMcpEnabled(cwd, opts);
2803
+ return workspaceMcpHint(opts) ?? (seeded === "failed" ? workspaceEnableHint(opts) : void 0);
2804
+ }
2805
+ function registerTraecodeWorkspaceMcp(cwd, opts = {}) {
2806
+ try {
2807
+ const home = opts.home ?? homedir8();
2808
+ if (!cwd || !isAbsolute3(cwd) || dirname11(cwd) === cwd || cwd === home) return "skipped";
2809
+ const dist = opts.dist ?? bundledDistDir();
2810
+ const script = join18(dist, "mcp-server.js");
2811
+ if (!existsSync8(script)) return "skipped";
2812
+ const file = join18(cwd, MCP_FILE_REL);
2813
+ let doc = {};
2814
+ let exists = false;
2815
+ try {
2816
+ doc = JSON.parse(readFileSync12(file, "utf8"));
2817
+ exists = true;
2818
+ } catch {
2819
+ if (existsSync8(file)) return "skipped";
2820
+ }
2821
+ const servers = doc.mcpServers && typeof doc.mcpServers === "object" && !Array.isArray(doc.mcpServers) ? doc.mcpServers : doc.mcpServers = {};
2822
+ const entry = {
2823
+ command: "node",
2824
+ args: [script],
2825
+ env: { HINDSIGHT_MCP_HARNESS: "traecode", HINDSIGHT_MCP_PROJECT_CWD: cwd }
2826
+ };
2827
+ const existing = servers[MCP_SERVER_NAME];
2828
+ let merged;
2829
+ if (existing === void 0) {
2830
+ merged = entry;
2831
+ } else if (isOurMcpEntry(existing)) {
2832
+ const env = existing.env;
2833
+ merged = {
2834
+ ...existing,
2835
+ command: entry.command,
2836
+ args: entry.args,
2837
+ env: { ...env ?? {}, ...entry.env }
2838
+ };
2839
+ } else {
2840
+ diag("traecode", "workspace_mcp_foreign_entry", { cwd, file });
2841
+ return "skipped";
2842
+ }
2843
+ if (existing !== void 0 && canon(merged) === canon(existing)) return "current";
2844
+ servers[MCP_SERVER_NAME] = merged;
2845
+ mkdirSync6(dirname11(file), { recursive: true });
2846
+ writeFileSync4(file, JSON.stringify(doc, null, 2) + "\n");
2847
+ if (!exists) ensureGitignored(cwd);
2848
+ diag("traecode", "workspace_mcp_registered", { cwd, file });
2849
+ return "registered";
2850
+ } catch (e) {
2851
+ diag("traecode", "workspace_mcp_register_failed", {
2852
+ cwd,
2853
+ error: e instanceof Error ? e.message : String(e)
2854
+ });
2855
+ return "failed";
2856
+ }
2857
+ }
2858
+ var WORKSPACE_STORAGE_REL = join18("User", "workspaceStorage");
2859
+ var ENABLED_KEY_PREFIX = "icubeAgentExtension.enabled.mcp.config.ws0.";
2860
+ var SQLITE_TIMEOUT_MS = 5e3;
2861
+ var TRAECODE_WORKSPACE_ENABLED_KEY = ENABLED_KEY_PREFIX + MCP_SERVER_NAME;
2862
+ var traecodeWorkspaceStorageDir = (home) => join18(traecodeUserDataDir(home), WORKSPACE_STORAGE_REL);
2863
+ function findWorkspaceStorageDir(storage, repo) {
2864
+ let entries;
2865
+ try {
2866
+ entries = readdirSync2(storage);
2867
+ } catch {
2868
+ return void 0;
2869
+ }
2870
+ for (const name of entries) {
2871
+ try {
2872
+ const doc = JSON.parse(readFileSync12(join18(storage, name, "workspace.json"), "utf8"));
2873
+ if (typeof doc.folder !== "string") continue;
2874
+ let folder;
2875
+ try {
2876
+ folder = fileURLToPath6(doc.folder);
2877
+ } catch {
2878
+ folder = doc.folder;
2879
+ }
2880
+ if (folder === repo) return join18(storage, name);
2881
+ } catch {
2882
+ continue;
2883
+ }
2884
+ }
2885
+ return void 0;
2886
+ }
2887
+ function ensureWorkspaceMcpEnabled(cwd, opts = {}) {
2888
+ try {
2889
+ const home = opts.home ?? homedir8();
2890
+ if (!cwd || !isAbsolute3(cwd) || dirname11(cwd) === cwd || cwd === home) return "failed";
2891
+ const dir = findWorkspaceStorageDir(traecodeWorkspaceStorageDir(home), cwd);
2892
+ if (!dir) return "failed";
2893
+ const db = join18(dir, "state.vscdb");
2894
+ if (!existsSync8(db)) return "failed";
2895
+ const sqlite = opts.sqlite ?? execFileSync4;
2896
+ const run = (sql) => sqlite("sqlite3", [db, ".timeout 3000", sql], {
2897
+ encoding: "utf8",
2898
+ timeout: SQLITE_TIMEOUT_MS,
2899
+ windowsHide: true,
2900
+ stdio: ["ignore", "pipe", "pipe"]
2901
+ }).trim();
2902
+ if (run(`SELECT value FROM ItemTable WHERE key='${TRAECODE_WORKSPACE_ENABLED_KEY}';`) === "true") {
2903
+ return "on";
2904
+ }
2905
+ run(
2906
+ `INSERT OR REPLACE INTO ItemTable (key, value) VALUES ('${TRAECODE_WORKSPACE_ENABLED_KEY}', 'true');`
2907
+ );
2908
+ diag("traecode", "workspace_mcp_enabled_seeded", { cwd, db });
2909
+ return "seeded";
2910
+ } catch (e) {
2911
+ diag("traecode", "workspace_mcp_enabled_seed_failed", {
2912
+ cwd,
2913
+ error: e instanceof Error ? e.message : String(e)
2914
+ });
2915
+ return "failed";
2916
+ }
2917
+ }
2918
+ function workspaceEnableHint(opts = {}) {
2919
+ try {
2920
+ const now = opts.now ?? Date.now();
2921
+ const state = readGateState(opts);
2922
+ if (typeof state.lastEnableHint === "number" && now - state.lastEnableHint < HINT_MIN_INTERVAL_MS) {
2923
+ return void 0;
2924
+ }
2925
+ writeFileSync4(
2926
+ opts.stateFile ?? gateStateFile(),
2927
+ JSON.stringify({ ...state, lastEnableHint: now }, null, 2) + "\n"
2928
+ );
2929
+ return "Hindsight's MCP server stays disabled in this window: auto-enabling it failed here. Switch hindsight on for this workspace in Trae's MCP panel, then reload the window.";
2930
+ } catch {
2931
+ return void 0;
2932
+ }
2933
+ }
2934
+
2935
+ // src/core/transcript-codex.ts
2936
+ function stampOf(line) {
2937
+ return typeof line.timestamp === "string" && line.timestamp ? { timestamp: line.timestamp } : {};
2938
+ }
2939
+ function isSyntheticUserText(text) {
2940
+ const s = text.trimStart();
2941
+ return s.startsWith("# AGENTS.md instructions for ") || s.startsWith("<environment_context>");
2942
+ }
2943
+ function contentText(content) {
2944
+ return (Array.isArray(content) ? content : []).filter((c) => c && typeof c.text === "string").map((c) => c.text).join("\n");
2945
+ }
2946
+ var startupKinds = /* @__PURE__ */ new Set([
2947
+ "agents_md.instructions",
2948
+ "environments.instructions",
2949
+ "environments.environment_context",
2950
+ "plugins.recommendations",
2951
+ "plugins.usage_instructions"
2952
+ ]);
2953
+ function fallbackUserText(payload) {
2954
+ const content = payload.content;
2955
+ const kinds = payload.internal_chat_message_metadata_passthrough?.content_item_kinds;
2956
+ if (Array.isArray(content) && Array.isArray(kinds) && kinds.length === content.length && kinds.every((kind) => typeof kind === "string" && kind.length > 0)) {
2957
+ return contentText(content.filter((_, index) => !startupKinds.has(kinds[index])));
2958
+ }
2959
+ const text = contentText(content);
2960
+ return isSyntheticUserText(stripInjectedMemory(text)) ? "" : text;
2961
+ }
2962
+ function isUserMessageEvent(line) {
2963
+ return line.type === "event_msg" && line.payload?.type === "item_completed" && line.payload.item?.type === "UserMessage";
2964
+ }
2965
+ var TOOL_ITEM_TYPES = /* @__PURE__ */ new Set(["McpToolCall", "CommandExecution"]);
2966
+ function isToolItemEvent(line) {
2967
+ return line.type === "event_msg" && line.payload?.type === "item_completed" && TOOL_ITEM_TYPES.has(line.payload.item?.type ?? "");
2968
+ }
2969
+ function parseArgs(raw) {
2970
+ if (typeof raw !== "string") return raw;
2971
+ try {
2972
+ return JSON.parse(raw);
2973
+ } catch {
2974
+ return void 0;
2975
+ }
2976
+ }
2977
+ var SHELL_RE = /(?:^|\/)(?:sh|bash|zsh|dash|ksh|fish)$/;
2978
+ function commandText(command) {
2979
+ if (typeof command === "string") return command;
2980
+ if (!Array.isArray(command) || !command.every((c) => typeof c === "string")) return "";
2981
+ const argv = command;
2982
+ if (argv.length === 3 && SHELL_RE.test(argv[0]) && /^-[a-z]*c$/.test(argv[1])) return argv[2];
2983
+ return argv.join(" ");
2984
+ }
2985
+ function toolItemAction(item) {
2986
+ if (item.type === "McpToolCall") {
2987
+ if (typeof item.tool !== "string" || !item.tool) return void 0;
2988
+ const name = typeof item.server === "string" && item.server ? `mcp__${item.server}__${item.tool}` : item.tool;
2989
+ return actionLine(name, parseArgs(item.arguments));
2990
+ }
2991
+ const command = commandText(item.command).trim();
2992
+ return command ? actionLine("exec_command", { command }) : void 0;
2993
+ }
2994
+ function readCodexTranscript(path) {
2995
+ const lines = [];
2996
+ for (const rawLine of readJsonl(path)) {
2997
+ const trimmed = rawLine.trim();
2998
+ if (!trimmed) continue;
2999
+ try {
3000
+ const parsed = JSON.parse(trimmed);
3001
+ if (typeof parsed === "object" && parsed !== null) lines.push(parsed);
3002
+ } catch {
3003
+ continue;
3004
+ }
3005
+ }
3006
+ const userFromEvents = lines.some(isUserMessageEvent);
3007
+ const actionsFromEvents = lines.some(isToolItemEvent);
3008
+ const turns = [];
3009
+ const push = (role, raw, stamp = {}) => {
3010
+ const text = stripInjectedMemory(raw).trim();
3011
+ if (text) turns.push({ role, content: text, ...stamp });
3012
+ };
3013
+ for (const line of lines) {
3014
+ if (isUserMessageEvent(line)) {
3015
+ push("user", contentText(line.payload?.item?.content), stampOf(line));
3016
+ continue;
3017
+ }
3018
+ if (isToolItemEvent(line)) {
3019
+ const action = toolItemAction(line.payload?.item ?? {});
3020
+ if (action) turns.push({ role: "action", content: action, ...stampOf(line) });
3021
+ continue;
3022
+ }
3023
+ if (line.type !== "response_item") continue;
3024
+ const p = line.payload;
3025
+ if (!p || typeof p !== "object") continue;
3026
+ if (p.type === "message") {
3027
+ if (p.role === "assistant") {
3028
+ if (p.channel === "analysis" || p.channel === "reasoning" || p.phase === "analysis" || p.phase === "reasoning")
3029
+ continue;
3030
+ push("assistant", contentText(p.content), stampOf(line));
3031
+ } else if (p.role === "user" && !userFromEvents) {
3032
+ push("user", fallbackUserText(p), stampOf(line));
3033
+ }
3034
+ } else if ((p.type === "function_call" || p.type === "custom_tool_call") && typeof p.name === "string") {
3035
+ if (actionsFromEvents && p.type === "custom_tool_call" && p.name === "exec") continue;
3036
+ const rawInput = p.type === "function_call" ? p.arguments : p.input;
3037
+ let input;
3038
+ try {
3039
+ input = JSON.parse(rawInput || "");
3040
+ } catch {
3041
+ input = void 0;
3042
+ }
3043
+ turns.push({ role: "action", content: actionLine(p.name, input), ...stampOf(line) });
3044
+ }
3045
+ }
3046
+ return turns;
3047
+ }
3048
+
3049
+ // src/core/transcript-cursor.ts
3050
+ function withTimestamp(turn, timestamp) {
3051
+ return timestamp ? { ...turn, timestamp } : turn;
3052
+ }
3053
+ function textFrom(content) {
3054
+ if (typeof content === "string") return content;
3055
+ if (!Array.isArray(content)) return "";
3056
+ return content.filter((block) => block?.type === "text" && typeof block.text === "string").map((block) => block.text).join("\n");
3057
+ }
3058
+ function readCursorTranscript(path) {
3059
+ const turns = [];
3060
+ for (const rawLine of readJsonl(path)) {
3061
+ let parsed;
3062
+ try {
3063
+ parsed = JSON.parse(rawLine);
3064
+ } catch {
3065
+ continue;
3066
+ }
3067
+ if (typeof parsed !== "object" || parsed === null) continue;
3068
+ const line = parsed;
3069
+ const role = line.message?.role ?? line.role ?? (line.type === "user" || line.type === "assistant" ? line.type : void 0);
3070
+ const content = line.message?.content ?? line.content;
3071
+ if (role === "user" || role === "assistant") {
3072
+ const text = stripInjectedMemory(textFrom(content)).trim();
3073
+ if (text) turns.push(withTimestamp({ role, content: text }, line.timestamp));
3074
+ if (role === "assistant" && Array.isArray(content)) {
3075
+ for (const block of content) {
3076
+ if (block?.type === "tool_use" && typeof block.name === "string") {
3077
+ turns.push(
3078
+ withTimestamp(
3079
+ { role: "action", content: actionLine(block.name, block.input) },
3080
+ line.timestamp
3081
+ )
3082
+ );
3083
+ }
3084
+ }
3085
+ }
3086
+ } else if (line.type === "tool_call" && typeof line.name === "string") {
3087
+ turns.push(
3088
+ withTimestamp({ role: "action", content: actionLine(line.name, line.args) }, line.timestamp)
3089
+ );
3090
+ }
3091
+ }
3092
+ return turns;
3093
+ }
3094
+
3095
+ // src/core/transcript-antigravity.ts
3096
+ function readAntigravityTranscript(path) {
3097
+ if (!path) return [];
3098
+ const turns = [];
3099
+ for (const line of readJsonl(path)) {
3100
+ try {
3101
+ const event = JSON.parse(line);
3102
+ const role = event.role ?? event.message?.role ?? event.type;
3103
+ const normalizedRole = role === "user" || role === "USER_INPUT" ? "user" : role === "assistant" || role === "model" || role === "PLANNER_RESPONSE" ? "assistant" : void 0;
3104
+ const content = event.content ?? event.text ?? event.message?.content ?? event.message?.text;
3105
+ const clean = typeof content === "string" ? stripInjectedMemory(content).trim() : "";
3106
+ if (normalizedRole && clean) {
3107
+ turns.push({
3108
+ role: normalizedRole,
3109
+ content: clean,
3110
+ ...event.timestamp ? { timestamp: event.timestamp } : {}
3111
+ });
3112
+ }
3113
+ } catch {
3114
+ }
3115
+ }
3116
+ return turns;
3117
+ }
3118
+
3119
+ // src/core/transcript-copilot.ts
3120
+ function readCopilotTranscript(path) {
3121
+ const turns = [];
3122
+ for (const rawLine of readJsonl(path)) {
3123
+ try {
3124
+ const event = JSON.parse(rawLine);
3125
+ const role = event.type === "user.message" ? "user" : event.type === "assistant.message" ? "assistant" : void 0;
3126
+ const content = typeof event.data?.content === "string" ? stripInjectedMemory(event.data.content).trim() : "";
3127
+ if (!role || !content) continue;
3128
+ turns.push({ role, content, ...event.timestamp ? { timestamp: event.timestamp } : {} });
3129
+ } catch {
3130
+ }
3131
+ }
3132
+ return turns;
3133
+ }
3134
+
3135
+ // src/core/transcript-grok.ts
3136
+ import { existsSync as existsSync9, readFileSync as readFileSync13, readdirSync as readdirSync3 } from "fs";
3137
+ import { homedir as homedir9 } from "os";
3138
+ import { join as join19 } from "path";
3139
+ var CHAT_HISTORY = "chat_history.jsonl";
3140
+ function grokTranscriptPath(cwd, sessionId, grokHome = process.env.GROK_HOME || join19(homedir9(), ".grok")) {
3141
+ const sessionsDir = join19(grokHome, "sessions");
3142
+ const direct = join19(sessionsDir, encodeURIComponent(cwd), sessionId, CHAT_HISTORY);
3143
+ if (existsSync9(direct)) return direct;
3144
+ try {
3145
+ for (const candidate of readdirSync3(sessionsDir)) {
3146
+ const directory = join19(sessionsDir, candidate);
3147
+ if (readFileSync13(join19(directory, ".cwd"), "utf8").trim() === cwd) {
3148
+ return join19(directory, sessionId, CHAT_HISTORY);
3149
+ }
3150
+ }
3151
+ } catch {
3152
+ }
3153
+ return direct;
3154
+ }
3155
+ function readGrokTranscript(path) {
3156
+ const turns = [];
3157
+ for (const rawLine of readJsonl(path)) {
3158
+ try {
3159
+ const event = JSON.parse(rawLine);
3160
+ if (event.type !== "user" && event.type !== "assistant") continue;
3161
+ if (event.type === "user" && typeof event.prompt_index !== "number") continue;
3162
+ const content = typeof event.content === "string" ? event.content : Array.isArray(event.content) ? event.content.filter((part) => part.type === "text").map((part) => part.text ?? "").join("\n") : "";
3163
+ const clean = stripInjectedMemory(content).trim();
3164
+ if (clean) turns.push({ role: event.type, content: clean });
3165
+ for (const toolCall of event.tool_calls ?? []) {
3166
+ if (!toolCall.name) continue;
3167
+ let input = toolCall.arguments;
3168
+ if (typeof input === "string") {
3169
+ try {
3170
+ input = JSON.parse(input);
3171
+ } catch {
3172
+ }
3173
+ }
3174
+ turns.push({ role: "action", content: actionLine(toolCall.name, input) });
3175
+ }
3176
+ } catch {
3177
+ }
3178
+ }
3179
+ return turns;
3180
+ }
3181
+
3182
+ // src/core/transcript-devin.ts
3183
+ import { existsSync as existsSync10 } from "fs";
3184
+ import { createRequire } from "module";
3185
+ import { homedir as homedir10 } from "os";
3186
+ import { join as join20 } from "path";
3187
+ function devinSessionDb(home = homedir10()) {
3188
+ return join20(home, ".local", "share", "devin", "cli", "sessions.db");
3189
+ }
3190
+ function parseDevinMessages(nodes) {
3191
+ const messages = /* @__PURE__ */ new Map();
3192
+ for (const node of nodes) {
3193
+ try {
3194
+ const message = JSON.parse(node.chat_message);
3195
+ if (message.role !== "user" && message.role !== "assistant" || !message.content?.trim())
3196
+ continue;
3197
+ const content = stripInjectedMemory(message.content).trim();
3198
+ if (!content) continue;
3199
+ const id = message.message_id || `node:${node.node_id}`;
3200
+ messages.set(id, {
3201
+ index: messages.get(id)?.index ?? node.node_id,
3202
+ role: message.role,
3203
+ content
3204
+ });
3205
+ } catch {
3206
+ }
3207
+ }
3208
+ return [...messages.values()].sort((a, b) => a.index - b.index).map(({ role, content }) => ({ role, content }));
3209
+ }
3210
+ var requireBuiltin = createRequire(import.meta.url);
3211
+ function loadSqlite() {
3212
+ try {
3213
+ return requireBuiltin("node:sqlite").DatabaseSync;
3214
+ } catch {
3215
+ return void 0;
3216
+ }
3217
+ }
3218
+ function readDevinTranscript(sessionId, dbPath = devinSessionDb()) {
3219
+ if (!sessionId) return [];
3220
+ const Database = loadSqlite();
3221
+ if (!Database) {
3222
+ diag("devin-cli", "sqlite_unavailable", { node: process.version, dbPath });
3223
+ return [];
3224
+ }
3225
+ if (!existsSync10(dbPath)) {
3226
+ diag("devin-cli", "session_db_missing", { dbPath });
3227
+ return [];
3228
+ }
3229
+ let db;
3230
+ try {
3231
+ db = new Database(dbPath, { readOnly: true });
3232
+ const rows = db.prepare(
3233
+ "SELECT node_id, chat_message FROM message_nodes WHERE session_id = ? ORDER BY node_id"
3234
+ ).all(sessionId);
3235
+ return parseDevinMessages(rows);
3236
+ } catch (error) {
3237
+ diag("devin-cli", "session_db_read_failed", { dbPath, error: String(error) });
3238
+ return [];
3239
+ } finally {
3240
+ try {
3241
+ db?.close();
3242
+ } catch {
3243
+ }
3244
+ }
3245
+ }
3246
+
3247
+ // src/core/transcript-dcode.ts
3248
+ var BLOCK_JOIN = "\n";
3249
+ function contentText2(content) {
3250
+ if (typeof content === "string") return content;
3251
+ if (!Array.isArray(content)) return "";
3252
+ return content.flatMap((block) => {
3253
+ if (typeof block === "string") return [block];
3254
+ if (!block || typeof block !== "object") return [];
3255
+ const text = block.text;
3256
+ return typeof text === "string" ? [text] : [];
3257
+ }).join(BLOCK_JOIN);
3258
+ }
3259
+ function readPyValue(s, i) {
3260
+ const skip = (j) => {
3261
+ while (j < s.length && /\s/.test(s[j])) j++;
3262
+ return j;
3263
+ };
3264
+ i = skip(i);
3265
+ if (i >= s.length) return null;
3266
+ const c = s[i];
3267
+ if (c === "'" || c === '"') {
3268
+ let out = "";
3269
+ let j = i + 1;
3270
+ while (j < s.length) {
3271
+ const ch = s[j];
3272
+ if (ch === "\\") {
3273
+ const esc = s[j + 1];
3274
+ if (esc === void 0) return null;
3275
+ if (esc === "n") out += "\n";
3276
+ else if (esc === "t") out += " ";
3277
+ else if (esc === "r") out += "\r";
3278
+ else if (esc === "x") {
3279
+ const hex = s.slice(j + 2, j + 4);
3280
+ if (!/^[0-9a-fA-F]{2}$/.test(hex)) return null;
3281
+ out += String.fromCharCode(parseInt(hex, 16));
3282
+ j += 4;
3283
+ continue;
3284
+ } else if (esc === "u") {
3285
+ const hex = s.slice(j + 2, j + 6);
3286
+ if (!/^[0-9a-fA-F]{4}$/.test(hex)) return null;
3287
+ out += String.fromCharCode(parseInt(hex, 16));
3288
+ j += 6;
3289
+ continue;
3290
+ } else out += esc;
3291
+ j += 2;
3292
+ continue;
3293
+ }
3294
+ if (ch === c) return { value: out, end: j + 1 };
3295
+ out += ch;
3296
+ j++;
3297
+ }
3298
+ return null;
3299
+ }
3300
+ if (s.startsWith("True", i)) return { value: true, end: i + 4 };
3301
+ if (s.startsWith("False", i)) return { value: false, end: i + 5 };
3302
+ if (s.startsWith("None", i)) return { value: null, end: i + 4 };
3303
+ if (c === "[" || c === "{") {
3304
+ const isList = c === "[";
3305
+ const close = isList ? "]" : "}";
3306
+ const list = [];
3307
+ const obj = {};
3308
+ let j = skip(i + 1);
3309
+ if (s[j] === close) return { value: isList ? list : obj, end: j + 1 };
3310
+ for (; ; ) {
3311
+ const key = readPyValue(s, j);
3312
+ if (!key) return null;
3313
+ j = skip(key.end);
3314
+ if (isList) {
3315
+ list.push(key.value);
3316
+ } else {
3317
+ if (s[j] !== ":" || typeof key.value !== "string") return null;
3318
+ const val = readPyValue(s, j + 1);
3319
+ if (!val) return null;
3320
+ obj[key.value] = val.value;
3321
+ j = skip(val.end);
3322
+ }
3323
+ if (s[j] === ",") {
3324
+ j = skip(j + 1);
3325
+ if (s[j] === close) return { value: isList ? list : obj, end: j + 1 };
3326
+ continue;
3327
+ }
3328
+ if (s[j] === close) return { value: isList ? list : obj, end: j + 1 };
3329
+ return null;
3330
+ }
3331
+ }
3332
+ const num = /^-?\d+(\.\d+)?([eE][-+]?\d+)?/.exec(s.slice(i));
3333
+ if (num) return { value: Number(num[0]), end: i + num[0].length };
3334
+ return null;
3335
+ }
3336
+ function dcodeAssistantText(raw) {
3337
+ const trimmed = raw.trim();
3338
+ if (!trimmed.startsWith("[{") && !trimmed.startsWith("[ {")) return raw;
3339
+ const parsed = readPyValue(trimmed, 0);
3340
+ if (!parsed || readPyValue(trimmed, parsed.end) !== null) return "";
3341
+ if (!Array.isArray(parsed.value)) return "";
3342
+ return contentText2(parsed.value);
3343
+ }
3344
+ function readDcodeTranscript(path) {
3345
+ const turns = [];
3346
+ for (const rawLine of readJsonl(path)) {
3347
+ if (!rawLine.trim()) continue;
3348
+ let parsed;
3349
+ try {
3350
+ parsed = JSON.parse(rawLine);
3351
+ } catch {
3352
+ continue;
3353
+ }
3354
+ if (!parsed || typeof parsed !== "object") continue;
3355
+ const record = parsed;
3356
+ if (record.schema_version !== 1) continue;
3357
+ const role = record.role;
3358
+ const stamp = typeof record.timestamp === "string" && record.timestamp ? { timestamp: record.timestamp } : {};
3359
+ if (role === "user" || role === "assistant") {
3360
+ const text = stripInjectedMemory(contentText2(record.content)).trim();
3361
+ if (text) turns.push({ role, content: text, ...stamp });
3362
+ } else if (role === "tool" && typeof record.name === "string" && record.name.trim()) {
3363
+ turns.push({ role: "action", content: actionLine(record.name, record.content), ...stamp });
3364
+ }
3365
+ }
3366
+ return turns;
3367
+ }
3368
+
3369
+ // src/core/transcript-qwen.ts
3370
+ var HOOK_CONTEXT_PART_RE = /^\s*<qwen:user-prompt-submit-context>[\s\S]*<\/qwen:user-prompt-submit-context>\s*$/;
3371
+ function isWholeHookContextPart(part) {
3372
+ return typeof part.text === "string" && HOOK_CONTEXT_PART_RE.test(part.text);
3373
+ }
3374
+ function isRealUser(line) {
3375
+ if (typeof line.provenance === "string") return line.provenance === "real_user";
3376
+ if (line.provenance !== void 0) return false;
3377
+ const isSubagentEnvelope = line.agentId !== void 0 || line.isSidechain !== void 0;
3378
+ if (!isSubagentEnvelope) return false;
3379
+ return line.subtype === void 0 || line.subtype === "mid_turn_user_message";
3380
+ }
3381
+ function renderLine2(parts, type) {
3382
+ if (!Array.isArray(parts)) return [];
3383
+ const last = parts.length > 1 ? parts[parts.length - 1] : void 0;
3384
+ const dropLast = !!last && typeof last === "object" && isWholeHookContextPart(last) ? parts.length - 1 : -1;
3385
+ const texts = [];
3386
+ const actions = [];
3387
+ for (const [i, part] of parts.entries()) {
3388
+ if (!part || typeof part !== "object") continue;
3389
+ if (i === dropLast) continue;
3390
+ if (part.thought === true) continue;
3391
+ if (typeof part.text === "string") {
3392
+ const text = stripInjectedMemory(part.text).trim();
3393
+ if (text) texts.push(text);
3394
+ } else if (part.functionCall && typeof part.functionCall.name === "string") {
3395
+ actions.push({
3396
+ role: "action",
3397
+ content: actionLine(part.functionCall.name, part.functionCall.args)
3398
+ });
3399
+ }
3400
+ }
3401
+ const out = [];
3402
+ const joined = texts.join("\n").trim();
3403
+ if (joined) out.push({ role: type, content: joined });
3404
+ out.push(...actions);
3405
+ return out;
3406
+ }
3407
+ function readQwenTranscript(path) {
3408
+ const turns = [];
3409
+ try {
3410
+ collectQwenTurns(path, turns);
3411
+ } catch (err) {
3412
+ log.warn("qwen-code", "transcript read failed \u2014 retaining what was parsed", {
3413
+ path,
3414
+ turns: turns.length,
3415
+ error: err instanceof Error ? err.message : String(err)
3416
+ });
3417
+ }
3418
+ return turns;
3419
+ }
3420
+ function collectQwenTurns(path, turns) {
3421
+ for (const rawLine of readJsonl(path)) {
3422
+ const trimmed = rawLine.trim();
3423
+ if (!trimmed) continue;
3424
+ let parsed;
3425
+ try {
3426
+ parsed = JSON.parse(trimmed);
3427
+ } catch {
3428
+ continue;
3429
+ }
3430
+ if (typeof parsed !== "object" || parsed === null) continue;
3431
+ const line = parsed;
3432
+ if (line.type !== "user" && line.type !== "assistant") continue;
3433
+ if (line.type === "user" && !isRealUser(line)) continue;
3434
+ if (typeof line.message !== "object" || line.message === null) continue;
3435
+ const sp = line.systemPayload;
3436
+ if (line.type === "user" && sp && typeof sp === "object" && typeof sp.hookContext === "string" && typeof sp.displayText === "string") {
3437
+ const content = stripInjectedMemory(sp.displayText).trim();
3438
+ if (content) {
3439
+ const turn = { role: "user", content };
3440
+ if (typeof line.timestamp === "string") turn.timestamp = line.timestamp;
3441
+ turns.push(turn);
3442
+ }
3443
+ continue;
3444
+ }
3445
+ for (const rendered of renderLine2(line.message.parts, line.type)) {
3446
+ const turn = { role: rendered.role, content: rendered.content };
3447
+ if (typeof line.timestamp === "string") turn.timestamp = line.timestamp;
3448
+ turns.push(turn);
3449
+ }
3450
+ }
3451
+ }
3452
+
3453
+ // src/core/transcript-droid.ts
3454
+ function renderContent(content, role) {
3455
+ if (!Array.isArray(content)) return [];
3456
+ const texts = [];
3457
+ const actions = [];
3458
+ for (const block of content) {
3459
+ if (!block || typeof block !== "object") continue;
3460
+ const b = block;
3461
+ if (b.type === "text" && typeof b.text === "string") {
3462
+ const text = stripInjectedMemory(b.text).trim();
3463
+ if (text) texts.push(text);
3464
+ } else if (b.type === "tool_use" && typeof b.name === "string") {
3465
+ actions.push({ role: "action", content: actionLine(b.name, b.input) });
3466
+ }
3467
+ }
3468
+ const out = [];
3469
+ const joined = texts.join("\n").trim();
3470
+ if (joined) out.push({ role, content: joined });
3471
+ out.push(...actions);
3472
+ return out;
3473
+ }
3474
+ function readDroidTranscript(path) {
3475
+ const turns = [];
3476
+ for (const rawLine of readJsonl(path)) {
3477
+ if (!rawLine.trim()) continue;
3478
+ let parsed;
3479
+ try {
3480
+ parsed = JSON.parse(rawLine);
3481
+ } catch {
3482
+ continue;
3483
+ }
3484
+ if (!parsed || typeof parsed !== "object") continue;
3485
+ const line = parsed;
3486
+ if (line.type !== "message" || !line.message || typeof line.message !== "object") continue;
3487
+ const message = line.message;
3488
+ const role = message.role;
3489
+ if (role !== "user" && role !== "assistant") continue;
3490
+ if (message.visibility === "user_only" || message.visibility === "llm_only") continue;
3491
+ const stamp = typeof line.timestamp === "string" && line.timestamp ? { timestamp: line.timestamp } : {};
3492
+ turns.push(...renderContent(message.content, role).map((turn) => ({ ...turn, ...stamp })));
3493
+ }
3494
+ return turns;
3495
+ }
3496
+
3497
+ // src/core/transcript-zcode.ts
3498
+ import { readFileSync as readFileSync14 } from "fs";
3499
+ function messageText(content) {
3500
+ if (typeof content === "string") return content.trim();
3501
+ if (!Array.isArray(content)) return "";
3502
+ return content.filter((block) => block && typeof block === "object" && typeof block.text === "string").map((block) => block.text.trim()).filter(Boolean).join("\n").trim();
3503
+ }
3504
+ function readZcodeTranscript(path) {
3505
+ if (!path) return [];
3506
+ let body;
3507
+ try {
3508
+ body = readFileSync14(path, "utf8");
3509
+ } catch {
3510
+ return [];
3511
+ }
3512
+ const turns = [];
3513
+ for (const line of body.split("\n")) {
3514
+ const trimmed = line.trim();
3515
+ if (!trimmed) continue;
3516
+ let parsed;
3517
+ try {
3518
+ parsed = JSON.parse(trimmed);
3519
+ } catch {
3520
+ continue;
3521
+ }
3522
+ if (typeof parsed !== "object" || parsed === null) continue;
3523
+ const record = parsed;
3524
+ const message = typeof record.message === "object" && record.message !== null ? record.message : void 0;
3525
+ const role = typeof message?.role === "string" ? message.role : record.type;
3526
+ if (role !== "user" && role !== "assistant") continue;
3527
+ const content = stripInjectedMemory(messageText(message?.content)).trim();
3528
+ if (!content) continue;
3529
+ turns.push({
3530
+ role,
3531
+ content,
3532
+ ...typeof record.timestamp === "string" ? { timestamp: record.timestamp } : {}
3533
+ });
3534
+ }
3535
+ return turns;
3536
+ }
3537
+ function zcodeAssistantText(path) {
3538
+ if (!path) return "";
3539
+ return readZcodeTranscript(path).filter((turn) => turn.role === "assistant").at(-1)?.content ?? "";
3540
+ }
3541
+
3542
+ // src/core/transcript-kimi.ts
3543
+ import { existsSync as existsSync11, readdirSync as readdirSync4 } from "fs";
3544
+ import { homedir as homedir11 } from "os";
3545
+ import { join as join21 } from "path";
3546
+ var HARNESS = "kimi-code";
3547
+ var SESSIONS_DIR = "sessions";
3548
+ var AGENTS_DIR = "agents";
3549
+ var WIRE_LOG = "wire.jsonl";
3550
+ var SESSION_PREFIX = "session_";
3551
+ var MAIN_AGENT = "main";
3552
+ var MAX_SESSION_CHARS = 32 * 1024 * 1024;
3553
+ function kimiSessionDir(sessionId, kimiHome = process.env.KIMI_CODE_HOME || join21(homedir11(), ".kimi-code")) {
3554
+ const name = sessionId.startsWith(SESSION_PREFIX) ? sessionId : `${SESSION_PREFIX}${sessionId}`;
3555
+ const sessions = join21(kimiHome, SESSIONS_DIR);
3556
+ try {
3557
+ for (const workspace of readdirSync4(sessions, { withFileTypes: true })) {
3558
+ if (!workspace.isDirectory()) continue;
3559
+ const candidate = join21(sessions, workspace.name, name);
3560
+ if (existsSync11(join21(candidate, AGENTS_DIR))) return candidate;
3561
+ }
3562
+ } catch {
3563
+ }
3564
+ diag(HARNESS, "session_dir_missing", { sessions, session: name });
3565
+ return void 0;
3566
+ }
3567
+ function stampOf2(event) {
3568
+ if (typeof event.time !== "number") return {};
3569
+ const at = new Date(event.time);
3570
+ return Number.isNaN(at.getTime()) ? {} : { timestamp: at.toISOString() };
3571
+ }
3572
+ function kimiPromptText(input) {
3573
+ if (!Array.isArray(input)) return "";
3574
+ return input.filter((block) => block?.type === "text" && typeof block.text === "string").map((block) => block.text).join("\n");
3575
+ }
3576
+ function readKimiWire(events) {
3577
+ const turns = [];
3578
+ let step;
3579
+ const flushStep = () => {
3580
+ if (!step) return;
3581
+ const content = stripInjectedMemory(step.texts.join("\n")).trim();
3582
+ if (content) turns.push({ role: "assistant", content, ...step.stamp });
3583
+ step = void 0;
3584
+ };
3585
+ for (const event of events || []) {
3586
+ if (!event || typeof event !== "object") continue;
3587
+ const stamp = stampOf2(event);
3588
+ if (event.type === "turn.prompt") {
3589
+ flushStep();
3590
+ if (event.origin?.kind !== "user") continue;
3591
+ const content = stripInjectedMemory(kimiPromptText(event.input)).trim();
3592
+ if (content) turns.push({ role: "user", content, ...stamp });
3593
+ continue;
3594
+ }
3595
+ if (event.type !== "context.append_loop_event") continue;
3596
+ const loop = event.event;
3597
+ if (!loop || typeof loop !== "object") continue;
3598
+ if (loop.type === "content.part") {
3599
+ if (loop.part?.type !== "text" || typeof loop.part.text !== "string") continue;
3600
+ const uuid = typeof loop.stepUuid === "string" ? loop.stepUuid : "";
3601
+ if (step && step.uuid !== uuid) flushStep();
3602
+ if (!step) step = { uuid, texts: [], stamp };
3603
+ step.texts.push(loop.part.text);
3604
+ } else if (loop.type === "tool.call") {
3605
+ flushStep();
3606
+ if (typeof loop.name !== "string" || !loop.name) continue;
3607
+ turns.push({ role: "action", content: actionLine(loop.name, loop.args), ...stamp });
3608
+ }
3609
+ }
3610
+ flushStep();
3611
+ return turns;
3612
+ }
3613
+ function agentIds(sessionDir) {
3614
+ try {
3615
+ return readdirSync4(join21(sessionDir, AGENTS_DIR), { withFileTypes: true }).filter((entry) => entry.isDirectory()).map((entry) => entry.name).sort(byAgentId);
3616
+ } catch {
3617
+ return [];
3618
+ }
3619
+ }
3620
+ function byAgentId(a, b) {
3621
+ if (a === b) return 0;
3622
+ if (a === MAIN_AGENT) return -1;
3623
+ if (b === MAIN_AGENT) return 1;
3624
+ const indexA = agentIndex(a);
3625
+ const indexB = agentIndex(b);
3626
+ return indexA === indexB ? a.localeCompare(b) : indexA - indexB;
3627
+ }
3628
+ function agentIndex(id) {
3629
+ const suffix = Number(id.slice(id.lastIndexOf("-") + 1));
3630
+ return Number.isFinite(suffix) ? suffix : Number.MAX_SAFE_INTEGER;
3631
+ }
3632
+ function parseEvent(rawLine) {
3633
+ const trimmed = rawLine.trim();
3634
+ if (!trimmed) return void 0;
3635
+ let parsed;
3636
+ try {
3637
+ parsed = JSON.parse(trimmed);
3638
+ } catch {
3639
+ return void 0;
3640
+ }
3641
+ return typeof parsed === "object" && parsed !== null ? parsed : void 0;
3642
+ }
3643
+ function readKimiTranscript(path) {
3644
+ const turns = [];
3645
+ let remaining = MAX_SESSION_CHARS;
3646
+ for (const agentId of agentIds(path)) {
3647
+ const wire = join21(path, AGENTS_DIR, agentId, WIRE_LOG);
3648
+ const events = [];
3649
+ for (const rawLine of readJsonl(wire)) {
3650
+ remaining -= rawLine.length;
3651
+ if (remaining < 0) break;
3652
+ const event = parseEvent(rawLine);
3653
+ if (event) events.push(event);
3654
+ }
3655
+ for (const turn of readKimiWire(events)) turns.push(turn);
3656
+ if (remaining < 0) {
3657
+ log.warn(HARNESS, "session exceeds the wire-log budget \u2014 later agents were not read", {
3658
+ sessionDir: path,
3659
+ stoppedAt: wire
3660
+ });
3661
+ break;
3662
+ }
3663
+ }
3664
+ return turns;
3665
+ }
3666
+
3667
+ // src/harness/hook-lifecycle.ts
3668
+ var cursorCwd = (ev) => ev.cwd ?? ev.workspace_root ?? (Array.isArray(ev.workspace_roots) ? ev.workspace_roots[0] : void 0);
3669
+ var claudePrompt = {
3670
+ harness: "claude-code",
3671
+ parse: (ev) => ({
3672
+ prompt: ev.prompt,
3673
+ cwd: ev.cwd,
3674
+ sessionId: ev.session_id
3675
+ }),
3676
+ emit: (context, notice) => ({
3677
+ ...notice ? { systemMessage: notice } : {},
3678
+ hookSpecificOutput: { hookEventName: "UserPromptSubmit", additionalContext: context }
3679
+ })
3680
+ };
3681
+ var codexPrompt = {
3682
+ ...claudePrompt,
3683
+ harness: "codex",
3684
+ parse: (ev) => ({
3685
+ prompt: ev.prompt ?? ev.user_prompt,
3686
+ cwd: ev.cwd,
3687
+ sessionId: ev.session_id
3688
+ })
3689
+ };
3690
+ var dcodePrompt = {
3691
+ ...claudePrompt,
3692
+ harness: "dcode"
3693
+ };
3694
+ var droidPrompt = {
3695
+ ...claudePrompt,
3696
+ harness: "factory-droid"
3697
+ };
3698
+ var qwenPrompt = {
3699
+ ...claudePrompt,
3700
+ harness: "qwen-code",
3701
+ parse: (ev) => ({
3702
+ prompt: ev.submitted_prompt,
3703
+ cwd: ev.cwd,
3704
+ sessionId: ev.session_id
3705
+ })
3706
+ };
3707
+ var zcodeSessionId = (ev) => ev.session_id ?? ev.sessionId;
3708
+ var antigravityCwd = (ev) => Array.isArray(ev.workspacePaths) ? ev.workspacePaths[0] : void 0;
3709
+ var antigravityPrompt = {
3710
+ harness: "antigravity-cli",
3711
+ requireCwd: true,
3712
+ parse: (ev) => ({
3713
+ // Antigravity's PreInvocation payload deliberately omits the prompt. Its transcript is already
3714
+ // persisted at that point, so recover the latest real user turn from the supplied JSONL path.
3715
+ prompt: readAntigravityTranscript(ev.transcriptPath).filter((turn) => turn.role === "user").at(-1)?.content,
3716
+ cwd: antigravityCwd(ev),
3717
+ sessionId: ev.conversationId
3718
+ }),
3719
+ emit: (context) => ({ injectSteps: context ? [{ ephemeralMessage: context }] : [] })
3720
+ };
3721
+ var cursorPrompt = {
3722
+ harness: "cursor-cli",
3723
+ parse: (ev) => ({
3724
+ prompt: ev.prompt ?? ev.user_prompt,
3725
+ cwd: cursorCwd(ev),
3726
+ sessionId: ev.conversation_id ?? ev.session_id
3727
+ }),
3728
+ emit: (context) => ({ continue: true, additional_context: context })
3729
+ };
3730
+ var copilotPrompt = {
3731
+ harness: "copilot-cli",
3732
+ parse: (ev) => ({
3733
+ prompt: ev.prompt,
3734
+ cwd: ev.cwd,
3735
+ sessionId: ev.sessionId
3736
+ }),
3737
+ emit: (context, _notice, ev) => ({
3738
+ // Copilot's userPromptTransformed hook replaces model-facing content rather than appending
3739
+ // hook context. Preserve its transformed prompt and add the shared Hindsight injection.
3740
+ modifiedTransformedPrompt: `${ev?.transformedPrompt ?? ""}
3741
+
3742
+ ${context}`.trim()
3743
+ })
3744
+ };
3745
+ var devinCwd = () => process.env.DEVIN_PROJECT_DIR || process.cwd();
3746
+ var devinPrompt = {
3747
+ harness: "devin-cli",
3748
+ requireCwd: true,
3749
+ parse: (ev) => ({
3750
+ prompt: ev.prompt,
3751
+ cwd: devinCwd(),
3752
+ sessionId: ev.session_id
3753
+ }),
3754
+ emit: (context) => ({
3755
+ hookSpecificOutput: { hookEventName: "UserPromptSubmit", additionalContext: context }
3756
+ })
3757
+ };
3758
+ var standardSessionStart = (harness) => ({
3759
+ harness,
3760
+ parse: (ev) => ({
3761
+ cwd: ev.cwd,
3762
+ sessionId: ev.session_id
3763
+ }),
3764
+ emit: (out) => ({
3765
+ ...out.systemMessage ? { systemMessage: out.systemMessage } : {},
3766
+ hookSpecificOutput: {
3767
+ hookEventName: "SessionStart",
3768
+ ...out.additionalContext ? { additionalContext: out.additionalContext } : {}
3769
+ }
3770
+ })
3771
+ });
3772
+ var notGrokHosted = () => !process.env.GROK_HOOK_EVENT;
3773
+ var HOOK_HARNESSES = {
3774
+ "claude-code": {
3775
+ configStyle: "nested",
3776
+ install: {
3777
+ sessionStart: { event: "SessionStart", entry: "claude-sessionstart-hook.js", timeout: 30 },
3778
+ prompt: { event: "UserPromptSubmit", entry: "claude-hook.js", timeout: 30 },
3779
+ stop: { event: "Stop", entry: "claude-stop-hook.js", timeout: 60 }
3780
+ },
3781
+ sessionStart: { ...standardSessionStart("claude-code"), accept: notGrokHosted },
3782
+ prompt: { ...claudePrompt, accept: notGrokHosted },
3783
+ retain: {
3784
+ hostTimeoutSec: 60,
3785
+ harness: "claude-code",
3786
+ accept: notGrokHosted,
3787
+ parse: (ev) => ({
3788
+ sessionId: ev.session_id,
3789
+ transcriptPath: ev.transcript_path,
3790
+ cwd: ev.cwd
3791
+ })
3792
+ }
3793
+ },
3794
+ codex: {
3795
+ configStyle: "nested",
3796
+ install: {
3797
+ sessionStart: { event: "SessionStart", entry: "codex-sessionstart-hook.js", timeout: 30 },
3798
+ prompt: { event: "UserPromptSubmit", entry: "codex-hook.js", timeout: 30 },
3799
+ stop: { event: "Stop", entry: "codex-stop-hook.js", timeout: 60 }
3800
+ },
3801
+ sessionStart: standardSessionStart("codex"),
3802
+ prompt: codexPrompt,
3803
+ retain: {
3804
+ hostTimeoutSec: 60,
3805
+ harness: "codex",
3806
+ parse: (ev) => ({
3807
+ sessionId: ev.session_id,
3808
+ transcriptPath: ev.transcript_path,
3809
+ cwd: ev.cwd
3810
+ }),
3811
+ readTranscript: readCodexTranscript
3812
+ }
3813
+ },
3814
+ dcode: {
3815
+ configStyle: "nested",
3816
+ install: {
3817
+ sessionStart: { event: "SessionStart", entry: "dcode-sessionstart-hook.js", timeout: 30 },
3818
+ prompt: { event: "UserPromptSubmit", entry: "dcode-hook.js", timeout: 30 },
3819
+ stop: { event: "Stop", entry: "dcode-stop-hook.js", timeout: 60 }
3820
+ },
3821
+ sessionStart: standardSessionStart("dcode"),
3822
+ prompt: dcodePrompt,
3823
+ retain: {
3824
+ hostTimeoutSec: 60,
3825
+ harness: "dcode",
3826
+ parse: (ev) => ({
3827
+ sessionId: ev.session_id,
3828
+ transcriptPath: ev.transcript_path,
3829
+ cwd: ev.cwd,
3830
+ lastAssistantMessage: ev.last_assistant_message
3831
+ }),
3832
+ readTranscript: readDcodeTranscript,
3833
+ readLastMessage: dcodeAssistantText
3834
+ }
3835
+ },
3836
+ "antigravity-cli": {
3837
+ configStyle: "flat",
3838
+ install: {
3839
+ // PreInvocation is Antigravity's only lifecycle point that can inject context. Its first
3840
+ // invocation also performs the SessionStart responsibilities through runHook's seed guard.
3841
+ sessionStart: { event: "PreInvocation", entry: "antigravity-hook.js", timeout: 30 },
3842
+ prompt: { event: "PreInvocation", entry: "antigravity-hook.js", timeout: 30 },
3843
+ stop: { event: "Stop", entry: "antigravity-stop-hook.js", timeout: 30 }
3844
+ },
3845
+ sessionStart: {
3846
+ harness: "antigravity-cli",
3847
+ parse: (ev) => ({
3848
+ cwd: antigravityCwd(ev),
3849
+ sessionId: ev.conversationId
3850
+ }),
3851
+ emit: () => ({})
3852
+ },
3853
+ prompt: antigravityPrompt,
3854
+ retain: {
3855
+ hostTimeoutSec: 30,
3856
+ harness: "antigravity-cli",
3857
+ parse: (ev) => ({
3858
+ sessionId: ev.conversationId,
3859
+ transcriptPath: ev.transcriptPath,
3860
+ cwd: antigravityCwd(ev)
3861
+ }),
3862
+ readTranscript: readAntigravityTranscript
3863
+ }
3864
+ },
3865
+ "cursor-cli": {
3866
+ configStyle: "flat",
3867
+ install: {
3868
+ sessionStart: { event: "sessionStart", entry: "cursor-sessionstart-hook.js", timeout: 30 },
3869
+ prompt: { event: "beforeSubmitPrompt", entry: "cursor-hook.js" },
3870
+ stop: { event: "stop", entry: "cursor-stop-hook.js", timeout: 30 }
3871
+ },
3872
+ sessionStart: {
3873
+ harness: "cursor-cli",
3874
+ parse: (ev) => ({
3875
+ cwd: cursorCwd(ev),
3876
+ sessionId: ev.conversation_id ?? ev.session_id
3877
+ }),
3878
+ emit: (out) => ({
3879
+ ...out.additionalContext ? { additional_context: out.additionalContext } : {}
3880
+ })
3881
+ },
3882
+ prompt: cursorPrompt,
3883
+ retain: {
3884
+ hostTimeoutSec: 30,
3885
+ harness: "cursor-cli",
3886
+ parse: (ev) => ({
3887
+ sessionId: ev.conversation_id ?? ev.session_id,
3888
+ transcriptPath: ev.transcript_path,
3889
+ cwd: cursorCwd(ev)
3890
+ }),
3891
+ readTranscript: readCursorTranscript
3892
+ }
3893
+ },
3894
+ "copilot-cli": {
3895
+ configStyle: "flat",
3896
+ install: {
3897
+ sessionStart: { event: "sessionStart", entry: "copilot-sessionstart-hook.js", timeout: 30 },
3898
+ prompt: { event: "userPromptTransformed", entry: "copilot-hook.js", timeout: 30 },
3899
+ stop: { event: "agentStop", entry: "copilot-stop-hook.js", timeout: 60 }
3900
+ },
3901
+ sessionStart: {
3902
+ harness: "copilot-cli",
3903
+ parse: (ev) => ({
3904
+ cwd: ev.cwd,
3905
+ sessionId: ev.sessionId
3906
+ }),
3907
+ // Copilot CLI's SessionStart response only has model-facing `additionalContext`; unlike
3908
+ // Claude/Cursor it has no supported in-TUI system-message/banner channel. Keep memory
3909
+ // quiet rather than auto-submitting a synthetic prompt or showing an OS notification. When
3910
+ // Copilot exposes a real TUI extension point, add the banner there without changing this
3911
+ // shared lifecycle output.
3912
+ emit: (out) => ({
3913
+ ...out.additionalContext ? { additionalContext: out.additionalContext } : {}
3914
+ })
3915
+ },
3916
+ prompt: copilotPrompt,
3917
+ retain: {
3918
+ hostTimeoutSec: 60,
3919
+ harness: "copilot-cli",
3920
+ parse: (ev) => ({
3921
+ sessionId: ev.sessionId,
3922
+ transcriptPath: ev.transcriptPath,
3923
+ cwd: ev.cwd
3924
+ }),
3925
+ readTranscript: readCopilotTranscript
3926
+ }
3927
+ },
3928
+ "devin-cli": {
3929
+ configStyle: "nested",
3930
+ install: {
3931
+ sessionStart: { event: "SessionStart", entry: "devin-sessionstart-hook.js", timeout: 30 },
3932
+ prompt: { event: "UserPromptSubmit", entry: "devin-hook.js", timeout: 30 },
3933
+ stop: { event: "Stop", entry: "devin-stop-hook.js", timeout: 60 }
3934
+ },
3935
+ sessionStart: {
3936
+ harness: "devin-cli",
3937
+ parse: (ev) => ({ cwd: devinCwd(), sessionId: ev.session_id }),
3938
+ emit: (out) => ({
3939
+ hookSpecificOutput: {
3940
+ hookEventName: "SessionStart",
3941
+ ...out.additionalContext ? { additionalContext: out.additionalContext } : {}
3942
+ }
3943
+ })
3944
+ },
3945
+ prompt: devinPrompt,
3946
+ retain: {
3947
+ hostTimeoutSec: 60,
3948
+ harness: "devin-cli",
3949
+ parse: (ev) => {
3950
+ const sessionId = ev.session_id;
3951
+ return {
3952
+ sessionId,
3953
+ // RetainHook calls the supplied reader with transcriptPath; Devin's reader uses its
3954
+ // session id because the CLI persists conversations in sessions.db rather than a file.
3955
+ transcriptPath: sessionId,
3956
+ cwd: devinCwd()
3957
+ };
3958
+ },
3959
+ readTranscript: readDevinTranscript
3960
+ }
3961
+ },
3962
+ "grok-build": {
3963
+ configStyle: "nested",
3964
+ install: {
3965
+ sessionStart: { event: "SessionStart", entry: "grok-sessionstart-hook.js", timeout: 30 },
3966
+ prompt: { event: "UserPromptSubmit", entry: "grok-hook.js", timeout: 30 },
3967
+ stop: { event: "Stop", entry: "grok-stop-hook.js", timeout: 60 }
3968
+ },
3969
+ sessionStart: {
3970
+ ...standardSessionStart("grok-build"),
3971
+ // Grok's wire envelope is camelCase, unlike Claude's similarly named hook events.
3972
+ parse: (ev) => ({
3973
+ cwd: ev.cwd,
3974
+ sessionId: ev.sessionId
3975
+ })
3976
+ },
3977
+ prompt: {
3978
+ ...claudePrompt,
3979
+ harness: "grok-build",
3980
+ parse: (ev) => ({
3981
+ prompt: ev.prompt,
3982
+ cwd: ev.cwd,
3983
+ sessionId: ev.sessionId
3984
+ })
3985
+ },
3986
+ retain: {
3987
+ hostTimeoutSec: 60,
3988
+ harness: "grok-build",
3989
+ parse: (ev) => ({
3990
+ sessionId: ev.sessionId,
3991
+ transcriptPath: typeof ev.cwd === "string" && typeof ev.sessionId === "string" ? grokTranscriptPath(ev.cwd, ev.sessionId) : void 0,
3992
+ cwd: ev.cwd
3993
+ }),
3994
+ readTranscript: readGrokTranscript
3995
+ }
3996
+ },
3997
+ "qwen-code": {
3998
+ configStyle: "nested",
3999
+ timeoutUnit: "milliseconds",
4000
+ // TIMEOUTS ARE MILLISECONDS HERE, not seconds like every other harness in this table: Qwen's
4001
+ // hookRunner does `setTimeout(..., hookConfig.timeout ?? DEFAULT_HOOK_TIMEOUT)` with
4002
+ // DEFAULT_HOOK_TIMEOUT = 60_000 ("Timeout in milliseconds, default 60000"). Writing 30/60
4003
+ // registers 30ms/60ms hooks, which die before a Node process starts — and Qwen spawns hooks
4004
+ // `detached` and terminates the whole process TREE on timeout, so the retain is genuinely lost
4005
+ // rather than merely orphaned. `retain.hostTimeoutSec` below stays SECONDS, as its name says;
4006
+ // these two numbers are the same budget in different units for this harness alone.
4007
+ // The prompt timeout must also stay above core/config.ts's DEFAULT_REFLECT_TIMEOUT_MS.
4008
+ install: {
4009
+ sessionStart: { event: "SessionStart", entry: "qwen-sessionstart-hook.js", timeout: 3e4 },
4010
+ prompt: { event: "UserPromptSubmit", entry: "qwen-hook.js", timeout: 3e4 },
4011
+ stop: { event: "Stop", entry: "qwen-stop-hook.js", timeout: 6e4 }
4012
+ },
4013
+ sessionStart: standardSessionStart("qwen-code"),
4014
+ prompt: qwenPrompt,
4015
+ retain: {
4016
+ hostTimeoutSec: 60,
4017
+ harness: "qwen-code",
4018
+ parse: (ev) => ({
4019
+ sessionId: ev.session_id,
4020
+ // Qwen supplies the path, but as the EMPTY STRING (not null, not absent) when chat
4021
+ // recording is off — runRetainHook's `if (!transcriptPath) return` already covers that.
4022
+ transcriptPath: ev.transcript_path,
4023
+ cwd: ev.cwd
4024
+ }),
4025
+ readTranscript: readQwenTranscript
4026
+ }
4027
+ },
4028
+ "factory-droid": {
4029
+ configStyle: "nested",
4030
+ install: {
4031
+ sessionStart: { event: "SessionStart", entry: "droid-sessionstart-hook.js", timeout: 30 },
4032
+ prompt: { event: "UserPromptSubmit", entry: "droid-hook.js", timeout: 30 },
4033
+ stop: { event: "Stop", entry: "droid-stop-hook.js", timeout: 60 }
4034
+ },
4035
+ // Droid emits Notification(idle_prompt), not Stop, after user cancellation. Reusing the
4036
+ // idempotent retain entry point captures that final partial turn; its event gate ignores every
4037
+ // other notification type before config or daemon work begins.
4038
+ additionalHooks: [{ event: "Notification", entry: "droid-stop-hook.js", timeout: 60 }],
4039
+ sessionStart: standardSessionStart("factory-droid"),
4040
+ prompt: droidPrompt,
4041
+ retain: {
4042
+ hostTimeoutSec: 60,
4043
+ harness: "factory-droid",
4044
+ accept: (ev) => ev.hook_event_name === "Stop" || ev.hook_event_name === "Notification" && ev.notification_type === "idle_prompt",
4045
+ parse: (ev) => ({
4046
+ sessionId: ev.session_id,
4047
+ transcriptPath: ev.transcript_path,
4048
+ cwd: ev.cwd
4049
+ }),
4050
+ readTranscript: readDroidTranscript
4051
+ }
4052
+ },
4053
+ /**
4054
+ * ZCode (Z.ai's GLM coding agent) embeds the Claude Code agent runtime, so its hook PROTOCOL is
4055
+ * Claude's — `prompt`/`cwd` in, `hookSpecificOutput.additionalContext` + `systemMessage` out —
4056
+ * with `sessionId` accepted alongside `session_id`, which its Stop payload sends instead.
4057
+ *
4058
+ * What is not Claude's is the TRANSCRIPT, and that is the whole of the difference here. ZCode
4059
+ * keeps no durable session file: `Stop` carries the reply in `responseText` plus a temp,
4060
+ * assistant-only transcript it deletes as soon as the hook returns, and no user prompt at all.
4061
+ * So this is the one harness that retains from the plugin's own journal (core/turn-journal.ts) —
4062
+ * the prompt hook appends the user turn, `journal.assistantText` closes it with the reply — and
4063
+ * everything downstream (cursor, append, stamping) sees the same full conversation as any host
4064
+ * transcript.
4065
+ */
4066
+ zcode: {
4067
+ configStyle: "process",
4068
+ // ZCode's `timeoutMs`, so MILLISECONDS — see the qwen-code note above for the same trap. The
4069
+ // prompt budget must stay above core/config.ts's DEFAULT_REFLECT_TIMEOUT_MS.
4070
+ timeoutUnit: "milliseconds",
4071
+ install: {
4072
+ sessionStart: { event: "SessionStart", entry: "zcode-sessionstart-hook.js", timeout: 3e4 },
4073
+ prompt: { event: "UserPromptSubmit", entry: "zcode-hook.js", timeout: 3e4 },
4074
+ stop: { event: "Stop", entry: "zcode-stop-hook.js", timeout: 6e4 }
4075
+ },
4076
+ sessionStart: {
4077
+ ...standardSessionStart("zcode"),
4078
+ parse: (ev) => ({ cwd: ev.cwd, sessionId: zcodeSessionId(ev) })
4079
+ },
4080
+ prompt: {
4081
+ ...claudePrompt,
4082
+ harness: "zcode",
4083
+ journalPrompt: true,
4084
+ parse: (ev) => ({
4085
+ prompt: ev.prompt ?? ev.user_prompt,
4086
+ cwd: ev.cwd,
4087
+ sessionId: zcodeSessionId(ev)
4088
+ })
4089
+ },
4090
+ retain: {
4091
+ hostTimeoutSec: 60,
4092
+ harness: "zcode",
4093
+ // No transcriptPath: the journal supplies it (see `journal` below).
4094
+ parse: (ev) => ({ sessionId: zcodeSessionId(ev), cwd: ev.cwd }),
4095
+ journal: {
4096
+ // `responseText` is the full reply and is what ZCode sends in practice. The ephemeral
4097
+ // transcript is the fallback when it is absent, and `responsePreview` — which is
4098
+ // TRUNCATED — is the last resort, preferred only over losing the turn entirely.
4099
+ assistantText: (ev) => (ev.responseText || zcodeAssistantText(ev.transcript_path) || ev.responsePreview || "").trim()
4100
+ }
4101
+ }
4102
+ },
4103
+ /**
4104
+ * TraeCode (TRAE CN's agent) also speaks Claude Code's hook protocol — `prompt`/`cwd`/`session_id`
4105
+ * in, `hookSpecificOutput.additionalContext` + `systemMessage` out — with registrations nested
4106
+ * under the top-level `hooks` key of `~/.trae-cn/hooks.json` (unlike Factory Droid, whose event
4107
+ * map IS the file) and a `version` field the host writes and expects.
4108
+ *
4109
+ * Like ZCode, what it does not have is a TRANSCRIPT: sessions live in an encrypted local DB or
4110
+ * the cloud and no `transcript_path` is ever supplied, so this is the second harness that retains
4111
+ * from the plugin's own journal (core/turn-journal.ts) — the prompt hook appends the user turn,
4112
+ * and Stop's `last_assistant_message` (the full reply) plays the role ZCode's `responseText`
4113
+ * plays: `journal.assistantText` closes the turn with it.
4114
+ */
4115
+ traecode: {
4116
+ configStyle: "nested",
4117
+ install: {
4118
+ sessionStart: { event: "SessionStart", entry: "traecode-sessionstart-hook.js", timeout: 30 },
4119
+ prompt: { event: "UserPromptSubmit", entry: "traecode-hook.js", timeout: 30 },
4120
+ stop: { event: "Stop", entry: "traecode-stop-hook.js", timeout: 60 }
4121
+ },
4122
+ sessionStart: {
4123
+ ...standardSessionStart("traecode"),
4124
+ // Trae launches USER-level MCP servers from the Electron process's cwd (home), where an
4125
+ // optInOnly config self-disables and the tools vanish. Each repo's own workspace file fixes
4126
+ // it — kept current here, once memory is confirmed live for the repo, along with the
4127
+ // workspace's per-server enable switch (seeded into Trae's storage DB,
4128
+ // core/traecode-mcp.ts). The returned hint (global gate off, or an unseedable switch)
4129
+ // rides the session banner.
4130
+ ensureMcpRegistration: (cwd) => ensureTraecodeWorkspaceMcp(cwd)
4131
+ },
4132
+ prompt: {
4133
+ ...claudePrompt,
4134
+ harness: "traecode",
4135
+ journalPrompt: true,
4136
+ // TraeCode's UserPromptSubmit payload carries `prompt` exactly like Claude Code's.
4137
+ parse: (ev) => ({
4138
+ prompt: ev.prompt,
4139
+ cwd: ev.cwd,
4140
+ sessionId: ev.session_id
4141
+ })
4142
+ },
4143
+ retain: {
4144
+ hostTimeoutSec: 60,
4145
+ harness: "traecode",
4146
+ // No transcriptPath: the journal supplies it (see `journal` below).
4147
+ parse: (ev) => ({
4148
+ sessionId: ev.session_id,
4149
+ cwd: ev.cwd
4150
+ }),
4151
+ journal: {
4152
+ // `last_assistant_message` is the full reply — TraeCode's `responseText`.
4153
+ assistantText: (ev) => (ev.last_assistant_message ?? "").trim()
4154
+ }
4155
+ }
4156
+ },
4157
+ "kimi-code": {
4158
+ // Kimi's ~/.kimi-code/config.toml takes a FLAT [[hooks]] array whose entries are validated by a
4159
+ // strict 4-key schema (event/matcher/command/timeout). Neither JSON style can express it, and a
4160
+ // fifth key drops EVERY hook in the file at warning severity, so its installer writes the block
4161
+ // itself (the grok-build pattern) rather than going through mergeHarnessHooks.
4162
+ configStyle: "toml-array",
4163
+ install: {
4164
+ // Timeouts are SECONDS here (integer 1-600, default 30) — the same unit as every other
4165
+ // supported host, and the opposite of qwen-code's identically named field.
4166
+ sessionStart: { event: "SessionStart", entry: "kimi-sessionstart-hook.js", timeout: 30 },
4167
+ prompt: { event: "UserPromptSubmit", entry: "kimi-hook.js", timeout: 30 },
4168
+ stop: { event: "Stop", entry: "kimi-stop-hook.js", timeout: 60 }
4169
+ },
4170
+ sessionStart: {
4171
+ harness: "kimi-code",
4172
+ parse: (ev) => ({
4173
+ cwd: ev.cwd,
4174
+ sessionId: ev.session_id
4175
+ }),
4176
+ // Kimi runs SessionStart hooks for their side effects only: it awaits the trigger and drops
4177
+ // the result, so nothing emitted here can reach the model or the terminal. Installed for the
4178
+ // seed/daemon/session-root work runSessionStartHook does, and silent like antigravity-cli's.
4179
+ emit: () => ({})
4180
+ },
4181
+ prompt: {
4182
+ harness: "kimi-code",
4183
+ parse: (ev) => ({
4184
+ // A block array, not a string — the same shape as the wire log's `turn.prompt.input`.
4185
+ prompt: kimiPromptText(ev.prompt),
4186
+ cwd: ev.cwd,
4187
+ sessionId: ev.session_id
4188
+ }),
4189
+ // Kimi has no additionalContext: a top-level `message` is the injection channel, which the
4190
+ // CLI wraps as <hook_result hook_event="UserPromptSubmit"> and appends to the conversation.
4191
+ // `notice` has no banner channel to reach (the copilot-cli precedent), but it cannot simply
4192
+ // be dropped: when a hook's stdout parses to JSON carrying no message, Kimi falls back to
4193
+ // injecting the RAW STDOUT, so an empty `{}` would put a literal "{}" in front of the model.
4194
+ // Emitting the notice on the notice-only turn is what keeps that from ever happening.
4195
+ emit: (context, notice) => ({ message: context || notice })
4196
+ },
4197
+ retain: {
4198
+ hostTimeoutSec: 60,
4199
+ harness: "kimi-code",
4200
+ parse: (ev) => {
4201
+ const sessionId = ev.session_id;
4202
+ return {
4203
+ sessionId,
4204
+ // Kimi's Stop payload carries no transcript path — its hook feature has no such field at
4205
+ // all — so resolve the session's own directory from the id, as grok-build does. The
4206
+ // reader takes that DIRECTORY and reads every agent's wire.jsonl beneath it.
4207
+ transcriptPath: sessionId ? kimiSessionDir(sessionId) : void 0,
4208
+ cwd: ev.cwd
4209
+ };
4210
+ },
4211
+ readTranscript: readKimiTranscript
4212
+ }
4213
+ }
4214
+ };
4215
+ var runHarnessRetain = (harness) => runRetainHook(HOOK_HARNESSES[harness].retain);
4216
+
4217
+ // src/kimi-stop-hook.ts
4218
+ void runHarnessRetain("kimi-code");