@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
package/dist/grok-hook.js CHANGED
@@ -267,13 +267,13 @@ function isWithin(directory, configured) {
267
267
  function mapLookup(map, directory) {
268
268
  const cwd = normalize(directory);
269
269
  let best;
270
- for (const [dir, bank] of Object.entries(map)) {
270
+ for (const [dir, value] of Object.entries(map)) {
271
271
  const p = configuredDir(dir);
272
272
  if (isWithin(cwd, p)) {
273
- if (!best || p.length > best.len) best = { len: p.length, bank };
273
+ if (!best || p.length > best.len) best = { len: p.length, value };
274
274
  }
275
275
  }
276
- return best?.bank;
276
+ return best?.value;
277
277
  }
278
278
  function lookupDirectories(config, directory, sessionRoot = "") {
279
279
  const directories = [normalize(directory)];
@@ -297,6 +297,10 @@ function isOptedIn(config, directory) {
297
297
  const pathMap = config.mapPathToBank;
298
298
  return Boolean(pathMap && directories.some((candidate) => mapLookup(pathMap, candidate)));
299
299
  }
300
+ function pathSection(config, paths, directory) {
301
+ if (!directory || !paths) return void 0;
302
+ return lookupDirectories(config, directory).map((candidate) => mapLookup(paths, candidate)).find((section) => section !== void 0);
303
+ }
300
304
  function mappedBank(config, directory, sessionRoot) {
301
305
  const pathMap = config.mapPathToBank;
302
306
  if (!directory || !pathMap) return void 0;
@@ -582,12 +586,17 @@ var CODING_BANK_TEMPLATE = {
582
586
  }
583
587
  };
584
588
  var MISSION_FIELDS = ["reflect_mission", "retain_mission", "observations_mission"];
589
+ var PLUGIN_GOVERNED_BANK_FIELDS = [
590
+ "retain_strategies",
591
+ "entity_labels",
592
+ "retain_extraction_mode"
593
+ ];
585
594
  function isSet(v) {
586
595
  if (v === null || v === void 0) return false;
587
596
  if (typeof v === "string") return v.trim() !== "";
588
597
  return true;
589
598
  }
590
- function codingBankManifest(overrides, mode = DEFAULT_RETAIN_EXTRACTION_MODE) {
599
+ function codingBankManifest(overrides, mode = DEFAULT_RETAIN_EXTRACTION_MODE, defaults = {}) {
591
600
  const current2 = overrides ?? {};
592
601
  const template = CODING_BANK_TEMPLATE.bank;
593
602
  const bank = {};
@@ -616,6 +625,10 @@ function codingBankManifest(overrides, mode = DEFAULT_RETAIN_EXTRACTION_MODE) {
616
625
  const [knowledgeGroup] = template.entity_labels;
617
626
  if (!labels.some((g) => g?.key === knowledgeGroup.key))
618
627
  bank.entity_labels = [...labels, knowledgeGroup];
628
+ for (const [key, value] of Object.entries(defaults)) {
629
+ if (PLUGIN_GOVERNED_BANK_FIELDS.includes(key) || !isSet(value) || isSet(current2[key])) continue;
630
+ bank[key] = value;
631
+ }
619
632
  return Object.keys(bank).length > 0 ? { version: "1", bank } : void 0;
620
633
  }
621
634
 
@@ -651,6 +664,15 @@ async function pool(items, n, fn, onError, onProgress) {
651
664
  }
652
665
  await Promise.all(Array.from({ length: Math.min(n, items.length) }, worker));
653
666
  }
667
+ function isOurMcpEntry(entry) {
668
+ if (!entry || typeof entry !== "object") return false;
669
+ const candidate = entry;
670
+ if (candidate.command !== "node" || !Array.isArray(candidate.args)) return false;
671
+ const script = candidate.args[0];
672
+ if (typeof script !== "string") return false;
673
+ const parts = script.replaceAll("\\", "/").split("/").filter(Boolean);
674
+ return parts.at(-1) === "mcp-server.js" && parts.at(-2) === "dist" && (parts.at(-3) === "coding-agents" || parts.at(-3) === "hindsight-coding-agents");
675
+ }
654
676
 
655
677
  // src/core/hindsight.ts
656
678
  function resolveRetainScopes(tags, configured) {
@@ -719,6 +741,18 @@ var DEFAULT_RECALL_OPTIONS = {
719
741
  var POLL_CYCLE_MS = 5e3;
720
742
  var RETRY_AFTER_FLOOR_MS = 10 * 1e3;
721
743
  var RETRY_AFTER_CEILING_MS = 60 * 1e3;
744
+ function shapePage(page) {
745
+ const p = page ?? {};
746
+ const body = typeof p.body === "string" && p.body.trim() ? p.body : p.markdown;
747
+ return {
748
+ id: p.id,
749
+ name: p.name,
750
+ ...p.description ? { description: p.description } : {},
751
+ ...Array.isArray(p.tags) && p.tags.length ? { tags: p.tags } : {},
752
+ ...p.timestamp ? { last_updated_at: p.timestamp } : {},
753
+ body
754
+ };
755
+ }
722
756
  var HindsightClient = class {
723
757
  apiUrl;
724
758
  /** The credential the NEXT request will sign with — NOT the one the config file holds. The two
@@ -756,7 +790,10 @@ var HindsightClient = class {
756
790
  return this.token;
757
791
  }
758
792
  headers() {
759
- const h = { "Content-Type": "application/json" };
793
+ const h = {
794
+ "Content-Type": "application/json",
795
+ "Accept-Encoding": "identity"
796
+ };
760
797
  if (this.token) h["Authorization"] = `Bearer ${this.token}`;
761
798
  return h;
762
799
  }
@@ -864,6 +901,23 @@ var HindsightClient = class {
864
901
  return false;
865
902
  }
866
903
  }
904
+ /**
905
+ * Whether a session write-back may use `update_mode="append"`: the server must dedupe by
906
+ * `operation_id` AND the bank must keep document text, or the server rejects the append in the
907
+ * background (#4613). Only an explicit `store_document_text: false` answers "no" — an unreachable
908
+ * or unparseable config assumes the default (stored), so a flaky probe never downgrades appends.
909
+ */
910
+ async supportsAppendRetain() {
911
+ if (!await this.supportsIdempotentRetain()) return false;
912
+ try {
913
+ const r = await this.req("GET", this.bankUrl("/config"));
914
+ if (!r.ok) return true;
915
+ const j = await r.json();
916
+ return j.config?.store_document_text !== false;
917
+ } catch {
918
+ return true;
919
+ }
920
+ }
867
921
  /**
868
922
  * Every document_id currently in the bank under a strategy tag (e.g. `source:git`), paginated into a
869
923
  * Set. Powers the incremental git-sync's "what's already ingested?" check — since git commits are stored
@@ -889,6 +943,24 @@ var HindsightClient = class {
889
943
  }
890
944
  return ids;
891
945
  }
946
+ /**
947
+ * The tags on one document, or undefined when the bank holds none with that id. Read from the
948
+ * document LISTING narrowed by `q` (a substring match on the id, so the exact id is picked out of
949
+ * the page) rather than GET /documents/{id}, which also sends the document's full text: the
950
+ * caller, the git-log freshness check on SessionStart, reads a ~100k-character document for one tag.
951
+ */
952
+ async documentTags(documentId) {
953
+ const limit = 100;
954
+ for (let offset = 0; ; offset += limit) {
955
+ const q = `?q=${encodeURIComponent(documentId)}&limit=${limit}&offset=${offset}`;
956
+ const r = await this.req("GET", this.bankUrl(`/documents${q}`));
957
+ const j = await r.json();
958
+ const items = j.items ?? [];
959
+ const hit = items.find((it) => it.id === documentId);
960
+ if (hit) return hit.tags ?? [];
961
+ if (items.length < limit || offset + limit >= (j.total ?? 0)) return void 0;
962
+ }
963
+ }
892
964
  /** Configure the bank: POST the coding bank manifest to /import (missions, retain strategies,
893
965
  * entity labels), then seed knowledge pages when the server supports them. Both halves are
894
966
  * idempotent and ADDITIVE — nothing the bank already says is overwritten (#3927), bar the
@@ -910,7 +982,8 @@ var HindsightClient = class {
910
982
  } else {
911
983
  const manifest = codingBankManifest(
912
984
  opts.reset ? void 0 : await this.readBankOverrides(),
913
- opts.extractionMode
985
+ opts.extractionMode,
986
+ opts.defaults
914
987
  );
915
988
  if (!manifest) {
916
989
  this.log(`[bank] ${this.bank} already carries the coding structure \u2014 nothing to apply`);
@@ -1116,8 +1189,8 @@ var HindsightClient = class {
1116
1189
  return { items };
1117
1190
  }
1118
1191
  /**
1119
- * Read one knowledge page's synthesized content by knowledge-base id, as an OKF document
1120
- * (YAML frontmatter + markdown body). The endpoint omits the internal reflect trace that built
1192
+ * Read one knowledge page's synthesized content by knowledge-base id, shaped by `shapePage` so
1193
+ * the body arrives once. The endpoint omits the internal reflect trace that built
1121
1194
  * the page — that is 70-95% of the raw bytes and can blow past an MCP host's per-tool-result
1122
1195
  * token cap.
1123
1196
  */
@@ -1128,7 +1201,7 @@ var HindsightClient = class {
1128
1201
  this.bankUrl(`/knowledge-base/pages/${encodeURIComponent(pageId)}`)
1129
1202
  );
1130
1203
  if (r.status === 404) throw new Error(`knowledge page not found: ${pageId}`);
1131
- return await r.json();
1204
+ return shapePage(await r.json());
1132
1205
  }
1133
1206
  /** Hybrid (BM25 + vector, RRF-fused) server-side search over the bank's knowledge pages.
1134
1207
  * Returns page-level hits with a relevance snippet — the real search behind
@@ -1149,6 +1222,7 @@ var HindsightClient = class {
1149
1222
  return (j.results ?? []).map((x) => ({
1150
1223
  id: x.id,
1151
1224
  name: x.name,
1225
+ ...x.source_query ? { source_query: x.source_query } : {},
1152
1226
  snippet: x.snippet ?? "",
1153
1227
  score: x.score ?? 0
1154
1228
  }));
@@ -1419,6 +1493,7 @@ function resolveCustomPages(raw) {
1419
1493
  }
1420
1494
  var DEFAULT_REFLECT_TIMEOUT_MS = 2e4;
1421
1495
  var DEFAULT_REFLECT_TOOL_TIMEOUT_MS = 33e4;
1496
+ var DEFAULT_INJECT_TIMEOUT_MS = 7e3;
1422
1497
  var REFLECT_BUDGETS = ["low", "mid", "high"];
1423
1498
  function resolveReflectBudget(raw) {
1424
1499
  const value = raw.reflectBudget;
@@ -1445,6 +1520,22 @@ function resolveObservationScopes(raw) {
1445
1520
  }
1446
1521
  return DEFAULT_OBSERVATION_SCOPES;
1447
1522
  }
1523
+ function resolveDefaultBankConfig(raw) {
1524
+ const value = raw;
1525
+ if (!value || typeof value !== "object" || Array.isArray(value)) return {};
1526
+ const out = {};
1527
+ for (const [key, v] of Object.entries(value)) {
1528
+ if (PLUGIN_GOVERNED_BANK_FIELDS.includes(key)) {
1529
+ log.warn(
1530
+ "config",
1531
+ `ignoring defaultBankConfig.${key} \u2014 the plugin manages this field itself` + (key === "retain_extraction_mode" ? " (set retainExtractionMode instead)" : "")
1532
+ );
1533
+ continue;
1534
+ }
1535
+ out[key] = v;
1536
+ }
1537
+ return out;
1538
+ }
1448
1539
  var AUTO_INJECT_MODES = ["reflect", "pages", "recall", "none"];
1449
1540
  function resolveAutoInject(raw) {
1450
1541
  if (raw.autoReflect !== void 0) {
@@ -1484,18 +1575,21 @@ function resolveConfig(raw = {}) {
1484
1575
  // write sessions back by default, every harness
1485
1576
  manageBankConfig: raw.manageBankConfig ?? true,
1486
1577
  retainExtractionMode: RETAIN_EXTRACTION_MODES.includes(raw.retainExtractionMode) ? raw.retainExtractionMode : DEFAULT_RETAIN_EXTRACTION_MODE,
1578
+ defaultBankConfig: resolveDefaultBankConfig(raw.defaultBankConfig),
1487
1579
  maxParallelRetains: raw.maxParallelRetains || 10,
1488
1580
  reflectTimeoutMs: raw.reflectTimeoutMs || DEFAULT_REFLECT_TIMEOUT_MS,
1489
1581
  // Inherit an explicitly-raised reflectTimeoutMs (that is what users reaching for a longer
1490
1582
  // reflect already set), but never let it LOWER the tool below the default — a short window is
1491
1583
  // set to bound the automatic hook, not to cut off a call the agent is waiting on.
1492
1584
  reflectToolTimeoutMs: raw.reflectToolTimeoutMs || Math.max(raw.reflectTimeoutMs || 0, DEFAULT_REFLECT_TOOL_TIMEOUT_MS),
1585
+ injectTimeoutMs: raw.injectTimeoutMs || DEFAULT_INJECT_TIMEOUT_MS,
1493
1586
  reflectBudget: resolveReflectBudget(raw),
1494
1587
  autoInject: resolveAutoInject(raw),
1495
1588
  pageSearchLimit: raw.pageSearchLimit || DEFAULT_PAGE_SEARCH_LIMIT,
1496
1589
  // Same shape as retainMetadata: an object, or nothing. An array would spread into numeric
1497
1590
  // keys and reach the API as garbage, so it is rejected like any other non-object.
1498
1591
  recallOptions: raw.recallOptions && typeof raw.recallOptions === "object" && !Array.isArray(raw.recallOptions) ? { ...raw.recallOptions } : {},
1592
+ toolGuideExtra: typeof raw.toolGuideExtra === "string" && raw.toolGuideExtra.trim() ? raw.toolGuideExtra : void 0,
1499
1593
  // Every turn, not every tenth. The guide is what tells the agent WHEN to reach for memory, and
1500
1594
  // at a cadence of 10 a normal session is told once, on turn 1, and never again. Measured over
1501
1595
  // 40 real Claude Code turns, moving this from 10 to 1 took searches from 15% of turns to 32.5%
@@ -1515,11 +1609,15 @@ function resolveConfig(raw = {}) {
1515
1609
  // Hostile input is a config typo, not an attack: keep only string entries so a stray number or
1516
1610
  // nested object cannot reach the API as a tag and fail the whole retain.
1517
1611
  retainTags: Array.isArray(raw.retainTags) ? raw.retainTags.filter((t) => typeof t === "string" && t.trim() !== "") : [],
1612
+ // Undefined, not "", when unset or blank: the retain call distinguishes "not configured" (use
1613
+ // the built-in default) from a configured value, and an empty context would strip the default.
1614
+ retainContext: typeof raw.retainContext === "string" && raw.retainContext.trim() !== "" ? raw.retainContext : void 0,
1518
1615
  retainMetadata: raw.retainMetadata && typeof raw.retainMetadata === "object" ? Object.fromEntries(
1519
1616
  Object.entries(raw.retainMetadata).filter(([, v]) => typeof v === "string")
1520
1617
  ) : {},
1521
1618
  observationScopes: resolveObservationScopes(raw.observationScopes),
1522
1619
  banks: raw.banks && typeof raw.banks === "object" ? raw.banks : {},
1620
+ paths: raw.paths && typeof raw.paths === "object" ? raw.paths : {},
1523
1621
  logLevel: ["debug", "info", "warn", "error"].includes(raw.logLevel) ? raw.logLevel : "info",
1524
1622
  autoUpdate: raw.autoUpdate ?? true
1525
1623
  };
@@ -1536,7 +1634,12 @@ function readRaw(path) {
1536
1634
  }
1537
1635
  function mergeRaw(a, b) {
1538
1636
  const { harnesses: _drop, ...flat } = b;
1539
- return { ...a, ...flat, banks: { ...a.banks ?? {}, ...b.banks ?? {} } };
1637
+ return {
1638
+ ...a,
1639
+ ...flat,
1640
+ banks: { ...a.banks ?? {}, ...b.banks ?? {} },
1641
+ paths: { ...a.paths ?? {}, ...b.paths ?? {} }
1642
+ };
1540
1643
  }
1541
1644
  function applyLayer(raw, layer, harness) {
1542
1645
  let out = mergeRaw(raw, layer);
@@ -1567,9 +1670,11 @@ var ENV_KEYS = {
1567
1670
  maxParallelRetains: "HINDSIGHT_MAX_PARALLEL_RETAINS",
1568
1671
  reflectTimeoutMs: "HINDSIGHT_REFLECT_TIMEOUT_MS",
1569
1672
  reflectToolTimeoutMs: "HINDSIGHT_REFLECT_TOOL_TIMEOUT_MS",
1673
+ injectTimeoutMs: "HINDSIGHT_INJECT_TIMEOUT_MS",
1570
1674
  reflectBudget: "HINDSIGHT_REFLECT_BUDGET",
1571
1675
  autoInject: "HINDSIGHT_AUTO_INJECT",
1572
1676
  pageSearchLimit: "HINDSIGHT_PAGE_SEARCH_LIMIT",
1677
+ toolGuideExtra: "HINDSIGHT_TOOL_GUIDE_EXTRA",
1573
1678
  autoReflect: "HINDSIGHT_AUTO_REFLECT",
1574
1679
  pageRefreshEveryTurns: "HINDSIGHT_PAGE_REFRESH_EVERY_TURNS",
1575
1680
  pageTriggerType: "HINDSIGHT_PAGE_TRIGGER_TYPE",
@@ -1611,6 +1716,7 @@ var ENV_NUMBERS = /* @__PURE__ */ new Set([
1611
1716
  "maxParallelRetains",
1612
1717
  "reflectTimeoutMs",
1613
1718
  "reflectToolTimeoutMs",
1719
+ "injectTimeoutMs",
1614
1720
  "pageSearchLimit",
1615
1721
  "pageRefreshEveryTurns",
1616
1722
  "seedLimit",
@@ -1659,15 +1765,25 @@ var BANK_OVERRIDE_EXCLUDED = [
1659
1765
  function applyBankConfig(cfg, resolvedId, directory) {
1660
1766
  if (directory !== void 0 && !isOptedIn(cfg, directory))
1661
1767
  return { cfg: { ...cfg, disabled: true }, bankId: resolvedId };
1768
+ const byPath = directory === void 0 ? void 0 : pathSection(cfg, cfg.paths, directory);
1769
+ if (byPath) {
1770
+ const { bank: _rename, ...rest } = overrideFields(byPath);
1771
+ cfg = { ...cfg, ...resolvePartial(cfg, rest) };
1772
+ }
1662
1773
  const section = cfg.banks[resolvedId];
1663
1774
  if (!section) return { cfg, bankId: resolvedId };
1664
- const safe = { ...section };
1665
- for (const k of BANK_OVERRIDE_EXCLUDED) delete safe[k];
1666
- delete safe.banks;
1775
+ const safe = overrideFields(section);
1667
1776
  const bankId = typeof safe.bank === "string" && safe.bank ? safe.bank : resolvedId;
1668
1777
  delete safe.bank;
1669
1778
  return { cfg: { ...cfg, ...resolvePartial(cfg, safe) }, bankId };
1670
1779
  }
1780
+ function overrideFields(section) {
1781
+ const safe = { ...section };
1782
+ for (const k of BANK_OVERRIDE_EXCLUDED) delete safe[k];
1783
+ delete safe.banks;
1784
+ delete safe.paths;
1785
+ return safe;
1786
+ }
1671
1787
  function resolvePartial(cfg, patch) {
1672
1788
  const full = resolveConfig(patch);
1673
1789
  const out = {};
@@ -1676,6 +1792,16 @@ function resolvePartial(cfg, patch) {
1676
1792
  out[key] = full[key];
1677
1793
  }
1678
1794
  if ("autoReflect" in patch && !("autoInject" in patch)) out.autoInject = full.autoInject;
1795
+ if ("serverMode" in patch || "apiUrl" in patch || "apiPort" in patch) {
1796
+ const conn = resolveConfig({
1797
+ serverMode: patch.serverMode ?? cfg.serverMode,
1798
+ apiPort: patch.apiPort ?? cfg.apiPort,
1799
+ apiUrl: patch.apiUrl ?? (cfg.serverMode === "daemon" ? void 0 : cfg.apiUrl)
1800
+ });
1801
+ out.serverMode = conn.serverMode;
1802
+ out.apiUrl = conn.apiUrl;
1803
+ out.apiPort = conn.apiPort;
1804
+ }
1679
1805
  return out;
1680
1806
  }
1681
1807
 
@@ -1753,13 +1879,13 @@ function indexLine(pages) {
1753
1879
  const count = pages.length === 1 ? "1 knowledge page covers" : `${pages.length} knowledge pages cover`;
1754
1880
  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.`;
1755
1881
  }
1756
- 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:
1757
- \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);
1882
+ 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:
1883
+ \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);
1758
1884
  \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);
1759
1885
  \u2022 you are implementing something new, or two parts have to fit together;
1760
1886
  \u2022 the user asks why something is the way it is, or what is left to do;
1761
1887
  \u2022 you are about to commit, and need to know what the change was supposed to honour.
1762
- It ranks the pages by relevance and returns the matching passage, which a page title cannot tell you.
1888
+ 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.
1763
1889
  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.
1764
1890
  - 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.
1765
1891
  - 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>").
@@ -1767,7 +1893,9 @@ var TOOL_GUIDE = `- hindsight_search_knowledge_pages(query) \u2014 FIRST STOP, a
1767
1893
  - 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).`;
1768
1894
  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";
1769
1895
  function toolGuide(opts) {
1770
- return (opts?.reflectOnNewGoals ? PAGES_FIRST_ON_GOALS : "") + TOOL_GUIDE;
1896
+ const extra = opts?.extra?.trim();
1897
+ return (opts?.reflectOnNewGoals ? PAGES_FIRST_ON_GOALS : "") + TOOL_GUIDE + (extra ? `
1898
+ ${extra}` : "");
1771
1899
  }
1772
1900
  function buildRosterRefresh(pages, opts) {
1773
1901
  const rosterBlock = pages.length ? `${indexLine(pages)}
@@ -1926,7 +2054,6 @@ function readJournalTranscript(path) {
1926
2054
  }
1927
2055
 
1928
2056
  // src/core/hook.ts
1929
- var HOOK_FALLBACK_BUDGET_MS = 7e3;
1930
2057
  var HOOK_INJECT_ATTEMPTS = 2;
1931
2058
  function resolveInjection(got, attempts) {
1932
2059
  if (got != null) return got;
@@ -1954,8 +2081,8 @@ async function injectRecall(harness, prompt, client, timeoutMs, event, lead) {
1954
2081
  return void 0;
1955
2082
  }
1956
2083
  }
1957
- async function reflectFallback(harness, prompt, client) {
1958
- const deadline = Date.now() + HOOK_FALLBACK_BUDGET_MS;
2084
+ async function reflectFallback(harness, prompt, client, timeoutMs) {
2085
+ const deadline = Date.now() + timeoutMs;
1959
2086
  const remaining = () => Math.max(deadline - Date.now(), 1);
1960
2087
  return await injectPages(harness, prompt, client, remaining(), "reflect_fallback_pages") ?? // Event name predates the `injectRecall` rename and is kept: it is a logged contract that
1961
2088
  // other tools read, so renaming it would silently break them.
@@ -1980,7 +2107,7 @@ async function buildHookOutput(args) {
1980
2107
  harness,
1981
2108
  prompt,
1982
2109
  client,
1983
- HOOK_FALLBACK_BUDGET_MS,
2110
+ cfg.injectTimeoutMs,
1984
2111
  "inject_pages",
1985
2112
  PAGE_INJECT_LEAD
1986
2113
  );
@@ -1993,7 +2120,7 @@ async function buildHookOutput(args) {
1993
2120
  harness,
1994
2121
  prompt,
1995
2122
  client,
1996
- HOOK_FALLBACK_BUDGET_MS,
2123
+ cfg.injectTimeoutMs,
1997
2124
  "inject_recall",
1998
2125
  RECALL_INJECT_LEAD
1999
2126
  );
@@ -2035,7 +2162,7 @@ async function buildHookOutput(args) {
2035
2162
  query: prompt.slice(0, 80)
2036
2163
  });
2037
2164
  if (e instanceof ReflectError && e.fallbackEligible) {
2038
- fallback = await reflectFallback(harness, prompt, client);
2165
+ fallback = await reflectFallback(harness, prompt, client, cfg.injectTimeoutMs);
2039
2166
  if (fallback) reflectAnswer = fallback;
2040
2167
  }
2041
2168
  }
@@ -2068,7 +2195,12 @@ async function buildHookOutput(args) {
2068
2195
  const blocks = [];
2069
2196
  if (reflectAnswer && reflectRanThisTurn) blocks.push(buildSystemInjection(reflectAnswer));
2070
2197
  if (cadence > 0 && turns % cadence === 0) {
2071
- blocks.push(buildRosterRefresh(pages, { reflectOnNewGoals: cfg.autoInject !== "reflect" }));
2198
+ blocks.push(
2199
+ buildRosterRefresh(pages, {
2200
+ reflectOnNewGoals: cfg.autoInject !== "reflect",
2201
+ extra: cfg.toolGuideExtra
2202
+ })
2203
+ );
2072
2204
  }
2073
2205
  const kept = blocks.filter(Boolean);
2074
2206
  let notice;
@@ -2093,6 +2225,7 @@ async function runHook(spec, makeClient = (o) => new HindsightClient(o)) {
2093
2225
  } catch {
2094
2226
  return;
2095
2227
  }
2228
+ if (spec.accept && !spec.accept(ev)) return;
2096
2229
  const { prompt: rawPrompt, cwd: rawCwd, sessionId } = spec.parse(ev);
2097
2230
  if (spec.requireCwd && !rawCwd) return;
2098
2231
  const cwd = rawCwd || process.cwd();
@@ -2249,15 +2382,246 @@ var NPM_VIEW_HARD_DEADLINE_MS = NPM_VIEW_TIMEOUT_MS + 1e3;
2249
2382
  var LOCK_STALE_MS = 10 * 60 * 1e3;
2250
2383
 
2251
2384
  // src/core/skill-sync.ts
2252
- import { cpSync, existsSync as existsSync5, readFileSync as readFileSync9 } from "fs";
2385
+ import { cpSync, existsSync as existsSync6, readFileSync as readFileSync9 } from "fs";
2253
2386
  import { homedir as homedir6 } from "os";
2254
- import { dirname as dirname10, join as join15 } from "path";
2387
+ import { dirname as dirname10, join as join16 } from "path";
2255
2388
  import { fileURLToPath as fileURLToPath5 } from "url";
2256
2389
 
2390
+ // src/core/skill-dirs.ts
2391
+ import { existsSync as existsSync5 } from "fs";
2392
+ import { join as join15 } from "path";
2393
+
2257
2394
  // src/core/legacy.ts
2258
- import { existsSync as existsSync6, readFileSync as readFileSync10 } from "fs";
2395
+ import { existsSync as existsSync7, readFileSync as readFileSync10 } from "fs";
2259
2396
  import { homedir as homedir7 } from "os";
2260
- import { join as join16, relative, isAbsolute as isAbsolute2 } from "path";
2397
+ import { join as join17, relative, isAbsolute as isAbsolute2 } from "path";
2398
+
2399
+ // src/core/traecode-mcp.ts
2400
+ import { execFileSync as execFileSync4 } from "child_process";
2401
+ import { existsSync as existsSync8, mkdirSync as mkdirSync6, readFileSync as readFileSync12, readdirSync as readdirSync2, rmSync as rmSync3, writeFileSync as writeFileSync4 } from "fs";
2402
+ import { homedir as homedir8 } from "os";
2403
+ import { dirname as dirname11, isAbsolute as isAbsolute3, join as join18 } from "path";
2404
+ import { fileURLToPath as fileURLToPath6 } from "url";
2405
+ var MCP_SERVER_NAME = "hindsight";
2406
+ var MCP_FILE_REL = join18(".trae", "mcp.json");
2407
+ function bundledDistDir() {
2408
+ const here = dirname11(fileURLToPath6(import.meta.url));
2409
+ return existsSync8(join18(here, "mcp-server.js")) ? here : join18(here, "..", "..", "dist");
2410
+ }
2411
+ function canon(value) {
2412
+ if (Array.isArray(value)) return `[${value.map(canon).join(",")}]`;
2413
+ if (value && typeof value === "object") {
2414
+ const entries = Object.entries(value).sort(
2415
+ ([a], [b]) => a < b ? -1 : a > b ? 1 : 0
2416
+ );
2417
+ return `{${entries.map(([k, v]) => `${JSON.stringify(k)}:${canon(v)}`).join(",")}}`;
2418
+ }
2419
+ return JSON.stringify(value);
2420
+ }
2421
+ var WORKSPACE_MCP_KEY = "trae.mcp.enableWorkspaceMcp";
2422
+ var HINT_MIN_INTERVAL_MS = 24 * 60 * 60 * 1e3;
2423
+ function traecodeUserDataDir(home) {
2424
+ 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");
2425
+ for (const brand of ["Trae CN", "Trae"]) {
2426
+ const dir = join18(root, brand);
2427
+ if (existsSync8(dir)) return dir;
2428
+ }
2429
+ return join18(root, "Trae CN");
2430
+ }
2431
+ var traecodeUserSettingsPath = (home) => join18(traecodeUserDataDir(home), "User", "settings.json");
2432
+ var gateStateFileFor = (dist) => join18(dirname11(dist), ".workspace-mcp.json");
2433
+ function gateStateFile() {
2434
+ return gateStateFileFor(bundledDistDir());
2435
+ }
2436
+ function readGateState(opts = {}) {
2437
+ try {
2438
+ return JSON.parse(readFileSync12(opts.stateFile ?? gateStateFile(), "utf8"));
2439
+ } catch {
2440
+ return {};
2441
+ }
2442
+ }
2443
+ function workspaceMcpGateState(settingsPath) {
2444
+ let raw;
2445
+ try {
2446
+ raw = readFileSync12(settingsPath, "utf8");
2447
+ } catch {
2448
+ return "unknown";
2449
+ }
2450
+ try {
2451
+ const doc = JSON.parse(raw);
2452
+ return doc[WORKSPACE_MCP_KEY] === true ? "on" : "off";
2453
+ } catch {
2454
+ const hit = raw.match(new RegExp(`"${WORKSPACE_MCP_KEY}"\\s*:\\s*(true|false)`));
2455
+ return hit ? hit[1] === "true" ? "on" : "off" : "unknown";
2456
+ }
2457
+ }
2458
+ function workspaceMcpHint(opts = {}) {
2459
+ try {
2460
+ const settingsPath = traecodeUserSettingsPath(opts.home ?? homedir8());
2461
+ if (workspaceMcpGateState(settingsPath) === "on") return void 0;
2462
+ const now = opts.now ?? Date.now();
2463
+ const state = readGateState(opts);
2464
+ if (state.workspaceMcpEnabled) return void 0;
2465
+ if (typeof state.lastHint === "number" && now - state.lastHint < HINT_MIN_INTERVAL_MS) {
2466
+ return void 0;
2467
+ }
2468
+ writeFileSync4(
2469
+ opts.stateFile ?? gateStateFile(),
2470
+ JSON.stringify({ ...state, lastHint: now }, null, 2) + "\n"
2471
+ );
2472
+ 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.';
2473
+ } catch {
2474
+ return void 0;
2475
+ }
2476
+ }
2477
+ function gitignoreCovers(lines) {
2478
+ return lines.some((l) => {
2479
+ const t = l.trim();
2480
+ return t.includes(".trae");
2481
+ });
2482
+ }
2483
+ function ensureGitignored(repo) {
2484
+ const gitignore = join18(repo, ".gitignore");
2485
+ if (!existsSync8(gitignore)) return;
2486
+ const current2 = readFileSync12(gitignore, "utf8");
2487
+ if (gitignoreCovers(current2.split("\n"))) return;
2488
+ const addition = (current2.endsWith("\n") || current2 === "" ? "" : "\n") + "# hindsight MCP registration (machine-specific)\n.trae/mcp.json\n";
2489
+ writeFileSync4(gitignore, current2 + addition);
2490
+ }
2491
+ function ensureTraecodeWorkspaceMcp(cwd, opts = {}) {
2492
+ registerTraecodeWorkspaceMcp(cwd, opts);
2493
+ const seeded = ensureWorkspaceMcpEnabled(cwd, opts);
2494
+ return workspaceMcpHint(opts) ?? (seeded === "failed" ? workspaceEnableHint(opts) : void 0);
2495
+ }
2496
+ function registerTraecodeWorkspaceMcp(cwd, opts = {}) {
2497
+ try {
2498
+ const home = opts.home ?? homedir8();
2499
+ if (!cwd || !isAbsolute3(cwd) || dirname11(cwd) === cwd || cwd === home) return "skipped";
2500
+ const dist = opts.dist ?? bundledDistDir();
2501
+ const script = join18(dist, "mcp-server.js");
2502
+ if (!existsSync8(script)) return "skipped";
2503
+ const file = join18(cwd, MCP_FILE_REL);
2504
+ let doc = {};
2505
+ let exists = false;
2506
+ try {
2507
+ doc = JSON.parse(readFileSync12(file, "utf8"));
2508
+ exists = true;
2509
+ } catch {
2510
+ if (existsSync8(file)) return "skipped";
2511
+ }
2512
+ const servers = doc.mcpServers && typeof doc.mcpServers === "object" && !Array.isArray(doc.mcpServers) ? doc.mcpServers : doc.mcpServers = {};
2513
+ const entry = {
2514
+ command: "node",
2515
+ args: [script],
2516
+ env: { HINDSIGHT_MCP_HARNESS: "traecode", HINDSIGHT_MCP_PROJECT_CWD: cwd }
2517
+ };
2518
+ const existing = servers[MCP_SERVER_NAME];
2519
+ let merged;
2520
+ if (existing === void 0) {
2521
+ merged = entry;
2522
+ } else if (isOurMcpEntry(existing)) {
2523
+ const env = existing.env;
2524
+ merged = {
2525
+ ...existing,
2526
+ command: entry.command,
2527
+ args: entry.args,
2528
+ env: { ...env ?? {}, ...entry.env }
2529
+ };
2530
+ } else {
2531
+ diag("traecode", "workspace_mcp_foreign_entry", { cwd, file });
2532
+ return "skipped";
2533
+ }
2534
+ if (existing !== void 0 && canon(merged) === canon(existing)) return "current";
2535
+ servers[MCP_SERVER_NAME] = merged;
2536
+ mkdirSync6(dirname11(file), { recursive: true });
2537
+ writeFileSync4(file, JSON.stringify(doc, null, 2) + "\n");
2538
+ if (!exists) ensureGitignored(cwd);
2539
+ diag("traecode", "workspace_mcp_registered", { cwd, file });
2540
+ return "registered";
2541
+ } catch (e) {
2542
+ diag("traecode", "workspace_mcp_register_failed", {
2543
+ cwd,
2544
+ error: e instanceof Error ? e.message : String(e)
2545
+ });
2546
+ return "failed";
2547
+ }
2548
+ }
2549
+ var WORKSPACE_STORAGE_REL = join18("User", "workspaceStorage");
2550
+ var ENABLED_KEY_PREFIX = "icubeAgentExtension.enabled.mcp.config.ws0.";
2551
+ var SQLITE_TIMEOUT_MS = 5e3;
2552
+ var TRAECODE_WORKSPACE_ENABLED_KEY = ENABLED_KEY_PREFIX + MCP_SERVER_NAME;
2553
+ var traecodeWorkspaceStorageDir = (home) => join18(traecodeUserDataDir(home), WORKSPACE_STORAGE_REL);
2554
+ function findWorkspaceStorageDir(storage, repo) {
2555
+ let entries;
2556
+ try {
2557
+ entries = readdirSync2(storage);
2558
+ } catch {
2559
+ return void 0;
2560
+ }
2561
+ for (const name of entries) {
2562
+ try {
2563
+ const doc = JSON.parse(readFileSync12(join18(storage, name, "workspace.json"), "utf8"));
2564
+ if (typeof doc.folder !== "string") continue;
2565
+ let folder;
2566
+ try {
2567
+ folder = fileURLToPath6(doc.folder);
2568
+ } catch {
2569
+ folder = doc.folder;
2570
+ }
2571
+ if (folder === repo) return join18(storage, name);
2572
+ } catch {
2573
+ continue;
2574
+ }
2575
+ }
2576
+ return void 0;
2577
+ }
2578
+ function ensureWorkspaceMcpEnabled(cwd, opts = {}) {
2579
+ try {
2580
+ const home = opts.home ?? homedir8();
2581
+ if (!cwd || !isAbsolute3(cwd) || dirname11(cwd) === cwd || cwd === home) return "failed";
2582
+ const dir = findWorkspaceStorageDir(traecodeWorkspaceStorageDir(home), cwd);
2583
+ if (!dir) return "failed";
2584
+ const db = join18(dir, "state.vscdb");
2585
+ if (!existsSync8(db)) return "failed";
2586
+ const sqlite = opts.sqlite ?? execFileSync4;
2587
+ const run = (sql) => sqlite("sqlite3", [db, ".timeout 3000", sql], {
2588
+ encoding: "utf8",
2589
+ timeout: SQLITE_TIMEOUT_MS,
2590
+ windowsHide: true,
2591
+ stdio: ["ignore", "pipe", "pipe"]
2592
+ }).trim();
2593
+ if (run(`SELECT value FROM ItemTable WHERE key='${TRAECODE_WORKSPACE_ENABLED_KEY}';`) === "true") {
2594
+ return "on";
2595
+ }
2596
+ run(
2597
+ `INSERT OR REPLACE INTO ItemTable (key, value) VALUES ('${TRAECODE_WORKSPACE_ENABLED_KEY}', 'true');`
2598
+ );
2599
+ diag("traecode", "workspace_mcp_enabled_seeded", { cwd, db });
2600
+ return "seeded";
2601
+ } catch (e) {
2602
+ diag("traecode", "workspace_mcp_enabled_seed_failed", {
2603
+ cwd,
2604
+ error: e instanceof Error ? e.message : String(e)
2605
+ });
2606
+ return "failed";
2607
+ }
2608
+ }
2609
+ function workspaceEnableHint(opts = {}) {
2610
+ try {
2611
+ const now = opts.now ?? Date.now();
2612
+ const state = readGateState(opts);
2613
+ if (typeof state.lastEnableHint === "number" && now - state.lastEnableHint < HINT_MIN_INTERVAL_MS) {
2614
+ return void 0;
2615
+ }
2616
+ writeFileSync4(
2617
+ opts.stateFile ?? gateStateFile(),
2618
+ JSON.stringify({ ...state, lastEnableHint: now }, null, 2) + "\n"
2619
+ );
2620
+ 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.";
2621
+ } catch {
2622
+ return void 0;
2623
+ }
2624
+ }
2261
2625
 
2262
2626
  // src/core/transcript-codex.ts
2263
2627
  function stampOf(line) {
@@ -2268,11 +2632,56 @@ function isSyntheticUserText(text) {
2268
2632
  return s.startsWith("# AGENTS.md instructions for ") || s.startsWith("<environment_context>");
2269
2633
  }
2270
2634
  function contentText(content) {
2271
- return (content || []).filter((c) => c && typeof c.text === "string").map((c) => c.text).join("\n");
2635
+ return (Array.isArray(content) ? content : []).filter((c) => c && typeof c.text === "string").map((c) => c.text).join("\n");
2636
+ }
2637
+ var startupKinds = /* @__PURE__ */ new Set([
2638
+ "agents_md.instructions",
2639
+ "environments.instructions",
2640
+ "environments.environment_context",
2641
+ "plugins.recommendations",
2642
+ "plugins.usage_instructions"
2643
+ ]);
2644
+ function fallbackUserText(payload) {
2645
+ const content = payload.content;
2646
+ const kinds = payload.internal_chat_message_metadata_passthrough?.content_item_kinds;
2647
+ if (Array.isArray(content) && Array.isArray(kinds) && kinds.length === content.length && kinds.every((kind) => typeof kind === "string" && kind.length > 0)) {
2648
+ return contentText(content.filter((_, index) => !startupKinds.has(kinds[index])));
2649
+ }
2650
+ const text = contentText(content);
2651
+ return isSyntheticUserText(stripInjectedMemory(text)) ? "" : text;
2272
2652
  }
2273
2653
  function isUserMessageEvent(line) {
2274
2654
  return line.type === "event_msg" && line.payload?.type === "item_completed" && line.payload.item?.type === "UserMessage";
2275
2655
  }
2656
+ var TOOL_ITEM_TYPES = /* @__PURE__ */ new Set(["McpToolCall", "CommandExecution"]);
2657
+ function isToolItemEvent(line) {
2658
+ return line.type === "event_msg" && line.payload?.type === "item_completed" && TOOL_ITEM_TYPES.has(line.payload.item?.type ?? "");
2659
+ }
2660
+ function parseArgs(raw) {
2661
+ if (typeof raw !== "string") return raw;
2662
+ try {
2663
+ return JSON.parse(raw);
2664
+ } catch {
2665
+ return void 0;
2666
+ }
2667
+ }
2668
+ var SHELL_RE = /(?:^|\/)(?:sh|bash|zsh|dash|ksh|fish)$/;
2669
+ function commandText(command) {
2670
+ if (typeof command === "string") return command;
2671
+ if (!Array.isArray(command) || !command.every((c) => typeof c === "string")) return "";
2672
+ const argv = command;
2673
+ if (argv.length === 3 && SHELL_RE.test(argv[0]) && /^-[a-z]*c$/.test(argv[1])) return argv[2];
2674
+ return argv.join(" ");
2675
+ }
2676
+ function toolItemAction(item) {
2677
+ if (item.type === "McpToolCall") {
2678
+ if (typeof item.tool !== "string" || !item.tool) return void 0;
2679
+ const name = typeof item.server === "string" && item.server ? `mcp__${item.server}__${item.tool}` : item.tool;
2680
+ return actionLine(name, parseArgs(item.arguments));
2681
+ }
2682
+ const command = commandText(item.command).trim();
2683
+ return command ? actionLine("exec_command", { command }) : void 0;
2684
+ }
2276
2685
  function readCodexTranscript(path) {
2277
2686
  const lines = [];
2278
2687
  for (const rawLine of readJsonl(path)) {
@@ -2286,6 +2695,7 @@ function readCodexTranscript(path) {
2286
2695
  }
2287
2696
  }
2288
2697
  const userFromEvents = lines.some(isUserMessageEvent);
2698
+ const actionsFromEvents = lines.some(isToolItemEvent);
2289
2699
  const turns = [];
2290
2700
  const push = (role, raw, stamp = {}) => {
2291
2701
  const text = stripInjectedMemory(raw).trim();
@@ -2296,16 +2706,24 @@ function readCodexTranscript(path) {
2296
2706
  push("user", contentText(line.payload?.item?.content), stampOf(line));
2297
2707
  continue;
2298
2708
  }
2709
+ if (isToolItemEvent(line)) {
2710
+ const action = toolItemAction(line.payload?.item ?? {});
2711
+ if (action) turns.push({ role: "action", content: action, ...stampOf(line) });
2712
+ continue;
2713
+ }
2299
2714
  if (line.type !== "response_item") continue;
2300
2715
  const p = line.payload;
2301
2716
  if (!p || typeof p !== "object") continue;
2302
2717
  if (p.type === "message") {
2303
- if (p.role === "assistant") push("assistant", contentText(p.content), stampOf(line));
2304
- else if (p.role === "user" && !userFromEvents) {
2305
- const text = contentText(p.content);
2306
- if (!isSyntheticUserText(stripInjectedMemory(text))) push("user", text, stampOf(line));
2718
+ if (p.role === "assistant") {
2719
+ if (p.channel === "analysis" || p.channel === "reasoning" || p.phase === "analysis" || p.phase === "reasoning")
2720
+ continue;
2721
+ push("assistant", contentText(p.content), stampOf(line));
2722
+ } else if (p.role === "user" && !userFromEvents) {
2723
+ push("user", fallbackUserText(p), stampOf(line));
2307
2724
  }
2308
2725
  } else if ((p.type === "function_call" || p.type === "custom_tool_call") && typeof p.name === "string") {
2726
+ if (actionsFromEvents && p.type === "custom_tool_call" && p.name === "exec") continue;
2309
2727
  const rawInput = p.type === "function_call" ? p.arguments : p.input;
2310
2728
  let input;
2311
2729
  try {
@@ -2406,19 +2824,19 @@ function readCopilotTranscript(path) {
2406
2824
  }
2407
2825
 
2408
2826
  // src/core/transcript-grok.ts
2409
- import { existsSync as existsSync7, readFileSync as readFileSync12, readdirSync as readdirSync2 } from "fs";
2410
- import { homedir as homedir8 } from "os";
2411
- import { join as join17 } from "path";
2827
+ import { existsSync as existsSync9, readFileSync as readFileSync13, readdirSync as readdirSync3 } from "fs";
2828
+ import { homedir as homedir9 } from "os";
2829
+ import { join as join19 } from "path";
2412
2830
  var CHAT_HISTORY = "chat_history.jsonl";
2413
- function grokTranscriptPath(cwd, sessionId, grokHome = process.env.GROK_HOME || join17(homedir8(), ".grok")) {
2414
- const sessionsDir = join17(grokHome, "sessions");
2415
- const direct = join17(sessionsDir, encodeURIComponent(cwd), sessionId, CHAT_HISTORY);
2416
- if (existsSync7(direct)) return direct;
2831
+ function grokTranscriptPath(cwd, sessionId, grokHome = process.env.GROK_HOME || join19(homedir9(), ".grok")) {
2832
+ const sessionsDir = join19(grokHome, "sessions");
2833
+ const direct = join19(sessionsDir, encodeURIComponent(cwd), sessionId, CHAT_HISTORY);
2834
+ if (existsSync9(direct)) return direct;
2417
2835
  try {
2418
- for (const candidate of readdirSync2(sessionsDir)) {
2419
- const directory = join17(sessionsDir, candidate);
2420
- if (readFileSync12(join17(directory, ".cwd"), "utf8").trim() === cwd) {
2421
- return join17(directory, sessionId, CHAT_HISTORY);
2836
+ for (const candidate of readdirSync3(sessionsDir)) {
2837
+ const directory = join19(sessionsDir, candidate);
2838
+ if (readFileSync13(join19(directory, ".cwd"), "utf8").trim() === cwd) {
2839
+ return join19(directory, sessionId, CHAT_HISTORY);
2422
2840
  }
2423
2841
  }
2424
2842
  } catch {
@@ -2453,12 +2871,12 @@ function readGrokTranscript(path) {
2453
2871
  }
2454
2872
 
2455
2873
  // src/core/transcript-devin.ts
2456
- import { existsSync as existsSync8 } from "fs";
2874
+ import { existsSync as existsSync10 } from "fs";
2457
2875
  import { createRequire } from "module";
2458
- import { homedir as homedir9 } from "os";
2459
- import { join as join18 } from "path";
2460
- function devinSessionDb(home = homedir9()) {
2461
- return join18(home, ".local", "share", "devin", "cli", "sessions.db");
2876
+ import { homedir as homedir10 } from "os";
2877
+ import { join as join20 } from "path";
2878
+ function devinSessionDb(home = homedir10()) {
2879
+ return join20(home, ".local", "share", "devin", "cli", "sessions.db");
2462
2880
  }
2463
2881
  function parseDevinMessages(nodes) {
2464
2882
  const messages = /* @__PURE__ */ new Map();
@@ -2495,7 +2913,7 @@ function readDevinTranscript(sessionId, dbPath = devinSessionDb()) {
2495
2913
  diag("devin-cli", "sqlite_unavailable", { node: process.version, dbPath });
2496
2914
  return [];
2497
2915
  }
2498
- if (!existsSync8(dbPath)) {
2916
+ if (!existsSync10(dbPath)) {
2499
2917
  diag("devin-cli", "session_db_missing", { dbPath });
2500
2918
  return [];
2501
2919
  }
@@ -2768,7 +3186,7 @@ function readDroidTranscript(path) {
2768
3186
  }
2769
3187
 
2770
3188
  // src/core/transcript-zcode.ts
2771
- import { readFileSync as readFileSync13 } from "fs";
3189
+ import { readFileSync as readFileSync14 } from "fs";
2772
3190
  function messageText(content) {
2773
3191
  if (typeof content === "string") return content.trim();
2774
3192
  if (!Array.isArray(content)) return "";
@@ -2778,7 +3196,7 @@ function readZcodeTranscript(path) {
2778
3196
  if (!path) return [];
2779
3197
  let body;
2780
3198
  try {
2781
- body = readFileSync13(path, "utf8");
3199
+ body = readFileSync14(path, "utf8");
2782
3200
  } catch {
2783
3201
  return [];
2784
3202
  }
@@ -2812,6 +3230,131 @@ function zcodeAssistantText(path) {
2812
3230
  return readZcodeTranscript(path).filter((turn) => turn.role === "assistant").at(-1)?.content ?? "";
2813
3231
  }
2814
3232
 
3233
+ // src/core/transcript-kimi.ts
3234
+ import { existsSync as existsSync11, readdirSync as readdirSync4 } from "fs";
3235
+ import { homedir as homedir11 } from "os";
3236
+ import { join as join21 } from "path";
3237
+ var HARNESS = "kimi-code";
3238
+ var SESSIONS_DIR = "sessions";
3239
+ var AGENTS_DIR = "agents";
3240
+ var WIRE_LOG = "wire.jsonl";
3241
+ var SESSION_PREFIX = "session_";
3242
+ var MAIN_AGENT = "main";
3243
+ var MAX_SESSION_CHARS = 32 * 1024 * 1024;
3244
+ function kimiSessionDir(sessionId, kimiHome = process.env.KIMI_CODE_HOME || join21(homedir11(), ".kimi-code")) {
3245
+ const name = sessionId.startsWith(SESSION_PREFIX) ? sessionId : `${SESSION_PREFIX}${sessionId}`;
3246
+ const sessions = join21(kimiHome, SESSIONS_DIR);
3247
+ try {
3248
+ for (const workspace of readdirSync4(sessions, { withFileTypes: true })) {
3249
+ if (!workspace.isDirectory()) continue;
3250
+ const candidate = join21(sessions, workspace.name, name);
3251
+ if (existsSync11(join21(candidate, AGENTS_DIR))) return candidate;
3252
+ }
3253
+ } catch {
3254
+ }
3255
+ diag(HARNESS, "session_dir_missing", { sessions, session: name });
3256
+ return void 0;
3257
+ }
3258
+ function stampOf2(event) {
3259
+ if (typeof event.time !== "number") return {};
3260
+ const at = new Date(event.time);
3261
+ return Number.isNaN(at.getTime()) ? {} : { timestamp: at.toISOString() };
3262
+ }
3263
+ function kimiPromptText(input) {
3264
+ if (!Array.isArray(input)) return "";
3265
+ return input.filter((block) => block?.type === "text" && typeof block.text === "string").map((block) => block.text).join("\n");
3266
+ }
3267
+ function readKimiWire(events) {
3268
+ const turns = [];
3269
+ let step;
3270
+ const flushStep = () => {
3271
+ if (!step) return;
3272
+ const content = stripInjectedMemory(step.texts.join("\n")).trim();
3273
+ if (content) turns.push({ role: "assistant", content, ...step.stamp });
3274
+ step = void 0;
3275
+ };
3276
+ for (const event of events || []) {
3277
+ if (!event || typeof event !== "object") continue;
3278
+ const stamp = stampOf2(event);
3279
+ if (event.type === "turn.prompt") {
3280
+ flushStep();
3281
+ if (event.origin?.kind !== "user") continue;
3282
+ const content = stripInjectedMemory(kimiPromptText(event.input)).trim();
3283
+ if (content) turns.push({ role: "user", content, ...stamp });
3284
+ continue;
3285
+ }
3286
+ if (event.type !== "context.append_loop_event") continue;
3287
+ const loop = event.event;
3288
+ if (!loop || typeof loop !== "object") continue;
3289
+ if (loop.type === "content.part") {
3290
+ if (loop.part?.type !== "text" || typeof loop.part.text !== "string") continue;
3291
+ const uuid = typeof loop.stepUuid === "string" ? loop.stepUuid : "";
3292
+ if (step && step.uuid !== uuid) flushStep();
3293
+ if (!step) step = { uuid, texts: [], stamp };
3294
+ step.texts.push(loop.part.text);
3295
+ } else if (loop.type === "tool.call") {
3296
+ flushStep();
3297
+ if (typeof loop.name !== "string" || !loop.name) continue;
3298
+ turns.push({ role: "action", content: actionLine(loop.name, loop.args), ...stamp });
3299
+ }
3300
+ }
3301
+ flushStep();
3302
+ return turns;
3303
+ }
3304
+ function agentIds(sessionDir) {
3305
+ try {
3306
+ return readdirSync4(join21(sessionDir, AGENTS_DIR), { withFileTypes: true }).filter((entry) => entry.isDirectory()).map((entry) => entry.name).sort(byAgentId);
3307
+ } catch {
3308
+ return [];
3309
+ }
3310
+ }
3311
+ function byAgentId(a, b) {
3312
+ if (a === b) return 0;
3313
+ if (a === MAIN_AGENT) return -1;
3314
+ if (b === MAIN_AGENT) return 1;
3315
+ const indexA = agentIndex(a);
3316
+ const indexB = agentIndex(b);
3317
+ return indexA === indexB ? a.localeCompare(b) : indexA - indexB;
3318
+ }
3319
+ function agentIndex(id) {
3320
+ const suffix = Number(id.slice(id.lastIndexOf("-") + 1));
3321
+ return Number.isFinite(suffix) ? suffix : Number.MAX_SAFE_INTEGER;
3322
+ }
3323
+ function parseEvent(rawLine) {
3324
+ const trimmed = rawLine.trim();
3325
+ if (!trimmed) return void 0;
3326
+ let parsed;
3327
+ try {
3328
+ parsed = JSON.parse(trimmed);
3329
+ } catch {
3330
+ return void 0;
3331
+ }
3332
+ return typeof parsed === "object" && parsed !== null ? parsed : void 0;
3333
+ }
3334
+ function readKimiTranscript(path) {
3335
+ const turns = [];
3336
+ let remaining = MAX_SESSION_CHARS;
3337
+ for (const agentId of agentIds(path)) {
3338
+ const wire = join21(path, AGENTS_DIR, agentId, WIRE_LOG);
3339
+ const events = [];
3340
+ for (const rawLine of readJsonl(wire)) {
3341
+ remaining -= rawLine.length;
3342
+ if (remaining < 0) break;
3343
+ const event = parseEvent(rawLine);
3344
+ if (event) events.push(event);
3345
+ }
3346
+ for (const turn of readKimiWire(events)) turns.push(turn);
3347
+ if (remaining < 0) {
3348
+ log.warn(HARNESS, "session exceeds the wire-log budget \u2014 later agents were not read", {
3349
+ sessionDir: path,
3350
+ stoppedAt: wire
3351
+ });
3352
+ break;
3353
+ }
3354
+ }
3355
+ return turns;
3356
+ }
3357
+
2815
3358
  // src/harness/hook-lifecycle.ts
2816
3359
  var cursorCwd = (ev) => ev.cwd ?? ev.workspace_root ?? (Array.isArray(ev.workspace_roots) ? ev.workspace_roots[0] : void 0);
2817
3360
  var claudePrompt = {
@@ -2890,7 +3433,7 @@ var copilotPrompt = {
2890
3433
  ${context}`.trim()
2891
3434
  })
2892
3435
  };
2893
- var devinCwd = () => process.env.DEVIN_PROJECT_DIR;
3436
+ var devinCwd = () => process.env.DEVIN_PROJECT_DIR || process.cwd();
2894
3437
  var devinPrompt = {
2895
3438
  harness: "devin-cli",
2896
3439
  requireCwd: true,
@@ -2917,6 +3460,7 @@ var standardSessionStart = (harness) => ({
2917
3460
  }
2918
3461
  })
2919
3462
  });
3463
+ var notGrokHosted = () => !process.env.GROK_HOOK_EVENT;
2920
3464
  var HOOK_HARNESSES = {
2921
3465
  "claude-code": {
2922
3466
  configStyle: "nested",
@@ -2925,11 +3469,12 @@ var HOOK_HARNESSES = {
2925
3469
  prompt: { event: "UserPromptSubmit", entry: "claude-hook.js", timeout: 30 },
2926
3470
  stop: { event: "Stop", entry: "claude-stop-hook.js", timeout: 60 }
2927
3471
  },
2928
- sessionStart: standardSessionStart("claude-code"),
2929
- prompt: claudePrompt,
3472
+ sessionStart: { ...standardSessionStart("claude-code"), accept: notGrokHosted },
3473
+ prompt: { ...claudePrompt, accept: notGrokHosted },
2930
3474
  retain: {
2931
3475
  hostTimeoutSec: 60,
2932
3476
  harness: "claude-code",
3477
+ accept: notGrokHosted,
2933
3478
  parse: (ev) => ({
2934
3479
  sessionId: ev.session_id,
2935
3480
  transcriptPath: ev.transcript_path,
@@ -3245,6 +3790,117 @@ var HOOK_HARNESSES = {
3245
3790
  assistantText: (ev) => (ev.responseText || zcodeAssistantText(ev.transcript_path) || ev.responsePreview || "").trim()
3246
3791
  }
3247
3792
  }
3793
+ },
3794
+ /**
3795
+ * TraeCode (TRAE CN's agent) also speaks Claude Code's hook protocol — `prompt`/`cwd`/`session_id`
3796
+ * in, `hookSpecificOutput.additionalContext` + `systemMessage` out — with registrations nested
3797
+ * under the top-level `hooks` key of `~/.trae-cn/hooks.json` (unlike Factory Droid, whose event
3798
+ * map IS the file) and a `version` field the host writes and expects.
3799
+ *
3800
+ * Like ZCode, what it does not have is a TRANSCRIPT: sessions live in an encrypted local DB or
3801
+ * the cloud and no `transcript_path` is ever supplied, so this is the second harness that retains
3802
+ * from the plugin's own journal (core/turn-journal.ts) — the prompt hook appends the user turn,
3803
+ * and Stop's `last_assistant_message` (the full reply) plays the role ZCode's `responseText`
3804
+ * plays: `journal.assistantText` closes the turn with it.
3805
+ */
3806
+ traecode: {
3807
+ configStyle: "nested",
3808
+ install: {
3809
+ sessionStart: { event: "SessionStart", entry: "traecode-sessionstart-hook.js", timeout: 30 },
3810
+ prompt: { event: "UserPromptSubmit", entry: "traecode-hook.js", timeout: 30 },
3811
+ stop: { event: "Stop", entry: "traecode-stop-hook.js", timeout: 60 }
3812
+ },
3813
+ sessionStart: {
3814
+ ...standardSessionStart("traecode"),
3815
+ // Trae launches USER-level MCP servers from the Electron process's cwd (home), where an
3816
+ // optInOnly config self-disables and the tools vanish. Each repo's own workspace file fixes
3817
+ // it — kept current here, once memory is confirmed live for the repo, along with the
3818
+ // workspace's per-server enable switch (seeded into Trae's storage DB,
3819
+ // core/traecode-mcp.ts). The returned hint (global gate off, or an unseedable switch)
3820
+ // rides the session banner.
3821
+ ensureMcpRegistration: (cwd) => ensureTraecodeWorkspaceMcp(cwd)
3822
+ },
3823
+ prompt: {
3824
+ ...claudePrompt,
3825
+ harness: "traecode",
3826
+ journalPrompt: true,
3827
+ // TraeCode's UserPromptSubmit payload carries `prompt` exactly like Claude Code's.
3828
+ parse: (ev) => ({
3829
+ prompt: ev.prompt,
3830
+ cwd: ev.cwd,
3831
+ sessionId: ev.session_id
3832
+ })
3833
+ },
3834
+ retain: {
3835
+ hostTimeoutSec: 60,
3836
+ harness: "traecode",
3837
+ // No transcriptPath: the journal supplies it (see `journal` below).
3838
+ parse: (ev) => ({
3839
+ sessionId: ev.session_id,
3840
+ cwd: ev.cwd
3841
+ }),
3842
+ journal: {
3843
+ // `last_assistant_message` is the full reply — TraeCode's `responseText`.
3844
+ assistantText: (ev) => (ev.last_assistant_message ?? "").trim()
3845
+ }
3846
+ }
3847
+ },
3848
+ "kimi-code": {
3849
+ // Kimi's ~/.kimi-code/config.toml takes a FLAT [[hooks]] array whose entries are validated by a
3850
+ // strict 4-key schema (event/matcher/command/timeout). Neither JSON style can express it, and a
3851
+ // fifth key drops EVERY hook in the file at warning severity, so its installer writes the block
3852
+ // itself (the grok-build pattern) rather than going through mergeHarnessHooks.
3853
+ configStyle: "toml-array",
3854
+ install: {
3855
+ // Timeouts are SECONDS here (integer 1-600, default 30) — the same unit as every other
3856
+ // supported host, and the opposite of qwen-code's identically named field.
3857
+ sessionStart: { event: "SessionStart", entry: "kimi-sessionstart-hook.js", timeout: 30 },
3858
+ prompt: { event: "UserPromptSubmit", entry: "kimi-hook.js", timeout: 30 },
3859
+ stop: { event: "Stop", entry: "kimi-stop-hook.js", timeout: 60 }
3860
+ },
3861
+ sessionStart: {
3862
+ harness: "kimi-code",
3863
+ parse: (ev) => ({
3864
+ cwd: ev.cwd,
3865
+ sessionId: ev.session_id
3866
+ }),
3867
+ // Kimi runs SessionStart hooks for their side effects only: it awaits the trigger and drops
3868
+ // the result, so nothing emitted here can reach the model or the terminal. Installed for the
3869
+ // seed/daemon/session-root work runSessionStartHook does, and silent like antigravity-cli's.
3870
+ emit: () => ({})
3871
+ },
3872
+ prompt: {
3873
+ harness: "kimi-code",
3874
+ parse: (ev) => ({
3875
+ // A block array, not a string — the same shape as the wire log's `turn.prompt.input`.
3876
+ prompt: kimiPromptText(ev.prompt),
3877
+ cwd: ev.cwd,
3878
+ sessionId: ev.session_id
3879
+ }),
3880
+ // Kimi has no additionalContext: a top-level `message` is the injection channel, which the
3881
+ // CLI wraps as <hook_result hook_event="UserPromptSubmit"> and appends to the conversation.
3882
+ // `notice` has no banner channel to reach (the copilot-cli precedent), but it cannot simply
3883
+ // be dropped: when a hook's stdout parses to JSON carrying no message, Kimi falls back to
3884
+ // injecting the RAW STDOUT, so an empty `{}` would put a literal "{}" in front of the model.
3885
+ // Emitting the notice on the notice-only turn is what keeps that from ever happening.
3886
+ emit: (context, notice) => ({ message: context || notice })
3887
+ },
3888
+ retain: {
3889
+ hostTimeoutSec: 60,
3890
+ harness: "kimi-code",
3891
+ parse: (ev) => {
3892
+ const sessionId = ev.session_id;
3893
+ return {
3894
+ sessionId,
3895
+ // Kimi's Stop payload carries no transcript path — its hook feature has no such field at
3896
+ // all — so resolve the session's own directory from the id, as grok-build does. The
3897
+ // reader takes that DIRECTORY and reads every agent's wire.jsonl beneath it.
3898
+ transcriptPath: sessionId ? kimiSessionDir(sessionId) : void 0,
3899
+ cwd: ev.cwd
3900
+ };
3901
+ },
3902
+ readTranscript: readKimiTranscript
3903
+ }
3248
3904
  }
3249
3905
  };
3250
3906
  var runHarnessPrompt = (harness) => runHook(HOOK_HARNESSES[harness].prompt);