@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
package/dist/installer.js CHANGED
@@ -1,23 +1,23 @@
1
1
  #!/usr/bin/env node
2
2
 
3
3
  // src/installer.ts
4
- import { execFileSync as execFileSync6 } from "child_process";
4
+ import { execFileSync as execFileSync7 } from "child_process";
5
5
  import {
6
6
  copyFileSync,
7
7
  cpSync as cpSync2,
8
- existsSync as existsSync10,
9
- mkdirSync as mkdirSync6,
8
+ existsSync as existsSync13,
9
+ mkdirSync as mkdirSync7,
10
10
  mkdtempSync as mkdtempSync2,
11
- readFileSync as readFileSync15,
11
+ readFileSync as readFileSync16,
12
12
  readSync as readSync4,
13
13
  realpathSync as realpathSync3,
14
- rmSync as rmSync3,
15
- writeFileSync as writeFileSync4
14
+ rmSync as rmSync4,
15
+ writeFileSync as writeFileSync5
16
16
  } from "fs";
17
- import { homedir as homedir11, tmpdir as tmpdir5 } from "os";
17
+ import { homedir as homedir13, tmpdir as tmpdir5 } from "os";
18
18
  import { isatty } from "tty";
19
- import { dirname as dirname11, join as join20 } from "path";
20
- import { fileURLToPath as fileURLToPath6, pathToFileURL } from "url";
19
+ import { dirname as dirname12, join as join23 } from "path";
20
+ import { fileURLToPath as fileURLToPath7, pathToFileURL } from "url";
21
21
 
22
22
  // node_modules/jsonc-parser/lib/esm/impl/scanner.js
