@vectorize-io/hindsight-coding-agents 0.7.0 → 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 +137 -13
  2. package/dist/antigravity-hook.js +711 -55
  3. package/dist/antigravity-statusline.js +68 -7
  4. package/dist/antigravity-stop-hook.js +771 -57
  5. package/dist/claude-hook.js +711 -55
  6. package/dist/claude-sessionstart-hook.js +789 -68
  7. package/dist/claude-stop-hook.js +771 -57
  8. package/dist/cline.js +295 -75
  9. package/dist/codex-hook.js +711 -55
  10. package/dist/codex-sessionstart-hook.js +789 -68
  11. package/dist/codex-stop-hook.js +771 -57
  12. package/dist/copilot-hook.js +711 -55
  13. package/dist/copilot-sessionstart-hook.js +789 -68
  14. package/dist/copilot-stop-hook.js +771 -57
  15. package/dist/cursor-hook.js +711 -55
  16. package/dist/cursor-sessionstart-hook.js +789 -68
  17. package/dist/cursor-stop-hook.js +771 -57
  18. package/dist/daemon-start.js +38 -1
  19. package/dist/dcode-hook.js +711 -55
  20. package/dist/dcode-sessionstart-hook.js +789 -68
  21. package/dist/dcode-stop-hook.js +771 -57
  22. package/dist/deepen.js +236 -61
  23. package/dist/devin-hook.js +711 -55
  24. package/dist/devin-sessionstart-hook.js +789 -68
  25. package/dist/devin-stop-hook.js +771 -57
  26. package/dist/droid-hook.js +711 -55
  27. package/dist/droid-sessionstart-hook.js +789 -68
  28. package/dist/droid-stop-hook.js +771 -57
  29. package/dist/dsh.js +296 -76
  30. package/dist/grok-hook.js +711 -55
  31. package/dist/grok-sessionstart-hook.js +789 -68
  32. package/dist/grok-stop-hook.js +771 -57
  33. package/dist/hindsight-seed.js +41 -4
  34. package/dist/index.js +295 -75
  35. package/dist/installer.js +1148 -303
  36. package/dist/kilo.js +295 -75
  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 +162 -33
  41. package/dist/opencode2.js +298 -76
  42. package/dist/pi.js +299 -75
  43. package/dist/prime-agent.js +299 -75
  44. package/dist/qwen-hook.js +711 -55
  45. package/dist/qwen-sessionstart-hook.js +789 -68
  46. package/dist/qwen-stop-hook.js +771 -57
  47. package/dist/status.js +132 -14
  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 +711 -55
  52. package/dist/zcode-sessionstart-hook.js +789 -68
  53. package/dist/zcode-stop-hook.js +771 -57
  54. package/package.json +15 -11
  55. package/plugin.json +1 -1
  56. package/skill/SKILL.md +70 -11