23
23
  function createScanner(text, ignoreTrivia = false) {
@@ -2074,10 +2074,47 @@ import { fileURLToPath } from "url";
2074
2074
 
2075
2075
  // src/core/missions.ts
2076
2076
  import { createHash } from "crypto";
2077
+ var PAGE_TAXONOMY = [
2078
+ {
2079
+ name: "Component map",
2080
+ 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.",
2081
+ tags: ["knowledge:component"]
2082
+ },
2083
+ {
2084
+ name: "Core concepts",
2085
+ 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.",
2086
+ tags: ["knowledge:concept"]
2087
+ },
2088
+ {
2089
+ name: "Conventions and patterns",
2090
+ 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.",
2091
+ tags: ["knowledge:convention"]
2092
+ },
2093
+ {
2094
+ name: "Key decisions and rationale",
2095
+ 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.",
2096
+ tags: ["knowledge:decision"]
2097
+ },
2098
+ {
2099
+ name: "Initiatives and enhancements",
2100
+ 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.",
2101
+ tags: ["knowledge:feature-work"]
2102
+ }
2103
+ ];
2104
+ var PAGE_NAMES = PAGE_TAXONOMY.map((page) => page.name);
2077
2105
 
2078
2106
  // src/core/util.ts
2079
2107
  import { accessSync, constants } from "fs";
2080
2108
  import { delimiter, join as join6 } from "path";
2109
+ function isOurMcpEntry(entry) {
2110
+ if (!entry || typeof entry !== "object") return false;
2111
+ const candidate = entry;
2112
+ if (candidate.command !== "node" || !Array.isArray(candidate.args)) return false;
2113
+ const script = candidate.args[0];
2114
+ if (typeof script !== "string") return false;
2115
+ const parts = script.replaceAll("\\", "/").split("/").filter(Boolean);
2116
+ return parts.at(-1) === "mcp-server.js" && parts.at(-2) === "dist" && (parts.at(-3) === "coding-agents" || parts.at(-3) === "hindsight-coding-agents");
2117
+ }
2081
2118
 
2082
2119
  // src/core/hindsight.ts
2083
2120
  var RETRY_AFTER_FLOOR_MS = 10 * 1e3;
@@ -2230,31 +2267,10 @@ function onPath(bin) {
2230
2267
  import { basename as basename2 } from "path";
2231
2268
 
2232
2269
  // src/core/jsonl.ts
2233
- import { closeSync, openSync, readSync, statSync as statSync3 } from "fs";
2270
+ import { closeSync, openSync, readSync } from "fs";
2234
2271
  import { StringDecoder } from "string_decoder";
2235
2272
  var CHUNK_BYTES = 64 * 1024;
2236
- var MAX_TRANSCRIPT_BYTES = 32 * 1024 * 1024;
2237
- function readJsonlTail(path, opts) {
2238
- const maxBytes = opts.maxBytes ?? MAX_TRANSCRIPT_BYTES;
2239
- let size;
2240
- try {
2241
- size = statSync3(path).size;
2242
- } catch {
2243
- return { lines: emptyLines(), skippedBytes: 0 };
2244
- }
2245
- const skippedBytes = size > maxBytes ? size - maxBytes : 0;
2246
- if (skippedBytes > 0) {
2247
- log.warn(opts.scope, "transcript too large \u2014 retaining the most recent portion only", {
2248
- path,
2249
- sizeBytes: size,
2250
- skippedBytes
2251
- });
2252
- }
2253
- return { lines: streamLines(path, skippedBytes), skippedBytes };
2254
- }
2255
- function* emptyLines() {
2256
- }
2257
- function* streamLines(path, start) {
2273
+ function* readJsonl(path) {
2258
2274
  let fd;
2259
2275
  try {
2260
2276
  fd = openSync(path, "r");
@@ -2265,8 +2281,7 @@ function* streamLines(path, start) {
2265
2281
  const buffer = Buffer.allocUnsafe(CHUNK_BYTES);
2266
2282
  const decoder = new StringDecoder("utf8");
2267
2283
  let pending = "";
2268
- let position = start > 0 ? start - 1 : 0;
2269
- let dropPartial = start > 0;
2284
+ let position = 0;
2270
2285
  for (; ; ) {
2271
2286
  const bytesRead = readSync(fd, buffer, 0, buffer.length, position);
2272
2287
  if (bytesRead <= 0) break;
@@ -2274,17 +2289,12 @@ function* streamLines(path, start) {
2274
2289
  pending += decoder.write(buffer.subarray(0, bytesRead));
2275
2290
  let newline;
2276
2291
  while ((newline = pending.indexOf("\n")) !== -1) {
2277
- const line = pending.slice(0, newline);
2292
+ yield pending.slice(0, newline);
2278
2293
  pending = pending.slice(newline + 1);
2279
- if (dropPartial) {
2280
- dropPartial = false;
2281
- continue;
2282
- }
2283
- yield line;
2284
2294
  }
2285
2295
  }
2286
2296
  pending += decoder.end();
2287
- if (pending && !dropPartial) yield pending;
2297
+ if (pending) yield pending;
2288
2298
  } finally {
2289
2299
  closeSync(fd);
2290
2300
  }
@@ -2316,7 +2326,7 @@ function renderLine(content, type) {
2316
2326
  }
2317
2327
  function readClaudeTranscript(path) {
2318
2328
  const turns = [];
2319
- for (const rawLine of readJsonlTail(path, { scope: "claude-code" }).lines) {
2329
+ for (const rawLine of readJsonl(path)) {
2320
2330
  const trimmed = rawLine.trim();
2321
2331
  if (!trimmed) continue;
2322
2332
  let parsed;
@@ -2448,7 +2458,7 @@ import {
2448
2458
  renameSync as renameSync3,
2449
2459
  rmdirSync,
2450
2460
  rmSync as rmSync2,
2451
- statSync as statSync4,
2461
+ statSync as statSync3,
2452
2462
  unlinkSync,
2453
2463
  utimesSync,
2454
2464
  writeFileSync as writeFileSync2
@@ -2469,15 +2479,19 @@ import { homedir as homedir5, tmpdir as tmpdir4 } from "os";
2469
2479
  import { dirname as dirname9, join as join14 } from "path";
2470
2480
  import { fileURLToPath as fileURLToPath4 } from "url";
2471
2481
  var CHECK_INTERVAL_MS = 24 * 60 * 60 * 1e3;
2482
+ var NPM_VIEW_TIMEOUT_MS = 5e3;
2483
+ var NPM_VIEW_HARD_DEADLINE_MS = NPM_VIEW_TIMEOUT_MS + 1e3;
2472
2484
  var LOCK_STALE_MS = 10 * 60 * 1e3;
2473
2485
 
2474
2486
  // src/core/skill-sync.ts
2475
- import { cpSync, existsSync as existsSync5, readFileSync as readFileSync9 } from "fs";
2487
+ import { cpSync, existsSync as existsSync6, readFileSync as readFileSync9 } from "fs";
2476
2488
  import { homedir as homedir6 } from "os";
2477
- import { dirname as dirname10, join as join15 } from "path";
2489
+ import { dirname as dirname10, join as join16 } from "path";
2478
2490
  import { fileURLToPath as fileURLToPath5 } from "url";
2479
2491
 
2480
2492
  // src/core/skill-dirs.ts
2493
+ import { existsSync as existsSync5 } from "fs";
2494
+ import { join as join15 } from "path";
2481
2495
  var SKILL_DIRS = {
2482
2496
  "claude-code": [".claude", "skills"],
2483
2497
  // Codex and dsh share the agentskills-standard root; uninstalling either removes the one copy.
@@ -2490,6 +2504,8 @@ var SKILL_DIRS = {
2490
2504
  "cline-cli": [".cline", "data", "settings", "skills"],
2491
2505
  "qwen-code": [".qwen", "skills"],
2492
2506
  // Qwen's user-level skills root (Storage.getUserSkillsDirs)
2507
+ // Kimi Code's user-level skills root, alongside its config.toml and mcp.json.
2508
+ "kimi-code": [".kimi-code", "skills"],
2493
2509
  "factory-droid": [".factory", "skills"],
2494
2510
  // Droid's user-level skills root
2495
2511
  // ZCode scans TWO user roots by default (its resolveDefaultSkillRoots): `~/.zcode/skills` and the
@@ -2497,23 +2513,40 @@ var SKILL_DIRS = {
2497
2513
  // skill removal is by fixed directory name, so installing into the shared root would make
2498
2514
  // `uninstall zcode` take Codex's and dsh's copy with it.
2499
2515
  zcode: [".zcode", "skills"],
2516
+ // TraeCode's user-level skills root, resolved per edition by traecodeDotDir below — like ZCode's
2517
+ // its own, never the shared agentskills root other hosts install into.
2518
+ traecode: [".trae-cn", "skills"],
2500
2519
  // The pi family reads the shared ~/.agents/skills too, but writes its OWN root: skill removal is
2501
2520
  // by fixed directory name, so installing to the shared one would make `uninstall pi` take Codex's
2502
2521
  // and dsh's copy with it.
2503
2522
  pi: [".pi", "agent", "skills"],
2504
2523
  "prime-agent": [".prime", "agent", "skills"]
2505
2524
  };
2525
+ var TRAE_DOT_DIRS = [".trae-cn", ".trae"];
2526
+ var traecodeDotDirName = (home, exists = existsSync5) => {
2527
+ for (const dir of TRAE_DOT_DIRS) {
2528
+ if (exists(join15(home, dir))) return dir;
2529
+ }
2530
+ return ".trae-cn";
2531
+ };
2532
+ var resolveSkillDirs = (harness, home) => {
2533
+ const parts = SKILL_DIRS[harness];
2534
+ if (harness === "traecode" && parts) {
2535
+ return [traecodeDotDirName(home), ...parts.slice(1)];
2536
+ }
2537
+ return parts;
2538
+ };
2506
2539
 
2507
2540
  // src/core/legacy.ts
2508
- import { existsSync as existsSync6, readFileSync as readFileSync10 } from "fs";
2541
+ import { existsSync as existsSync7, readFileSync as readFileSync10 } from "fs";
2509
2542
  import { homedir as homedir7 } from "os";
2510
- import { join as join16, relative, isAbsolute as isAbsolute2 } from "path";
2543
+ import { join as join17, relative, isAbsolute as isAbsolute2 } from "path";
2511
2544
  var LEGACY_CONFIG_FILES = {
2512
2545
  "claude-code": "claude-code.json",
2513
2546
  codex: "codex.json"
2514
2547
  };
2515
2548
  function legacyConfigPath(harness, home = homedir7()) {
2516
- return join16(home, ".hindsight", LEGACY_CONFIG_FILES[harness] ?? `${harness}.json`);
2549
+ return join17(home, ".hindsight", LEGACY_CONFIG_FILES[harness] ?? `${harness}.json`);
2517
2550
  }
2518
2551
  var CLOUD_URL = "https://api.hindsight.vectorize.io";
2519
2552
  function readLegacyEndpoint(home = homedir7(), prefer = []) {
@@ -2528,7 +2561,7 @@ function readLegacyEndpoint(home = homedir7(), prefer = []) {
2528
2561
  }
2529
2562
  function readOne(harness, home) {
2530
2563
  const source = legacyConfigPath(harness, home);
2531
- if (!existsSync6(source)) return void 0;
2564
+ if (!existsSync7(source)) return void 0;
2532
2565
  let raw;
2533
2566
  try {
2534
2567
  raw = JSON.parse(readFileSync10(source, "utf8"));
@@ -2557,44 +2590,420 @@ function readOne(harness, home) {
2557
2590
  };
2558
2591
  }
2559
2592
 
2593
+ // src/core/traecode-mcp.ts
2594
+ import { execFileSync as execFileSync4 } from "child_process";
2595
+ import { existsSync as existsSync8, mkdirSync as mkdirSync6, readFileSync as readFileSync12, readdirSync as readdirSync2, rmSync as rmSync3, writeFileSync as writeFileSync4 } from "fs";
2596
+ import { homedir as homedir8 } from "os";
2597
+ import { dirname as dirname11, isAbsolute as isAbsolute3, join as join18 } from "path";
2598
+ import { fileURLToPath as fileURLToPath6 } from "url";
2599
+ var MCP_SERVER_NAME = "hindsight";
2600
+ var MCP_FILE_REL = join18(".trae", "mcp.json");
2601
+ function bundledDistDir() {
2602
+ const here = dirname11(fileURLToPath6(import.meta.url));
2603
+ return existsSync8(join18(here, "mcp-server.js")) ? here : join18(here, "..", "..", "dist");
2604
+ }
2605
+ function canon(value) {
2606
+ if (Array.isArray(value)) return `[${value.map(canon).join(",")}]`;
2607
+ if (value && typeof value === "object") {
2608
+ const entries = Object.entries(value).sort(
2609
+ ([a], [b]) => a < b ? -1 : a > b ? 1 : 0
2610
+ );
2611
+ return `{${entries.map(([k, v]) => `${JSON.stringify(k)}:${canon(v)}`).join(",")}}`;
2612
+ }
2613
+ return JSON.stringify(value);
2614
+ }
2615
+ var WORKSPACE_MCP_KEY = "trae.mcp.enableWorkspaceMcp";
2616
+ var HINT_MIN_INTERVAL_MS = 24 * 60 * 60 * 1e3;
2617
+ function traecodeUserDataDir(home) {
2618
+ 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");
2619
+ for (const brand of ["Trae CN", "Trae"]) {
2620
+ const dir = join18(root, brand);
2621
+ if (existsSync8(dir)) return dir;
2622
+ }
2623
+ return join18(root, "Trae CN");
2624
+ }
2625
+ var traecodeUserSettingsPath = (home) => join18(traecodeUserDataDir(home), "User", "settings.json");
2626
+ var gateStateFileFor = (dist) => join18(dirname11(dist), ".workspace-mcp.json");
2627
+ function gateStateFile() {
2628
+ return gateStateFileFor(bundledDistDir());
2629
+ }
2630
+ function readGateState(opts = {}) {
2631
+ try {
2632
+ return JSON.parse(readFileSync12(opts.stateFile ?? gateStateFile(), "utf8"));
2633
+ } catch {
2634
+ return {};
2635
+ }
2636
+ }
2637
+ function workspaceMcpGateState(settingsPath) {
2638
+ let raw;
2639
+ try {
2640
+ raw = readFileSync12(settingsPath, "utf8");
2641
+ } catch {
2642
+ return "unknown";
2643
+ }
2644
+ try {
2645
+ const doc = JSON.parse(raw);
2646
+ return doc[WORKSPACE_MCP_KEY] === true ? "on" : "off";
2647
+ } catch {
2648
+ const hit = raw.match(new RegExp(`"${WORKSPACE_MCP_KEY}"\\s*:\\s*(true|false)`));
2649
+ return hit ? hit[1] === "true" ? "on" : "off" : "unknown";
2650
+ }
2651
+ }
2652
+ function enableWorkspaceMcpSetting(settingsPath) {
2653
+ try {
2654
+ let doc = {};
2655
+ try {
2656
+ doc = JSON.parse(readFileSync12(settingsPath, "utf8"));
2657
+ } catch {
2658
+ if (existsSync8(settingsPath)) return false;
2659
+ }
2660
+ doc[WORKSPACE_MCP_KEY] = true;
2661
+ mkdirSync6(dirname11(settingsPath), { recursive: true });
2662
+ writeFileSync4(settingsPath, JSON.stringify(doc, null, 2) + "\n");
2663
+ return true;
2664
+ } catch {
2665
+ return false;
2666
+ }
2667
+ }
2668
+ function markWorkspaceMcpEnabled(opts = {}) {
2669
+ try {
2670
+ writeFileSync4(
2671
+ opts.stateFile ?? gateStateFile(),
2672
+ JSON.stringify({ ...readGateState(opts), workspaceMcpEnabled: true }, null, 2) + "\n"
2673
+ );
2674
+ } catch {
2675
+ }
2676
+ }
2677
+ function workspaceMcpHint(opts = {}) {
2678
+ try {
2679
+ const settingsPath = traecodeUserSettingsPath(opts.home ?? homedir8());
2680
+ if (workspaceMcpGateState(settingsPath) === "on") return void 0;
2681
+ const now = opts.now ?? Date.now();
2682
+ const state = readGateState(opts);
2683
+ if (state.workspaceMcpEnabled) return void 0;
2684
+ if (typeof state.lastHint === "number" && now - state.lastHint < HINT_MIN_INTERVAL_MS) {
2685
+ return void 0;
2686
+ }
2687
+ writeFileSync4(
2688
+ opts.stateFile ?? gateStateFile(),
2689
+ JSON.stringify({ ...state, lastHint: now }, null, 2) + "\n"
2690
+ );
2691
+ 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.';
2692
+ } catch {
2693
+ return void 0;
2694
+ }
2695
+ }
2696
+ function gitignoreCovers(lines) {
2697
+ return lines.some((l) => {
2698
+ const t = l.trim();
2699
+ return t.includes(".trae");
2700
+ });
2701
+ }
2702
+ function ensureGitignored(repo) {
2703
+ const gitignore = join18(repo, ".gitignore");
2704
+ if (!existsSync8(gitignore)) return;
2705
+ const current2 = readFileSync12(gitignore, "utf8");
2706
+ if (gitignoreCovers(current2.split("\n"))) return;
2707
+ const addition = (current2.endsWith("\n") || current2 === "" ? "" : "\n") + "# hindsight MCP registration (machine-specific)\n.trae/mcp.json\n";
2708
+ writeFileSync4(gitignore, current2 + addition);
2709
+ }
2710
+ function ensureTraecodeWorkspaceMcp(cwd, opts = {}) {
2711
+ registerTraecodeWorkspaceMcp(cwd, opts);
2712
+ const seeded = ensureWorkspaceMcpEnabled(cwd, opts);
2713
+ return workspaceMcpHint(opts) ?? (seeded === "failed" ? workspaceEnableHint(opts) : void 0);
2714
+ }
2715
+ function registerTraecodeWorkspaceMcp(cwd, opts = {}) {
2716
+ try {
2717
+ const home = opts.home ?? homedir8();
2718
+ if (!cwd || !isAbsolute3(cwd) || dirname11(cwd) === cwd || cwd === home) return "skipped";
2719
+ const dist = opts.dist ?? bundledDistDir();
2720
+ const script = join18(dist, "mcp-server.js");
2721
+ if (!existsSync8(script)) return "skipped";
2722
+ const file = join18(cwd, MCP_FILE_REL);
2723
+ let doc = {};
2724
+ let exists = false;
2725
+ try {
2726
+ doc = JSON.parse(readFileSync12(file, "utf8"));
2727
+ exists = true;
2728
+ } catch {
2729
+ if (existsSync8(file)) return "skipped";
2730
+ }
2731
+ const servers = doc.mcpServers && typeof doc.mcpServers === "object" && !Array.isArray(doc.mcpServers) ? doc.mcpServers : doc.mcpServers = {};
2732
+ const entry = {
2733
+ command: "node",
2734
+ args: [script],
2735
+ env: { HINDSIGHT_MCP_HARNESS: "traecode", HINDSIGHT_MCP_PROJECT_CWD: cwd }
2736
+ };
2737
+ const existing = servers[MCP_SERVER_NAME];
2738
+ let merged;
2739
+ if (existing === void 0) {
2740
+ merged = entry;
2741
+ } else if (isOurMcpEntry(existing)) {
2742
+ const env = existing.env;
2743
+ merged = {
2744
+ ...existing,
2745
+ command: entry.command,
2746
+ args: entry.args,
2747
+ env: { ...env ?? {}, ...entry.env }
2748
+ };
2749
+ } else {
2750
+ diag("traecode", "workspace_mcp_foreign_entry", { cwd, file });
2751
+ return "skipped";
2752
+ }
2753
+ if (existing !== void 0 && canon(merged) === canon(existing)) return "current";
2754
+ servers[MCP_SERVER_NAME] = merged;
2755
+ mkdirSync6(dirname11(file), { recursive: true });
2756
+ writeFileSync4(file, JSON.stringify(doc, null, 2) + "\n");
2757
+ if (!exists) ensureGitignored(cwd);
2758
+ diag("traecode", "workspace_mcp_registered", { cwd, file });
2759
+ return "registered";
2760
+ } catch (e) {
2761
+ diag("traecode", "workspace_mcp_register_failed", {
2762
+ cwd,
2763
+ error: e instanceof Error ? e.message : String(e)
2764
+ });
2765
+ return "failed";
2766
+ }
2767
+ }
2768
+ function removeTraecodeWorkspaceMcpEntry(cwd, opts = {}) {
2769
+ try {
2770
+ const home = opts.home ?? homedir8();
2771
+ if (!cwd || !isAbsolute3(cwd) || dirname11(cwd) === cwd || cwd === home) return false;
2772
+ const file = join18(cwd, MCP_FILE_REL);
2773
+ let doc;
2774
+ try {
2775
+ doc = JSON.parse(readFileSync12(file, "utf8"));
2776
+ } catch {
2777
+ return false;
2778
+ }
2779
+ const servers = doc.mcpServers;
2780
+ if (!servers || typeof servers !== "object" || Array.isArray(servers)) return false;
2781
+ const record = servers;
2782
+ if (!isOurMcpEntry(record[MCP_SERVER_NAME])) return false;
2783
+ delete record[MCP_SERVER_NAME];
2784
+ if (Object.keys(record).length === 0) delete doc.mcpServers;
2785
+ if (Object.keys(doc).length === 0) rmSync3(file);
2786
+ else writeFileSync4(file, JSON.stringify(doc, null, 2) + "\n");
2787
+ return true;
2788
+ } catch {
2789
+ return false;
2790
+ }
2791
+ }
2792
+ var WORKSPACE_STORAGE_REL = join18("User", "workspaceStorage");
2793
+ var ENABLED_KEY_PREFIX = "icubeAgentExtension.enabled.mcp.config.ws0.";
2794
+ var SQLITE_TIMEOUT_MS = 5e3;
2795
+ var TRAECODE_WORKSPACE_ENABLED_KEY = ENABLED_KEY_PREFIX + MCP_SERVER_NAME;
2796
+ var traecodeWorkspaceStorageDir = (home) => join18(traecodeUserDataDir(home), WORKSPACE_STORAGE_REL);
2797
+ function removeWorkspaceMcpEnabledKeys(home) {
2798
+ const storage = traecodeWorkspaceStorageDir(home);
2799
+ let entries;
2800
+ try {
2801
+ entries = readdirSync2(storage);
2802
+ } catch {
2803
+ return;
2804
+ }
2805
+ for (const name of entries) {
2806
+ const db = join18(storage, name, "state.vscdb");
2807
+ if (!existsSync8(db)) continue;
2808
+ try {
2809
+ execFileSync4(
2810
+ "sqlite3",
2811
+ [
2812
+ db,
2813
+ ".timeout 3000",
2814
+ `DELETE FROM ItemTable WHERE key='${TRAECODE_WORKSPACE_ENABLED_KEY}';`
2815
+ ],
2816
+ {
2817
+ timeout: SQLITE_TIMEOUT_MS,
2818
+ windowsHide: true,
2819
+ stdio: ["ignore", "pipe", "pipe"]
2820
+ }
2821
+ );
2822
+ } catch {
2823
+ }
2824
+ }
2825
+ }
2826
+ function findWorkspaceStorageDir(storage, repo) {
2827
+ let entries;
2828
+ try {
2829
+ entries = readdirSync2(storage);
2830
+ } catch {
2831
+ return void 0;
2832
+ }
2833
+ for (const name of entries) {
2834
+ try {
2835
+ const doc = JSON.parse(readFileSync12(join18(storage, name, "workspace.json"), "utf8"));
2836
+ if (typeof doc.folder !== "string") continue;
2837
+ let folder;
2838
+ try {
2839
+ folder = fileURLToPath6(doc.folder);
2840
+ } catch {
2841
+ folder = doc.folder;
2842
+ }
2843
+ if (folder === repo) return join18(storage, name);
2844
+ } catch {
2845
+ continue;
2846
+ }
2847
+ }
2848
+ return void 0;
2849
+ }
2850
+ function ensureWorkspaceMcpEnabled(cwd, opts = {}) {
2851
+ try {
2852
+ const home = opts.home ?? homedir8();
2853
+ if (!cwd || !isAbsolute3(cwd) || dirname11(cwd) === cwd || cwd === home) return "failed";
2854
+ const dir = findWorkspaceStorageDir(traecodeWorkspaceStorageDir(home), cwd);
2855
+ if (!dir) return "failed";
2856
+ const db = join18(dir, "state.vscdb");
2857
+ if (!existsSync8(db)) return "failed";
2858
+ const sqlite = opts.sqlite ?? execFileSync4;
2859
+ const run2 = (sql) => sqlite("sqlite3", [db, ".timeout 3000", sql], {
2860
+ encoding: "utf8",
2861
+ timeout: SQLITE_TIMEOUT_MS,
2862
+ windowsHide: true,
2863
+ stdio: ["ignore", "pipe", "pipe"]
2864
+ }).trim();
2865
+ if (run2(`SELECT value FROM ItemTable WHERE key='${TRAECODE_WORKSPACE_ENABLED_KEY}';`) === "true") {
2866
+ return "on";
2867
+ }
2868
+ run2(
2869
+ `INSERT OR REPLACE INTO ItemTable (key, value) VALUES ('${TRAECODE_WORKSPACE_ENABLED_KEY}', 'true');`
2870
+ );
2871
+ diag("traecode", "workspace_mcp_enabled_seeded", { cwd, db });
2872
+ return "seeded";
2873
+ } catch (e) {
2874
+ diag("traecode", "workspace_mcp_enabled_seed_failed", {
2875
+ cwd,
2876
+ error: e instanceof Error ? e.message : String(e)
2877
+ });
2878
+ return "failed";
2879
+ }
2880
+ }
2881
+ function workspaceEnableHint(opts = {}) {
2882
+ try {
2883
+ const now = opts.now ?? Date.now();
2884
+ const state = readGateState(opts);
2885
+ if (typeof state.lastEnableHint === "number" && now - state.lastEnableHint < HINT_MIN_INTERVAL_MS) {
2886
+ return void 0;
2887
+ }
2888
+ writeFileSync4(
2889
+ opts.stateFile ?? gateStateFile(),
2890
+ JSON.stringify({ ...state, lastEnableHint: now }, null, 2) + "\n"
2891
+ );
2892
+ 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.";
2893
+ } catch {
2894
+ return void 0;
2895
+ }
2896
+ }
2897
+
2560
2898
  // src/core/transcript-codex.ts
2899
+ function stampOf(line) {
2900
+ return typeof line.timestamp === "string" && line.timestamp ? { timestamp: line.timestamp } : {};
2901
+ }
2561
2902
  function isSyntheticUserText(text) {
2562
2903
  const s = text.trimStart();
2563
2904
  return s.startsWith("# AGENTS.md instructions for ") || s.startsWith("<environment_context>");
2564
2905
  }
2565
- function messageText(payload) {
2566
- return (payload.content || []).filter((c) => c && typeof c.text === "string").map((c) => c.text).join("\n");
2906
+ function contentText(content) {
2907
+ return (Array.isArray(content) ? content : []).filter((c) => c && typeof c.text === "string").map((c) => c.text).join("\n");
2908
+ }
2909
+ var startupKinds = /* @__PURE__ */ new Set([
2910
+ "agents_md.instructions",
2911
+ "environments.instructions",
2912
+ "environments.environment_context",
2913
+ "plugins.recommendations",
2914
+ "plugins.usage_instructions"
2915
+ ]);
2916
+ function fallbackUserText(payload) {
2917
+ const content = payload.content;
2918
+ const kinds = payload.internal_chat_message_metadata_passthrough?.content_item_kinds;
2919
+ if (Array.isArray(content) && Array.isArray(kinds) && kinds.length === content.length && kinds.every((kind) => typeof kind === "string" && kind.length > 0)) {
2920
+ return contentText(content.filter((_, index) => !startupKinds.has(kinds[index])));
2921
+ }
2922
+ const text = contentText(content);
2923
+ return isSyntheticUserText(stripInjectedMemory(text)) ? "" : text;
2924
+ }
2925
+ function isUserMessageEvent(line) {
2926
+ return line.type === "event_msg" && line.payload?.type === "item_completed" && line.payload.item?.type === "UserMessage";
2927
+ }
2928
+ var TOOL_ITEM_TYPES = /* @__PURE__ */ new Set(["McpToolCall", "CommandExecution"]);
2929
+ function isToolItemEvent(line) {
2930
+ return line.type === "event_msg" && line.payload?.type === "item_completed" && TOOL_ITEM_TYPES.has(line.payload.item?.type ?? "");
2931
+ }
2932
+ function parseArgs(raw) {
2933
+ if (typeof raw !== "string") return raw;
2934
+ try {
2935
+ return JSON.parse(raw);
2936
+ } catch {
2937
+ return void 0;
2938
+ }
2939
+ }
2940
+ var SHELL_RE = /(?:^|\/)(?:sh|bash|zsh|dash|ksh|fish)$/;
2941
+ function commandText(command) {
2942
+ if (typeof command === "string") return command;
2943
+ if (!Array.isArray(command) || !command.every((c) => typeof c === "string")) return "";
2944
+ const argv = command;
2945
+ if (argv.length === 3 && SHELL_RE.test(argv[0]) && /^-[a-z]*c$/.test(argv[1])) return argv[2];
2946
+ return argv.join(" ");
2947
+ }
2948
+ function toolItemAction(item) {
2949
+ if (item.type === "McpToolCall") {
2950
+ if (typeof item.tool !== "string" || !item.tool) return void 0;
2951
+ const name = typeof item.server === "string" && item.server ? `mcp__${item.server}__${item.tool}` : item.tool;
2952
+ return actionLine(name, parseArgs(item.arguments));
2953
+ }
2954
+ const command = commandText(item.command).trim();
2955
+ return command ? actionLine("exec_command", { command }) : void 0;
2567
2956
  }
2568
2957
  function readCodexTranscript(path) {
2569
- const turns = [];
2570
- for (const rawLine of readJsonlTail(path, { scope: "codex" }).lines) {
2958
+ const lines = [];
2959
+ for (const rawLine of readJsonl(path)) {
2571
2960
  const trimmed = rawLine.trim();
2572
2961
  if (!trimmed) continue;
2573
- let parsed;
2574
2962
  try {
2575
- parsed = JSON.parse(trimmed);
2963
+ const parsed = JSON.parse(trimmed);
2964
+ if (typeof parsed === "object" && parsed !== null) lines.push(parsed);
2576
2965
  } catch {
2577
2966
  continue;
2578
2967
  }
2579
- if (typeof parsed !== "object" || parsed === null) continue;
2580
- const line = parsed;
2968
+ }
2969
+ const userFromEvents = lines.some(isUserMessageEvent);
2970
+ const actionsFromEvents = lines.some(isToolItemEvent);
2971
+ const turns = [];
2972
+ const push = (role, raw, stamp = {}) => {
2973
+ const text = stripInjectedMemory(raw).trim();
2974
+ if (text) turns.push({ role, content: text, ...stamp });
2975
+ };
2976
+ for (const line of lines) {
2977
+ if (isUserMessageEvent(line)) {
2978
+ push("user", contentText(line.payload?.item?.content), stampOf(line));
2979
+ continue;
2980
+ }
2981
+ if (isToolItemEvent(line)) {
2982
+ const action = toolItemAction(line.payload?.item ?? {});
2983
+ if (action) turns.push({ role: "action", content: action, ...stampOf(line) });
2984
+ continue;
2985
+ }
2581
2986
  if (line.type !== "response_item") continue;
2582
2987
  const p = line.payload;
2583
2988
  if (!p || typeof p !== "object") continue;
2584
2989
  if (p.type === "message") {
2585
- if (p.role !== "user" && p.role !== "assistant") continue;
2586
- const text = stripInjectedMemory(messageText(p)).trim();
2587
- if (!text) continue;
2588
- if (p.role === "user" && isSyntheticUserText(text)) continue;
2589
- turns.push({ role: p.role, content: text });
2590
- } else if (p.type === "function_call" && typeof p.name === "string") {
2990
+ if (p.role === "assistant") {
2991
+ if (p.channel === "analysis" || p.channel === "reasoning" || p.phase === "analysis" || p.phase === "reasoning")
2992
+ continue;
2993
+ push("assistant", contentText(p.content), stampOf(line));
2994
+ } else if (p.role === "user" && !userFromEvents) {
2995
+ push("user", fallbackUserText(p), stampOf(line));
2996
+ }
2997
+ } else if ((p.type === "function_call" || p.type === "custom_tool_call") && typeof p.name === "string") {
2998
+ if (actionsFromEvents && p.type === "custom_tool_call" && p.name === "exec") continue;
2999
+ const rawInput = p.type === "function_call" ? p.arguments : p.input;
2591
3000
  let input;
2592
3001
  try {
2593
- input = JSON.parse(p.arguments || "");
3002
+ input = JSON.parse(rawInput || "");
2594
3003
  } catch {
2595
3004
  input = void 0;
2596
3005
  }
2597
- turns.push({ role: "action", content: actionLine(p.name, input) });
3006
+ turns.push({ role: "action", content: actionLine(p.name, input), ...stampOf(line) });
2598
3007
  }
2599
3008
  }
2600
3009
  return turns;
@@ -2611,7 +3020,7 @@ function textFrom(content) {
2611
3020
  }
2612
3021
  function readCursorTranscript(path) {
2613
3022
  const turns = [];
2614
- for (const rawLine of readJsonlTail(path, { scope: "cursor-cli" }).lines) {
3023
+ for (const rawLine of readJsonl(path)) {
2615
3024
  let parsed;
2616
3025
  try {
2617
3026
  parsed = JSON.parse(rawLine);
@@ -2650,7 +3059,7 @@ function readCursorTranscript(path) {
2650
3059
  function readAntigravityTranscript(path) {
2651
3060
  if (!path) return [];
2652
3061
  const turns = [];
2653
- for (const line of readJsonlTail(path, { scope: "antigravity-cli" }).lines) {
3062
+ for (const line of readJsonl(path)) {
2654
3063
  try {
2655
3064
  const event = JSON.parse(line);
2656
3065
  const role = event.role ?? event.message?.role ?? event.type;
@@ -2673,7 +3082,7 @@ function readAntigravityTranscript(path) {
2673
3082
  // src/core/transcript-copilot.ts
2674
3083
  function readCopilotTranscript(path) {
2675
3084
  const turns = [];
2676
- for (const rawLine of readJsonlTail(path, { scope: "copilot-cli" }).lines) {
3085
+ for (const rawLine of readJsonl(path)) {
2677
3086
  try {
2678
3087
  const event = JSON.parse(rawLine);
2679
3088
  const role = event.type === "user.message" ? "user" : event.type === "assistant.message" ? "assistant" : void 0;
@@ -2687,19 +3096,19 @@ function readCopilotTranscript(path) {
2687
3096
  }
2688
3097
 
2689
3098
  // src/core/transcript-grok.ts
2690
- import { existsSync as existsSync7, readFileSync as readFileSync12, readdirSync as readdirSync2 } from "fs";
2691
- import { homedir as homedir8 } from "os";
2692
- import { join as join17 } from "path";
3099
+ import { existsSync as existsSync9, readFileSync as readFileSync13, readdirSync as readdirSync3 } from "fs";
3100
+ import { homedir as homedir9 } from "os";
3101
+ import { join as join19 } from "path";
2693
3102
  var CHAT_HISTORY = "chat_history.jsonl";
2694
- function grokTranscriptPath(cwd, sessionId, grokHome = process.env.GROK_HOME || join17(homedir8(), ".grok")) {
2695
- const sessionsDir = join17(grokHome, "sessions");
2696
- const direct = join17(sessionsDir, encodeURIComponent(cwd), sessionId, CHAT_HISTORY);
2697
- if (existsSync7(direct)) return direct;
3103
+ function grokTranscriptPath(cwd, sessionId, grokHome = process.env.GROK_HOME || join19(homedir9(), ".grok")) {
3104
+ const sessionsDir = join19(grokHome, "sessions");
3105
+ const direct = join19(sessionsDir, encodeURIComponent(cwd), sessionId, CHAT_HISTORY);
3106
+ if (existsSync9(direct)) return direct;
2698
3107
  try {
2699
- for (const candidate of readdirSync2(sessionsDir)) {
2700
- const directory = join17(sessionsDir, candidate);
2701
- if (readFileSync12(join17(directory, ".cwd"), "utf8").trim() === cwd) {
2702
- return join17(directory, sessionId, CHAT_HISTORY);
3108
+ for (const candidate of readdirSync3(sessionsDir)) {
3109
+ const directory = join19(sessionsDir, candidate);
3110
+ if (readFileSync13(join19(directory, ".cwd"), "utf8").trim() === cwd) {
3111
+ return join19(directory, sessionId, CHAT_HISTORY);
2703
3112
  }
2704
3113
  }
2705
3114
  } catch {
@@ -2708,7 +3117,7 @@ function grokTranscriptPath(cwd, sessionId, grokHome = process.env.GROK_HOME ||
2708
3117
  }
2709
3118
  function readGrokTranscript(path) {
2710
3119
  const turns = [];
2711
- for (const rawLine of readJsonlTail(path, { scope: "grok-build" }).lines) {
3120
+ for (const rawLine of readJsonl(path)) {
2712
3121
  try {
2713
3122
  const event = JSON.parse(rawLine);
2714
3123
  if (event.type !== "user" && event.type !== "assistant") continue;
@@ -2734,12 +3143,12 @@ function readGrokTranscript(path) {
2734
3143
  }
2735
3144
 
2736
3145
  // src/core/transcript-devin.ts
2737
- import { existsSync as existsSync8 } from "fs";
3146
+ import { existsSync as existsSync10 } from "fs";
2738
3147
  import { createRequire } from "module";
2739
- import { homedir as homedir9 } from "os";
2740
- import { join as join18 } from "path";
2741
- function devinSessionDb(home = homedir9()) {
2742
- return join18(home, ".local", "share", "devin", "cli", "sessions.db");
3148
+ import { homedir as homedir10 } from "os";
3149
+ import { join as join20 } from "path";
3150
+ function devinSessionDb(home = homedir10()) {
3151
+ return join20(home, ".local", "share", "devin", "cli", "sessions.db");
2743
3152
  }
2744
3153
  function parseDevinMessages(nodes) {
2745
3154
  const messages = /* @__PURE__ */ new Map();
@@ -2776,7 +3185,7 @@ function readDevinTranscript(sessionId, dbPath = devinSessionDb()) {
2776
3185
  diag("devin-cli", "sqlite_unavailable", { node: process.version, dbPath });
2777
3186
  return [];
2778
3187
  }
2779
- if (!existsSync8(dbPath)) {
3188
+ if (!existsSync10(dbPath)) {
2780
3189
  diag("devin-cli", "session_db_missing", { dbPath });
2781
3190
  return [];
2782
3191
  }
@@ -2800,7 +3209,7 @@ function readDevinTranscript(sessionId, dbPath = devinSessionDb()) {
2800
3209
 
2801
3210
  // src/core/transcript-dcode.ts
2802
3211
  var BLOCK_JOIN = "\n";
2803
- function contentText(content) {
3212
+ function contentText2(content) {
2804
3213
  if (typeof content === "string") return content;
2805
3214
  if (!Array.isArray(content)) return "";
2806
3215
  return content.flatMap((block) => {
@@ -2893,11 +3302,11 @@ function dcodeAssistantText(raw) {
2893
3302
  const parsed = readPyValue(trimmed, 0);
2894
3303
  if (!parsed || readPyValue(trimmed, parsed.end) !== null) return "";
2895
3304
  if (!Array.isArray(parsed.value)) return "";
2896
- return contentText(parsed.value);
3305
+ return contentText2(parsed.value);
2897
3306
  }
2898
3307
  function readDcodeTranscript(path) {
2899
3308
  const turns = [];
2900
- for (const rawLine of readJsonlTail(path, { scope: "dcode" }).lines) {
3309
+ for (const rawLine of readJsonl(path)) {
2901
3310
  if (!rawLine.trim()) continue;
2902
3311
  let parsed;
2903
3312
  try {
@@ -2911,7 +3320,7 @@ function readDcodeTranscript(path) {
2911
3320
  const role = record.role;
2912
3321
  const stamp = typeof record.timestamp === "string" && record.timestamp ? { timestamp: record.timestamp } : {};
2913
3322
  if (role === "user" || role === "assistant") {
2914
- const text = stripInjectedMemory(contentText(record.content)).trim();
3323
+ const text = stripInjectedMemory(contentText2(record.content)).trim();
2915
3324
  if (text) turns.push({ role, content: text, ...stamp });
2916
3325
  } else if (role === "tool" && typeof record.name === "string" && record.name.trim()) {
2917
3326
  turns.push({ role: "action", content: actionLine(record.name, record.content), ...stamp });
@@ -2972,7 +3381,7 @@ function readQwenTranscript(path) {
2972
3381
  return turns;
2973
3382
  }
2974
3383
  function collectQwenTurns(path, turns) {
2975
- for (const rawLine of readJsonlTail(path, { scope: "qwen-code" }).lines) {
3384
+ for (const rawLine of readJsonl(path)) {
2976
3385
  const trimmed = rawLine.trim();
2977
3386
  if (!trimmed) continue;
2978
3387
  let parsed;
@@ -3027,7 +3436,7 @@ function renderContent(content, role) {
3027
3436
  }
3028
3437
  function readDroidTranscript(path) {
3029
3438
  const turns = [];
3030
- for (const rawLine of readJsonlTail(path, { scope: "factory-droid" }).lines) {
3439
+ for (const rawLine of readJsonl(path)) {
3031
3440
  if (!rawLine.trim()) continue;
3032
3441
  let parsed;
3033
3442
  try {
@@ -3049,8 +3458,8 @@ function readDroidTranscript(path) {
3049
3458
  }
3050
3459
 
3051
3460
  // src/core/transcript-zcode.ts
3052
- import { readFileSync as readFileSync13 } from "fs";
3053
- function messageText2(content) {
3461
+ import { readFileSync as readFileSync14 } from "fs";
3462
+ function messageText(content) {
3054
3463
  if (typeof content === "string") return content.trim();
3055
3464
  if (!Array.isArray(content)) return "";
3056
3465
  return content.filter((block) => block && typeof block === "object" && typeof block.text === "string").map((block) => block.text.trim()).filter(Boolean).join("\n").trim();
@@ -3059,7 +3468,7 @@ function readZcodeTranscript(path) {
3059
3468
  if (!path) return [];
3060
3469
  let body;
3061
3470
  try {
3062
- body = readFileSync13(path, "utf8");
3471
+ body = readFileSync14(path, "utf8");
3063
3472
  } catch {
3064
3473
  return [];
3065
3474
  }
@@ -3078,7 +3487,7 @@ function readZcodeTranscript(path) {
3078
3487
  const message = typeof record.message === "object" && record.message !== null ? record.message : void 0;
3079
3488
  const role = typeof message?.role === "string" ? message.role : record.type;
3080
3489
  if (role !== "user" && role !== "assistant") continue;
3081
- const content = stripInjectedMemory(messageText2(message?.content)).trim();
3490
+ const content = stripInjectedMemory(messageText(message?.content)).trim();
3082
3491
  if (!content) continue;
3083
3492
  turns.push({
3084
3493
  role,
@@ -3093,6 +3502,131 @@ function zcodeAssistantText(path) {
3093
3502
  return readZcodeTranscript(path).filter((turn) => turn.role === "assistant").at(-1)?.content ?? "";
3094
3503
  }
3095
3504
 
3505
+ // src/core/transcript-kimi.ts
3506
+ import { existsSync as existsSync11, readdirSync as readdirSync4 } from "fs";
3507
+ import { homedir as homedir11 } from "os";
3508
+ import { join as join21 } from "path";
3509
+ var HARNESS = "kimi-code";
3510
+ var SESSIONS_DIR = "sessions";
3511
+ var AGENTS_DIR = "agents";
3512
+ var WIRE_LOG = "wire.jsonl";
3513
+ var SESSION_PREFIX = "session_";
3514
+ var MAIN_AGENT = "main";
3515
+ var MAX_SESSION_CHARS = 32 * 1024 * 1024;
3516
+ function kimiSessionDir(sessionId, kimiHome2 = process.env.KIMI_CODE_HOME || join21(homedir11(), ".kimi-code")) {
3517
+ const name = sessionId.startsWith(SESSION_PREFIX) ? sessionId : `${SESSION_PREFIX}${sessionId}`;
3518
+ const sessions = join21(kimiHome2, SESSIONS_DIR);
3519
+ try {
3520
+ for (const workspace of readdirSync4(sessions, { withFileTypes: true })) {
3521
+ if (!workspace.isDirectory()) continue;
3522
+ const candidate = join21(sessions, workspace.name, name);
3523
+ if (existsSync11(join21(candidate, AGENTS_DIR))) return candidate;
3524
+ }
3525
+ } catch {
3526
+ }
3527
+ diag(HARNESS, "session_dir_missing", { sessions, session: name });
3528
+ return void 0;
3529
+ }
3530
+ function stampOf2(event) {
3531
+ if (typeof event.time !== "number") return {};
3532
+ const at = new Date(event.time);
3533
+ return Number.isNaN(at.getTime()) ? {} : { timestamp: at.toISOString() };
3534
+ }
3535
+ function kimiPromptText(input) {
3536
+ if (!Array.isArray(input)) return "";
3537
+ return input.filter((block) => block?.type === "text" && typeof block.text === "string").map((block) => block.text).join("\n");
3538
+ }
3539
+ function readKimiWire(events) {
3540
+ const turns = [];
3541
+ let step;
3542
+ const flushStep = () => {
3543
+ if (!step) return;
3544
+ const content = stripInjectedMemory(step.texts.join("\n")).trim();
3545
+ if (content) turns.push({ role: "assistant", content, ...step.stamp });
3546
+ step = void 0;
3547
+ };
3548
+ for (const event of events || []) {
3549
+ if (!event || typeof event !== "object") continue;
3550
+ const stamp = stampOf2(event);
3551
+ if (event.type === "turn.prompt") {
3552
+ flushStep();
3553
+ if (event.origin?.kind !== "user") continue;
3554
+ const content = stripInjectedMemory(kimiPromptText(event.input)).trim();
3555
+ if (content) turns.push({ role: "user", content, ...stamp });
3556
+ continue;
3557
+ }
3558
+ if (event.type !== "context.append_loop_event") continue;
3559
+ const loop = event.event;
3560
+ if (!loop || typeof loop !== "object") continue;
3561
+ if (loop.type === "content.part") {
3562
+ if (loop.part?.type !== "text" || typeof loop.part.text !== "string") continue;
3563
+ const uuid = typeof loop.stepUuid === "string" ? loop.stepUuid : "";
3564
+ if (step && step.uuid !== uuid) flushStep();
3565
+ if (!step) step = { uuid, texts: [], stamp };
3566
+ step.texts.push(loop.part.text);
3567
+ } else if (loop.type === "tool.call") {
3568
+ flushStep();
3569
+ if (typeof loop.name !== "string" || !loop.name) continue;
3570
+ turns.push({ role: "action", content: actionLine(loop.name, loop.args), ...stamp });
3571
+ }
3572
+ }
3573
+ flushStep();
3574
+ return turns;
3575
+ }
3576
+ function agentIds(sessionDir) {
3577
+ try {
3578
+ return readdirSync4(join21(sessionDir, AGENTS_DIR), { withFileTypes: true }).filter((entry) => entry.isDirectory()).map((entry) => entry.name).sort(byAgentId);
3579
+ } catch {
3580
+ return [];
3581
+ }
3582
+ }
3583
+ function byAgentId(a, b) {
3584
+ if (a === b) return 0;
3585
+ if (a === MAIN_AGENT) return -1;
3586
+ if (b === MAIN_AGENT) return 1;
3587
+ const indexA = agentIndex(a);
3588
+ const indexB = agentIndex(b);
3589
+ return indexA === indexB ? a.localeCompare(b) : indexA - indexB;
3590
+ }
3591
+ function agentIndex(id) {
3592
+ const suffix = Number(id.slice(id.lastIndexOf("-") + 1));
3593
+ return Number.isFinite(suffix) ? suffix : Number.MAX_SAFE_INTEGER;
3594
+ }
3595
+ function parseEvent(rawLine) {
3596
+ const trimmed = rawLine.trim();
3597
+ if (!trimmed) return void 0;
3598
+ let parsed;
3599
+ try {
3600
+ parsed = JSON.parse(trimmed);
3601
+ } catch {
3602
+ return void 0;
3603
+ }
3604
+ return typeof parsed === "object" && parsed !== null ? parsed : void 0;
3605
+ }
3606
+ function readKimiTranscript(path) {
3607
+ const turns = [];
3608
+ let remaining = MAX_SESSION_CHARS;
3609
+ for (const agentId of agentIds(path)) {
3610
+ const wire = join21(path, AGENTS_DIR, agentId, WIRE_LOG);
3611
+ const events = [];
3612
+ for (const rawLine of readJsonl(wire)) {
3613
+ remaining -= rawLine.length;
3614
+ if (remaining < 0) break;
3615
+ const event = parseEvent(rawLine);
3616
+ if (event) events.push(event);
3617
+ }
3618
+ for (const turn of readKimiWire(events)) turns.push(turn);
3619
+ if (remaining < 0) {
3620
+ log.warn(HARNESS, "session exceeds the wire-log budget \u2014 later agents were not read", {
3621
+ sessionDir: path,
3622
+ stoppedAt: wire
3623
+ });
3624
+ break;
3625
+ }
3626
+ }
3627
+ return turns;
3628
+ }
3629
+
3096
3630
  // src/harness/hook-lifecycle.ts
3097
3631
  var cursorCwd = (ev) => ev.cwd ?? ev.workspace_root ?? (Array.isArray(ev.workspace_roots) ? ev.workspace_roots[0] : void 0);
3098
3632
  var claudePrompt = {
@@ -3171,7 +3705,7 @@ var copilotPrompt = {
3171
3705
  ${context}`.trim()
3172
3706
  })
3173
3707
  };
3174
- var devinCwd = () => process.env.DEVIN_PROJECT_DIR;
3708
+ var devinCwd = () => process.env.DEVIN_PROJECT_DIR || process.cwd();
3175
3709
  var devinPrompt = {
3176
3710
  harness: "devin-cli",
3177
3711
  requireCwd: true,
@@ -3198,6 +3732,7 @@ var standardSessionStart = (harness) => ({
3198
3732
  }
3199
3733
  })
3200
3734
  });
3735
+ var notGrokHosted = () => !process.env.GROK_HOOK_EVENT;
3201
3736
  var HOOK_HARNESSES = {
3202
3737
  "claude-code": {
3203
3738
  configStyle: "nested",
@@ -3206,11 +3741,12 @@ var HOOK_HARNESSES = {
3206
3741
  prompt: { event: "UserPromptSubmit", entry: "claude-hook.js", timeout: 30 },
3207
3742
  stop: { event: "Stop", entry: "claude-stop-hook.js", timeout: 60 }
3208
3743
  },
3209
- sessionStart: standardSessionStart("claude-code"),
3210
- prompt: claudePrompt,
3744
+ sessionStart: { ...standardSessionStart("claude-code"), accept: notGrokHosted },
3745
+ prompt: { ...claudePrompt, accept: notGrokHosted },
3211
3746
  retain: {
3212
3747
  hostTimeoutSec: 60,
3213
3748
  harness: "claude-code",
3749
+ accept: notGrokHosted,
3214
3750
  parse: (ev) => ({
3215
3751
  sessionId: ev.session_id,
3216
3752
  transcriptPath: ev.transcript_path,
@@ -3431,7 +3967,7 @@ var HOOK_HARNESSES = {
3431
3967
  // `detached` and terminates the whole process TREE on timeout, so the retain is genuinely lost
3432
3968
  // rather than merely orphaned. `retain.hostTimeoutSec` below stays SECONDS, as its name says;
3433
3969
  // these two numbers are the same budget in different units for this harness alone.
3434
- // The prompt timeout must also stay above core/hook.ts's HOOK_REFLECT_CAP_MS (25_000).
3970
+ // The prompt timeout must also stay above core/config.ts's DEFAULT_REFLECT_TIMEOUT_MS.
3435
3971
  install: {
3436
3972
  sessionStart: { event: "SessionStart", entry: "qwen-sessionstart-hook.js", timeout: 3e4 },
3437
3973
  prompt: { event: "UserPromptSubmit", entry: "qwen-hook.js", timeout: 3e4 },
@@ -3493,7 +4029,7 @@ var HOOK_HARNESSES = {
3493
4029
  zcode: {
3494
4030
  configStyle: "process",
3495
4031
  // ZCode's `timeoutMs`, so MILLISECONDS — see the qwen-code note above for the same trap. The
3496
- // prompt budget must stay above core/hook.ts's HOOK_REFLECT_CAP_MS (25_000).
4032
+ // prompt budget must stay above core/config.ts's DEFAULT_REFLECT_TIMEOUT_MS.
3497
4033
  timeoutUnit: "milliseconds",
3498
4034
  install: {
3499
4035
  sessionStart: { event: "SessionStart", entry: "zcode-sessionstart-hook.js", timeout: 3e4 },
@@ -3526,37 +4062,148 @@ var HOOK_HARNESSES = {
3526
4062
  assistantText: (ev) => (ev.responseText || zcodeAssistantText(ev.transcript_path) || ev.responsePreview || "").trim()
3527
4063
  }
3528
4064
  }
4065
+ },
4066
+ /**
4067
+ * TraeCode (TRAE CN's agent) also speaks Claude Code's hook protocol — `prompt`/`cwd`/`session_id`
4068
+ * in, `hookSpecificOutput.additionalContext` + `systemMessage` out — with registrations nested
4069
+ * under the top-level `hooks` key of `~/.trae-cn/hooks.json` (unlike Factory Droid, whose event
4070
+ * map IS the file) and a `version` field the host writes and expects.
4071
+ *
4072
+ * Like ZCode, what it does not have is a TRANSCRIPT: sessions live in an encrypted local DB or
4073
+ * the cloud and no `transcript_path` is ever supplied, so this is the second harness that retains
4074
+ * from the plugin's own journal (core/turn-journal.ts) — the prompt hook appends the user turn,
4075
+ * and Stop's `last_assistant_message` (the full reply) plays the role ZCode's `responseText`
4076
+ * plays: `journal.assistantText` closes the turn with it.
4077
+ */
4078
+ traecode: {
4079
+ configStyle: "nested",
4080
+ install: {
4081
+ sessionStart: { event: "SessionStart", entry: "traecode-sessionstart-hook.js", timeout: 30 },
4082
+ prompt: { event: "UserPromptSubmit", entry: "traecode-hook.js", timeout: 30 },
4083
+ stop: { event: "Stop", entry: "traecode-stop-hook.js", timeout: 60 }
4084
+ },
4085
+ sessionStart: {
4086
+ ...standardSessionStart("traecode"),
4087
+ // Trae launches USER-level MCP servers from the Electron process's cwd (home), where an
4088
+ // optInOnly config self-disables and the tools vanish. Each repo's own workspace file fixes
4089
+ // it — kept current here, once memory is confirmed live for the repo, along with the
4090
+ // workspace's per-server enable switch (seeded into Trae's storage DB,
4091
+ // core/traecode-mcp.ts). The returned hint (global gate off, or an unseedable switch)
4092
+ // rides the session banner.
4093
+ ensureMcpRegistration: (cwd) => ensureTraecodeWorkspaceMcp(cwd)
4094
+ },
4095
+ prompt: {
4096
+ ...claudePrompt,
4097
+ harness: "traecode",
4098
+ journalPrompt: true,
4099
+ // TraeCode's UserPromptSubmit payload carries `prompt` exactly like Claude Code's.
4100
+ parse: (ev) => ({
4101
+ prompt: ev.prompt,
4102
+ cwd: ev.cwd,
4103
+ sessionId: ev.session_id
4104
+ })
4105
+ },
4106
+ retain: {
4107
+ hostTimeoutSec: 60,
4108
+ harness: "traecode",
4109
+ // No transcriptPath: the journal supplies it (see `journal` below).
4110
+ parse: (ev) => ({
4111
+ sessionId: ev.session_id,
4112
+ cwd: ev.cwd
4113
+ }),
4114
+ journal: {
4115
+ // `last_assistant_message` is the full reply — TraeCode's `responseText`.
4116
+ assistantText: (ev) => (ev.last_assistant_message ?? "").trim()
4117
+ }
4118
+ }
4119
+ },
4120
+ "kimi-code": {
4121
+ // Kimi's ~/.kimi-code/config.toml takes a FLAT [[hooks]] array whose entries are validated by a
4122
+ // strict 4-key schema (event/matcher/command/timeout). Neither JSON style can express it, and a
4123
+ // fifth key drops EVERY hook in the file at warning severity, so its installer writes the block
4124
+ // itself (the grok-build pattern) rather than going through mergeHarnessHooks.
4125
+ configStyle: "toml-array",
4126
+ install: {
4127
+ // Timeouts are SECONDS here (integer 1-600, default 30) — the same unit as every other
4128
+ // supported host, and the opposite of qwen-code's identically named field.
4129
+ sessionStart: { event: "SessionStart", entry: "kimi-sessionstart-hook.js", timeout: 30 },
4130
+ prompt: { event: "UserPromptSubmit", entry: "kimi-hook.js", timeout: 30 },
4131
+ stop: { event: "Stop", entry: "kimi-stop-hook.js", timeout: 60 }
4132
+ },
4133
+ sessionStart: {
4134
+ harness: "kimi-code",
4135
+ parse: (ev) => ({
4136
+ cwd: ev.cwd,
4137
+ sessionId: ev.session_id
4138
+ }),
4139
+ // Kimi runs SessionStart hooks for their side effects only: it awaits the trigger and drops
4140
+ // the result, so nothing emitted here can reach the model or the terminal. Installed for the
4141
+ // seed/daemon/session-root work runSessionStartHook does, and silent like antigravity-cli's.
4142
+ emit: () => ({})
4143
+ },
4144
+ prompt: {
4145
+ harness: "kimi-code",
4146
+ parse: (ev) => ({
4147
+ // A block array, not a string — the same shape as the wire log's `turn.prompt.input`.
4148
+ prompt: kimiPromptText(ev.prompt),
4149
+ cwd: ev.cwd,
4150
+ sessionId: ev.session_id
4151
+ }),
4152
+ // Kimi has no additionalContext: a top-level `message` is the injection channel, which the
4153
+ // CLI wraps as <hook_result hook_event="UserPromptSubmit"> and appends to the conversation.
4154
+ // `notice` has no banner channel to reach (the copilot-cli precedent), but it cannot simply
4155
+ // be dropped: when a hook's stdout parses to JSON carrying no message, Kimi falls back to
4156
+ // injecting the RAW STDOUT, so an empty `{}` would put a literal "{}" in front of the model.
4157
+ // Emitting the notice on the notice-only turn is what keeps that from ever happening.
4158
+ emit: (context, notice) => ({ message: context || notice })
4159
+ },
4160
+ retain: {
4161
+ hostTimeoutSec: 60,
4162
+ harness: "kimi-code",
4163
+ parse: (ev) => {
4164
+ const sessionId = ev.session_id;
4165
+ return {
4166
+ sessionId,
4167
+ // Kimi's Stop payload carries no transcript path — its hook feature has no such field at
4168
+ // all — so resolve the session's own directory from the id, as grok-build does. The
4169
+ // reader takes that DIRECTORY and reads every agent's wire.jsonl beneath it.
4170
+ transcriptPath: sessionId ? kimiSessionDir(sessionId) : void 0,
4171
+ cwd: ev.cwd
4172
+ };
4173
+ },
4174
+ readTranscript: readKimiTranscript
4175
+ }
3529
4176
  }
3530
4177
  };
3531
4178
 
3532
4179
  // src/core/history.ts
3533
- import { execFileSync as execFileSync4 } from "child_process";
4180
+ import { execFileSync as execFileSync5 } from "child_process";
3534
4181
  import {
3535
4182
  closeSync as closeSync2,
3536
- existsSync as existsSync9,
4183
+ existsSync as existsSync12,
3537
4184
  openSync as openSync2,
3538
- readdirSync as readdirSync3,
3539
- readFileSync as readFileSync14,
4185
+ readdirSync as readdirSync5,
4186
+ readFileSync as readFileSync15,
3540
4187
  readSync as readSync2,
3541
- statSync as statSync5
4188
+ statSync as statSync4
3542
4189
  } from "fs";
3543
4190
  import { createHash as createHash5 } from "crypto";
3544
- import { homedir as homedir10 } from "os";
3545
- import { join as join19 } from "path";
4191
+ import { homedir as homedir12 } from "os";
4192
+ import { join as join22 } from "path";
3546
4193
  import * as zlib2 from "zlib";
3547
4194
 
3548
4195
  // src/core/transcript-dsh.ts
3549
4196
  function textOf(message) {
3550
4197
  return (message.content || []).filter((block) => block?.type === "text" && typeof block.text === "string").map((block) => block.text).join("\n").trim();
3551
4198
  }
3552
- function stampOf(event) {
4199
+ function stampOf3(event) {
3553
4200
  return typeof event.time === "number" ? { timestamp: new Date(event.time).toISOString() } : {};
3554
4201
  }
3555
4202
  function readDshEvents(events) {
3556
4203
  const turns = [];
3557
4204
  for (const event of events || []) {
3558
4205
  if (!event || typeof event !== "object") continue;
3559
- const stamp = stampOf(event);
4206
+ const stamp = stampOf3(event);
3560
4207
  if (event.type === "user/message") {
3561
4208
  const message = event.data;
3562
4209
  if (!message || message.source?.kind !== "user") continue;
@@ -3572,14 +4219,14 @@ function readDshEvents(events) {
3572
4219
  if (!call?.name) continue;
3573
4220
  turns.push({
3574
4221
  role: "action",
3575
- content: actionLine(call.name, parseArgs(call.arguments)),
4222
+ content: actionLine(call.name, parseArgs2(call.arguments)),
3576
4223
  ...stamp
3577
4224
  });
3578
4225
  }
3579
4226
  }
3580
4227
  return turns;
3581
4228
  }
3582
- function parseArgs(raw) {
4229
+ function parseArgs2(raw) {
3583
4230
  if (!raw) return void 0;
3584
4231
  try {
3585
4232
  return JSON.parse(raw);
@@ -3618,7 +4265,7 @@ function renderMessage(m) {
3618
4265
  }
3619
4266
  function readPiTranscript(path) {
3620
4267
  const turns = [];
3621
- for (const rawLine of readJsonlTail(path, { scope: "pi" }).lines) {
4268
+ for (const rawLine of readJsonl(path)) {
3622
4269
  const trimmed = rawLine.trim();
3623
4270
  if (!trimmed) continue;
3624
4271
  let parsed;
@@ -3686,8 +4333,8 @@ function zstdDecompressFrames(buffer) {
3686
4333
  }
3687
4334
 
3688
4335
  // src/core/history.ts
3689
- function claudeProjectDir(repoDir, home = homedir10()) {
3690
- return join19(home, ".claude", "projects", repoDir.replace(/[^a-zA-Z0-9]/g, "-"));
4336
+ function claudeProjectDir(repoDir, home = homedir12()) {
4337
+ return join22(home, ".claude", "projects", repoDir.replace(/[^a-zA-Z0-9]/g, "-"));
3691
4338
  }
3692
4339
  function piSessionDir(repoDir) {
3693
4340
  return `--${repoDir.replace(/^[/\\]/, "").replace(/[/\\:]/g, "-")}--`;
@@ -3697,7 +4344,7 @@ function withinRepo(dir, repoDir) {
3697
4344
  }
3698
4345
  function claudeSessionCwd(file) {
3699
4346
  try {
3700
- for (const line of readFileSync14(file, "utf8").split("\n", 400)) {
4347
+ for (const line of readFileSync15(file, "utf8").split("\n", 400)) {
3701
4348
  if (!line.includes('"cwd"')) continue;
3702
4349
  const cwd = JSON.parse(line).cwd;
3703
4350
  if (cwd) return cwd;
@@ -3733,19 +4380,19 @@ function firstLine(path, cap = 1e6) {
3733
4380
  }
3734
4381
  function listDir(dir) {
3735
4382
  try {
3736
- return readdirSync3(dir);
4383
+ return readdirSync5(dir);
3737
4384
  } catch {
3738
4385
  return [];
3739
4386
  }
3740
4387
  }
3741
4388
  function jsonlFiles(dir) {
3742
- return listDir(dir).filter((f) => f.endsWith(".jsonl")).map((f) => join19(dir, f));
4389
+ return listDir(dir).filter((f) => f.endsWith(".jsonl")).map((f) => join22(dir, f));
3743
4390
  }
3744
4391
  function claudeHistory(repoDir, home) {
3745
- const root = join19(home, ".claude", "projects");
4392
+ const root = join22(home, ".claude", "projects");
3746
4393
  const exact = claudeProjectDir(repoDir, home);
3747
4394
  const prefix = exact + "-";
3748
- const dirs = listDir(root).map((d) => join19(root, d)).filter((d) => d === exact || d.startsWith(prefix));
4395
+ const dirs = listDir(root).map((d) => join22(root, d)).filter((d) => d === exact || d.startsWith(prefix));
3749
4396
  const sessions = [];
3750
4397
  let unattributed = 0;
3751
4398
  for (const file of dirs.flatMap(jsonlFiles)) {
@@ -3765,13 +4412,13 @@ function claudeHistory(repoDir, home) {
3765
4412
  return { supported: true, sessions, unattributed };
3766
4413
  }
3767
4414
  function codexHistory(repoDir, home) {
3768
- const root = join19(home, ".codex", "sessions");
3769
- if (!existsSync9(root)) return { supported: true, sessions: [] };
4415
+ const root = join22(home, ".codex", "sessions");
4416
+ if (!existsSync12(root)) return { supported: true, sessions: [] };
3770
4417
  const files = [];
3771
4418
  const walk = (dir) => {
3772
- for (const entry of readdirSync3(dir)) {
3773
- const p = join19(dir, entry);
3774
- if (statSync5(p).isDirectory()) walk(p);
4419
+ for (const entry of readdirSync5(dir)) {
4420
+ const p = join22(dir, entry);
4421
+ if (statSync4(p).isDirectory()) walk(p);
3775
4422
  else if (entry.endsWith(".jsonl")) files.push(p);
3776
4423
  }
3777
4424
  };
@@ -3799,15 +4446,15 @@ function dcodeTranscriptPath(root, threadId) {
3799
4446
  const digest = createHash5("sha256").update(threadId, "utf8").digest("hex");
3800
4447
  const suffix = `--${digest}.jsonl`;
3801
4448
  try {
3802
- const match = readdirSync3(root).find((entry) => entry.endsWith(suffix));
3803
- return match ? join19(root, match) : void 0;
4449
+ const match = readdirSync5(root).find((entry) => entry.endsWith(suffix));
4450
+ return match ? join22(root, match) : void 0;
3804
4451
  } catch {
3805
4452
  return void 0;
3806
4453
  }
3807
4454
  }
3808
4455
  function dcodeHistory(repoDir, home, runCli) {
3809
- const root = join19(process.env.DEEPAGENTS_HOME || join19(home, ".deepagents"), "transcripts");
3810
- if (!existsSync9(root)) return { supported: true, sessions: [] };
4456
+ const root = join22(process.env.DEEPAGENTS_HOME || join22(home, ".deepagents"), "transcripts");
4457
+ if (!existsSync12(root)) return { supported: true, sessions: [] };
3811
4458
  let listed;
3812
4459
  try {
3813
4460
  listed = JSON.parse(runCli(["threads", "list", "--json"]));
@@ -3847,8 +4494,8 @@ function dcodeHistory(repoDir, home, runCli) {
3847
4494
  return { supported: true, sessions, ...unattributed ? { unattributed } : {} };
3848
4495
  }
3849
4496
  function dshHistory(repoDir, home) {
3850
- const root = process.env.DSH_HOME ? join19(process.env.DSH_HOME, "sessions") : join19(home, ".dsh", "sessions");
3851
- if (!existsSync9(root)) return { supported: true, sessions: [] };
4497
+ const root = process.env.DSH_HOME ? join22(process.env.DSH_HOME, "sessions") : join22(home, ".dsh", "sessions");
4498
+ if (!existsSync12(root)) return { supported: true, sessions: [] };
3852
4499
  if (typeof zlib2.zstdDecompressSync !== "function") {
3853
4500
  return {
3854
4501
  supported: false,
@@ -3858,15 +4505,15 @@ function dshHistory(repoDir, home) {
3858
4505
  }
3859
4506
  const sessions = [];
3860
4507
  let unattributed = 0;
3861
- for (const dir of readdirSync3(root).map((project) => join19(root, project))) {
4508
+ for (const dir of readdirSync5(root).map((project) => join22(root, project))) {
3862
4509
  let sessionDirs;
3863
4510
  try {
3864
- sessionDirs = readdirSync3(dir).map((id) => join19(dir, id));
4511
+ sessionDirs = readdirSync5(dir).map((id) => join22(dir, id));
3865
4512
  } catch {
3866
4513
  continue;
3867
4514
  }
3868
4515
  for (const sessionDir of sessionDirs) {
3869
- const file = ["session.jsonl.zstd", "session.jsonl"].map((name) => join19(sessionDir, name)).find((candidate) => existsSync9(candidate));
4516
+ const file = ["session.jsonl.zstd", "session.jsonl"].map((name) => join22(sessionDir, name)).find((candidate) => existsSync12(candidate));
3870
4517
  if (!file) continue;
3871
4518
  try {
3872
4519
  const lines = readDshLog(file);
@@ -3892,7 +4539,7 @@ function dshHistory(repoDir, home) {
3892
4539
  return { supported: true, sessions, unattributed };
3893
4540
  }
3894
4541
  function readDshLog(file) {
3895
- const bytes = readFileSync14(file);
4542
+ const bytes = readFileSync15(file);
3896
4543
  const text = file.endsWith(".zstd") ? zstdDecompressFrames(bytes) : bytes.toString("utf8");
3897
4544
  return text.split("\n").filter((line) => line.trim());
3898
4545
  }
@@ -3918,23 +4565,23 @@ function piFamilySessions(files, repoDir) {
3918
4565
  return { supported: true, sessions, unattributed };
3919
4566
  }
3920
4567
  function piHistory(repoDir, home) {
3921
- const root = join19(home, ".pi", "agent", "sessions");
3922
- if (!existsSync9(root)) return { supported: true, sessions: [] };
4568
+ const root = join22(home, ".pi", "agent", "sessions");
4569
+ if (!existsSync12(root)) return { supported: true, sessions: [] };
3923
4570
  const exact = piSessionDir(repoDir);
3924
4571
  const nested = `${exact.slice(0, -2)}-`;
3925
4572
  const files = [];
3926
4573
  for (const dir of listDir(root).filter((d) => d === exact || d.startsWith(nested))) {
3927
- files.push(...jsonlFiles(join19(root, dir)));
4574
+ files.push(...jsonlFiles(join22(root, dir)));
3928
4575
  }
3929
4576
  return piFamilySessions(files, repoDir);
3930
4577
  }
3931
4578
  function primeAgentHistory(repoDir, home) {
3932
- const root = join19(home, ".prime", "agent", "sessions");
3933
- if (!existsSync9(root)) return { supported: true, sessions: [] };
4579
+ const root = join22(home, ".prime", "agent", "sessions");
4580
+ if (!existsSync12(root)) return { supported: true, sessions: [] };
3934
4581
  return piFamilySessions(jsonlFiles(root), repoDir);
3935
4582
  }
3936
4583
  var SQLITE_HISTORY = "keeps session history in an internal SQLite database, whose schema is unversioned and would break on any upstream change";
3937
- function importLocalHistory(harness, repoDir, home = homedir10(), runDcodeCli) {
4584
+ function importLocalHistory(harness, repoDir, home = homedir12(), runDcodeCli) {
3938
4585
  switch (harness) {
3939
4586
  case "claude-code":
3940
4587
  return claudeHistory(repoDir, home);
@@ -3944,7 +4591,7 @@ function importLocalHistory(harness, repoDir, home = homedir10(), runDcodeCli) {
3944
4591
  return dcodeHistory(
3945
4592
  repoDir,
3946
4593
  home,
3947
- runDcodeCli ?? ((args) => execFileSync4("dcode", args, { encoding: "utf8", stdio: ["ignore", "pipe", "ignore"] }))
4594
+ runDcodeCli ?? ((args) => execFileSync5("dcode", args, { encoding: "utf8", stdio: ["ignore", "pipe", "ignore"] }))
3948
4595
  );
3949
4596
  case "dsh":
3950
4597
  return dshHistory(repoDir, home);
@@ -3961,10 +4608,14 @@ function importLocalHistory(harness, repoDir, home = homedir10(), runDcodeCli) {
3961
4608
  case "copilot-cli":
3962
4609
  case "devin-cli":
3963
4610
  return { supported: false, reason: `${harness} ${SQLITE_HISTORY}`, sessions: [] };
4611
+ // TraeCode has no reader for the same reason as ZCode below: no session files on disk at all
4612
+ // (sessions live in an encrypted local DB / the cloud), which is why the plugin journals live
4613
+ // sessions itself (core/turn-journal.ts) — and why there is no past history to backfill from.
4614
+ case "traecode":
3964
4615
  case "zcode":
3965
4616
  return {
3966
4617
  supported: false,
3967
- reason: "ZCode keeps no session transcripts on disk to import",
4618
+ reason: `${harness} keeps no session transcripts on disk to import`,
3968
4619
  sessions: []
3969
4620
  };
3970
4621
  default:
@@ -3973,7 +4624,7 @@ function importLocalHistory(harness, repoDir, home = homedir10(), runDcodeCli) {
3973
4624
  }
3974
4625
 
3975
4626
  // src/install-ui.ts
3976
- import { execFileSync as execFileSync5 } from "child_process";
4627
+ import { execFileSync as execFileSync6 } from "child_process";
3977
4628
  import { readSync as readSync3 } from "fs";
3978
4629
  function fitSelectRow(label, hint, width) {
3979
4630
  const room = Math.max(10, width - 6);
@@ -4068,7 +4719,7 @@ function createInstallerUi(o) {
4068
4719
  return `${bar} ${question}`;
4069
4720
  },
4070
4721
  select(question, options, defaultIndex) {
4071
- const stty = (args) => execFileSync5("stty", args, { stdio: ["inherit", "pipe", "pipe"], encoding: "utf8" }).trim();
4722
+ const stty = (args) => execFileSync6("stty", args, { stdio: ["inherit", "pipe", "pipe"], encoding: "utf8" }).trim();
4072
4723
  let savedTty;
4073
4724
  try {
4074
4725
  savedTty = stty(["-g"]);
@@ -4177,10 +4828,14 @@ function createInstallerUi(o) {
4177
4828
  // src/installer.ts
4178
4829
  var MARKER = "coding-agents";
4179
4830
  var ZCODE_MAX_OUTPUT_BYTES = 32768;
4180
- var zcodeConfigPath = (c) => join20(c.home, ".zcode", "cli", "config.json");
4831
+ var zcodeConfigPath = (c) => join23(c.home, ".zcode", "cli", "config.json");
4832
+ function isPlainObject(value) {
4833
+ return value !== null && typeof value === "object" && !Array.isArray(value);
4834
+ }
4181
4835
  function readJson(path) {
4182
4836
  try {
4183
- return JSON.parse(readFileSync15(path, "utf8"));
4837
+ const parsed = JSON.parse(readFileSync16(path, "utf8"));
4838
+ return isPlainObject(parsed) ? parsed : {};
4184
4839
  } catch {
4185
4840
  return {};
4186
4841
  }
@@ -4195,17 +4850,17 @@ function parseJsonc(text) {
4195
4850
  }
4196
4851
  }
4197
4852
  function writeJson(path, value) {
4198
- mkdirSync6(dirname11(path), { recursive: true });
4853
+ mkdirSync7(dirname12(path), { recursive: true });
4199
4854
  backupOnce(path);
4200
- writeFileSync4(path, JSON.stringify(value, null, 2) + "\n");
4855
+ writeFileSync5(path, JSON.stringify(value, null, 2) + "\n");
4201
4856
  }
4202
4857
  function backupOnce(path) {
4203
- if (existsSync10(path) && !existsSync10(`${path}.hindsight-backup`)) {
4858
+ if (existsSync13(path) && !existsSync13(`${path}.hindsight-backup`)) {
4204
4859
  copyFileSync(path, `${path}.hindsight-backup`);
4205
4860
  }
4206
4861
  }
4207
4862
  function writeJsonc(path, key, value) {
4208
- const text = existsSync10(path) ? readFileSync15(path, "utf8") : "";
4863
+ const text = existsSync13(path) ? readFileSync16(path, "utf8") : "";
4209
4864
  const edits = modify(text, [key], value, {
4210
4865
  formattingOptions: {
4211
4866
  tabSize: 2,
@@ -4216,9 +4871,9 @@ function writeJsonc(path, key, value) {
4216
4871
  }
4217
4872
  });
4218
4873
  const next = applyEdits(text, edits);
4219
- mkdirSync6(dirname11(path), { recursive: true });
4874
+ mkdirSync7(dirname12(path), { recursive: true });
4220
4875
  backupOnce(path);
4221
- writeFileSync4(path, next.endsWith("\n") ? next : `${next}
4876
+ writeFileSync5(path, next.endsWith("\n") ? next : `${next}
4222
4877
  `);
4223
4878
  }
4224
4879
  function mergeHookEvent(existing, entry) {
@@ -4233,33 +4888,26 @@ function setOrDelete(obj, key, arr) {
4233
4888
  else delete obj[key];
4234
4889
  }
4235
4890
  var cmdHook = (dist, file, timeout) => ({
4236
- hooks: [{ type: "command", command: `node "${join20(dist, file)}"`, timeout }]
4891
+ hooks: [{ type: "command", command: `node "${join23(dist, file)}"`, timeout }]
4237
4892
  });
4238
4893
  var processHook = (dist, file, timeoutMs) => ({
4239
- hooks: [{ type: "process", command: "node", args: [join20(dist, file)], timeoutMs }]
4894
+ hooks: [{ type: "process", command: "node", args: [join23(dist, file)], timeoutMs }]
4240
4895
  });
4241
- var mcpServerEntry = (dist, harness) => ({
4896
+ var mcpServerEntry = (dist, harness, extraArgs = []) => ({
4242
4897
  command: "node",
4243
- args: [join20(dist, "mcp-server.js")],
4898
+ args: [join23(dist, "mcp-server.js"), ...extraArgs],
4244
4899
  env: { HINDSIGHT_MCP_HARNESS: harness }
4245
4900
  });
4246
- function isOurMcpEntry(entry) {
4247
- if (!entry || typeof entry !== "object") return false;
4248
- const candidate = entry;
4249
- if (candidate.command !== "node" || !Array.isArray(candidate.args)) return false;
4250
- const script = candidate.args[0];
4251
- if (typeof script !== "string") return false;
4252
- const parts = script.replaceAll("\\", "/").split("/").filter(Boolean);
4253
- return parts.at(-1) === "mcp-server.js" && parts.at(-2) === "dist" && (parts.at(-3) === "coding-agents" || parts.at(-3) === "hindsight-coding-agents");
4254
- }
4255
4901
  function mergeHarnessHooks(hooks, harness, dist) {
4256
4902
  const spec = HOOK_HARNESSES[harness];
4903
+ if (spec.configStyle === "toml-array")
4904
+ throw new Error(`${harness} writes its own TOML hook block; mergeHarnessHooks cannot emit it`);
4257
4905
  const installedEvents = /* @__PURE__ */ new Set();
4258
4906
  for (const hook of [...Object.values(spec.install), ...spec.additionalHooks ?? []]) {
4259
4907
  if (installedEvents.has(hook.event)) continue;
4260
4908
  installedEvents.add(hook.event);
4261
4909
  const entry = spec.configStyle === "nested" ? cmdHook(dist, hook.entry, hook.timeout) : spec.configStyle === "process" ? processHook(dist, hook.entry, hook.timeout) : {
4262
- command: `node "${join20(dist, hook.entry)}"`,
4910
+ command: `node "${join23(dist, hook.entry)}"`,
4263
4911
  ...hook.timeout ? { timeout: hook.timeout } : {}
4264
4912
  };
4265
4913
  hooks[hook.event] = mergeHookEvent(hooks[hook.event], entry);
@@ -4275,28 +4923,28 @@ function stripHarnessHooks(hooks, harness) {
4275
4923
  }
4276
4924
  }
4277
4925
  function skillsBaseFor(c, harness) {
4278
- const parts = SKILL_DIRS[harness];
4926
+ const parts = resolveSkillDirs(harness, c.home);
4279
4927
  if (!parts) throw new Error(`${harness} installs a skill but names no directory in SKILL_DIRS`);
4280
- return join20(c.home, ...parts);
4928
+ return join23(c.home, ...parts);
4281
4929
  }
4282
4930
  function installSkill(c, harness) {
4283
- const src = join20(c.pkgRoot, "skill");
4284
- if (!existsSync10(join20(src, "SKILL.md"))) return;
4931
+ const src = join23(c.pkgRoot, "skill");
4932
+ if (!existsSync13(join23(src, "SKILL.md"))) return;
4285
4933
  const skillsBase = skillsBaseFor(c, harness);
4286
- const dst = join20(skillsBase, "hindsight-coding-agent");
4287
- mkdirSync6(skillsBase, { recursive: true });
4934
+ const dst = join23(skillsBase, "hindsight-coding-agent");
4935
+ mkdirSync7(skillsBase, { recursive: true });
4288
4936
  cpSync2(src, dst, { recursive: true });
4289
4937
  c.log?.(`${harness}: skill installed at ${dst}`);
4290
4938
  }
4291
4939
  function uninstallSkill(c, harness) {
4292
- rmSync3(join20(skillsBaseFor(c, harness), "hindsight-coding-agent"), {
4940
+ rmSync4(join23(skillsBaseFor(c, harness), "hindsight-coding-agent"), {
4293
4941
  recursive: true,
4294
4942
  force: true
4295
4943
  });
4296
4944
  }
4297
4945
  function onPath2(bin) {
4298
4946
  try {
4299
- execFileSync6("which", [bin], { stdio: "pipe" });
4947
+ execFileSync7("which", [bin], { stdio: "pipe" });
4300
4948
  return true;
4301
4949
  } catch {
4302
4950
  return false;
@@ -4304,7 +4952,7 @@ function onPath2(bin) {
4304
4952
  }
4305
4953
  function runClinePlugin(args) {
4306
4954
  try {
4307
- execFileSync6("cline", args, { stdio: "pipe" });
4955
+ execFileSync7("cline", args, { stdio: "pipe" });
4308
4956
  return true;
4309
4957
  } catch {
4310
4958
  return false;
@@ -4312,13 +4960,13 @@ function runClinePlugin(args) {
4312
4960
  }
4313
4961
  var OPENCODE_CONFIG_CANDIDATES = ["opencode.jsonc", "opencode.json"];
4314
4962
  function opencodeConfigPath(c) {
4315
- const dir = join20(c.home, ".config", "opencode");
4316
- const existing = OPENCODE_CONFIG_CANDIDATES.map((f) => join20(dir, f)).find((p) => existsSync10(p));
4317
- return existing ?? join20(dir, "opencode.json");
4963
+ const dir = join23(c.home, ".config", "opencode");
4964
+ const existing = OPENCODE_CONFIG_CANDIDATES.map((f) => join23(dir, f)).find((p) => existsSync13(p));
4965
+ return existing ?? join23(dir, "opencode.json");
4318
4966
  }
4319
4967
  function runDcodePlugin(args) {
4320
4968
  try {
4321
- execFileSync6("dcode", args, { stdio: "pipe" });
4969
+ execFileSync7("dcode", args, { stdio: "pipe" });
4322
4970
  return true;
4323
4971
  } catch {
4324
4972
  return false;
@@ -4327,8 +4975,8 @@ function runDcodePlugin(args) {
4327
4975
  function registerOpencodePlugin(c, name) {
4328
4976
  const path = opencodeConfigPath(c);
4329
4977
  let cfg = {};
4330
- if (existsSync10(path)) {
4331
- const parsed = parseJsonc(readFileSync15(path, "utf8"));
4978
+ if (existsSync13(path)) {
4979
+ const parsed = parseJsonc(readFileSync16(path, "utf8"));
4332
4980
  if (!parsed) {
4333
4981
  c.log?.(`${name}: SKIPPED \u2014 could not parse ${path}; add the plugin entry manually`);
4334
4982
  return;
@@ -4341,8 +4989,8 @@ function registerOpencodePlugin(c, name) {
4341
4989
  }
4342
4990
  function unregisterOpencodePlugin(c, name) {
4343
4991
  const path = opencodeConfigPath(c);
4344
- if (!existsSync10(path)) return;
4345
- const cfg = parseJsonc(readFileSync15(path, "utf8"));
4992
+ if (!existsSync13(path)) return;
4993
+ const cfg = parseJsonc(readFileSync16(path, "utf8"));
4346
4994
  if (!cfg || !Array.isArray(cfg.plugin)) return;
4347
4995
  const kept = cfg.plugin.filter((p) => !String(p).includes(MARKER));
4348
4996
  writeJsonc(path, "plugin", kept.length ? kept : void 0);
@@ -4350,7 +4998,7 @@ function unregisterOpencodePlugin(c, name) {
4350
4998
  }
4351
4999
  var opencode = {
4352
5000
  name: "opencode",
4353
- detect: (c) => onPath2("opencode") || existsSync10(join20(c.home, ".config", "opencode")),
5001
+ detect: (c) => onPath2("opencode") || existsSync13(join23(c.home, ".config", "opencode")),
4354
5002
  install: (c) => registerOpencodePlugin(c, "opencode"),
4355
5003
  uninstall: (c) => unregisterOpencodePlugin(c, "opencode")
4356
5004
  };
@@ -4361,16 +5009,16 @@ var opencode2 = {
4361
5009
  uninstall: (c) => unregisterOpencodePlugin(c, "opencode2")
4362
5010
  };
4363
5011
  function piFamilyInstaller(harness, configDir) {
4364
- const settings = (c) => join20(c.home, ...configDir, "settings.json");
5012
+ const settings = (c) => join23(c.home, ...configDir, "settings.json");
4365
5013
  return {
4366
5014
  name: harness,
4367
5015
  // Both hosts name their executable exactly as we name the harness, so the harness id doubles
4368
5016
  // as the PATH probe here — unlike, say, antigravity-cli, whose binary is `agy`.
4369
- detect: (c) => onPath2(harness) || existsSync10(join20(c.home, ...configDir)),
5017
+ detect: (c) => onPath2(harness) || existsSync13(join23(c.home, ...configDir)),
4370
5018
  install(c) {
4371
5019
  const path = settings(c);
4372
5020
  const cfg = readJson(path);
4373
- const entry = join20(c.pkgRoot, "dist", `${harness}.js`);
5021
+ const entry = join23(c.pkgRoot, "dist", `${harness}.js`);
4374
5022
  const exts = Array.isArray(cfg.extensions) ? cfg.extensions : [];
4375
5023
  cfg.extensions = [...exts.filter((p) => !String(p).includes(MARKER)), entry];
4376
5024
  writeJson(path, cfg);
@@ -4380,7 +5028,7 @@ function piFamilyInstaller(harness, configDir) {
4380
5028
  uninstall(c) {
4381
5029
  uninstallSkill(c, harness);
4382
5030
  const path = settings(c);
4383
- if (!existsSync10(path)) return;
5031
+ if (!existsSync13(path)) return;
4384
5032
  const cfg = readJson(path);
4385
5033
  if (Array.isArray(cfg.extensions)) {
4386
5034
  cfg.extensions = cfg.extensions.filter((p) => !String(p).includes(MARKER));
@@ -4395,33 +5043,33 @@ var pi = piFamilyInstaller("pi", [".pi", "agent"]);
4395
5043
  var primeAgent = piFamilyInstaller("prime-agent", [".prime", "agent"]);
4396
5044
  var KILO_CONFIG_CANDIDATES = ["kilo.jsonc", "kilo.json", "opencode.json"];
4397
5045
  function kiloConfigPath(c) {
4398
- const dir = join20(c.home, ".config", "kilo");
4399
- const existing = KILO_CONFIG_CANDIDATES.map((f) => join20(dir, f)).find((p) => existsSync10(p));
4400
- return existing ?? join20(dir, "kilo.json");
5046
+ const dir = join23(c.home, ".config", "kilo");
5047
+ const existing = KILO_CONFIG_CANDIDATES.map((f) => join23(dir, f)).find((p) => existsSync13(p));
5048
+ return existing ?? join23(dir, "kilo.json");
4401
5049
  }
4402
5050
  var kilo = {
4403
5051
  name: "kilo",
4404
- detect: (c) => onPath2("kilo") || existsSync10(join20(c.home, ".config", "kilo")),
5052
+ detect: (c) => onPath2("kilo") || existsSync13(join23(c.home, ".config", "kilo")),
4405
5053
  install(c) {
4406
5054
  const path = kiloConfigPath(c);
4407
5055
  let cfg = {};
4408
- if (existsSync10(path)) {
4409
- const parsed = parseJsonc(readFileSync15(path, "utf8"));
5056
+ if (existsSync13(path)) {
5057
+ const parsed = parseJsonc(readFileSync16(path, "utf8"));
4410
5058
  if (!parsed) {
4411
5059
  c.log?.(`kilo: SKIPPED \u2014 could not parse ${path}; add the plugin entry manually`);
4412
5060
  return;
4413
5061
  }
4414
5062
  cfg = parsed;
4415
5063
  }
4416
- const entry = pathToFileURL(join20(c.dist, "kilo.js")).href;
5064
+ const entry = pathToFileURL(join23(c.dist, "kilo.js")).href;
4417
5065
  const plugins = Array.isArray(cfg.plugin) ? cfg.plugin : [];
4418
5066
  writeJsonc(path, "plugin", [...plugins.filter((p) => !String(p).includes(MARKER)), entry]);
4419
5067
  c.log?.(`kilo: plugin registered in ${path}`);
4420
5068
  },
4421
5069
  uninstall(c) {
4422
5070
  const path = kiloConfigPath(c);
4423
- if (!existsSync10(path)) return;
4424
- const cfg = parseJsonc(readFileSync15(path, "utf8"));
5071
+ if (!existsSync13(path)) return;
5072
+ const cfg = parseJsonc(readFileSync16(path, "utf8"));
4425
5073
  if (!cfg || !Array.isArray(cfg.plugin)) return;
4426
5074
  const kept = cfg.plugin.filter((p) => !String(p).includes(MARKER));
4427
5075
  writeJsonc(path, "plugin", kept.length ? kept : void 0);
@@ -4430,9 +5078,9 @@ var kilo = {
4430
5078
  };
4431
5079
  var claudeCode = {
4432
5080
  name: "claude-code",
4433
- detect: (c) => onPath2("claude") || existsSync10(join20(c.home, ".claude")),
5081
+ detect: (c) => onPath2("claude") || existsSync13(join23(c.home, ".claude")),
4434
5082
  install(c) {
4435
- const path = join20(c.home, ".claude", "settings.json");
5083
+ const path = join23(c.home, ".claude", "settings.json");
4436
5084
  const settings = readJson(path);
4437
5085
  settings.hooks = settings.hooks ?? {};
4438
5086
  mergeHarnessHooks(settings.hooks, "claude-code", c.dist);
@@ -4451,19 +5099,19 @@ var claudeCode = {
4451
5099
  "HINDSIGHT_MCP_HARNESS=claude-code",
4452
5100
  "--",
4453
5101
  "node",
4454
- join20(c.dist, "mcp-server.js")
5102
+ join23(c.dist, "mcp-server.js")
4455
5103
  ])) {
4456
5104
  c.log?.("claude-code: MCP server registered (claude mcp add, user scope)");
4457
5105
  } else {
4458
5106
  c.log?.(
4459
5107
  `claude-code: could not run \`claude mcp add\` \u2014 register the tools manually:
4460
- claude mcp add --scope user hindsight --env HINDSIGHT_MCP_HARNESS=claude-code -- node "${join20(c.dist, "mcp-server.js")}"`
5108
+ claude mcp add --scope user hindsight --env HINDSIGHT_MCP_HARNESS=claude-code -- node "${join23(c.dist, "mcp-server.js")}"`
4461
5109
  );
4462
5110
  }
4463
5111
  },
4464
5112
  uninstall(c) {
4465
- const path = join20(c.home, ".claude", "settings.json");
4466
- if (existsSync10(path)) {
5113
+ const path = join23(c.home, ".claude", "settings.json");
5114
+ if (existsSync13(path)) {
4467
5115
  const settings = readJson(path);
4468
5116
  if (settings.hooks) {
4469
5117
  stripHarnessHooks(settings.hooks, "claude-code");
@@ -4479,7 +5127,7 @@ var claudeCode = {
4479
5127
  };
4480
5128
  function defaultClaudeMcp(args) {
4481
5129
  try {
4482
- execFileSync6("claude", args, { stdio: "pipe" });
5130
+ execFileSync7("claude", args, { stdio: "pipe" });
4483
5131
  return true;
4484
5132
  } catch {
4485
5133
  return false;
@@ -4488,20 +5136,20 @@ function defaultClaudeMcp(args) {
4488
5136
  var CODEX_MCP_BLOCK_RE = /^\[mcp_servers\.hindsight(?:\.[^\]]+)?\][^\n]*\n(?:(?!\[)[^\n]*\n?)*/gm;
4489
5137
  var codexMcpBlock = (dist) => `[mcp_servers.hindsight]
4490
5138
  command = "node"
4491
- args = [${JSON.stringify(join20(dist, "mcp-server.js"))}]
5139
+ args = [${JSON.stringify(join23(dist, "mcp-server.js"))}]
4492
5140
  env = { HINDSIGHT_MCP_HARNESS = "codex" }`;
4493
5141
  var codex = {
4494
5142
  name: "codex",
4495
- detect: (c) => onPath2("codex") || existsSync10(join20(c.home, ".codex")),
5143
+ detect: (c) => onPath2("codex") || existsSync13(join23(c.home, ".codex")),
4496
5144
  install(c) {
4497
- const hooksPath = join20(c.home, ".codex", "hooks.json");
5145
+ const hooksPath = join23(c.home, ".codex", "hooks.json");
4498
5146
  const cfg = readJson(hooksPath);
4499
5147
  cfg.hooks = cfg.hooks ?? {};
4500
5148
  mergeHarnessHooks(cfg.hooks, "codex", c.dist);
4501
5149
  writeJson(hooksPath, cfg);
4502
5150
  c.log?.(`codex: hooks merged into ${hooksPath}`);
4503
- const tomlPath = join20(c.home, ".codex", "config.toml");
4504
- const existing = existsSync10(tomlPath) ? readFileSync15(tomlPath, "utf8") : "";
5151
+ const tomlPath = join23(c.home, ".codex", "config.toml");
5152
+ const existing = existsSync13(tomlPath) ? readFileSync16(tomlPath, "utf8") : "";
4505
5153
  const toml = existing.replace(CODEX_MCP_BLOCK_RE, "");
4506
5154
  const additions = [];
4507
5155
  if (!/^\s*(codex_hooks|hooks)\s*=/m.test(toml)) {
@@ -4517,18 +5165,18 @@ var codex = {
4517
5165
  const next = `${toml.replace(/\n*$/, "\n\n")}${additions.join("\n\n")}
4518
5166
  `;
4519
5167
  if (next !== existing) {
4520
- if (existsSync10(tomlPath) && !existsSync10(`${tomlPath}.hindsight-backup`)) {
5168
+ if (existsSync13(tomlPath) && !existsSync13(`${tomlPath}.hindsight-backup`)) {
4521
5169
  copyFileSync(tomlPath, `${tomlPath}.hindsight-backup`);
4522
5170
  }
4523
- mkdirSync6(dirname11(tomlPath), { recursive: true });
4524
- writeFileSync4(tomlPath, next);
5171
+ mkdirSync7(dirname12(tomlPath), { recursive: true });
5172
+ writeFileSync5(tomlPath, next);
4525
5173
  c.log?.(`codex: wrote ${additions.length} section(s) to ${tomlPath}`);
4526
5174
  }
4527
5175
  installSkill(c, "codex");
4528
5176
  },
4529
5177
  uninstall(c) {
4530
- const hooksPath = join20(c.home, ".codex", "hooks.json");
4531
- if (existsSync10(hooksPath)) {
5178
+ const hooksPath = join23(c.home, ".codex", "hooks.json");
5179
+ if (existsSync13(hooksPath)) {
4532
5180
  const cfg = readJson(hooksPath);
4533
5181
  if (cfg.hooks) {
4534
5182
  stripHarnessHooks(cfg.hooks, "codex");
@@ -4536,11 +5184,11 @@ var codex = {
4536
5184
  }
4537
5185
  }
4538
5186
  uninstallSkill(c, "codex");
4539
- const tomlPath = join20(c.home, ".codex", "config.toml");
4540
- if (existsSync10(tomlPath)) {
4541
- const toml = readFileSync15(tomlPath, "utf8");
5187
+ const tomlPath = join23(c.home, ".codex", "config.toml");
5188
+ if (existsSync13(tomlPath)) {
5189
+ const toml = readFileSync16(tomlPath, "utf8");
4542
5190
  const cleaned = toml.replace(CODEX_MCP_BLOCK_RE, "");
4543
- if (cleaned !== toml) writeFileSync4(tomlPath, cleaned);
5191
+ if (cleaned !== toml) writeFileSync5(tomlPath, cleaned);
4544
5192
  }
4545
5193
  c.log?.(
4546
5194
  "codex: hooks + MCP section + skill removed ([features] hooks flag left as-is \u2014 other hooks may use it)"
@@ -4554,7 +5202,7 @@ var antigravity = {
4554
5202
  // can consume this integration.
4555
5203
  detect: (c) => onPath2("agy"),
4556
5204
  install(c) {
4557
- const hooksPath = join20(c.home, ".gemini", "config", "hooks.json");
5205
+ const hooksPath = join23(c.home, ".gemini", "config", "hooks.json");
4558
5206
  const hooks = readJson(hooksPath);
4559
5207
  for (const key of Object.keys(hooks)) {
4560
5208
  if (key !== MARKER && key.includes(MARKER)) delete hooks[key];
@@ -4565,26 +5213,26 @@ var antigravity = {
4565
5213
  setOrDelete(hooks, event, stripOurs(hooks[event]));
4566
5214
  }
4567
5215
  writeJson(hooksPath, hooks);
4568
- const mcpPath = join20(c.home, ".gemini", "config", "mcp_config.json");
5216
+ const mcpPath = join23(c.home, ".gemini", "config", "mcp_config.json");
4569
5217
  const mcp = readJson(mcpPath);
4570
5218
  mcp.mcpServers = {
4571
5219
  ...mcp.mcpServers ?? {},
4572
5220
  hindsight: mcpServerEntry(c.dist, "antigravity-cli")
4573
5221
  };
4574
5222
  writeJson(mcpPath, mcp);
4575
- const settingsPath = join20(c.home, ".gemini", "antigravity-cli", "settings.json");
5223
+ const settingsPath = join23(c.home, ".gemini", "antigravity-cli", "settings.json");
4576
5224
  const settings = readJson(settingsPath);
4577
5225
  if (!settings.statusLine) {
4578
5226
  settings.statusLine = {
4579
5227
  type: "command",
4580
- command: `node "${join20(c.dist, "antigravity-statusline.js")}"`
5228
+ command: `node "${join23(c.dist, "antigravity-statusline.js")}"`
4581
5229
  };
4582
5230
  writeJson(settingsPath, settings);
4583
5231
  c.log?.(`antigravity-cli: Hindsight status line enabled in ${settingsPath}`);
4584
5232
  } else if (JSON.stringify(settings.statusLine).includes(MARKER)) {
4585
5233
  settings.statusLine = {
4586
5234
  type: "command",
4587
- command: `node "${join20(c.dist, "antigravity-statusline.js")}"`
5235
+ command: `node "${join23(c.dist, "antigravity-statusline.js")}"`
4588
5236
  };
4589
5237
  writeJson(settingsPath, settings);
4590
5238
  } else {
@@ -4596,8 +5244,8 @@ var antigravity = {
4596
5244
  installSkill(c, "antigravity-cli");
4597
5245
  },
4598
5246
  uninstall(c) {
4599
- const hooksPath = join20(c.home, ".gemini", "config", "hooks.json");
4600
- if (existsSync10(hooksPath)) {
5247
+ const hooksPath = join23(c.home, ".gemini", "config", "hooks.json");
5248
+ if (existsSync13(hooksPath)) {
4601
5249
  const hooks = readJson(hooksPath);
4602
5250
  if (hooks[MARKER]) {
4603
5251
  stripHarnessHooks(hooks[MARKER], "antigravity-cli");
@@ -4608,16 +5256,16 @@ var antigravity = {
4608
5256
  }
4609
5257
  writeJson(hooksPath, hooks);
4610
5258
  }
4611
- const mcpPath = join20(c.home, ".gemini", "config", "mcp_config.json");
4612
- if (existsSync10(mcpPath)) {
5259
+ const mcpPath = join23(c.home, ".gemini", "config", "mcp_config.json");
5260
+ if (existsSync13(mcpPath)) {
4613
5261
  const mcp = readJson(mcpPath);
4614
5262
  if (mcp.mcpServers?.hindsight) {
4615
5263
  delete mcp.mcpServers.hindsight;
4616
5264
  writeJson(mcpPath, mcp);
4617
5265
  }
4618
5266
  }
4619
- const settingsPath = join20(c.home, ".gemini", "antigravity-cli", "settings.json");
4620
- if (existsSync10(settingsPath)) {
5267
+ const settingsPath = join23(c.home, ".gemini", "antigravity-cli", "settings.json");
5268
+ if (existsSync13(settingsPath)) {
4621
5269
  const settings = readJson(settingsPath);
4622
5270
  if (JSON.stringify(settings.statusLine ?? {}).includes(MARKER)) {
4623
5271
  delete settings.statusLine;
@@ -4630,7 +5278,7 @@ var antigravity = {
4630
5278
  };
4631
5279
  function pathNodeHasSqlite() {
4632
5280
  try {
4633
- execFileSync6("node", ["-e", "require('node:sqlite')"], { stdio: "pipe", timeout: 1e4 });
5281
+ execFileSync7("node", ["-e", "require('node:sqlite')"], { stdio: "pipe", timeout: 1e4 });
4634
5282
  return true;
4635
5283
  } catch {
4636
5284
  return false;
@@ -4638,13 +5286,13 @@ function pathNodeHasSqlite() {
4638
5286
  }
4639
5287
  function pathNodeVersion() {
4640
5288
  try {
4641
- return execFileSync6("node", ["-v"], { encoding: "utf8", stdio: "pipe" }).trim();
5289
+ return execFileSync7("node", ["-v"], { encoding: "utf8", stdio: "pipe" }).trim();
4642
5290
  } catch {
4643
5291
  return "not found";
4644
5292
  }
4645
5293
  }
4646
5294
  function runtimeDir(home) {
4647
- return join20(home, ".hindsight", "coding-agents");
5295
+ return join23(home, ".hindsight", "coding-agents");
4648
5296
  }
4649
5297
  var ORIGIN_FILE = ".install-origin.json";
4650
5298
  function stageRuntime(c) {
@@ -4657,25 +5305,25 @@ function stageRuntime(c) {
4657
5305
  }
4658
5306
  };
4659
5307
  if (same(c.pkgRoot, target)) return c;
4660
- if (!existsSync10(join20(c.dist, "installer.js"))) return c;
5308
+ if (!existsSync13(join23(c.dist, "installer.js"))) return c;
4661
5309
  try {
4662
- rmSync3(join20(target, "dist"), { recursive: true, force: true });
4663
- mkdirSync6(target, { recursive: true });
4664
- cpSync2(c.dist, join20(target, "dist"), { recursive: true });
4665
- const skill = join20(c.pkgRoot, "skill");
4666
- if (existsSync10(skill)) cpSync2(skill, join20(target, "skill"), { recursive: true });
4667
- const pkgJson = join20(c.pkgRoot, "package.json");
4668
- if (existsSync10(pkgJson)) copyFileSync(pkgJson, join20(target, "package.json"));
5310
+ rmSync4(join23(target, "dist"), { recursive: true, force: true });
5311
+ mkdirSync7(target, { recursive: true });
5312
+ cpSync2(c.dist, join23(target, "dist"), { recursive: true });
5313
+ const skill = join23(c.pkgRoot, "skill");
5314
+ if (existsSync13(skill)) cpSync2(skill, join23(target, "skill"), { recursive: true });
5315
+ const pkgJson = join23(c.pkgRoot, "package.json");
5316
+ if (existsSync13(pkgJson)) copyFileSync(pkgJson, join23(target, "package.json"));
4669
5317
  for (const resource of ["plugin.json", "hooks", "index.js"]) {
4670
- const source = join20(c.pkgRoot, resource);
4671
- if (existsSync10(source)) cpSync2(source, join20(target, resource), { recursive: true });
5318
+ const source = join23(c.pkgRoot, resource);
5319
+ if (existsSync13(source)) cpSync2(source, join23(target, resource), { recursive: true });
4672
5320
  }
4673
- writeFileSync4(
4674
- join20(target, ORIGIN_FILE),
5321
+ writeFileSync5(
5322
+ join23(target, ORIGIN_FILE),
4675
5323
  JSON.stringify({ source: c.pkgRoot, stagedAt: (/* @__PURE__ */ new Date()).toISOString() })
4676
5324
  );
4677
5325
  c.log?.(`runtime staged at ${target}`);
4678
- return { ...c, pkgRoot: target, dist: join20(target, "dist") };
5326
+ return { ...c, pkgRoot: target, dist: join23(target, "dist") };
4679
5327
  } catch (error) {
4680
5328
  c.log?.(`could not stage the runtime at ${target}: ${String(error)}`);
4681
5329
  return c;
@@ -4697,6 +5345,7 @@ function flagValueArgs(args, names) {
4697
5345
  return taken;
4698
5346
  }
4699
5347
  var CONFIG_RELATIVE = [".hindsight", "coding-agent.json"];
5348
+ var hindsightConfigPath = (c) => process.env.HINDSIGHT_CONFIG || join23(c.home, ...CONFIG_RELATIVE);
4700
5349
  var SERVER_CHOICES = [
4701
5350
  { mode: "cloud", label: "Hindsight Cloud", hint: "hosted, needs an API token" },
4702
5351
  { mode: "self-hosted", label: "Self-hosted server", hint: "a Hindsight server you already run" },
@@ -4753,7 +5402,7 @@ function configureServer(c, args, installing) {
4753
5402
  c.log?.(`unknown --server "${explicit}" \u2014 expected one of: ${SERVER_MODES.join(", ")}`);
4754
5403
  return false;
4755
5404
  }
4756
- const configPath = process.env.HINDSIGHT_CONFIG || join20(c.home, ...CONFIG_RELATIVE);
5405
+ const configPath = hindsightConfigPath(c);
4757
5406
  const existing = readJson(configPath);
4758
5407
  const alreadyConfigured = !!(existing.serverMode || existing.apiUrl);
4759
5408
  let mode = explicit;
@@ -4849,7 +5498,7 @@ function reportDaemonPrereqs(c) {
4849
5498
  }
4850
5499
  var devin = {
4851
5500
  name: "devin-cli",
4852
- detect: (c) => onPath2("devin") || existsSync10(join20(c.home, ".config", "devin")),
5501
+ detect: (c) => onPath2("devin") || existsSync13(join23(c.home, ".config", "devin")),
4853
5502
  // Devin is the ONLY harness whose hooks never hand over a transcript: they carry a session id and
4854
5503
  // nothing else, so retain can only work by reading the CLI's own sessions.db. That makes SQLite
4855
5504
  // support a hard prerequisite here — and one worth checking now, because the alternative is an
@@ -4862,12 +5511,12 @@ var devin = {
4862
5511
  Upgrade to Node 22.5 or newer (24 LTS recommended) and re-run this command.`;
4863
5512
  },
4864
5513
  install(c) {
4865
- const configPath = join20(c.home, ".config", "devin", "config.json");
5514
+ const configPath = join23(c.home, ".config", "devin", "config.json");
4866
5515
  const config = readJson(configPath);
4867
5516
  config.hooks = config.hooks ?? {};
4868
5517
  mergeHarnessHooks(config.hooks, "devin-cli", c.dist);
4869
5518
  writeJson(configPath, config);
4870
- const mcpPath = join20(c.home, ".config", "devin", "mcp_config.json");
5519
+ const mcpPath = join23(c.home, ".config", "devin", "mcp_config.json");
4871
5520
  const mcp = readJson(mcpPath);
4872
5521
  mcp.mcpServers = {
4873
5522
  ...mcp.mcpServers ?? {},
@@ -4877,8 +5526,8 @@ var devin = {
4877
5526
  c.log?.(`devin-cli: hooks merged into ${configPath}, MCP into ${mcpPath}`);
4878
5527
  },
4879
5528
  uninstall(c) {
4880
- const configPath = join20(c.home, ".config", "devin", "config.json");
4881
- if (existsSync10(configPath)) {
5529
+ const configPath = join23(c.home, ".config", "devin", "config.json");
5530
+ if (existsSync13(configPath)) {
4882
5531
  const config = readJson(configPath);
4883
5532
  if (config.hooks) {
4884
5533
  stripHarnessHooks(config.hooks, "devin-cli");
@@ -4886,8 +5535,8 @@ var devin = {
4886
5535
  writeJson(configPath, config);
4887
5536
  }
4888
5537
  }
4889
- const mcpPath = join20(c.home, ".config", "devin", "mcp_config.json");
4890
- if (existsSync10(mcpPath)) {
5538
+ const mcpPath = join23(c.home, ".config", "devin", "mcp_config.json");
5539
+ if (existsSync13(mcpPath)) {
4891
5540
  const mcp = readJson(mcpPath);
4892
5541
  if (mcp.mcpServers?.hindsight) {
4893
5542
  delete mcp.mcpServers.hindsight;
@@ -4899,26 +5548,27 @@ var devin = {
4899
5548
  };
4900
5549
  var cursor = {
4901
5550
  name: "cursor-cli",
4902
- detect: (c) => onPath2("cursor-agent") || existsSync10(join20(c.home, ".cursor")),
5551
+ detect: (c) => onPath2("cursor-agent") || existsSync13(join23(c.home, ".cursor")),
4903
5552
  install(c) {
4904
- const hooksPath = join20(c.home, ".cursor", "hooks.json");
5553
+ const hooksPath = join23(c.home, ".cursor", "hooks.json");
4905
5554
  const cfg = readJson(hooksPath);
5555
+ cfg.version ??= 1;
4906
5556
  cfg.hooks = cfg.hooks ?? {};
4907
5557
  mergeHarnessHooks(cfg.hooks, "cursor-cli", c.dist);
4908
5558
  writeJson(hooksPath, cfg);
4909
- const mcpPath = join20(c.home, ".cursor", "mcp.json");
5559
+ const mcpPath = join23(c.home, ".cursor", "mcp.json");
4910
5560
  const mcp = readJson(mcpPath);
4911
5561
  mcp.mcpServers = {
4912
5562
  ...mcp.mcpServers ?? {},
4913
- hindsight: mcpServerEntry(c.dist, "cursor-cli")
5563
+ hindsight: mcpServerEntry(c.dist, "cursor-cli", ["${workspaceFolder}"])
4914
5564
  };
4915
5565
  writeJson(mcpPath, mcp);
4916
5566
  c.log?.(`cursor-cli: hooks merged into ${hooksPath}, MCP into ${mcpPath}`);
4917
5567
  installSkill(c, "cursor-cli");
4918
5568
  },
4919
5569
  uninstall(c) {
4920
- const hooksPath = join20(c.home, ".cursor", "hooks.json");
4921
- if (existsSync10(hooksPath)) {
5570
+ const hooksPath = join23(c.home, ".cursor", "hooks.json");
5571
+ if (existsSync13(hooksPath)) {
4922
5572
  const cfg = readJson(hooksPath);
4923
5573
  if (cfg.hooks) {
4924
5574
  stripHarnessHooks(cfg.hooks, "cursor-cli");
@@ -4926,8 +5576,8 @@ var cursor = {
4926
5576
  writeJson(hooksPath, cfg);
4927
5577
  }
4928
5578
  }
4929
- const mcpPath = join20(c.home, ".cursor", "mcp.json");
4930
- if (existsSync10(mcpPath)) {
5579
+ const mcpPath = join23(c.home, ".cursor", "mcp.json");
5580
+ if (existsSync13(mcpPath)) {
4931
5581
  const mcp = readJson(mcpPath);
4932
5582
  if (mcp.mcpServers?.hindsight) {
4933
5583
  delete mcp.mcpServers.hindsight;
@@ -4940,13 +5590,13 @@ var cursor = {
4940
5590
  };
4941
5591
  var copilot = {
4942
5592
  name: "copilot-cli",
4943
- detect: (c) => onPath2("copilot") || existsSync10(join20(c.home, ".copilot")),
5593
+ detect: (c) => onPath2("copilot") || existsSync13(join23(c.home, ".copilot")),
4944
5594
  install(c) {
4945
- const hooksPath = join20(c.home, ".copilot", "hooks", "hindsight-coding-agents.json");
5595
+ const hooksPath = join23(c.home, ".copilot", "hooks", "hindsight-coding-agents.json");
4946
5596
  const hooks = {};
4947
5597
  mergeHarnessHooks(hooks, "copilot-cli", c.dist);
4948
5598
  writeJson(hooksPath, { version: 1, hooks });
4949
- const mcpPath = join20(c.home, ".copilot", "mcp-config.json");
5599
+ const mcpPath = join23(c.home, ".copilot", "mcp-config.json");
4950
5600
  const mcp = readJson(mcpPath);
4951
5601
  mcp.mcpServers = {
4952
5602
  ...mcp.mcpServers ?? {},
@@ -4957,11 +5607,11 @@ var copilot = {
4957
5607
  c.log?.(`copilot-cli: hooks installed at ${hooksPath}, MCP into ${mcpPath}`);
4958
5608
  },
4959
5609
  uninstall(c) {
4960
- rmSync3(join20(c.home, ".copilot", "hooks", "hindsight-coding-agents.json"), {
5610
+ rmSync4(join23(c.home, ".copilot", "hooks", "hindsight-coding-agents.json"), {
4961
5611
  force: true
4962
5612
  });
4963
- const mcpPath = join20(c.home, ".copilot", "mcp-config.json");
4964
- if (existsSync10(mcpPath)) {
5613
+ const mcpPath = join23(c.home, ".copilot", "mcp-config.json");
5614
+ if (existsSync13(mcpPath)) {
4965
5615
  const mcp = readJson(mcpPath);
4966
5616
  if (mcp.mcpServers?.hindsight) {
4967
5617
  delete mcp.mcpServers.hindsight;
@@ -5025,39 +5675,21 @@ function stripUnmarkedGrokEntries(toml) {
5025
5675
  if (!drop.some(Boolean)) return toml;
5026
5676
  return sections.filter((_, i) => !drop[i]).map((s) => s.lines.join("\n")).join("\n").replace(/\n{3,}/g, "\n\n");
5027
5677
  }
5678
+ var grokHooksPath = (c) => join23(c.home, ".grok", "hooks", "hindsight.json");
5028
5679
  var grok = {
5029
5680
  name: "grok-build",
5030
- detect: (c) => onPath2("grok") || existsSync10(join20(c.home, ".grok")),
5681
+ detect: (c) => onPath2("grok") || existsSync13(join23(c.home, ".grok")),
5031
5682
  install(c) {
5032
- const path = join20(c.home, ".grok", "config.toml");
5033
- const existing = existsSync10(path) ? readFileSync15(path, "utf8") : "";
5683
+ const path = join23(c.home, ".grok", "config.toml");
5684
+ const existing = existsSync13(path) ? readFileSync16(path, "utf8") : "";
5034
5685
  const stripped = existing.replace(GROK_BLOCK_RE, "\n");
5035
5686
  const withoutOurs = hasUnmarkedGrokEntries(stripped) ? stripUnmarkedGrokEntries(stripped) : stripped;
5036
- const command = (entry) => JSON.stringify(`node "${join20(c.dist, entry)}"`);
5037
5687
  const tomlString = (value) => JSON.stringify(value);
5038
5688
  const block = `
5039
5689
  ${GROK_MARKER_START}
5040
- [[hooks.SessionStart]]
5041
- [[hooks.SessionStart.hooks]]
5042
- type = "command"
5043
- command = ${command("grok-sessionstart-hook.js")}
5044
- timeout = 30
5045
-
5046
- [[hooks.UserPromptSubmit]]
5047
- [[hooks.UserPromptSubmit.hooks]]
5048
- type = "command"
5049
- command = ${command("grok-hook.js")}
5050
- timeout = 30
5051
-
5052
- [[hooks.Stop]]
5053
- [[hooks.Stop.hooks]]
5054
- type = "command"
5055
- command = ${command("grok-stop-hook.js")}
5056
- timeout = 60
5057
-
5058
5690
  [mcp_servers.hindsight]
5059
5691
  command = "node"
5060
- args = [${tomlString(join20(c.dist, "mcp-server.js"))}]
5692
+ args = [${tomlString(join23(c.dist, "mcp-server.js"))}]
5061
5693
  env = { HINDSIGHT_MCP_HARNESS = "grok-build" }
5062
5694
  ${GROK_MARKER_END}
5063
5695
  `;
@@ -5068,41 +5700,111 @@ ${GROK_MARKER_END}
5068
5700
  );
5069
5701
  return false;
5070
5702
  }
5071
- if (existsSync10(path) && !existsSync10(`${path}.hindsight-backup`))
5703
+ if (existsSync13(path) && !existsSync13(`${path}.hindsight-backup`))
5072
5704
  copyFileSync(path, `${path}.hindsight-backup`);
5073
- mkdirSync6(dirname11(path), { recursive: true });
5074
- writeFileSync4(path, next);
5705
+ mkdirSync7(dirname12(path), { recursive: true });
5706
+ writeFileSync5(path, next);
5707
+ const hooksPath = grokHooksPath(c);
5708
+ const file = readJson(hooksPath);
5709
+ const hooks = isPlainObject(file.hooks) ? file.hooks : {};
5710
+ mergeHarnessHooks(hooks, "grok-build", c.dist);
5711
+ writeJson(hooksPath, { ...file, hooks });
5075
5712
  installSkill(c, "grok-build");
5076
- c.log?.(`grok-build: native hooks + MCP installed in ${path}`);
5713
+ c.log?.(`grok-build: hooks installed in ${hooksPath}, MCP in ${path}`);
5077
5714
  },
5078
5715
  uninstall(c) {
5079
- const path = join20(c.home, ".grok", "config.toml");
5080
- if (existsSync10(path)) {
5081
- const existing = readFileSync15(path, "utf8");
5716
+ const path = join23(c.home, ".grok", "config.toml");
5717
+ if (existsSync13(path)) {
5718
+ const existing = readFileSync16(path, "utf8");
5082
5719
  const stripped = existing.replace(GROK_BLOCK_RE, "\n");
5083
5720
  const cleaned = hasUnmarkedGrokEntries(stripped) ? stripUnmarkedGrokEntries(stripped) : stripped;
5084
5721
  const safe = parseGrokToml(cleaned) !== null || parseGrokToml(existing) === null;
5085
- if (cleaned !== existing && safe) writeFileSync4(path, cleaned);
5722
+ if (cleaned !== existing && safe) writeFileSync5(path, cleaned);
5723
+ }
5724
+ const hooksPath = grokHooksPath(c);
5725
+ if (existsSync13(hooksPath)) {
5726
+ const file = readJson(hooksPath);
5727
+ if (isPlainObject(file.hooks)) {
5728
+ stripHarnessHooks(file.hooks, "grok-build");
5729
+ if (!Object.keys(file.hooks).length) delete file.hooks;
5730
+ }
5731
+ if (Object.keys(file).length) writeJson(hooksPath, file);
5732
+ else rmSync4(hooksPath);
5086
5733
  }
5087
5734
  uninstallSkill(c, "grok-build");
5088
5735
  c.log?.("grok-build: native hooks + MCP + skill removed");
5089
5736
  }
5090
5737
  };
5738
+ var KIMI_MARKER_START = "# HINDSIGHT_CODING_AGENTS_KIMI_START";
5739
+ var KIMI_MARKER_END = "# HINDSIGHT_CODING_AGENTS_KIMI_END";
5740
+ var KIMI_BLOCK_RE = new RegExp(`\\n?${KIMI_MARKER_START}[\\s\\S]*?${KIMI_MARKER_END}\\n?`);
5741
+ function kimiHome(c) {
5742
+ return process.env.KIMI_CODE_HOME || join23(c.home, ".kimi-code");
5743
+ }
5744
+ var kimi = {
5745
+ name: "kimi-code",
5746
+ detect: (c) => onPath2("kimi") || existsSync13(kimiHome(c)),
5747
+ install(c) {
5748
+ const path = join23(kimiHome(c), "config.toml");
5749
+ const existing = existsSync13(path) ? readFileSync16(path, "utf8") : "";
5750
+ const withoutOurs = existing.replace(KIMI_BLOCK_RE, "\n");
5751
+ const spec = HOOK_HARNESSES["kimi-code"];
5752
+ const entries = Object.values(spec.install).map(
5753
+ (h) => `[[hooks]]
5754
+ event = ${JSON.stringify(h.event)}
5755
+ command = ${JSON.stringify(`node "${join23(c.dist, h.entry)}"`)}
5756
+ timeout = ${h.timeout}
5757
+ `
5758
+ ).join("\n");
5759
+ const block = `
5760
+ ${KIMI_MARKER_START}
5761
+ ${entries}${KIMI_MARKER_END}
5762
+ `;
5763
+ if (existsSync13(path) && !existsSync13(`${path}.hindsight-backup`))
5764
+ copyFileSync(path, `${path}.hindsight-backup`);
5765
+ mkdirSync7(dirname12(path), { recursive: true });
5766
+ writeFileSync5(path, `${withoutOurs.replace(/\n*$/, "\n")}${block}`);
5767
+ const mcpPath = join23(kimiHome(c), "mcp.json");
5768
+ const mcp = readJson(mcpPath);
5769
+ mcp.mcpServers = { ...mcp.mcpServers ?? {}, hindsight: mcpServerEntry(c.dist, "kimi-code") };
5770
+ writeJson(mcpPath, mcp);
5771
+ installSkill(c, "kimi-code");
5772
+ c.log?.(`kimi-code: native hooks installed in ${path}, MCP in ${mcpPath}`);
5773
+ },
5774
+ uninstall(c) {
5775
+ const path = join23(kimiHome(c), "config.toml");
5776
+ if (existsSync13(path)) {
5777
+ const existing = readFileSync16(path, "utf8");
5778
+ const cleaned = existing.replace(KIMI_BLOCK_RE, "\n");
5779
+ if (cleaned !== existing) writeFileSync5(path, cleaned);
5780
+ }
5781
+ const mcpPath = join23(kimiHome(c), "mcp.json");
5782
+ if (existsSync13(mcpPath)) {
5783
+ const mcp = readJson(mcpPath);
5784
+ if (mcp.mcpServers?.hindsight) {
5785
+ delete mcp.mcpServers.hindsight;
5786
+ writeJson(mcpPath, mcp);
5787
+ }
5788
+ }
5789
+ uninstallSkill(c, "kimi-code");
5790
+ c.log?.("kimi-code: native hooks + MCP + skill removed");
5791
+ }
5792
+ };
5091
5793
  var CLINE_HOOK_MARKER = "HINDSIGHT_CODING_AGENTS_CLINE";
5092
5794
  var CLINE_OLD_HOOK_EVENTS = ["TaskStart", "UserPromptSubmit", "TaskComplete"];
5093
5795
  var CLINE_PLUGIN_NAME = "@vectorize-io/hindsight-coding-agents";
5094
5796
  function removeLegacyClineHooks(c) {
5095
- const hooksDir = join20(c.home, "Documents", "Cline", "Hooks");
5797
+ const hooksDir = join23(c.home, "Documents", "Cline", "Hooks");
5096
5798
  for (const event of CLINE_OLD_HOOK_EVENTS) {
5097
- const path = join20(hooksDir, event);
5098
- if (existsSync10(path) && readFileSync15(path, "utf8").includes(CLINE_HOOK_MARKER)) {
5099
- rmSync3(path, { force: true });
5799
+ const path = join23(hooksDir, event);
5800
+ if (existsSync13(path) && readFileSync16(path, "utf8").includes(CLINE_HOOK_MARKER)) {
5801
+ rmSync4(path, { force: true });
5100
5802
  }
5101
5803
  }
5102
5804
  }
5103
5805
  var cline = {
5104
5806
  name: "cline-cli",
5105
- detect: (c) => onPath2("cline") || existsSync10(join20(c.home, ".cline")),
5807
+ detect: (c) => onPath2("cline") || existsSync13(join23(c.home, ".cline")),
5106
5808
  install(c) {
5107
5809
  removeLegacyClineHooks(c);
5108
5810
  const installed = (c.clinePlugin ?? runClinePlugin)([
@@ -5111,7 +5813,7 @@ var cline = {
5111
5813
  "--force",
5112
5814
  c.pkgRoot
5113
5815
  ]);
5114
- const mcpPath = join20(c.home, ".cline", "data", "settings", "cline_mcp_settings.json");
5816
+ const mcpPath = join23(c.home, ".cline", "data", "settings", "cline_mcp_settings.json");
5115
5817
  const mcp = readJson(mcpPath);
5116
5818
  mcp.mcpServers = {
5117
5819
  ...mcp.mcpServers ?? {},
@@ -5126,8 +5828,8 @@ var cline = {
5126
5828
  uninstall(c) {
5127
5829
  removeLegacyClineHooks(c);
5128
5830
  (c.clinePlugin ?? runClinePlugin)(["plugin", "uninstall", CLINE_PLUGIN_NAME]);
5129
- const mcpPath = join20(c.home, ".cline", "data", "settings", "cline_mcp_settings.json");
5130
- if (existsSync10(mcpPath)) {
5831
+ const mcpPath = join23(c.home, ".cline", "data", "settings", "cline_mcp_settings.json");
5832
+ if (existsSync13(mcpPath)) {
5131
5833
  const mcp = readJson(mcpPath);
5132
5834
  if (mcp.mcpServers?.hindsight) {
5133
5835
  delete mcp.mcpServers.hindsight;
@@ -5140,31 +5842,31 @@ var cline = {
5140
5842
  };
5141
5843
  var DCODE_MARKETPLACE = "hindsight-coding-agents";
5142
5844
  var DCODE_PLUGIN_ID = "hindsight-coding-agents@hindsight-coding-agents";
5143
- var DCODE_MARKETPLACE_RELATIVE_PATH = join20(".agents", "plugins", "marketplace.json");
5845
+ var DCODE_MARKETPLACE_RELATIVE_PATH = join23(".agents", "plugins", "marketplace.json");
5144
5846
  var DCODE_FALLBACK_MARKETPLACE = "hindsight-coding-agents-marketplace.json";
5145
5847
  function prepareDcodeMarketplace(c) {
5146
- const root = join20(c.home, ".hindsight");
5147
- const conventionalPath = join20(root, DCODE_MARKETPLACE_RELATIVE_PATH);
5848
+ const root = join23(c.home, ".hindsight");
5849
+ const conventionalPath = join23(root, DCODE_MARKETPLACE_RELATIVE_PATH);
5148
5850
  let path = conventionalPath;
5149
5851
  let registrationSource = root;
5150
5852
  let marketplace = { plugins: [] };
5151
- if (existsSync10(conventionalPath)) {
5853
+ if (existsSync13(conventionalPath)) {
5152
5854
  try {
5153
- const parsed = JSON.parse(readFileSync15(conventionalPath, "utf8"));
5855
+ const parsed = JSON.parse(readFileSync16(conventionalPath, "utf8"));
5154
5856
  if (!parsed || typeof parsed !== "object" || !Array.isArray(parsed.plugins)) {
5155
- path = join20(root, DCODE_FALLBACK_MARKETPLACE);
5857
+ path = join23(root, DCODE_FALLBACK_MARKETPLACE);
5156
5858
  } else if (typeof parsed.name === "string" && parsed.name !== DCODE_MARKETPLACE) {
5157
- path = join20(root, DCODE_FALLBACK_MARKETPLACE);
5859
+ path = join23(root, DCODE_FALLBACK_MARKETPLACE);
5158
5860
  } else {
5159
5861
  marketplace = parsed;
5160
5862
  }
5161
5863
  } catch {
5162
- path = join20(root, DCODE_FALLBACK_MARKETPLACE);
5864
+ path = join23(root, DCODE_FALLBACK_MARKETPLACE);
5163
5865
  }
5164
5866
  }
5165
- if (path !== conventionalPath && existsSync10(path)) {
5867
+ if (path !== conventionalPath && existsSync13(path)) {
5166
5868
  try {
5167
- const parsed = JSON.parse(readFileSync15(path, "utf8"));
5869
+ const parsed = JSON.parse(readFileSync16(path, "utf8"));
5168
5870
  if (!parsed || typeof parsed !== "object" || !Array.isArray(parsed.plugins) || parsed.name !== DCODE_MARKETPLACE) {
5169
5871
  c.log?.(`dcode: refusing to replace malformed marketplace file ${path}`);
5170
5872
  return false;
@@ -5192,7 +5894,7 @@ function prepareDcodeMarketplace(c) {
5192
5894
  }
5193
5895
  var dcode = {
5194
5896
  name: "dcode",
5195
- detect: (c) => onPath2("dcode") || existsSync10(join20(c.home, ".deepagents")),
5897
+ detect: (c) => onPath2("dcode") || existsSync13(join23(c.home, ".deepagents")),
5196
5898
  preflight: (c) => c.dcodePlugin || onPath2("dcode") ? void 0 : "the `dcode` CLI is not on PATH",
5197
5899
  install(c) {
5198
5900
  const plugin = c.dcodePlugin ?? runDcodePlugin;
@@ -5201,7 +5903,7 @@ var dcode = {
5201
5903
  if (installed) {
5202
5904
  c.log?.(`dcode: native Agent Plugin installed (${DCODE_PLUGIN_ID})`);
5203
5905
  } else {
5204
- const source = marketplacePath === false ? join20(c.home, ".hindsight") : marketplacePath;
5906
+ const source = marketplacePath === false ? join23(c.home, ".hindsight") : marketplacePath;
5205
5907
  c.log?.(
5206
5908
  `dcode: could not install the native plugin \u2014 run dcode plugin marketplace add "${source}" && dcode plugin install ${DCODE_PLUGIN_ID}`
5207
5909
  );
@@ -5228,39 +5930,48 @@ var dcode = {
5228
5930
  var DSH_MARKER_START = "# HINDSIGHT_CODING_AGENTS_DSH_START";
5229
5931
  var DSH_MARKER_END = "# HINDSIGHT_CODING_AGENTS_DSH_END";
5230
5932
  var DSH_BLOCK_RE = new RegExp(`\\n?${DSH_MARKER_START}[\\s\\S]*?${DSH_MARKER_END}\\n?`);
5933
+ var DSH_EMPTY_LIST = "[]";
5934
+ function dshUserPatches(existing) {
5935
+ const others = existing.replace(DSH_BLOCK_RE, "\n").trim();
5936
+ return others === DSH_EMPTY_LIST ? "" : others;
5937
+ }
5231
5938
  function dshHome(c) {
5232
- return process.env.DSH_HOME || join20(c.home, ".dsh");
5939
+ return process.env.DSH_HOME || join23(c.home, ".dsh");
5233
5940
  }
5234
5941
  var dsh = {
5235
5942
  name: "dsh",
5236
- detect: (c) => onPath2("dsh") || existsSync10(dshHome(c)),
5943
+ detect: (c) => onPath2("dsh") || existsSync13(dshHome(c)),
5237
5944
  install(c) {
5238
- const path = join20(dshHome(c), "cordis.patch.yml");
5239
- const existing = existsSync10(path) ? readFileSync15(path, "utf8") : "";
5240
- const others = existing.replace(DSH_BLOCK_RE, "\n").trim();
5241
- const entry = pathToFileURL(join20(c.dist, "dsh.js")).href;
5945
+ const path = join23(dshHome(c), "cordis.patch.yml");
5946
+ const existing = existsSync13(path) ? readFileSync16(path, "utf8") : "";
5947
+ const others = dshUserPatches(existing);
5948
+ const entry = pathToFileURL(join23(c.dist, "dsh.js")).href;
5242
5949
  const block = `${DSH_MARKER_START}
5243
5950
  - insert:
5244
5951
  - id: hindsight
5245
5952
  name: ${JSON.stringify(entry)}
5246
5953
  ${DSH_MARKER_END}
5247
5954
  `;
5248
- if (existsSync10(path) && !existsSync10(`${path}.hindsight-backup`))
5955
+ if (existsSync13(path) && !existsSync13(`${path}.hindsight-backup`))
5249
5956
  copyFileSync(path, `${path}.hindsight-backup`);
5250
- mkdirSync6(dirname11(path), { recursive: true });
5251
- writeFileSync4(path, others ? `${others}
5957
+ mkdirSync7(dirname12(path), { recursive: true });
5958
+ writeFileSync5(path, others ? `${others}
5252
5959
 
5253
5960
  ${block}` : block);
5254
5961
  installSkill(c, "dsh");
5255
- c.log?.(`dsh: plugin registered in ${path} (applies to every dsh profile)`);
5962
+ c.log?.(
5963
+ `dsh: plugin registered in ${path} (applies to every dsh profile; start new sessions \u2014 ones already open would gain the tools mid-conversation)`
5964
+ );
5256
5965
  },
5257
5966
  uninstall(c) {
5258
- const path = join20(dshHome(c), "cordis.patch.yml");
5259
- if (existsSync10(path)) {
5260
- const existing = readFileSync15(path, "utf8");
5967
+ const path = join23(dshHome(c), "cordis.patch.yml");
5968
+ if (existsSync13(path)) {
5969
+ const existing = readFileSync16(path, "utf8");
5261
5970
  const others = existing.replace(DSH_BLOCK_RE, "\n").trim();
5262
- if (others !== existing.trim()) writeFileSync4(path, others ? `${others}
5263
- ` : "[]\n");
5971
+ if (others !== existing.trim())
5972
+ writeFileSync5(path, others ? `${others}
5973
+ ` : `${DSH_EMPTY_LIST}
5974
+ `);
5264
5975
  }
5265
5976
  uninstallSkill(c, "dsh");
5266
5977
  c.log?.("dsh: plugin entry + skill removed");
@@ -5268,9 +5979,9 @@ ${block}` : block);
5268
5979
  };
5269
5980
  var qwen = {
5270
5981
  name: "qwen-code",
5271
- detect: (c) => onPath2("qwen") || existsSync10(join20(c.home, ".qwen")),
5982
+ detect: (c) => onPath2("qwen") || existsSync13(join23(c.home, ".qwen")),
5272
5983
  install(c) {
5273
- const path = join20(c.home, ".qwen", "settings.json");
5984
+ const path = join23(c.home, ".qwen", "settings.json");
5274
5985
  const settings = readJson(path);
5275
5986
  settings.hooks = settings.hooks ?? {};
5276
5987
  mergeHarnessHooks(settings.hooks, "qwen-code", c.dist);
@@ -5288,19 +5999,19 @@ var qwen = {
5288
5999
  "HINDSIGHT_MCP_HARNESS=qwen-code",
5289
6000
  "hindsight",
5290
6001
  "node",
5291
- join20(c.dist, "mcp-server.js")
6002
+ join23(c.dist, "mcp-server.js")
5292
6003
  ])) {
5293
6004
  c.log?.("qwen-code: MCP server registered (qwen mcp add, user scope)");
5294
6005
  } else {
5295
6006
  c.log?.(
5296
6007
  `qwen-code: could not run \`qwen mcp add\` \u2014 register the tools manually:
5297
- qwen mcp add -s user -e HINDSIGHT_MCP_HARNESS=qwen-code hindsight node "${join20(c.dist, "mcp-server.js")}"`
6008
+ qwen mcp add -s user -e HINDSIGHT_MCP_HARNESS=qwen-code hindsight node "${join23(c.dist, "mcp-server.js")}"`
5298
6009
  );
5299
6010
  }
5300
6011
  },
5301
6012
  uninstall(c) {
5302
- const path = join20(c.home, ".qwen", "settings.json");
5303
- if (existsSync10(path)) {
6013
+ const path = join23(c.home, ".qwen", "settings.json");
6014
+ if (existsSync13(path)) {
5304
6015
  const settings = readJson(path);
5305
6016
  if (settings.hooks) {
5306
6017
  stripHarnessHooks(settings.hooks, "qwen-code");
@@ -5316,7 +6027,7 @@ var qwen = {
5316
6027
  };
5317
6028
  function defaultQwenMcp(args) {
5318
6029
  try {
5319
- execFileSync6("qwen", args, { stdio: "pipe" });
6030
+ execFileSync7("qwen", args, { stdio: "pipe" });
5320
6031
  return true;
5321
6032
  } catch {
5322
6033
  return false;
@@ -5324,19 +6035,19 @@ function defaultQwenMcp(args) {
5324
6035
  }
5325
6036
  var factoryDroid = {
5326
6037
  name: "factory-droid",
5327
- detect: (c) => onPath2("droid") || existsSync10(join20(c.home, ".factory")),
6038
+ detect: (c) => onPath2("droid") || existsSync13(join23(c.home, ".factory")),
5328
6039
  preflight(c) {
5329
- const mcpPath = join20(c.home, ".factory", "mcp.json");
6040
+ const mcpPath = join23(c.home, ".factory", "mcp.json");
5330
6041
  const existing = readJson(mcpPath).mcpServers?.hindsight;
5331
6042
  if (existing && !isOurMcpEntry(existing)) {
5332
6043
  return `${mcpPath} already contains a user-managed MCP server named "hindsight". Rename or remove that entry, then re-run install.`;
5333
6044
  }
5334
6045
  },
5335
6046
  install(c) {
5336
- const hooksPath = join20(c.home, ".factory", "hooks.json");
6047
+ const hooksPath = join23(c.home, ".factory", "hooks.json");
5337
6048
  const hooks = readJson(hooksPath);
5338
- if (!existsSync10(hooksPath)) {
5339
- const fallback = readJson(join20(c.home, ".factory", "settings.json")).hooks;
6049
+ if (!existsSync13(hooksPath)) {
6050
+ const fallback = readJson(join23(c.home, ".factory", "settings.json")).hooks;
5340
6051
  if (fallback && typeof fallback === "object" && !Array.isArray(fallback)) {
5341
6052
  Object.assign(hooks, fallback);
5342
6053
  }
@@ -5345,7 +6056,7 @@ var factoryDroid = {
5345
6056
  writeJson(hooksPath, hooks);
5346
6057
  c.log?.(`factory-droid: hooks merged into ${hooksPath}`);
5347
6058
  installSkill(c, "factory-droid");
5348
- const mcpPath = join20(c.home, ".factory", "mcp.json");
6059
+ const mcpPath = join23(c.home, ".factory", "mcp.json");
5349
6060
  const mcp = readJson(mcpPath);
5350
6061
  mcp.mcpServers = mcp.mcpServers ?? {};
5351
6062
  mcp.mcpServers.hindsight = mcpServerEntry(c.dist, "factory-droid");
@@ -5353,20 +6064,20 @@ var factoryDroid = {
5353
6064
  c.log?.(`factory-droid: MCP server registered in ${mcpPath}`);
5354
6065
  },
5355
6066
  uninstall(c) {
5356
- const hooksPath = join20(c.home, ".factory", "hooks.json");
5357
- if (existsSync10(hooksPath)) {
6067
+ const hooksPath = join23(c.home, ".factory", "hooks.json");
6068
+ if (existsSync13(hooksPath)) {
5358
6069
  const hooks = readJson(hooksPath);
5359
6070
  stripHarnessHooks(hooks, "factory-droid");
5360
6071
  if (Object.keys(hooks).length) writeJson(hooksPath, hooks);
5361
- else rmSync3(hooksPath);
6072
+ else rmSync4(hooksPath);
5362
6073
  }
5363
- const mcpPath = join20(c.home, ".factory", "mcp.json");
5364
- if (existsSync10(mcpPath)) {
6074
+ const mcpPath = join23(c.home, ".factory", "mcp.json");
6075
+ if (existsSync13(mcpPath)) {
5365
6076
  const mcp = readJson(mcpPath);
5366
6077
  if (isOurMcpEntry(mcp.mcpServers?.hindsight)) {
5367
6078
  delete mcp.mcpServers.hindsight;
5368
6079
  if (Object.keys(mcp.mcpServers).length) writeJson(mcpPath, mcp);
5369
- else rmSync3(mcpPath);
6080
+ else rmSync4(mcpPath);
5370
6081
  }
5371
6082
  }
5372
6083
  uninstallSkill(c, "factory-droid");
@@ -5375,7 +6086,7 @@ var factoryDroid = {
5375
6086
  };
5376
6087
  var zcode = {
5377
6088
  name: "zcode",
5378
- detect: (c) => onPath2("zcode") || existsSync10(join20(c.home, ".zcode")),
6089
+ detect: (c) => onPath2("zcode") || existsSync13(join23(c.home, ".zcode")),
5379
6090
  preflight(c) {
5380
6091
  const configPath = zcodeConfigPath(c);
5381
6092
  const existing = readJson(configPath).mcp?.servers?.hindsight;
@@ -5400,7 +6111,7 @@ var zcode = {
5400
6111
  },
5401
6112
  uninstall(c) {
5402
6113
  const configPath = zcodeConfigPath(c);
5403
- if (existsSync10(configPath)) {
6114
+ if (existsSync13(configPath)) {
5404
6115
  const config = readJson(configPath);
5405
6116
  if (isOurMcpEntry(config.mcp?.servers?.hindsight)) {
5406
6117
  delete config.mcp.servers.hindsight;
@@ -5417,6 +6128,159 @@ var zcode = {
5417
6128
  c.log?.(`zcode: hooks + MCP registration + skill removed`);
5418
6129
  }
5419
6130
  };
6131
+ var traecodeMcpPath = (c) => join23(traecodeUserDataDir(c.home), "User", "mcp.json");
6132
+ function removeTraecodeUserMcpEntry(c) {
6133
+ try {
6134
+ const mcpPath = traecodeMcpPath(c);
6135
+ if (!existsSync13(mcpPath)) return false;
6136
+ const mcp = readJson(mcpPath);
6137
+ if (!isOurMcpEntry(mcp.mcpServers?.hindsight)) return false;
6138
+ delete mcp.mcpServers.hindsight;
6139
+ if (Object.keys(mcp.mcpServers).length) writeJson(mcpPath, mcp);
6140
+ else rmSync4(mcpPath);
6141
+ return true;
6142
+ } catch {
6143
+ return false;
6144
+ }
6145
+ }
6146
+ function ensureTraecodeWorkspaceMcpGate(c) {
6147
+ const settingsPath = traecodeUserSettingsPath(c.home);
6148
+ if (workspaceMcpGateState(settingsPath) === "on") return;
6149
+ const ask = "\n Trae ignores per-repo MCP configs until workspace MCP is enabled, which keeps\n hindsight's MCP tools hidden. Enable it globally now? (one-time setting)\n";
6150
+ const skipNote = ' Skipped. Enable later in Trae settings (search "enableWorkspaceMcp") or re-run with\n --enable-workspace-mcp.';
6151
+ if (!(c.args ?? []).includes("--enable-workspace-mcp")) {
6152
+ if (c.interactive !== true) {
6153
+ c.log?.(`${ask} ${skipNote}`);
6154
+ return;
6155
+ }
6156
+ const answer = readLineSync(c, `${ask} Enable workspace MCP? [Y/n]: `).trim().toLowerCase();
6157
+ if (answer === "n" || answer === "no") {
6158
+ c.log?.(skipNote);
6159
+ return;
6160
+ }
6161
+ }
6162
+ if (enableWorkspaceMcpSetting(settingsPath)) {
6163
+ markWorkspaceMcpEnabled({ stateFile: gateStateFileFor(c.dist) });
6164
+ c.log?.(
6165
+ `traecode: workspace MCP enabled in ${settingsPath} \u2014 restart Trae windows to pick it up`
6166
+ );
6167
+ } else {
6168
+ c.log?.(
6169
+ `traecode: could not update ${settingsPath} (comments or unreadable JSON) \u2014 set
6170
+ "trae.mcp.enableWorkspaceMcp": true in Trae settings instead.`
6171
+ );
6172
+ }
6173
+ }
6174
+ var traecode = {
6175
+ name: "traecode",
6176
+ detect: (c) => existsSync13(join23(c.home, traecodeDotDirName(c.home))) || onPath2("trae"),
6177
+ install(c) {
6178
+ const hooksPath = join23(c.home, traecodeDotDirName(c.home), "hooks.json");
6179
+ const doc = readJson(hooksPath);
6180
+ doc.version = doc.version ?? 1;
6181
+ const hooks = doc.hooks = doc.hooks ?? {};
6182
+ mergeHarnessHooks(hooks, "traecode", c.dist);
6183
+ writeJson(hooksPath, doc);
6184
+ c.log?.(`traecode: hooks merged into ${hooksPath}`);
6185
+ installSkill(c, "traecode");
6186
+ if (removeTraecodeUserMcpEntry(c)) {
6187
+ c.log?.(
6188
+ `traecode: stale user-level MCP entry removed from ${traecodeMcpPath(c)} \u2014 per-repo
6189
+ .trae/mcp.json files register the server instead`
6190
+ );
6191
+ }
6192
+ const sandboxPath = join23(c.home, traecodeDotDirName(c.home), "sandbox.json");
6193
+ const sandbox = readJson(sandboxPath);
6194
+ const fsRules = sandbox.filesystem = sandbox.filesystem ?? {};
6195
+ const readWrite = fsRules.readWrite = fsRules.readWrite ?? [];
6196
+ const needed = [join23(c.home, ".hindsight"), traecodeWorkspaceStorageDir(c.home)];
6197
+ let sandboxChanged = false;
6198
+ for (const dir of needed) {
6199
+ if (!readWrite.includes(dir)) {
6200
+ readWrite.push(dir);
6201
+ sandboxChanged = true;
6202
+ }
6203
+ }
6204
+ if (sandboxChanged) {
6205
+ writeJson(sandboxPath, sandbox);
6206
+ c.log?.(`traecode: sandbox readWrite rules added (${needed.join(", ")})`);
6207
+ }
6208
+ const config = readJson(hindsightConfigPath(c));
6209
+ const repos = Object.keys(config.mapPathToBank ?? {}).sort();
6210
+ if (repos.length) {
6211
+ const written = [];
6212
+ const current2 = [];
6213
+ const skipped = [];
6214
+ let seeded = 0;
6215
+ for (const repo of repos) {
6216
+ if (!existsSync13(repo)) {
6217
+ skipped.push(repo);
6218
+ continue;
6219
+ }
6220
+ const outcome = registerTraecodeWorkspaceMcp(repo, { home: c.home, dist: c.dist });
6221
+ if (outcome === "registered") written.push(repo);
6222
+ else if (outcome === "current") current2.push(repo);
6223
+ else skipped.push(repo);
6224
+ if (ensureWorkspaceMcpEnabled(repo, { home: c.home }) !== "failed") seeded++;
6225
+ }
6226
+ c.log?.(
6227
+ `traecode: per-repo MCP registration \u2014 ${written.length} written, ${current2.length} already current, ${skipped.length} skipped across ${repos.length} opted-in repo(s); enable switch on for ${seeded}`
6228
+ );
6229
+ if (written.length) c.log?.(` registered: ${written.join(", ")}`);
6230
+ if (skipped.length) {
6231
+ c.log?.(
6232
+ ` skipped (missing repo, no dist build, or a foreign hindsight entry): ` + skipped.join(", ")
6233
+ );
6234
+ }
6235
+ if (written.length) {
6236
+ c.log?.(
6237
+ " new registrations appear in the next Trae window \u2014 if a repo's server still shows\n disabled in the MCP panel, flip it on once there"
6238
+ );
6239
+ }
6240
+ }
6241
+ ensureTraecodeWorkspaceMcpGate(c);
6242
+ },
6243
+ uninstall(c) {
6244
+ const hooksPath = join23(c.home, traecodeDotDirName(c.home), "hooks.json");
6245
+ if (existsSync13(hooksPath)) {
6246
+ const doc = readJson(hooksPath);
6247
+ if (doc.hooks) {
6248
+ stripHarnessHooks(doc.hooks, "traecode");
6249
+ if (!Object.keys(doc.hooks).length) delete doc.hooks;
6250
+ }
6251
+ if (Object.keys(doc).length > 1) writeJson(hooksPath, doc);
6252
+ else rmSync4(hooksPath);
6253
+ }
6254
+ if (removeTraecodeUserMcpEntry(c)) {
6255
+ c.log?.(`traecode: MCP entry removed from ${traecodeMcpPath(c)}`);
6256
+ }
6257
+ const config = readJson(hindsightConfigPath(c));
6258
+ const repoEntries = Object.keys(config.mapPathToBank ?? {}).sort();
6259
+ const cleaned = repoEntries.filter(
6260
+ (repo) => removeTraecodeWorkspaceMcpEntry(repo, { home: c.home })
6261
+ );
6262
+ if (cleaned.length) {
6263
+ c.log?.(`traecode: per-repo MCP registration removed from:
6264
+ ${cleaned.join("\n ")}`);
6265
+ }
6266
+ const sandboxPath = join23(c.home, traecodeDotDirName(c.home), "sandbox.json");
6267
+ if (existsSync13(sandboxPath)) {
6268
+ const sandbox = readJson(sandboxPath);
6269
+ const readWrite = sandbox.filesystem?.readWrite;
6270
+ if (Array.isArray(readWrite)) {
6271
+ const ours = [join23(c.home, ".hindsight"), traecodeWorkspaceStorageDir(c.home)];
6272
+ const filtered = readWrite.filter((p) => !ours.includes(p));
6273
+ if (filtered.length !== readWrite.length) {
6274
+ sandbox.filesystem.readWrite = filtered;
6275
+ writeJson(sandboxPath, sandbox);
6276
+ }
6277
+ }
6278
+ }
6279
+ removeWorkspaceMcpEnabledKeys(c.home);
6280
+ uninstallSkill(c, "traecode");
6281
+ c.log?.(`traecode: hooks + MCP registration + skill removed`);
6282
+ }
6283
+ };
5420
6284
  var INSTALLERS = [
5421
6285
  opencode,
5422
6286
  opencode2,
@@ -5431,11 +6295,13 @@ var INSTALLERS = [
5431
6295
  copilot,
5432
6296
  grok,
5433
6297
  qwen,
6298
+ kimi,
5434
6299
  cline,
5435
6300
  dcode,
5436
6301
  dsh,
5437
6302
  factoryDroid,
5438
- zcode
6303
+ zcode,
6304
+ traecode
5439
6305
  ];
5440
6306
  var HARNESS_ALIASES = { agy: "antigravity-cli" };
5441
6307
  function importConversations(harness, ctx) {
@@ -5455,23 +6321,24 @@ function importConversations(harness, ctx) {
5455
6321
  return;
5456
6322
  }
5457
6323
  const turns = found.sessions.reduce((n, s) => n + s.turns.length, 0);
5458
- const file = join20(mkdtempSync2(join20(tmpdir5(), "hindsight-import-")), "conversations.json");
5459
- writeFileSync4(file, JSON.stringify(found.sessions));
6324
+ const file = join23(mkdtempSync2(join23(tmpdir5(), "hindsight-import-")), "conversations.json");
6325
+ writeFileSync5(file, JSON.stringify(found.sessions));
5460
6326
  ctx.log?.(
5461
6327
  `${harness}: importing ${found.sessions.length} past sessions (${turns} turns) from ${repo} \u2014 this runs extraction and may take a while`
5462
6328
  );
5463
6329
  try {
5464
- execFileSync6("node", [join20(ctx.dist, "deepen.js"), "--repo", repo, "--conversations", file], {
6330
+ execFileSync7("node", [join23(ctx.dist, "deepen.js"), "--repo", repo, "--conversations", file], {
5465
6331
  stdio: "inherit"
5466
6332
  });
5467
6333
  } catch {
5468
6334
  ctx.log?.(`${harness}: conversation import did not finish \u2014 re-run it any time with:`);
5469
- ctx.log?.(` node "${join20(ctx.dist, "deepen.js")}" --repo "${repo}" --conversations "${file}"`);
6335
+ ctx.log?.(` node "${join23(ctx.dist, "deepen.js")}" --repo "${repo}" --conversations "${file}"`);
5470
6336
  }
5471
6337
  }
5472
6338
  function run(argv, ctxIn) {
5473
6339
  let ctx = ctxIn;
5474
6340
  const [command, ...rawArgs] = argv;
6341
+ ctx = { ...ctx, args: rawArgs };
5475
6342
  const importHistory = rawArgs.includes("--import-conversations");
5476
6343
  const valueArgs = flagValueArgs(rawArgs, ["server", "api-url", "api-token"]);
5477
6344
  const names = rawArgs.filter((a) => !a.startsWith("--") && !valueArgs.has(a));
@@ -5492,7 +6359,7 @@ function run(argv, ctxIn) {
5492
6359
  hindsight-coding-agents update
5493
6360
  hindsight-coding-agents stats
5494
6361
  [--server cloud|self-hosted|daemon] [--api-url <url>] [--api-token <token>]
5495
- [--import-conversations]
6362
+ [--import-conversations] [--enable-workspace-mcp]
5496
6363
  all every agent detected on this machine
5497
6364
  harness ${INSTALLERS.map((i) => i.name).join(", ")} (agy aliases antigravity-cli)
5498
6365
  update re-stage the runtime only, leaving every host config untouched
@@ -5570,16 +6437,16 @@ var mainPath = process.argv[1] ? (() => {
5570
6437
  })() : void 0;
5571
6438
  var isMain = mainPath && import.meta.url === pathToFileURL(mainPath).href;
5572
6439
  if (isMain || mainPath?.endsWith("installer.js")) {
5573
- const dist = dirname11(fileURLToPath6(import.meta.url));
5574
- const pkgRoot = dirname11(dist);
6440
+ const dist = dirname12(fileURLToPath7(import.meta.url));
6441
+ const pkgRoot = dirname12(dist);
5575
6442
  let version;
5576
6443
  try {
5577
- version = JSON.parse(readFileSync15(join20(pkgRoot, "package.json"), "utf8")).version;
6444
+ version = JSON.parse(readFileSync16(join23(pkgRoot, "package.json"), "utf8")).version;
5578
6445
  } catch {
5579
6446
  version = void 0;
5580
6447
  }
5581
6448
  const ui = createInstallerUi({
5582
- home: homedir11(),
6449
+ home: homedir13(),
5583
6450
  command: process.argv[2],
5584
6451
  version,
5585
6452
  harnessNames: INSTALLERS.map((i) => i.name),
@@ -5589,7 +6456,7 @@ if (isMain || mainPath?.endsWith("installer.js")) {
5589
6456
  });
5590
6457
  ui.intro();
5591
6458
  const code = run(process.argv.slice(2), {
5592
- home: homedir11(),
6459
+ home: homedir13(),
5593
6460
  pkgRoot,
5594
6461
  dist,
5595
6462
  // Only a real terminal gets prompted; piped/CI installs take the documented default.