@@ -270,13 +270,13 @@ function isWithin(directory, configured) {
270
270
  function mapLookup(map, directory) {
271
271
  const cwd = normalize(directory);
272
272
  let best;
273
- for (const [dir, bank] of Object.entries(map)) {
273
+ for (const [dir, value] of Object.entries(map)) {
274
274
  const p = configuredDir(dir);
275
275
  if (isWithin(cwd, p)) {
276
- if (!best || p.length > best.len) best = { len: p.length, bank };
276
+ if (!best || p.length > best.len) best = { len: p.length, value };
277
277
  }
278
278
  }
279
- return best?.bank;
279
+ return best?.value;
280
280
  }
281
281
  function lookupDirectories(config, directory, sessionRoot = "") {
282
282
  const directories = [normalize(directory)];
@@ -300,6 +300,10 @@ function isOptedIn(config, directory) {
300
300
  const pathMap = config.mapPathToBank;
301
301
  return Boolean(pathMap && directories.some((candidate) => mapLookup(pathMap, candidate)));
302
302
  }
303
+ function pathSection(config, paths, directory) {
304
+ if (!directory || !paths) return void 0;
305
+ return lookupDirectories(config, directory).map((candidate) => mapLookup(paths, candidate)).find((section) => section !== void 0);
306
+ }
303
307
  function mappedBank(config, directory, sessionRoot) {
304
308
  const pathMap = config.mapPathToBank;
305
309
  if (!directory || !pathMap) return void 0;
@@ -585,12 +589,17 @@ var CODING_BANK_TEMPLATE = {
585
589
  }
586
590
  };
587
591
  var MISSION_FIELDS = ["reflect_mission", "retain_mission", "observations_mission"];
592
+ var PLUGIN_GOVERNED_BANK_FIELDS = [
593
+ "retain_strategies",
594
+ "entity_labels",
595
+ "retain_extraction_mode"
596
+ ];
588
597
  function isSet(v) {
589
598
  if (v === null || v === void 0) return false;
590
599
  if (typeof v === "string") return v.trim() !== "";
591
600
  return true;
592
601
  }
593
- function codingBankManifest(overrides, mode = DEFAULT_RETAIN_EXTRACTION_MODE) {
602
+ function codingBankManifest(overrides, mode = DEFAULT_RETAIN_EXTRACTION_MODE, defaults = {}) {
594
603
  const current2 = overrides ?? {};
595
604
  const template = CODING_BANK_TEMPLATE.bank;
596
605
  const bank = {};
@@ -619,6 +628,10 @@ function codingBankManifest(overrides, mode = DEFAULT_RETAIN_EXTRACTION_MODE) {
619
628
  const [knowledgeGroup] = template.entity_labels;
620
629
  if (!labels.some((g) => g?.key === knowledgeGroup.key))
621
630
  bank.entity_labels = [...labels, knowledgeGroup];
631
+ for (const [key, value] of Object.entries(defaults)) {
632
+ if (PLUGIN_GOVERNED_BANK_FIELDS.includes(key) || !isSet(value) || isSet(current2[key])) continue;
633
+ bank[key] = value;
634
+ }
622
635
  return Object.keys(bank).length > 0 ? { version: "1", bank } : void 0;
623
636
  }
624
637
 
@@ -673,6 +686,15 @@ async function pool(items, n, fn, onError, onProgress) {
673
686
  }
674
687
  await Promise.all(Array.from({ length: Math.min(n, items.length) }, worker));
675
688
  }
689
+ function isOurMcpEntry(entry) {
690
+ if (!entry || typeof entry !== "object") return false;
691
+ const candidate = entry;
692
+ if (candidate.command !== "node" || !Array.isArray(candidate.args)) return false;
693
+ const script = candidate.args[0];
694
+ if (typeof script !== "string") return false;
695
+ const parts = script.replaceAll("\\", "/").split("/").filter(Boolean);
696
+ return parts.at(-1) === "mcp-server.js" && parts.at(-2) === "dist" && (parts.at(-3) === "coding-agents" || parts.at(-3) === "hindsight-coding-agents");
697
+ }
676
698
 
677
699
  // src/core/hindsight.ts
678
700
  function resolveRetainScopes(tags, configured) {
@@ -741,6 +763,18 @@ var DEFAULT_RECALL_OPTIONS = {
741
763
  var POLL_CYCLE_MS = 5e3;
742
764
  var RETRY_AFTER_FLOOR_MS = 10 * 1e3;
743
765
  var RETRY_AFTER_CEILING_MS = 60 * 1e3;
766
+ function shapePage(page) {
767
+ const p = page ?? {};
768
+ const body = typeof p.body === "string" && p.body.trim() ? p.body : p.markdown;
769
+ return {
770
+ id: p.id,
771
+ name: p.name,
772
+ ...p.description ? { description: p.description } : {},
773
+ ...Array.isArray(p.tags) && p.tags.length ? { tags: p.tags } : {},
774
+ ...p.timestamp ? { last_updated_at: p.timestamp } : {},
775
+ body
776
+ };
777
+ }
744
778
  var HindsightClient = class {
745
779
  apiUrl;
746
780
  /** The credential the NEXT request will sign with — NOT the one the config file holds. The two
@@ -778,7 +812,10 @@ var HindsightClient = class {
778
812
  return this.token;
779
813
  }
780
814
  headers() {
781
- const h = { "Content-Type": "application/json" };
815
+ const h = {
816
+ "Content-Type": "application/json",
817
+ "Accept-Encoding": "identity"
818
+ };
782
819
  if (this.token) h["Authorization"] = `Bearer ${this.token}`;
783
820
  return h;
784
821
  }
@@ -886,6 +923,23 @@ var HindsightClient = class {
886
923
  return false;
887
924
  }
888
925
  }
926
+ /**
927
+ * Whether a session write-back may use `update_mode="append"`: the server must dedupe by
928
+ * `operation_id` AND the bank must keep document text, or the server rejects the append in the
929
+ * background (#4613). Only an explicit `store_document_text: false` answers "no" — an unreachable
930
+ * or unparseable config assumes the default (stored), so a flaky probe never downgrades appends.
931
+ */
932
+ async supportsAppendRetain() {
933
+ if (!await this.supportsIdempotentRetain()) return false;
934
+ try {
935
+ const r = await this.req("GET", this.bankUrl("/config"));
936
+ if (!r.ok) return true;
937
+ const j = await r.json();
938
+ return j.config?.store_document_text !== false;
939
+ } catch {
940
+ return true;
941
+ }
942
+ }
889
943
  /**
890
944
  * Every document_id currently in the bank under a strategy tag (e.g. `source:git`), paginated into a
891
945
  * Set. Powers the incremental git-sync's "what's already ingested?" check — since git commits are stored
@@ -911,6 +965,24 @@ var HindsightClient = class {
911
965
  }
912
966
  return ids;
913
967
  }
968
+ /**
969
+ * The tags on one document, or undefined when the bank holds none with that id. Read from the
970
+ * document LISTING narrowed by `q` (a substring match on the id, so the exact id is picked out of
971
+ * the page) rather than GET /documents/{id}, which also sends the document's full text: the
972
+ * caller, the git-log freshness check on SessionStart, reads a ~100k-character document for one tag.
973
+ */
974
+ async documentTags(documentId) {
975
+ const limit = 100;
976
+ for (let offset = 0; ; offset += limit) {
977
+ const q = `?q=${encodeURIComponent(documentId)}&limit=${limit}&offset=${offset}`;
978
+ const r = await this.req("GET", this.bankUrl(`/documents${q}`));
979
+ const j = await r.json();
980
+ const items = j.items ?? [];
981
+ const hit = items.find((it) => it.id === documentId);
982
+ if (hit) return hit.tags ?? [];
983
+ if (items.length < limit || offset + limit >= (j.total ?? 0)) return void 0;
984
+ }
985
+ }
914
986
  /** Configure the bank: POST the coding bank manifest to /import (missions, retain strategies,
915
987
  * entity labels), then seed knowledge pages when the server supports them. Both halves are
916
988
  * idempotent and ADDITIVE — nothing the bank already says is overwritten (#3927), bar the
@@ -932,7 +1004,8 @@ var HindsightClient = class {
932
1004
  } else {
933
1005
  const manifest = codingBankManifest(
934
1006
  opts.reset ? void 0 : await this.readBankOverrides(),
935
- opts.extractionMode
1007
+ opts.extractionMode,
1008
+ opts.defaults
936
1009
  );
937
1010
  if (!manifest) {
938
1011
  this.log(`[bank] ${this.bank} already carries the coding structure \u2014 nothing to apply`);
@@ -1138,8 +1211,8 @@ var HindsightClient = class {
1138
1211
  return { items };
1139
1212
  }
1140
1213
  /**
1141
- * Read one knowledge page's synthesized content by knowledge-base id, as an OKF document
1142
- * (YAML frontmatter + markdown body). The endpoint omits the internal reflect trace that built
1214
+ * Read one knowledge page's synthesized content by knowledge-base id, shaped by `shapePage` so
1215
+ * the body arrives once. The endpoint omits the internal reflect trace that built
1143
1216
  * the page — that is 70-95% of the raw bytes and can blow past an MCP host's per-tool-result
1144
1217
  * token cap.
1145
1218
  */
@@ -1150,7 +1223,7 @@ var HindsightClient = class {
1150
1223
  this.bankUrl(`/knowledge-base/pages/${encodeURIComponent(pageId)}`)
1151
1224
  );
1152
1225
  if (r.status === 404) throw new Error(`knowledge page not found: ${pageId}`);
1153
- return await r.json();
1226
+ return shapePage(await r.json());
1154
1227
  }
1155
1228
  /** Hybrid (BM25 + vector, RRF-fused) server-side search over the bank's knowledge pages.
1156
1229
  * Returns page-level hits with a relevance snippet — the real search behind
@@ -1171,6 +1244,7 @@ var HindsightClient = class {
1171
1244
  return (j.results ?? []).map((x) => ({
1172
1245
  id: x.id,
1173
1246
  name: x.name,
1247
+ ...x.source_query ? { source_query: x.source_query } : {},
1174
1248
  snippet: x.snippet ?? "",
1175
1249
  score: x.score ?? 0
1176
1250
  }));
@@ -1441,6 +1515,7 @@ function resolveCustomPages(raw) {
1441
1515
  }
1442
1516
  var DEFAULT_REFLECT_TIMEOUT_MS = 2e4;
1443
1517
  var DEFAULT_REFLECT_TOOL_TIMEOUT_MS = 33e4;
1518
+ var DEFAULT_INJECT_TIMEOUT_MS = 7e3;
1444
1519
  var REFLECT_BUDGETS = ["low", "mid", "high"];
1445
1520
  function resolveReflectBudget(raw) {
1446
1521
  const value = raw.reflectBudget;
@@ -1467,6 +1542,22 @@ function resolveObservationScopes(raw) {
1467
1542
  }
1468
1543
  return DEFAULT_OBSERVATION_SCOPES;
1469
1544
  }
1545
+ function resolveDefaultBankConfig(raw) {
1546
+ const value = raw;
1547
+ if (!value || typeof value !== "object" || Array.isArray(value)) return {};
1548
+ const out = {};
1549
+ for (const [key, v] of Object.entries(value)) {
1550
+ if (PLUGIN_GOVERNED_BANK_FIELDS.includes(key)) {
1551
+ log.warn(
1552
+ "config",
1553
+ `ignoring defaultBankConfig.${key} \u2014 the plugin manages this field itself` + (key === "retain_extraction_mode" ? " (set retainExtractionMode instead)" : "")
1554
+ );
1555
+ continue;
1556
+ }
1557
+ out[key] = v;
1558
+ }
1559
+ return out;
1560
+ }
1470
1561
  var AUTO_INJECT_MODES = ["reflect", "pages", "recall", "none"];
1471
1562
  function resolveAutoInject(raw) {
1472
1563
  if (raw.autoReflect !== void 0) {
@@ -1506,18 +1597,21 @@ function resolveConfig(raw = {}) {
1506
1597
  // write sessions back by default, every harness
1507
1598
  manageBankConfig: raw.manageBankConfig ?? true,
1508
1599
  retainExtractionMode: RETAIN_EXTRACTION_MODES.includes(raw.retainExtractionMode) ? raw.retainExtractionMode : DEFAULT_RETAIN_EXTRACTION_MODE,
1600
+ defaultBankConfig: resolveDefaultBankConfig(raw.defaultBankConfig),
1509
1601
  maxParallelRetains: raw.maxParallelRetains || 10,
1510
1602
  reflectTimeoutMs: raw.reflectTimeoutMs || DEFAULT_REFLECT_TIMEOUT_MS,
1511
1603
  // Inherit an explicitly-raised reflectTimeoutMs (that is what users reaching for a longer
1512
1604
  // reflect already set), but never let it LOWER the tool below the default — a short window is
1513
1605
  // set to bound the automatic hook, not to cut off a call the agent is waiting on.
1514
1606
  reflectToolTimeoutMs: raw.reflectToolTimeoutMs || Math.max(raw.reflectTimeoutMs || 0, DEFAULT_REFLECT_TOOL_TIMEOUT_MS),
1607
+ injectTimeoutMs: raw.injectTimeoutMs || DEFAULT_INJECT_TIMEOUT_MS,
1515
1608
  reflectBudget: resolveReflectBudget(raw),
1516
1609
  autoInject: resolveAutoInject(raw),
1517
1610
  pageSearchLimit: raw.pageSearchLimit || DEFAULT_PAGE_SEARCH_LIMIT,
1518
1611
  // Same shape as retainMetadata: an object, or nothing. An array would spread into numeric
1519
1612
  // keys and reach the API as garbage, so it is rejected like any other non-object.
1520
1613
  recallOptions: raw.recallOptions && typeof raw.recallOptions === "object" && !Array.isArray(raw.recallOptions) ? { ...raw.recallOptions } : {},
1614
+ toolGuideExtra: typeof raw.toolGuideExtra === "string" && raw.toolGuideExtra.trim() ? raw.toolGuideExtra : void 0,
1521
1615
  // Every turn, not every tenth. The guide is what tells the agent WHEN to reach for memory, and
1522
1616
  // at a cadence of 10 a normal session is told once, on turn 1, and never again. Measured over
1523
1617
  // 40 real Claude Code turns, moving this from 10 to 1 took searches from 15% of turns to 32.5%
@@ -1537,11 +1631,15 @@ function resolveConfig(raw = {}) {
1537
1631
  // Hostile input is a config typo, not an attack: keep only string entries so a stray number or
1538
1632
  // nested object cannot reach the API as a tag and fail the whole retain.
1539
1633
  retainTags: Array.isArray(raw.retainTags) ? raw.retainTags.filter((t) => typeof t === "string" && t.trim() !== "") : [],
1634
+ // Undefined, not "", when unset or blank: the retain call distinguishes "not configured" (use
1635
+ // the built-in default) from a configured value, and an empty context would strip the default.
1636
+ retainContext: typeof raw.retainContext === "string" && raw.retainContext.trim() !== "" ? raw.retainContext : void 0,
1540
1637
  retainMetadata: raw.retainMetadata && typeof raw.retainMetadata === "object" ? Object.fromEntries(
1541
1638
  Object.entries(raw.retainMetadata).filter(([, v]) => typeof v === "string")
1542
1639
  ) : {},
1543
1640
  observationScopes: resolveObservationScopes(raw.observationScopes),
1544
1641
  banks: raw.banks && typeof raw.banks === "object" ? raw.banks : {},
1642
+ paths: raw.paths && typeof raw.paths === "object" ? raw.paths : {},
1545
1643
  logLevel: ["debug", "info", "warn", "error"].includes(raw.logLevel) ? raw.logLevel : "info",
1546
1644
  autoUpdate: raw.autoUpdate ?? true
1547
1645
  };
@@ -1558,7 +1656,12 @@ function readRaw(path) {
1558
1656
  }
1559
1657
  function mergeRaw(a, b) {
1560
1658
  const { harnesses: _drop, ...flat } = b;
1561
- return { ...a, ...flat, banks: { ...a.banks ?? {}, ...b.banks ?? {} } };
1659
+ return {
1660
+ ...a,
1661
+ ...flat,
1662
+ banks: { ...a.banks ?? {}, ...b.banks ?? {} },
1663
+ paths: { ...a.paths ?? {}, ...b.paths ?? {} }
1664
+ };
1562
1665
  }
1563
1666
  function applyLayer(raw, layer, harness) {
1564
1667
  let out = mergeRaw(raw, layer);
@@ -1589,9 +1692,11 @@ var ENV_KEYS = {
1589
1692
  maxParallelRetains: "HINDSIGHT_MAX_PARALLEL_RETAINS",
1590
1693
  reflectTimeoutMs: "HINDSIGHT_REFLECT_TIMEOUT_MS",
1591
1694
  reflectToolTimeoutMs: "HINDSIGHT_REFLECT_TOOL_TIMEOUT_MS",
1695
+ injectTimeoutMs: "HINDSIGHT_INJECT_TIMEOUT_MS",
1592
1696
  reflectBudget: "HINDSIGHT_REFLECT_BUDGET",
1593
1697
  autoInject: "HINDSIGHT_AUTO_INJECT",
1594
1698
  pageSearchLimit: "HINDSIGHT_PAGE_SEARCH_LIMIT",
1699
+ toolGuideExtra: "HINDSIGHT_TOOL_GUIDE_EXTRA",
1595
1700
  autoReflect: "HINDSIGHT_AUTO_REFLECT",
1596
1701
  pageRefreshEveryTurns: "HINDSIGHT_PAGE_REFRESH_EVERY_TURNS",
1597
1702
  pageTriggerType: "HINDSIGHT_PAGE_TRIGGER_TYPE",
@@ -1633,6 +1738,7 @@ var ENV_NUMBERS = /* @__PURE__ */ new Set([
1633
1738
  "maxParallelRetains",
1634
1739
  "reflectTimeoutMs",
1635
1740
  "reflectToolTimeoutMs",
1741
+ "injectTimeoutMs",
1636
1742
  "pageSearchLimit",
1637
1743
  "pageRefreshEveryTurns",
1638
1744
  "seedLimit",
@@ -1681,15 +1787,25 @@ var BANK_OVERRIDE_EXCLUDED = [
1681
1787
  function applyBankConfig(cfg, resolvedId, directory) {
1682
1788
  if (directory !== void 0 && !isOptedIn(cfg, directory))
1683
1789
  return { cfg: { ...cfg, disabled: true }, bankId: resolvedId };
1790
+ const byPath = directory === void 0 ? void 0 : pathSection(cfg, cfg.paths, directory);
1791
+ if (byPath) {
1792
+ const { bank: _rename, ...rest } = overrideFields(byPath);
1793
+ cfg = { ...cfg, ...resolvePartial(cfg, rest) };
1794
+ }
1684
1795
  const section = cfg.banks[resolvedId];
1685
1796
  if (!section) return { cfg, bankId: resolvedId };
1686
- const safe = { ...section };
1687
- for (const k of BANK_OVERRIDE_EXCLUDED) delete safe[k];
1688
- delete safe.banks;
1797
+ const safe = overrideFields(section);
1689
1798
  const bankId = typeof safe.bank === "string" && safe.bank ? safe.bank : resolvedId;
1690
1799
  delete safe.bank;
1691
1800
  return { cfg: { ...cfg, ...resolvePartial(cfg, safe) }, bankId };
1692
1801
  }
1802
+ function overrideFields(section) {
1803
+ const safe = { ...section };
1804
+ for (const k of BANK_OVERRIDE_EXCLUDED) delete safe[k];
1805
+ delete safe.banks;
1806
+ delete safe.paths;
1807
+ return safe;
1808
+ }
1693
1809
  function resolvePartial(cfg, patch) {
1694
1810
  const full = resolveConfig(patch);
1695
1811
  const out = {};
@@ -1698,6 +1814,16 @@ function resolvePartial(cfg, patch) {
1698
1814
  out[key] = full[key];
1699
1815
  }
1700
1816
  if ("autoReflect" in patch && !("autoInject" in patch)) out.autoInject = full.autoInject;
1817
+ if ("serverMode" in patch || "apiUrl" in patch || "apiPort" in patch) {
1818
+ const conn = resolveConfig({
1819
+ serverMode: patch.serverMode ?? cfg.serverMode,
1820
+ apiPort: patch.apiPort ?? cfg.apiPort,
1821
+ apiUrl: patch.apiUrl ?? (cfg.serverMode === "daemon" ? void 0 : cfg.apiUrl)
1822
+ });
1823
+ out.serverMode = conn.serverMode;
1824
+ out.apiUrl = conn.apiUrl;
1825
+ out.apiPort = conn.apiPort;
1826
+ }
1701
1827
  return out;
1702
1828
  }
1703
1829
 
@@ -1732,13 +1858,13 @@ function indexLine(pages) {
1732
1858
  const count = pages.length === 1 ? "1 knowledge page covers" : `${pages.length} knowledge pages cover`;
1733
1859
  return `${count} this repository \u2014 architecture, conventions, past decisions and in-flight initiatives. They are deliberately NOT listed here: call hindsight_search_knowledge_pages(query) to find the ones that bear on the current turn, then hindsight_read_knowledge_page(<id>) on anything the results show is worth reading in full.`;
1734
1860
  }
1735
- var TOOL_GUIDE = `- hindsight_search_knowledge_pages(query) \u2014 FIRST STOP, and the way IN to everything below. The code shows what is true today, never what was decided or why, so work built from code alone quietly re-litigates settled questions. Search BEFORE you act whenever the turn is one of these \u2014 they are the ones that go wrong silently:
1736
- \u2022 the user reports a bug or a wrong response (the intended behaviour, and the status code or value it should return, is usually already decided);
1861
+ var TOOL_GUIDE = `- hindsight_search_knowledge_pages(query) \u2014 FIRST STOP, and the way IN to everything below. The code shows what is true today but not what was decided or why; memory shows what was decided or said back then but not whether it still holds. Work built from either alone goes wrong: from code alone it quietly re-litigates settled questions, from memory alone it acts on stale claims. Search BEFORE you act whenever the turn is one of these \u2014 they are the ones that go wrong silently:
1862
+ \u2022 the user reports a bug or a wrong response (the intended behaviour, and the status code or value it should return, may already have been decided);
1737
1863
  \u2022 you are about to write or change a test (what this project expects a change to ship with, and how it asserts, is a convention, not a preference);
1738
1864
  \u2022 you are implementing something new, or two parts have to fit together;
1739
1865
  \u2022 the user asks why something is the way it is, or what is left to do;
1740
1866
  \u2022 you are about to commit, and need to know what the change was supposed to honour.
1741
- It ranks the pages by relevance and returns the matching passage, which a page title cannot tell you.
1867
+ It ranks the pages by relevance and returns the matching passage, which a page title cannot tell you. What it returns is a past record, not a live reading: a claim that something was fixed, passes, or works is what someone said then \u2014 check it against the code before you rely on it, and say so when the two disagree.
1742
1868
  CREDITING IS NOT OPTIONAL AND NOT A JUDGEMENT CALL. If you called this tool and anything it returned reached your reply \u2014 quoted, paraphrased, or merely confirming what you were about to say \u2014 open that part with a markdown blockquote, exactly: "> \u{1F9E0} **From Hindsight memory (<page>)** \u2014 <the specific facts you drew on>". Rewriting a snippet in your own words does not make it yours. A search that turned up nothing useful needs no mention at all \u2014 just carry on.
1743
1869
  - hindsight_list_knowledge_pages / hindsight_read_knowledge_page \u2014 BEFORE substantial work, list the pages and read the relevant ones to ground yourself in this repo's architecture, conventions, and past decisions instead of re-deriving them from the code; follow any [[page:<id>]] links you see.
1744
1870
  - hindsight_reflect(query) \u2014 when pages are too shallow and you need the WHY: deep reasoning over the repo's full memory for the past decision and exact values that explain a behavior or bug (slower \u2014 use deliberately, and credit results with a blockquote header "> \u{1F9E0} **From Hindsight memory** \u2014 <summary>").
@@ -1746,7 +1872,9 @@ var TOOL_GUIDE = `- hindsight_search_knowledge_pages(query) \u2014 FIRST STOP, a
1746
1872
  - hindsight_ingest_document(title, content) \u2014 save an external document or durable notes/findings you want remembered (not the current conversation \u2014 that is captured automatically at session end).`;
1747
1873
  var PAGES_FIRST_ON_GOALS = "- The user just set a NEW task or goal \u2192 search the knowledge pages FIRST with hindsight_search_knowledge_pages. No synthesis is injected automatically in this configuration; call hindsight_reflect only when those pages are too shallow and deeper reasoning is needed.\n";
1748
1874
  function toolGuide(opts) {
1749
- return (opts?.reflectOnNewGoals ? PAGES_FIRST_ON_GOALS : "") + TOOL_GUIDE;
1875
+ const extra = opts?.extra?.trim();
1876
+ return (opts?.reflectOnNewGoals ? PAGES_FIRST_ON_GOALS : "") + TOOL_GUIDE + (extra ? `
1877
+ ${extra}` : "");
1750
1878
  }
1751
1879
  function buildKnowledgePreamble(pages, opts) {
1752
1880
  const body = pages.length ? indexLine(pages) : EMPTY_STATE;
@@ -1947,12 +2075,46 @@ function startDaemonDetached(cfg, harness, spawnFn = realSpawn2) {
1947
2075
  } catch {
1948
2076
  }
1949
2077
  }
2078
+ var coldStarts = /* @__PURE__ */ new Map();
2079
+ async function waitBounded(p, ms) {
2080
+ let timer;
2081
+ try {
2082
+ await Promise.race([
2083
+ p,
2084
+ new Promise((resolve3) => {
2085
+ timer = setTimeout(resolve3, Math.max(ms, 0));
2086
+ })
2087
+ ]);
2088
+ } finally {
2089
+ clearTimeout(timer);
2090
+ }
2091
+ }
1950
2092
  async function ensureDaemon(cfg, harness, opts = {}) {
1951
2093
  if (cfg.serverMode !== "daemon") return;
1952
2094
  if (await isServerHealthy(cfg.apiUrl)) return;
1953
2095
  if (!preflightDaemon(cfg, harness)) return;
1954
- startDaemonDetached(cfg, harness, opts.spawnFn);
1955
- await waitForHealth(cfg.apiUrl, opts.waitMs ?? 0);
2096
+ const waitMs = opts.waitMs ?? 0;
2097
+ const running = coldStarts.get(cfg.apiUrl);
2098
+ if (running) {
2099
+ const startedAt = Date.now();
2100
+ await waitBounded(
2101
+ running.catch(() => void 0),
2102
+ waitMs
2103
+ );
2104
+ const remaining = waitMs - (Date.now() - startedAt);
2105
+ if (remaining > 0) await waitForHealth(cfg.apiUrl, remaining);
2106
+ return;
2107
+ }
2108
+ const attempt = (async () => {
2109
+ startDaemonDetached(cfg, harness, opts.spawnFn);
2110
+ await waitForHealth(cfg.apiUrl, waitMs);
2111
+ })();
2112
+ coldStarts.set(cfg.apiUrl, attempt);
2113
+ try {
2114
+ await attempt;
2115
+ } finally {
2116
+ if (coldStarts.get(cfg.apiUrl) === attempt) coldStarts.delete(cfg.apiUrl);
2117
+ }
1956
2118
  }
1957
2119
  async function waitForHealth(baseUrl, budgetMs, pollMs = 1e3) {
1958
2120
  const deadline = Date.now() + budgetMs;
@@ -2007,7 +2169,8 @@ function resolversFor(ctx) {
2007
2169
  function buildRetainStamp(cfg, ctx) {
2008
2170
  const hasTags = Boolean(cfg.retainTags?.length);
2009
2171
  const hasMetadata = Boolean(cfg.retainMetadata && Object.keys(cfg.retainMetadata).length);
2010
- if (!hasTags && !hasMetadata) return { tags: [], metadata: {} };
2172
+ const hasContext = Boolean(cfg.retainContext?.trim());
2173
+ if (!hasTags && !hasMetadata && !hasContext) return { tags: [], metadata: {} };
2011
2174
  const base = resolversFor(ctx);
2012
2175
  const cache = /* @__PURE__ */ new Map();
2013
2176
  const resolvers = Object.fromEntries(
@@ -2031,7 +2194,8 @@ function buildRetainStamp(cfg, ctx) {
2031
2194
  for (const [key, value] of Object.entries(cfg.retainMetadata ?? {})) {
2032
2195
  metadata[key] = applyTemplate(value, resolvers, "retainMetadata");
2033
2196
  }
2034
- return { tags, metadata };
2197
+ const context = hasContext ? applyTemplate(cfg.retainContext, resolvers, "retainContext").trim() || void 0 : void 0;
2198
+ return { tags, metadata, context };
2035
2199
  }
2036
2200
 
2037
2201
  // src/core/jsonl.ts
@@ -2078,6 +2242,7 @@ import { readFileSync as readFileSync11 } from "fs";
2078
2242
  // src/core/git.ts
2079
2243
  import { execFileSync as execFileSync2 } from "child_process";
2080
2244
  import { resolve as resolve2 } from "path";
2245
+ var GITLOG_HEAD = "gitlog-head:";
2081
2246
  function git(repo, ...args) {
2082
2247
  return execFileSync2("git", ["-C", repo, ...args], {
2083
2248
  encoding: "utf8",
@@ -2099,6 +2264,7 @@ function gitHeadSha(dir) {
2099
2264
  }
2100
2265
  }
2101
2266
  function commitsSince(dir, sinceSha) {
2267
+ if (!/^[0-9a-f]{40}(?:[0-9a-f]{24})?$/.test(sinceSha)) return null;
2102
2268
  try {
2103
2269
  const n = Number.parseInt(git(dir, "rev-list", "--count", `${sinceSha}..HEAD`).trim(), 10);
2104
2270
  return Number.isFinite(n) ? n : null;
@@ -2113,6 +2279,15 @@ function hasGitHistory(dir) {
2113
2279
  return false;
2114
2280
  }
2115
2281
  }
2282
+ async function gitLogIsCurrent(client, repo, head) {
2283
+ const canonical2 = `gitlog:${repoNameOf(repo)}`;
2284
+ if ((await client.listDocumentIds(`${GITLOG_HEAD}${head}`, "all_strict")).has(canonical2))
2285
+ return true;
2286
+ const tags = await client.documentTags?.(canonical2) ?? [];
2287
+ return tags.some(
2288
+ (tag) => tag.startsWith(GITLOG_HEAD) && commitsSince(repo, tag.slice(GITLOG_HEAD.length)) === 0
2289
+ );
2290
+ }
2116
2291
 
2117
2292
  // src/core/status.ts
2118
2293
  import { execFileSync as execFileSync3 } from "child_process";
@@ -2636,12 +2811,14 @@ async function maybeAutoUpdate(cfg, opts = {}) {
2636
2811
  }
2637
2812
 
2638
2813
  // src/core/skill-sync.ts
2639
- import { cpSync, existsSync as existsSync5, readFileSync as readFileSync9 } from "fs";
2814
+ import { cpSync, existsSync as existsSync6, readFileSync as readFileSync9 } from "fs";
2640
2815
  import { homedir as homedir6 } from "os";
2641
- import { dirname as dirname10, join as join15 } from "path";
2816
+ import { dirname as dirname10, join as join16 } from "path";
2642
2817
  import { fileURLToPath as fileURLToPath5 } from "url";
2643
2818
 
2644
2819
  // src/core/skill-dirs.ts
2820
+ import { existsSync as existsSync5 } from "fs";
2821
+ import { join as join15 } from "path";
2645
2822
  var SKILL_DIRS = {
2646
2823
  "claude-code": [".claude", "skills"],
2647
2824
  // Codex and dsh share the agentskills-standard root; uninstalling either removes the one copy.
@@ -2654,6 +2831,8 @@ var SKILL_DIRS = {
2654
2831
  "cline-cli": [".cline", "data", "settings", "skills"],
2655
2832
  "qwen-code": [".qwen", "skills"],
2656
2833
  // Qwen's user-level skills root (Storage.getUserSkillsDirs)
2834
+ // Kimi Code's user-level skills root, alongside its config.toml and mcp.json.
2835
+ "kimi-code": [".kimi-code", "skills"],
2657
2836
  "factory-droid": [".factory", "skills"],
2658
2837
  // Droid's user-level skills root
2659
2838
  // ZCode scans TWO user roots by default (its resolveDefaultSkillRoots): `~/.zcode/skills` and the
@@ -2661,29 +2840,46 @@ var SKILL_DIRS = {
2661
2840
  // skill removal is by fixed directory name, so installing into the shared root would make
2662
2841
  // `uninstall zcode` take Codex's and dsh's copy with it.
2663
2842
  zcode: [".zcode", "skills"],
2843
+ // TraeCode's user-level skills root, resolved per edition by traecodeDotDir below — like ZCode's
2844
+ // its own, never the shared agentskills root other hosts install into.
2845
+ traecode: [".trae-cn", "skills"],
2664
2846
  // The pi family reads the shared ~/.agents/skills too, but writes its OWN root: skill removal is
2665
2847
  // by fixed directory name, so installing to the shared one would make `uninstall pi` take Codex's
2666
2848
  // and dsh's copy with it.
2667
2849
  pi: [".pi", "agent", "skills"],
2668
2850
  "prime-agent": [".prime", "agent", "skills"]
2669
2851
  };
2852
+ var TRAE_DOT_DIRS = [".trae-cn", ".trae"];
2853
+ var traecodeDotDirName = (home, exists = existsSync5) => {
2854
+ for (const dir of TRAE_DOT_DIRS) {
2855
+ if (exists(join15(home, dir))) return dir;
2856
+ }
2857
+ return ".trae-cn";
2858
+ };
2859
+ var resolveSkillDirs = (harness, home) => {
2860
+ const parts = SKILL_DIRS[harness];
2861
+ if (harness === "traecode" && parts) {
2862
+ return [traecodeDotDirName(home), ...parts.slice(1)];
2863
+ }
2864
+ return parts;
2865
+ };
2670
2866
 
2671
2867
  // src/core/skill-sync.ts
2672
2868
  function packagedSkillDir() {
2673
2869
  const here = dirname10(fileURLToPath5(import.meta.url));
2674
- const dist = join15(here, "..", "skill");
2675
- return existsSync5(join15(dist, "SKILL.md")) ? dist : join15(here, "..", "..", "skill");
2870
+ const dist = join16(here, "..", "skill");
2871
+ return existsSync6(join16(dist, "SKILL.md")) ? dist : join16(here, "..", "..", "skill");
2676
2872
  }
2677
2873
  function syncCompanionSkill(harness, opts = {}) {
2678
2874
  try {
2679
- const parts = SKILL_DIRS[harness];
2875
+ const parts = resolveSkillDirs(harness, opts.home ?? homedir6());
2680
2876
  if (!parts) return;
2681
2877
  const src = opts.srcDir ?? packagedSkillDir();
2682
- const srcMd = join15(src, "SKILL.md");
2683
- if (!existsSync5(srcMd)) return;
2684
- const dst = join15(opts.home ?? homedir6(), ...parts, "hindsight-coding-agent");
2685
- const dstMd = join15(dst, "SKILL.md");
2686
- const installed = existsSync5(dstMd);
2878
+ const srcMd = join16(src, "SKILL.md");
2879
+ if (!existsSync6(srcMd)) return;
2880
+ const dst = join16(opts.home ?? homedir6(), ...parts, "hindsight-coding-agent");
2881
+ const dstMd = join16(dst, "SKILL.md");
2882
+ const installed = existsSync6(dstMd);
2687
2883
  if (!installed && !opts.install) return;
2688
2884
  if (!installed || readFileSync9(srcMd, "utf8") !== readFileSync9(dstMd, "utf8")) {
2689
2885
  cpSync(src, dst, { recursive: true });
@@ -2693,15 +2889,15 @@ function syncCompanionSkill(harness, opts = {}) {
2693
2889
  }
2694
2890
 
2695
2891
  // src/core/legacy.ts
2696
- import { existsSync as existsSync6, readFileSync as readFileSync10 } from "fs";
2892
+ import { existsSync as existsSync7, readFileSync as readFileSync10 } from "fs";
2697
2893
  import { homedir as homedir7 } from "os";
2698
- import { join as join16, relative, isAbsolute as isAbsolute2 } from "path";
2894
+ import { join as join17, relative, isAbsolute as isAbsolute2 } from "path";
2699
2895
  var LEGACY_CLAUDE_PLUGIN = "hindsight-memory";
2700
- function detectLegacyClaudePlugin(cwd, claudeDir = join16(homedir7(), ".claude")) {
2701
- const registry = readJson(join16(claudeDir, "plugins", "installed_plugins.json"));
2896
+ function detectLegacyClaudePlugin(cwd, claudeDir = join17(homedir7(), ".claude")) {
2897
+ const registry = readJson(join17(claudeDir, "plugins", "installed_plugins.json"));
2702
2898
  const plugins = registry?.plugins;
2703
2899
  if (!plugins || typeof plugins !== "object") return void 0;
2704
- const enabled = readJson(join16(claudeDir, "settings.json"))?.enabledPlugins;
2900
+ const enabled = readJson(join17(claudeDir, "settings.json"))?.enabledPlugins;
2705
2901
  for (const [key, raw] of Object.entries(plugins)) {
2706
2902
  if (key.split("@")[0] !== LEGACY_CLAUDE_PLUGIN) continue;
2707
2903
  if (enabled && enabled[key] === false) continue;
@@ -2741,15 +2937,15 @@ async function gitSyncNote(args) {
2741
2937
  if (mode === "none" || cold) return void 0;
2742
2938
  const head = gitHeadSha(cwd);
2743
2939
  if (!head) return void 0;
2744
- const gitlogCurrent = await client.listDocumentIds(`gitlog-head:${head}`, "all_strict").then((s) => s.has(`gitlog:${repoNameOf(cwd)}`)).catch(() => void 0);
2940
+ const gitlogCurrent = await gitLogIsCurrent(client, cwd, head).catch(() => void 0);
2745
2941
  if (gitlogCurrent === void 0) return void 0;
2746
2942
  if (mode === "message") return gitlogCurrent ? "git in sync" : "catching up on new commits";
2747
2943
  const deepened = [...gitIds].filter((id) => id.startsWith("git:")).length;
2748
2944
  let target = DEEPEN_DIFF_TARGET;
2749
2945
  try {
2750
- const { execFileSync: execFileSync4 } = await import("child_process");
2946
+ const { execFileSync: execFileSync5 } = await import("child_process");
2751
2947
  const n = Number(
2752
- execFileSync4("git", ["-C", cwd, "rev-list", "--count", "HEAD"], {
2948
+ execFileSync5("git", ["-C", cwd, "rev-list", "--count", "HEAD"], {
2753
2949
  encoding: "utf8",
2754
2950
  windowsHide: true,
2755
2951
  stdio: ["ignore", "pipe", "pipe"]
@@ -2867,7 +3063,8 @@ async function buildSessionStartContext(args) {
2867
3063
  }
2868
3064
  }
2869
3065
  const additionalContext = buildKnowledgePreamble(pages, {
2870
- reflectOnNewGoals: cfg.autoInject !== "reflect"
3066
+ reflectOnNewGoals: cfg.autoInject !== "reflect",
3067
+ extra: cfg.toolGuideExtra
2871
3068
  });
2872
3069
  const deferInitialReflect = cold === true || pageListKnown && pages.length === 0;
2873
3070
  let gitNote;
@@ -2900,6 +3097,7 @@ async function runSessionStartHook(spec, makeClient = (o) => new HindsightClient
2900
3097
  } catch {
2901
3098
  return;
2902
3099
  }
3100
+ if (spec.accept && !spec.accept(ev)) return;
2903
3101
  const { harness } = spec;
2904
3102
  const { cwd: rawCwd, sessionId } = spec.parse(ev);
2905
3103
  const cwd = rawCwd || process.cwd();
@@ -2915,6 +3113,7 @@ async function runSessionStartHook(spec, makeClient = (o) => new HindsightClient
2915
3113
  cfg = resolved2.cfg;
2916
3114
  const bankId = resolved2.bankId;
2917
3115
  if (cfg.disabled) return;
3116
+ const mcpHint = spec.ensureMcpRegistration?.(cwd);
2918
3117
  await ensureDaemon(cfg, harness, { waitMs: DAEMON_WAIT_SESSION_START_MS });
2919
3118
  const client = makeClient({
2920
3119
  apiUrl: cfg.apiUrl,
@@ -2924,6 +3123,9 @@ async function runSessionStartHook(spec, makeClient = (o) => new HindsightClient
2924
3123
  observationScopes: cfg.observationScopes
2925
3124
  });
2926
3125
  const out = await buildSessionStartContext({ cwd, sessionRoot, bankId, cfg, client, harness });
3126
+ if (mcpHint)
3127
+ out.systemMessage = out.systemMessage ? `${out.systemMessage}
3128
+ ${mcpHint}` : mcpHint;
2927
3129
  if (out.deferInitialReflect && sessionId) {
2928
3130
  writeSessionCache(sessionCacheFile(harness, sessionId), { deferInitialReflect: true });
2929
3131
  }
@@ -2935,6 +3137,233 @@ async function runSessionStartHook(spec, makeClient = (o) => new HindsightClient
2935
3137
  }
2936
3138
  }
2937
3139
 
3140
+ // src/core/traecode-mcp.ts
3141
+ import { execFileSync as execFileSync4 } from "child_process";
3142
+ import { existsSync as existsSync8, mkdirSync as mkdirSync6, readFileSync as readFileSync12, readdirSync as readdirSync2, rmSync as rmSync3, writeFileSync as writeFileSync4 } from "fs";
3143
+ import { homedir as homedir8 } from "os";
3144
+ import { dirname as dirname11, isAbsolute as isAbsolute3, join as join18 } from "path";
3145
+ import { fileURLToPath as fileURLToPath6 } from "url";
3146
+ var MCP_SERVER_NAME = "hindsight";
3147
+ var MCP_FILE_REL = join18(".trae", "mcp.json");
3148
+ function bundledDistDir() {
3149
+ const here = dirname11(fileURLToPath6(import.meta.url));
3150
+ return existsSync8(join18(here, "mcp-server.js")) ? here : join18(here, "..", "..", "dist");
3151
+ }
3152
+ function canon(value) {
3153
+ if (Array.isArray(value)) return `[${value.map(canon).join(",")}]`;
3154
+ if (value && typeof value === "object") {
3155
+ const entries = Object.entries(value).sort(
3156
+ ([a], [b]) => a < b ? -1 : a > b ? 1 : 0
3157
+ );
3158
+ return `{${entries.map(([k, v]) => `${JSON.stringify(k)}:${canon(v)}`).join(",")}}`;
3159
+ }
3160
+ return JSON.stringify(value);
3161
+ }
3162
+ var WORKSPACE_MCP_KEY = "trae.mcp.enableWorkspaceMcp";
3163
+ var HINT_MIN_INTERVAL_MS = 24 * 60 * 60 * 1e3;
3164
+ function traecodeUserDataDir(home) {
3165
+ 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");
3166
+ for (const brand of ["Trae CN", "Trae"]) {
3167
+ const dir = join18(root, brand);
3168
+ if (existsSync8(dir)) return dir;
3169
+ }
3170
+ return join18(root, "Trae CN");
3171
+ }
3172
+ var traecodeUserSettingsPath = (home) => join18(traecodeUserDataDir(home), "User", "settings.json");
3173
+ var gateStateFileFor = (dist) => join18(dirname11(dist), ".workspace-mcp.json");
3174
+ function gateStateFile() {
3175
+ return gateStateFileFor(bundledDistDir());
3176
+ }
3177
+ function readGateState(opts = {}) {
3178
+ try {
3179
+ return JSON.parse(readFileSync12(opts.stateFile ?? gateStateFile(), "utf8"));
3180
+ } catch {
3181
+ return {};
3182
+ }
3183
+ }
3184
+ function workspaceMcpGateState(settingsPath) {
3185
+ let raw;
3186
+ try {
3187
+ raw = readFileSync12(settingsPath, "utf8");
3188
+ } catch {
3189
+ return "unknown";
3190
+ }
3191
+ try {
3192
+ const doc = JSON.parse(raw);
3193
+ return doc[WORKSPACE_MCP_KEY] === true ? "on" : "off";
3194
+ } catch {
3195
+ const hit = raw.match(new RegExp(`"${WORKSPACE_MCP_KEY}"\\s*:\\s*(true|false)`));
3196
+ return hit ? hit[1] === "true" ? "on" : "off" : "unknown";
3197
+ }
3198
+ }
3199
+ function workspaceMcpHint(opts = {}) {
3200
+ try {
3201
+ const settingsPath = traecodeUserSettingsPath(opts.home ?? homedir8());
3202
+ if (workspaceMcpGateState(settingsPath) === "on") return void 0;
3203
+ const now = opts.now ?? Date.now();
3204
+ const state = readGateState(opts);
3205
+ if (state.workspaceMcpEnabled) return void 0;
3206
+ if (typeof state.lastHint === "number" && now - state.lastHint < HINT_MIN_INTERVAL_MS) {
3207
+ return void 0;
3208
+ }
3209
+ writeFileSync4(
3210
+ opts.stateFile ?? gateStateFile(),
3211
+ JSON.stringify({ ...state, lastHint: now }, null, 2) + "\n"
3212
+ );
3213
+ 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.';
3214
+ } catch {
3215
+ return void 0;
3216
+ }
3217
+ }
3218
+ function gitignoreCovers(lines) {
3219
+ return lines.some((l) => {
3220
+ const t = l.trim();
3221
+ return t.includes(".trae");
3222
+ });
3223
+ }
3224
+ function ensureGitignored(repo) {
3225
+ const gitignore = join18(repo, ".gitignore");
3226
+ if (!existsSync8(gitignore)) return;
3227
+ const current2 = readFileSync12(gitignore, "utf8");
3228
+ if (gitignoreCovers(current2.split("\n"))) return;
3229
+ const addition = (current2.endsWith("\n") || current2 === "" ? "" : "\n") + "# hindsight MCP registration (machine-specific)\n.trae/mcp.json\n";
3230
+ writeFileSync4(gitignore, current2 + addition);
3231
+ }
3232
+ function ensureTraecodeWorkspaceMcp(cwd, opts = {}) {
3233
+ registerTraecodeWorkspaceMcp(cwd, opts);
3234
+ const seeded = ensureWorkspaceMcpEnabled(cwd, opts);
3235
+ return workspaceMcpHint(opts) ?? (seeded === "failed" ? workspaceEnableHint(opts) : void 0);
3236
+ }
3237
+ function registerTraecodeWorkspaceMcp(cwd, opts = {}) {
3238
+ try {
3239
+ const home = opts.home ?? homedir8();
3240
+ if (!cwd || !isAbsolute3(cwd) || dirname11(cwd) === cwd || cwd === home) return "skipped";
3241
+ const dist = opts.dist ?? bundledDistDir();
3242
+ const script = join18(dist, "mcp-server.js");
3243
+ if (!existsSync8(script)) return "skipped";
3244
+ const file = join18(cwd, MCP_FILE_REL);
3245
+ let doc = {};
3246
+ let exists = false;
3247
+ try {
3248
+ doc = JSON.parse(readFileSync12(file, "utf8"));
3249
+ exists = true;
3250
+ } catch {
3251
+ if (existsSync8(file)) return "skipped";
3252
+ }
3253
+ const servers = doc.mcpServers && typeof doc.mcpServers === "object" && !Array.isArray(doc.mcpServers) ? doc.mcpServers : doc.mcpServers = {};
3254
+ const entry = {
3255
+ command: "node",
3256
+ args: [script],
3257
+ env: { HINDSIGHT_MCP_HARNESS: "traecode", HINDSIGHT_MCP_PROJECT_CWD: cwd }
3258
+ };
3259
+ const existing = servers[MCP_SERVER_NAME];
3260
+ let merged;
3261
+ if (existing === void 0) {
3262
+ merged = entry;
3263
+ } else if (isOurMcpEntry(existing)) {
3264
+ const env = existing.env;
3265
+ merged = {
3266
+ ...existing,
3267
+ command: entry.command,
3268
+ args: entry.args,
3269
+ env: { ...env ?? {}, ...entry.env }
3270
+ };
3271
+ } else {
3272
+ diag("traecode", "workspace_mcp_foreign_entry", { cwd, file });
3273
+ return "skipped";
3274
+ }
3275
+ if (existing !== void 0 && canon(merged) === canon(existing)) return "current";
3276
+ servers[MCP_SERVER_NAME] = merged;
3277
+ mkdirSync6(dirname11(file), { recursive: true });
3278
+ writeFileSync4(file, JSON.stringify(doc, null, 2) + "\n");
3279
+ if (!exists) ensureGitignored(cwd);
3280
+ diag("traecode", "workspace_mcp_registered", { cwd, file });
3281
+ return "registered";
3282
+ } catch (e) {
3283
+ diag("traecode", "workspace_mcp_register_failed", {
3284
+ cwd,
3285
+ error: e instanceof Error ? e.message : String(e)
3286
+ });
3287
+ return "failed";
3288
+ }
3289
+ }
3290
+ var WORKSPACE_STORAGE_REL = join18("User", "workspaceStorage");
3291
+ var ENABLED_KEY_PREFIX = "icubeAgentExtension.enabled.mcp.config.ws0.";
3292
+ var SQLITE_TIMEOUT_MS = 5e3;
3293
+ var TRAECODE_WORKSPACE_ENABLED_KEY = ENABLED_KEY_PREFIX + MCP_SERVER_NAME;
3294
+ var traecodeWorkspaceStorageDir = (home) => join18(traecodeUserDataDir(home), WORKSPACE_STORAGE_REL);
3295
+ function findWorkspaceStorageDir(storage, repo) {
3296
+ let entries;
3297
+ try {
3298
+ entries = readdirSync2(storage);
3299
+ } catch {
3300
+ return void 0;
3301
+ }
3302
+ for (const name of entries) {
3303
+ try {
3304
+ const doc = JSON.parse(readFileSync12(join18(storage, name, "workspace.json"), "utf8"));
3305
+ if (typeof doc.folder !== "string") continue;
3306
+ let folder;
3307
+ try {
3308
+ folder = fileURLToPath6(doc.folder);
3309
+ } catch {
3310
+ folder = doc.folder;
3311
+ }
3312
+ if (folder === repo) return join18(storage, name);
3313
+ } catch {
3314
+ continue;
3315
+ }
3316
+ }
3317
+ return void 0;
3318
+ }
3319
+ function ensureWorkspaceMcpEnabled(cwd, opts = {}) {
3320
+ try {
3321
+ const home = opts.home ?? homedir8();
3322
+ if (!cwd || !isAbsolute3(cwd) || dirname11(cwd) === cwd || cwd === home) return "failed";
3323
+ const dir = findWorkspaceStorageDir(traecodeWorkspaceStorageDir(home), cwd);
3324
+ if (!dir) return "failed";
3325
+ const db = join18(dir, "state.vscdb");
3326
+ if (!existsSync8(db)) return "failed";
3327
+ const sqlite = opts.sqlite ?? execFileSync4;
3328
+ const run = (sql) => sqlite("sqlite3", [db, ".timeout 3000", sql], {
3329
+ encoding: "utf8",
3330
+ timeout: SQLITE_TIMEOUT_MS,
3331
+ windowsHide: true,
3332
+ stdio: ["ignore", "pipe", "pipe"]
3333
+ }).trim();
3334
+ if (run(`SELECT value FROM ItemTable WHERE key='${TRAECODE_WORKSPACE_ENABLED_KEY}';`) === "true") {
3335
+ return "on";
3336
+ }
3337
+ run(
3338
+ `INSERT OR REPLACE INTO ItemTable (key, value) VALUES ('${TRAECODE_WORKSPACE_ENABLED_KEY}', 'true');`
3339
+ );
3340
+ diag("traecode", "workspace_mcp_enabled_seeded", { cwd, db });
3341
+ return "seeded";
3342
+ } catch (e) {
3343
+ diag("traecode", "workspace_mcp_enabled_seed_failed", {
3344
+ cwd,
3345
+ error: e instanceof Error ? e.message : String(e)
3346
+ });
3347
+ return "failed";
3348
+ }
3349
+ }
3350
+ function workspaceEnableHint(opts = {}) {
3351
+ try {
3352
+ const now = opts.now ?? Date.now();
3353
+ const state = readGateState(opts);
3354
+ if (typeof state.lastEnableHint === "number" && now - state.lastEnableHint < HINT_MIN_INTERVAL_MS) {
3355
+ return void 0;
3356
+ }
3357
+ writeFileSync4(
3358
+ opts.stateFile ?? gateStateFile(),
3359
+ JSON.stringify({ ...state, lastEnableHint: now }, null, 2) + "\n"
3360
+ );
3361
+ 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.";
3362
+ } catch {
3363
+ return void 0;
3364
+ }
3365
+ }
3366
+
2938
3367
  // src/core/transcript-codex.ts
2939
3368
  function stampOf(line) {
2940
3369
  return typeof line.timestamp === "string" && line.timestamp ? { timestamp: line.timestamp } : {};
@@ -2944,11 +3373,56 @@ function isSyntheticUserText(text) {
2944
3373
  return s.startsWith("# AGENTS.md instructions for ") || s.startsWith("<environment_context>");
2945
3374
  }
2946
3375
  function contentText(content) {
2947
- return (content || []).filter((c) => c && typeof c.text === "string").map((c) => c.text).join("\n");
3376
+ return (Array.isArray(content) ? content : []).filter((c) => c && typeof c.text === "string").map((c) => c.text).join("\n");
3377
+ }
3378
+ var startupKinds = /* @__PURE__ */ new Set([
3379
+ "agents_md.instructions",
3380
+ "environments.instructions",
3381
+ "environments.environment_context",
3382
+ "plugins.recommendations",
3383
+ "plugins.usage_instructions"
3384
+ ]);
3385
+ function fallbackUserText(payload) {
3386
+ const content = payload.content;
3387
+ const kinds = payload.internal_chat_message_metadata_passthrough?.content_item_kinds;
3388
+ if (Array.isArray(content) && Array.isArray(kinds) && kinds.length === content.length && kinds.every((kind) => typeof kind === "string" && kind.length > 0)) {
3389
+ return contentText(content.filter((_, index) => !startupKinds.has(kinds[index])));
3390
+ }
3391
+ const text = contentText(content);
3392
+ return isSyntheticUserText(stripInjectedMemory(text)) ? "" : text;
2948
3393
  }
2949
3394
  function isUserMessageEvent(line) {
2950
3395
  return line.type === "event_msg" && line.payload?.type === "item_completed" && line.payload.item?.type === "UserMessage";
2951
3396
  }
3397
+ var TOOL_ITEM_TYPES = /* @__PURE__ */ new Set(["McpToolCall", "CommandExecution"]);
3398
+ function isToolItemEvent(line) {
3399
+ return line.type === "event_msg" && line.payload?.type === "item_completed" && TOOL_ITEM_TYPES.has(line.payload.item?.type ?? "");
3400
+ }
3401
+ function parseArgs(raw) {
3402
+ if (typeof raw !== "string") return raw;
3403
+ try {
3404
+ return JSON.parse(raw);
3405
+ } catch {
3406
+ return void 0;
3407
+ }
3408
+ }
3409
+ var SHELL_RE = /(?:^|\/)(?:sh|bash|zsh|dash|ksh|fish)$/;
3410
+ function commandText(command) {
3411
+ if (typeof command === "string") return command;
3412
+ if (!Array.isArray(command) || !command.every((c) => typeof c === "string")) return "";
3413
+ const argv = command;
3414
+ if (argv.length === 3 && SHELL_RE.test(argv[0]) && /^-[a-z]*c$/.test(argv[1])) return argv[2];
3415
+ return argv.join(" ");
3416
+ }
3417
+ function toolItemAction(item) {
3418
+ if (item.type === "McpToolCall") {
3419
+ if (typeof item.tool !== "string" || !item.tool) return void 0;
3420
+ const name = typeof item.server === "string" && item.server ? `mcp__${item.server}__${item.tool}` : item.tool;
3421
+ return actionLine(name, parseArgs(item.arguments));
3422
+ }
3423
+ const command = commandText(item.command).trim();
3424
+ return command ? actionLine("exec_command", { command }) : void 0;
3425
+ }
2952
3426
  function readCodexTranscript(path) {
2953
3427
  const lines = [];
2954
3428
  for (const rawLine of readJsonl(path)) {
@@ -2962,6 +3436,7 @@ function readCodexTranscript(path) {
2962
3436
  }
2963
3437
  }
2964
3438
  const userFromEvents = lines.some(isUserMessageEvent);
3439
+ const actionsFromEvents = lines.some(isToolItemEvent);
2965
3440
  const turns = [];
2966
3441
  const push = (role, raw, stamp = {}) => {
2967
3442
  const text = stripInjectedMemory(raw).trim();
@@ -2972,16 +3447,24 @@ function readCodexTranscript(path) {
2972
3447
  push("user", contentText(line.payload?.item?.content), stampOf(line));
2973
3448
  continue;
2974
3449
  }
3450
+ if (isToolItemEvent(line)) {
3451
+ const action = toolItemAction(line.payload?.item ?? {});
3452
+ if (action) turns.push({ role: "action", content: action, ...stampOf(line) });
3453
+ continue;
3454
+ }
2975
3455
  if (line.type !== "response_item") continue;
2976
3456
  const p = line.payload;
2977
3457
  if (!p || typeof p !== "object") continue;
2978
3458
  if (p.type === "message") {
2979
- if (p.role === "assistant") push("assistant", contentText(p.content), stampOf(line));
2980
- else if (p.role === "user" && !userFromEvents) {
2981
- const text = contentText(p.content);
2982
- if (!isSyntheticUserText(stripInjectedMemory(text))) push("user", text, stampOf(line));
3459
+ if (p.role === "assistant") {
3460
+ if (p.channel === "analysis" || p.channel === "reasoning" || p.phase === "analysis" || p.phase === "reasoning")
3461
+ continue;
3462
+ push("assistant", contentText(p.content), stampOf(line));
3463
+ } else if (p.role === "user" && !userFromEvents) {
3464
+ push("user", fallbackUserText(p), stampOf(line));
2983
3465
  }
2984
3466
  } else if ((p.type === "function_call" || p.type === "custom_tool_call") && typeof p.name === "string") {
3467
+ if (actionsFromEvents && p.type === "custom_tool_call" && p.name === "exec") continue;
2985
3468
  const rawInput = p.type === "function_call" ? p.arguments : p.input;
2986
3469
  let input;
2987
3470
  try {
@@ -3082,19 +3565,19 @@ function readCopilotTranscript(path) {
3082
3565
  }
3083
3566
 
3084
3567
  // src/core/transcript-grok.ts
3085
- import { existsSync as existsSync7, readFileSync as readFileSync12, readdirSync as readdirSync2 } from "fs";
3086
- import { homedir as homedir8 } from "os";
3087
- import { join as join17 } from "path";
3568
+ import { existsSync as existsSync9, readFileSync as readFileSync13, readdirSync as readdirSync3 } from "fs";
3569
+ import { homedir as homedir9 } from "os";
3570
+ import { join as join19 } from "path";
3088
3571
  var CHAT_HISTORY = "chat_history.jsonl";
3089
- function grokTranscriptPath(cwd, sessionId, grokHome = process.env.GROK_HOME || join17(homedir8(), ".grok")) {
3090
- const sessionsDir = join17(grokHome, "sessions");
3091
- const direct = join17(sessionsDir, encodeURIComponent(cwd), sessionId, CHAT_HISTORY);
3092
- if (existsSync7(direct)) return direct;
3093
- try {
3094
- for (const candidate of readdirSync2(sessionsDir)) {
3095
- const directory = join17(sessionsDir, candidate);
3096
- if (readFileSync12(join17(directory, ".cwd"), "utf8").trim() === cwd) {
3097
- return join17(directory, sessionId, CHAT_HISTORY);
3572
+ function grokTranscriptPath(cwd, sessionId, grokHome = process.env.GROK_HOME || join19(homedir9(), ".grok")) {
3573
+ const sessionsDir = join19(grokHome, "sessions");
3574
+ const direct = join19(sessionsDir, encodeURIComponent(cwd), sessionId, CHAT_HISTORY);
3575
+ if (existsSync9(direct)) return direct;
3576
+ try {
3577
+ for (const candidate of readdirSync3(sessionsDir)) {
3578
+ const directory = join19(sessionsDir, candidate);
3579
+ if (readFileSync13(join19(directory, ".cwd"), "utf8").trim() === cwd) {
3580
+ return join19(directory, sessionId, CHAT_HISTORY);
3098
3581
  }
3099
3582
  }
3100
3583
  } catch {
@@ -3129,12 +3612,12 @@ function readGrokTranscript(path) {
3129
3612
  }
3130
3613
 
3131
3614
  // src/core/transcript-devin.ts
3132
- import { existsSync as existsSync8 } from "fs";
3615
+ import { existsSync as existsSync10 } from "fs";
3133
3616
  import { createRequire } from "module";
3134
- import { homedir as homedir9 } from "os";
3135
- import { join as join18 } from "path";
3136
- function devinSessionDb(home = homedir9()) {
3137
- return join18(home, ".local", "share", "devin", "cli", "sessions.db");
3617
+ import { homedir as homedir10 } from "os";
3618
+ import { join as join20 } from "path";
3619
+ function devinSessionDb(home = homedir10()) {
3620
+ return join20(home, ".local", "share", "devin", "cli", "sessions.db");
3138
3621
  }
3139
3622
  function parseDevinMessages(nodes) {
3140
3623
  const messages = /* @__PURE__ */ new Map();
@@ -3171,7 +3654,7 @@ function readDevinTranscript(sessionId, dbPath = devinSessionDb()) {
3171
3654
  diag("devin-cli", "sqlite_unavailable", { node: process.version, dbPath });
3172
3655
  return [];
3173
3656
  }
3174
- if (!existsSync8(dbPath)) {
3657
+ if (!existsSync10(dbPath)) {
3175
3658
  diag("devin-cli", "session_db_missing", { dbPath });
3176
3659
  return [];
3177
3660
  }
@@ -3444,7 +3927,7 @@ function readDroidTranscript(path) {
3444
3927
  }
3445
3928
 
3446
3929
  // src/core/transcript-zcode.ts
3447
- import { readFileSync as readFileSync13 } from "fs";
3930
+ import { readFileSync as readFileSync14 } from "fs";
3448
3931
  function messageText(content) {
3449
3932
  if (typeof content === "string") return content.trim();
3450
3933
  if (!Array.isArray(content)) return "";
@@ -3454,7 +3937,7 @@ function readZcodeTranscript(path) {
3454
3937
  if (!path) return [];
3455
3938
  let body;
3456
3939
  try {
3457
- body = readFileSync13(path, "utf8");
3940
+ body = readFileSync14(path, "utf8");
3458
3941
  } catch {
3459
3942
  return [];
3460
3943
  }
@@ -3488,6 +3971,131 @@ function zcodeAssistantText(path) {
3488
3971
  return readZcodeTranscript(path).filter((turn) => turn.role === "assistant").at(-1)?.content ?? "";
3489
3972
  }
3490
3973
 
3974
+ // src/core/transcript-kimi.ts
3975
+ import { existsSync as existsSync11, readdirSync as readdirSync4 } from "fs";
3976
+ import { homedir as homedir11 } from "os";
3977
+ import { join as join21 } from "path";
3978
+ var HARNESS = "kimi-code";
3979
+ var SESSIONS_DIR = "sessions";
3980
+ var AGENTS_DIR = "agents";
3981
+ var WIRE_LOG = "wire.jsonl";
3982
+ var SESSION_PREFIX = "session_";
3983
+ var MAIN_AGENT = "main";
3984
+ var MAX_SESSION_CHARS = 32 * 1024 * 1024;
3985
+ function kimiSessionDir(sessionId, kimiHome = process.env.KIMI_CODE_HOME || join21(homedir11(), ".kimi-code")) {
3986
+ const name = sessionId.startsWith(SESSION_PREFIX) ? sessionId : `${SESSION_PREFIX}${sessionId}`;
3987
+ const sessions = join21(kimiHome, SESSIONS_DIR);
3988
+ try {
3989
+ for (const workspace of readdirSync4(sessions, { withFileTypes: true })) {
3990
+ if (!workspace.isDirectory()) continue;
3991
+ const candidate = join21(sessions, workspace.name, name);
3992
+ if (existsSync11(join21(candidate, AGENTS_DIR))) return candidate;
3993
+ }
3994
+ } catch {
3995
+ }
3996
+ diag(HARNESS, "session_dir_missing", { sessions, session: name });
3997
+ return void 0;
3998
+ }
3999
+ function stampOf2(event) {
4000
+ if (typeof event.time !== "number") return {};
4001
+ const at = new Date(event.time);
4002
+ return Number.isNaN(at.getTime()) ? {} : { timestamp: at.toISOString() };
4003
+ }
4004
+ function kimiPromptText(input) {
4005
+ if (!Array.isArray(input)) return "";
4006
+ return input.filter((block) => block?.type === "text" && typeof block.text === "string").map((block) => block.text).join("\n");
4007
+ }
4008
+ function readKimiWire(events) {
4009
+ const turns = [];
4010
+ let step;
4011
+ const flushStep = () => {
4012
+ if (!step) return;
4013
+ const content = stripInjectedMemory(step.texts.join("\n")).trim();
4014
+ if (content) turns.push({ role: "assistant", content, ...step.stamp });
4015
+ step = void 0;
4016
+ };
4017
+ for (const event of events || []) {
4018
+ if (!event || typeof event !== "object") continue;
4019
+ const stamp = stampOf2(event);
4020
+ if (event.type === "turn.prompt") {
4021
+ flushStep();
4022
+ if (event.origin?.kind !== "user") continue;
4023
+ const content = stripInjectedMemory(kimiPromptText(event.input)).trim();
4024
+ if (content) turns.push({ role: "user", content, ...stamp });
4025
+ continue;
4026
+ }
4027
+ if (event.type !== "context.append_loop_event") continue;
4028
+ const loop = event.event;
4029
+ if (!loop || typeof loop !== "object") continue;
4030
+ if (loop.type === "content.part") {
4031
+ if (loop.part?.type !== "text" || typeof loop.part.text !== "string") continue;
4032
+ const uuid = typeof loop.stepUuid === "string" ? loop.stepUuid : "";
4033
+ if (step && step.uuid !== uuid) flushStep();
4034
+ if (!step) step = { uuid, texts: [], stamp };
4035
+ step.texts.push(loop.part.text);
4036
+ } else if (loop.type === "tool.call") {
4037
+ flushStep();
4038
+ if (typeof loop.name !== "string" || !loop.name) continue;
4039
+ turns.push({ role: "action", content: actionLine(loop.name, loop.args), ...stamp });
4040
+ }
4041
+ }
4042
+ flushStep();
4043
+ return turns;
4044
+ }
4045
+ function agentIds(sessionDir) {
4046
+ try {
4047
+ return readdirSync4(join21(sessionDir, AGENTS_DIR), { withFileTypes: true }).filter((entry) => entry.isDirectory()).map((entry) => entry.name).sort(byAgentId);
4048
+ } catch {
4049
+ return [];
4050
+ }
4051
+ }
4052
+ function byAgentId(a, b) {
4053
+ if (a === b) return 0;
4054
+ if (a === MAIN_AGENT) return -1;
4055
+ if (b === MAIN_AGENT) return 1;
4056
+ const indexA = agentIndex(a);
4057
+ const indexB = agentIndex(b);
4058
+ return indexA === indexB ? a.localeCompare(b) : indexA - indexB;
4059
+ }
4060
+ function agentIndex(id) {
4061
+ const suffix = Number(id.slice(id.lastIndexOf("-") + 1));
4062
+ return Number.isFinite(suffix) ? suffix : Number.MAX_SAFE_INTEGER;
4063
+ }
4064
+ function parseEvent(rawLine) {
4065
+ const trimmed = rawLine.trim();
4066
+ if (!trimmed) return void 0;
4067
+ let parsed;
4068
+ try {
4069
+ parsed = JSON.parse(trimmed);
4070
+ } catch {
4071
+ return void 0;
4072
+ }
4073
+ return typeof parsed === "object" && parsed !== null ? parsed : void 0;
4074
+ }
4075
+ function readKimiTranscript(path) {
4076
+ const turns = [];
4077
+ let remaining = MAX_SESSION_CHARS;
4078
+ for (const agentId of agentIds(path)) {
4079
+ const wire = join21(path, AGENTS_DIR, agentId, WIRE_LOG);
4080
+ const events = [];
4081
+ for (const rawLine of readJsonl(wire)) {
4082
+ remaining -= rawLine.length;
4083
+ if (remaining < 0) break;
4084
+ const event = parseEvent(rawLine);
4085
+ if (event) events.push(event);
4086
+ }
4087
+ for (const turn of readKimiWire(events)) turns.push(turn);
4088
+ if (remaining < 0) {
4089
+ log.warn(HARNESS, "session exceeds the wire-log budget \u2014 later agents were not read", {
4090
+ sessionDir: path,
4091
+ stoppedAt: wire
4092
+ });
4093
+ break;
4094
+ }
4095
+ }
4096
+ return turns;
4097
+ }
4098
+
3491
4099
  // src/harness/hook-lifecycle.ts
3492
4100
  var cursorCwd = (ev) => ev.cwd ?? ev.workspace_root ?? (Array.isArray(ev.workspace_roots) ? ev.workspace_roots[0] : void 0);
3493
4101
  var claudePrompt = {
@@ -3566,7 +4174,7 @@ var copilotPrompt = {
3566
4174
  ${context}`.trim()
3567
4175
  })
3568
4176
  };
3569
- var devinCwd = () => process.env.DEVIN_PROJECT_DIR;
4177
+ var devinCwd = () => process.env.DEVIN_PROJECT_DIR || process.cwd();
3570
4178
  var devinPrompt = {
3571
4179
  harness: "devin-cli",
3572
4180
  requireCwd: true,
@@ -3593,6 +4201,7 @@ var standardSessionStart = (harness) => ({
3593
4201
  }
3594
4202
  })
3595
4203
  });
4204
+ var notGrokHosted = () => !process.env.GROK_HOOK_EVENT;
3596
4205
  var HOOK_HARNESSES = {
3597
4206
  "claude-code": {
3598
4207
  configStyle: "nested",
@@ -3601,11 +4210,12 @@ var HOOK_HARNESSES = {
3601
4210
  prompt: { event: "UserPromptSubmit", entry: "claude-hook.js", timeout: 30 },
3602
4211
  stop: { event: "Stop", entry: "claude-stop-hook.js", timeout: 60 }
3603
4212
  },
3604
- sessionStart: standardSessionStart("claude-code"),
3605
- prompt: claudePrompt,
4213
+ sessionStart: { ...standardSessionStart("claude-code"), accept: notGrokHosted },
4214
+ prompt: { ...claudePrompt, accept: notGrokHosted },
3606
4215
  retain: {
3607
4216
  hostTimeoutSec: 60,
3608
4217
  harness: "claude-code",
4218
+ accept: notGrokHosted,
3609
4219
  parse: (ev) => ({
3610
4220
  sessionId: ev.session_id,
3611
4221
  transcriptPath: ev.transcript_path,
@@ -3921,6 +4531,117 @@ var HOOK_HARNESSES = {
3921
4531
  assistantText: (ev) => (ev.responseText || zcodeAssistantText(ev.transcript_path) || ev.responsePreview || "").trim()
3922
4532
  }
3923
4533
  }
4534
+ },
4535
+ /**
4536
+ * TraeCode (TRAE CN's agent) also speaks Claude Code's hook protocol — `prompt`/`cwd`/`session_id`
4537
+ * in, `hookSpecificOutput.additionalContext` + `systemMessage` out — with registrations nested
4538
+ * under the top-level `hooks` key of `~/.trae-cn/hooks.json` (unlike Factory Droid, whose event
4539
+ * map IS the file) and a `version` field the host writes and expects.
4540
+ *
4541
+ * Like ZCode, what it does not have is a TRANSCRIPT: sessions live in an encrypted local DB or
4542
+ * the cloud and no `transcript_path` is ever supplied, so this is the second harness that retains
4543
+ * from the plugin's own journal (core/turn-journal.ts) — the prompt hook appends the user turn,
4544
+ * and Stop's `last_assistant_message` (the full reply) plays the role ZCode's `responseText`
4545
+ * plays: `journal.assistantText` closes the turn with it.
4546
+ */
4547
+ traecode: {
4548
+ configStyle: "nested",
4549
+ install: {
4550
+ sessionStart: { event: "SessionStart", entry: "traecode-sessionstart-hook.js", timeout: 30 },
4551
+ prompt: { event: "UserPromptSubmit", entry: "traecode-hook.js", timeout: 30 },
4552
+ stop: { event: "Stop", entry: "traecode-stop-hook.js", timeout: 60 }
4553
+ },
4554
+ sessionStart: {
4555
+ ...standardSessionStart("traecode"),
4556
+ // Trae launches USER-level MCP servers from the Electron process's cwd (home), where an
4557
+ // optInOnly config self-disables and the tools vanish. Each repo's own workspace file fixes
4558
+ // it — kept current here, once memory is confirmed live for the repo, along with the
4559
+ // workspace's per-server enable switch (seeded into Trae's storage DB,
4560
+ // core/traecode-mcp.ts). The returned hint (global gate off, or an unseedable switch)
4561
+ // rides the session banner.
4562
+ ensureMcpRegistration: (cwd) => ensureTraecodeWorkspaceMcp(cwd)
4563
+ },
4564
+ prompt: {
4565
+ ...claudePrompt,
4566
+ harness: "traecode",
4567
+ journalPrompt: true,
4568
+ // TraeCode's UserPromptSubmit payload carries `prompt` exactly like Claude Code's.
4569
+ parse: (ev) => ({
4570
+ prompt: ev.prompt,
4571
+ cwd: ev.cwd,
4572
+ sessionId: ev.session_id
4573
+ })
4574
+ },
4575
+ retain: {
4576
+ hostTimeoutSec: 60,
4577
+ harness: "traecode",
4578
+ // No transcriptPath: the journal supplies it (see `journal` below).
4579
+ parse: (ev) => ({
4580
+ sessionId: ev.session_id,
4581
+ cwd: ev.cwd
4582
+ }),
4583
+ journal: {
4584
+ // `last_assistant_message` is the full reply — TraeCode's `responseText`.
4585
+ assistantText: (ev) => (ev.last_assistant_message ?? "").trim()
4586
+ }
4587
+ }
4588
+ },
4589
+ "kimi-code": {
4590
+ // Kimi's ~/.kimi-code/config.toml takes a FLAT [[hooks]] array whose entries are validated by a
4591
+ // strict 4-key schema (event/matcher/command/timeout). Neither JSON style can express it, and a
4592
+ // fifth key drops EVERY hook in the file at warning severity, so its installer writes the block
4593
+ // itself (the grok-build pattern) rather than going through mergeHarnessHooks.
4594
+ configStyle: "toml-array",
4595
+ install: {
4596
+ // Timeouts are SECONDS here (integer 1-600, default 30) — the same unit as every other
4597
+ // supported host, and the opposite of qwen-code's identically named field.
4598
+ sessionStart: { event: "SessionStart", entry: "kimi-sessionstart-hook.js", timeout: 30 },
4599
+ prompt: { event: "UserPromptSubmit", entry: "kimi-hook.js", timeout: 30 },
4600
+ stop: { event: "Stop", entry: "kimi-stop-hook.js", timeout: 60 }
4601
+ },
4602
+ sessionStart: {
4603
+ harness: "kimi-code",
4604
+ parse: (ev) => ({
4605
+ cwd: ev.cwd,
4606
+ sessionId: ev.session_id
4607
+ }),
4608
+ // Kimi runs SessionStart hooks for their side effects only: it awaits the trigger and drops
4609
+ // the result, so nothing emitted here can reach the model or the terminal. Installed for the
4610
+ // seed/daemon/session-root work runSessionStartHook does, and silent like antigravity-cli's.
4611
+ emit: () => ({})
4612
+ },
4613
+ prompt: {
4614
+ harness: "kimi-code",
4615
+ parse: (ev) => ({
4616
+ // A block array, not a string — the same shape as the wire log's `turn.prompt.input`.
4617
+ prompt: kimiPromptText(ev.prompt),
4618
+ cwd: ev.cwd,
4619
+ sessionId: ev.session_id
4620
+ }),
4621
+ // Kimi has no additionalContext: a top-level `message` is the injection channel, which the
4622
+ // CLI wraps as <hook_result hook_event="UserPromptSubmit"> and appends to the conversation.
4623
+ // `notice` has no banner channel to reach (the copilot-cli precedent), but it cannot simply
4624
+ // be dropped: when a hook's stdout parses to JSON carrying no message, Kimi falls back to
4625
+ // injecting the RAW STDOUT, so an empty `{}` would put a literal "{}" in front of the model.
4626
+ // Emitting the notice on the notice-only turn is what keeps that from ever happening.
4627
+ emit: (context, notice) => ({ message: context || notice })
4628
+ },
4629
+ retain: {
4630
+ hostTimeoutSec: 60,
4631
+ harness: "kimi-code",
4632
+ parse: (ev) => {
4633
+ const sessionId = ev.session_id;
4634
+ return {
4635
+ sessionId,
4636
+ // Kimi's Stop payload carries no transcript path — its hook feature has no such field at
4637
+ // all — so resolve the session's own directory from the id, as grok-build does. The
4638
+ // reader takes that DIRECTORY and reads every agent's wire.jsonl beneath it.
4639
+ transcriptPath: sessionId ? kimiSessionDir(sessionId) : void 0,
4640
+ cwd: ev.cwd
4641
+ };
4642
+ },
4643
+ readTranscript: readKimiTranscript
4644
+ }
3924
4645
  }
3925
4646
  };
3926
4647
  var runHarnessSessionStart = (harness) => runSessionStartHook(HOOK_HARNESSES[harness].sessionStart);