@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;
@@ -558,12 +562,17 @@ var CODING_BANK_TEMPLATE = {
558
562
  }
559
563
  };
560
564
  var MISSION_FIELDS = ["reflect_mission", "retain_mission", "observations_mission"];
565
+ var PLUGIN_GOVERNED_BANK_FIELDS = [
566
+ "retain_strategies",
567
+ "entity_labels",
568
+ "retain_extraction_mode"
569
+ ];
561
570
  function isSet(v) {
562
571
  if (v === null || v === void 0) return false;
563
572
  if (typeof v === "string") return v.trim() !== "";
564
573
  return true;
565
574
  }
566
- function codingBankManifest(overrides, mode = DEFAULT_RETAIN_EXTRACTION_MODE) {
575
+ function codingBankManifest(overrides, mode = DEFAULT_RETAIN_EXTRACTION_MODE, defaults = {}) {
567
576
  const current2 = overrides ?? {};
568
577
  const template = CODING_BANK_TEMPLATE.bank;
569
578
  const bank = {};
@@ -592,6 +601,10 @@ function codingBankManifest(overrides, mode = DEFAULT_RETAIN_EXTRACTION_MODE) {
592
601
  const [knowledgeGroup] = template.entity_labels;
593
602
  if (!labels.some((g) => g?.key === knowledgeGroup.key))
594
603
  bank.entity_labels = [...labels, knowledgeGroup];
604
+ for (const [key, value] of Object.entries(defaults)) {
605
+ if (PLUGIN_GOVERNED_BANK_FIELDS.includes(key) || !isSet(value) || isSet(current2[key])) continue;
606
+ bank[key] = value;
607
+ }
595
608
  return Object.keys(bank).length > 0 ? { version: "1", bank } : void 0;
596
609
  }
597
610
 
@@ -627,6 +640,15 @@ async function pool(items, n, fn, onError, onProgress) {
627
640
  }
628
641
  await Promise.all(Array.from({ length: Math.min(n, items.length) }, worker));
629
642
  }
643
+ function isOurMcpEntry(entry) {
644
+ if (!entry || typeof entry !== "object") return false;
645
+ const candidate = entry;
646
+ if (candidate.command !== "node" || !Array.isArray(candidate.args)) return false;
647
+ const script = candidate.args[0];
648
+ if (typeof script !== "string") return false;
649
+ const parts = script.replaceAll("\\", "/").split("/").filter(Boolean);
650
+ return parts.at(-1) === "mcp-server.js" && parts.at(-2) === "dist" && (parts.at(-3) === "coding-agents" || parts.at(-3) === "hindsight-coding-agents");
651
+ }
630
652
 
631
653
  // src/core/hindsight.ts
632
654
  function resolveRetainScopes(tags, configured) {
@@ -695,6 +717,18 @@ var DEFAULT_RECALL_OPTIONS = {
695
717
  var POLL_CYCLE_MS = 5e3;
696
718
  var RETRY_AFTER_FLOOR_MS = 10 * 1e3;
697
719
  var RETRY_AFTER_CEILING_MS = 60 * 1e3;
720
+ function shapePage(page) {
721
+ const p = page ?? {};
722
+ const body = typeof p.body === "string" && p.body.trim() ? p.body : p.markdown;
723
+ return {
724
+ id: p.id,
725
+ name: p.name,
726
+ ...p.description ? { description: p.description } : {},
727
+ ...Array.isArray(p.tags) && p.tags.length ? { tags: p.tags } : {},
728
+ ...p.timestamp ? { last_updated_at: p.timestamp } : {},
729
+ body
730
+ };
731
+ }
698
732
  var HindsightClient = class {
699
733
  apiUrl;
700
734
  /** The credential the NEXT request will sign with — NOT the one the config file holds. The two
@@ -732,7 +766,10 @@ var HindsightClient = class {
732
766
  return this.token;
733
767
  }
734
768
  headers() {
735
- const h = { "Content-Type": "application/json" };
769
+ const h = {
770
+ "Content-Type": "application/json",
771
+ "Accept-Encoding": "identity"
772
+ };
736
773
  if (this.token) h["Authorization"] = `Bearer ${this.token}`;
737
774
  return h;
738
775
  }
@@ -840,6 +877,23 @@ var HindsightClient = class {
840
877
  return false;
841
878
  }
842
879
  }
880
+ /**
881
+ * Whether a session write-back may use `update_mode="append"`: the server must dedupe by
882
+ * `operation_id` AND the bank must keep document text, or the server rejects the append in the
883
+ * background (#4613). Only an explicit `store_document_text: false` answers "no" — an unreachable
884
+ * or unparseable config assumes the default (stored), so a flaky probe never downgrades appends.
885
+ */
886
+ async supportsAppendRetain() {
887
+ if (!await this.supportsIdempotentRetain()) return false;
888
+ try {
889
+ const r = await this.req("GET", this.bankUrl("/config"));
890
+ if (!r.ok) return true;
891
+ const j = await r.json();
892
+ return j.config?.store_document_text !== false;
893
+ } catch {
894
+ return true;
895
+ }
896
+ }
843
897
  /**
844
898
  * Every document_id currently in the bank under a strategy tag (e.g. `source:git`), paginated into a
845
899
  * Set. Powers the incremental git-sync's "what's already ingested?" check — since git commits are stored
@@ -865,6 +919,24 @@ var HindsightClient = class {
865
919
  }
866
920
  return ids;
867
921
  }
922
+ /**
923
+ * The tags on one document, or undefined when the bank holds none with that id. Read from the
924
+ * document LISTING narrowed by `q` (a substring match on the id, so the exact id is picked out of
925
+ * the page) rather than GET /documents/{id}, which also sends the document's full text: the
926
+ * caller, the git-log freshness check on SessionStart, reads a ~100k-character document for one tag.
927
+ */
928
+ async documentTags(documentId) {
929
+ const limit = 100;
930
+ for (let offset = 0; ; offset += limit) {
931
+ const q = `?q=${encodeURIComponent(documentId)}&limit=${limit}&offset=${offset}`;
932
+ const r = await this.req("GET", this.bankUrl(`/documents${q}`));
933
+ const j = await r.json();
934
+ const items = j.items ?? [];
935
+ const hit = items.find((it) => it.id === documentId);
936
+ if (hit) return hit.tags ?? [];
937
+ if (items.length < limit || offset + limit >= (j.total ?? 0)) return void 0;
938
+ }
939
+ }
868
940
  /** Configure the bank: POST the coding bank manifest to /import (missions, retain strategies,
869
941
  * entity labels), then seed knowledge pages when the server supports them. Both halves are
870
942
  * idempotent and ADDITIVE — nothing the bank already says is overwritten (#3927), bar the
@@ -886,7 +958,8 @@ var HindsightClient = class {
886
958
  } else {
887
959
  const manifest = codingBankManifest(
888
960
  opts.reset ? void 0 : await this.readBankOverrides(),
889
- opts.extractionMode
961
+ opts.extractionMode,
962
+ opts.defaults
890
963
  );
891
964
  if (!manifest) {
892
965
  this.log(`[bank] ${this.bank} already carries the coding structure \u2014 nothing to apply`);
@@ -1092,8 +1165,8 @@ var HindsightClient = class {
1092
1165
  return { items };
1093
1166
  }
1094
1167
  /**
1095
- * Read one knowledge page's synthesized content by knowledge-base id, as an OKF document
1096
- * (YAML frontmatter + markdown body). The endpoint omits the internal reflect trace that built
1168
+ * Read one knowledge page's synthesized content by knowledge-base id, shaped by `shapePage` so
1169
+ * the body arrives once. The endpoint omits the internal reflect trace that built
1097
1170
  * the page — that is 70-95% of the raw bytes and can blow past an MCP host's per-tool-result
1098
1171
  * token cap.
1099
1172
  */
@@ -1104,7 +1177,7 @@ var HindsightClient = class {
1104
1177
  this.bankUrl(`/knowledge-base/pages/${encodeURIComponent(pageId)}`)
1105
1178
  );
1106
1179
  if (r.status === 404) throw new Error(`knowledge page not found: ${pageId}`);
1107
- return await r.json();
1180
+ return shapePage(await r.json());
1108
1181
  }
1109
1182
  /** Hybrid (BM25 + vector, RRF-fused) server-side search over the bank's knowledge pages.
1110
1183
  * Returns page-level hits with a relevance snippet — the real search behind
@@ -1125,6 +1198,7 @@ var HindsightClient = class {
1125
1198
  return (j.results ?? []).map((x) => ({
1126
1199
  id: x.id,
1127
1200
  name: x.name,
1201
+ ...x.source_query ? { source_query: x.source_query } : {},
1128
1202
  snippet: x.snippet ?? "",
1129
1203
  score: x.score ?? 0
1130
1204
  }));
@@ -1395,6 +1469,7 @@ function resolveCustomPages(raw) {
1395
1469
  }
1396
1470
  var DEFAULT_REFLECT_TIMEOUT_MS = 2e4;
1397
1471
  var DEFAULT_REFLECT_TOOL_TIMEOUT_MS = 33e4;
1472
+ var DEFAULT_INJECT_TIMEOUT_MS = 7e3;
1398
1473
  var REFLECT_BUDGETS = ["low", "mid", "high"];
1399
1474
  function resolveReflectBudget(raw) {
1400
1475
  const value = raw.reflectBudget;
@@ -1421,6 +1496,22 @@ function resolveObservationScopes(raw) {
1421
1496
  }
1422
1497
  return DEFAULT_OBSERVATION_SCOPES;
1423
1498
  }
1499
+ function resolveDefaultBankConfig(raw) {
1500
+ const value = raw;
1501
+ if (!value || typeof value !== "object" || Array.isArray(value)) return {};
1502
+ const out = {};
1503
+ for (const [key, v] of Object.entries(value)) {
1504
+ if (PLUGIN_GOVERNED_BANK_FIELDS.includes(key)) {
1505
+ log.warn(
1506
+ "config",
1507
+ `ignoring defaultBankConfig.${key} \u2014 the plugin manages this field itself` + (key === "retain_extraction_mode" ? " (set retainExtractionMode instead)" : "")
1508
+ );
1509
+ continue;
1510
+ }
1511
+ out[key] = v;
1512
+ }
1513
+ return out;
1514
+ }
1424
1515
  var AUTO_INJECT_MODES = ["reflect", "pages", "recall", "none"];
1425
1516
  function resolveAutoInject(raw) {
1426
1517
  if (raw.autoReflect !== void 0) {
@@ -1460,18 +1551,21 @@ function resolveConfig(raw = {}) {
1460
1551
  // write sessions back by default, every harness
1461
1552
  manageBankConfig: raw.manageBankConfig ?? true,
1462
1553
  retainExtractionMode: RETAIN_EXTRACTION_MODES.includes(raw.retainExtractionMode) ? raw.retainExtractionMode : DEFAULT_RETAIN_EXTRACTION_MODE,
1554
+ defaultBankConfig: resolveDefaultBankConfig(raw.defaultBankConfig),
1463
1555
  maxParallelRetains: raw.maxParallelRetains || 10,
1464
1556
  reflectTimeoutMs: raw.reflectTimeoutMs || DEFAULT_REFLECT_TIMEOUT_MS,
1465
1557
  // Inherit an explicitly-raised reflectTimeoutMs (that is what users reaching for a longer
1466
1558
  // reflect already set), but never let it LOWER the tool below the default — a short window is
1467
1559
  // set to bound the automatic hook, not to cut off a call the agent is waiting on.
1468
1560
  reflectToolTimeoutMs: raw.reflectToolTimeoutMs || Math.max(raw.reflectTimeoutMs || 0, DEFAULT_REFLECT_TOOL_TIMEOUT_MS),
1561
+ injectTimeoutMs: raw.injectTimeoutMs || DEFAULT_INJECT_TIMEOUT_MS,
1469
1562
  reflectBudget: resolveReflectBudget(raw),
1470
1563
  autoInject: resolveAutoInject(raw),
1471
1564
  pageSearchLimit: raw.pageSearchLimit || DEFAULT_PAGE_SEARCH_LIMIT,
1472
1565
  // Same shape as retainMetadata: an object, or nothing. An array would spread into numeric
1473
1566
  // keys and reach the API as garbage, so it is rejected like any other non-object.
1474
1567
  recallOptions: raw.recallOptions && typeof raw.recallOptions === "object" && !Array.isArray(raw.recallOptions) ? { ...raw.recallOptions } : {},
1568
+ toolGuideExtra: typeof raw.toolGuideExtra === "string" && raw.toolGuideExtra.trim() ? raw.toolGuideExtra : void 0,
1475
1569
  // Every turn, not every tenth. The guide is what tells the agent WHEN to reach for memory, and
1476
1570
  // at a cadence of 10 a normal session is told once, on turn 1, and never again. Measured over
1477
1571
  // 40 real Claude Code turns, moving this from 10 to 1 took searches from 15% of turns to 32.5%
@@ -1491,11 +1585,15 @@ function resolveConfig(raw = {}) {
1491
1585
  // Hostile input is a config typo, not an attack: keep only string entries so a stray number or
1492
1586
  // nested object cannot reach the API as a tag and fail the whole retain.
1493
1587
  retainTags: Array.isArray(raw.retainTags) ? raw.retainTags.filter((t) => typeof t === "string" && t.trim() !== "") : [],
1588
+ // Undefined, not "", when unset or blank: the retain call distinguishes "not configured" (use
1589
+ // the built-in default) from a configured value, and an empty context would strip the default.
1590
+ retainContext: typeof raw.retainContext === "string" && raw.retainContext.trim() !== "" ? raw.retainContext : void 0,
1494
1591
  retainMetadata: raw.retainMetadata && typeof raw.retainMetadata === "object" ? Object.fromEntries(
1495
1592
  Object.entries(raw.retainMetadata).filter(([, v]) => typeof v === "string")
1496
1593
  ) : {},
1497
1594
  observationScopes: resolveObservationScopes(raw.observationScopes),
1498
1595
  banks: raw.banks && typeof raw.banks === "object" ? raw.banks : {},
1596
+ paths: raw.paths && typeof raw.paths === "object" ? raw.paths : {},
1499
1597
  logLevel: ["debug", "info", "warn", "error"].includes(raw.logLevel) ? raw.logLevel : "info",
1500
1598
  autoUpdate: raw.autoUpdate ?? true
1501
1599
  };
@@ -1512,7 +1610,12 @@ function readRaw(path) {
1512
1610
  }
1513
1611
  function mergeRaw(a, b) {
1514
1612
  const { harnesses: _drop, ...flat } = b;
1515
- return { ...a, ...flat, banks: { ...a.banks ?? {}, ...b.banks ?? {} } };
1613
+ return {
1614
+ ...a,
1615
+ ...flat,
1616
+ banks: { ...a.banks ?? {}, ...b.banks ?? {} },
1617
+ paths: { ...a.paths ?? {}, ...b.paths ?? {} }
1618
+ };
1516
1619
  }
1517
1620
  function applyLayer(raw, layer, harness) {
1518
1621
  let out = mergeRaw(raw, layer);
@@ -1543,9 +1646,11 @@ var ENV_KEYS = {
1543
1646
  maxParallelRetains: "HINDSIGHT_MAX_PARALLEL_RETAINS",
1544
1647
  reflectTimeoutMs: "HINDSIGHT_REFLECT_TIMEOUT_MS",
1545
1648
  reflectToolTimeoutMs: "HINDSIGHT_REFLECT_TOOL_TIMEOUT_MS",
1649
+ injectTimeoutMs: "HINDSIGHT_INJECT_TIMEOUT_MS",
1546
1650
  reflectBudget: "HINDSIGHT_REFLECT_BUDGET",
1547
1651
  autoInject: "HINDSIGHT_AUTO_INJECT",
1548
1652
  pageSearchLimit: "HINDSIGHT_PAGE_SEARCH_LIMIT",
1653
+ toolGuideExtra: "HINDSIGHT_TOOL_GUIDE_EXTRA",
1549
1654
  autoReflect: "HINDSIGHT_AUTO_REFLECT",
1550
1655
  pageRefreshEveryTurns: "HINDSIGHT_PAGE_REFRESH_EVERY_TURNS",
1551
1656
  pageTriggerType: "HINDSIGHT_PAGE_TRIGGER_TYPE",
@@ -1587,6 +1692,7 @@ var ENV_NUMBERS = /* @__PURE__ */ new Set([
1587
1692
  "maxParallelRetains",
1588
1693
  "reflectTimeoutMs",
1589
1694
  "reflectToolTimeoutMs",
1695
+ "injectTimeoutMs",
1590
1696
  "pageSearchLimit",
1591
1697
  "pageRefreshEveryTurns",
1592
1698
  "seedLimit",
@@ -1635,15 +1741,25 @@ var BANK_OVERRIDE_EXCLUDED = [
1635
1741
  function applyBankConfig(cfg, resolvedId, directory) {
1636
1742
  if (directory !== void 0 && !isOptedIn(cfg, directory))
1637
1743
  return { cfg: { ...cfg, disabled: true }, bankId: resolvedId };
1744
+ const byPath = directory === void 0 ? void 0 : pathSection(cfg, cfg.paths, directory);
1745
+ if (byPath) {
1746
+ const { bank: _rename, ...rest } = overrideFields(byPath);
1747
+ cfg = { ...cfg, ...resolvePartial(cfg, rest) };
1748
+ }
1638
1749
  const section = cfg.banks[resolvedId];
1639
1750
  if (!section) return { cfg, bankId: resolvedId };
1640
- const safe = { ...section };
1641
- for (const k of BANK_OVERRIDE_EXCLUDED) delete safe[k];
1642
- delete safe.banks;
1751
+ const safe = overrideFields(section);
1643
1752
  const bankId = typeof safe.bank === "string" && safe.bank ? safe.bank : resolvedId;
1644
1753
  delete safe.bank;
1645
1754
  return { cfg: { ...cfg, ...resolvePartial(cfg, safe) }, bankId };
1646
1755
  }
1756
+ function overrideFields(section) {
1757
+ const safe = { ...section };
1758
+ for (const k of BANK_OVERRIDE_EXCLUDED) delete safe[k];
1759
+ delete safe.banks;
1760
+ delete safe.paths;
1761
+ return safe;
1762
+ }
1647
1763
  function resolvePartial(cfg, patch) {
1648
1764
  const full = resolveConfig(patch);
1649
1765
  const out = {};
@@ -1652,6 +1768,16 @@ function resolvePartial(cfg, patch) {
1652
1768
  out[key] = full[key];
1653
1769
  }
1654
1770
  if ("autoReflect" in patch && !("autoInject" in patch)) out.autoInject = full.autoInject;
1771
+ if ("serverMode" in patch || "apiUrl" in patch || "apiPort" in patch) {
1772
+ const conn = resolveConfig({
1773
+ serverMode: patch.serverMode ?? cfg.serverMode,
1774
+ apiPort: patch.apiPort ?? cfg.apiPort,
1775
+ apiUrl: patch.apiUrl ?? (cfg.serverMode === "daemon" ? void 0 : cfg.apiUrl)
1776
+ });
1777
+ out.serverMode = conn.serverMode;
1778
+ out.apiUrl = conn.apiUrl;
1779
+ out.apiPort = conn.apiPort;
1780
+ }
1655
1781
  return out;
1656
1782
  }
1657
1783
 
@@ -1833,6 +1959,11 @@ import { readFileSync as readFileSync7 } from "fs";
1833
1959
  import { createHash as createHash2 } from "crypto";
1834
1960
  var PENDING_MAX_AGE_MS = 12 * 60 * 60 * 1e3;
1835
1961
  var PENDING_MAX_BYTES = 256 * 1024;
1962
+ var MAX_CURSOR_PATHS = 16;
1963
+ function advancePaths(seen, path) {
1964
+ if (!path) return seen;
1965
+ return [...(seen ?? []).filter((p) => p !== path), path].slice(-MAX_CURSOR_PATHS);
1966
+ }
1836
1967
  function pendingReplayable(cursor, now) {
1837
1968
  const pending = cursor.pending ?? [];
1838
1969
  if (!pending.length) return true;
@@ -1849,8 +1980,10 @@ function planRetain(turns, cursor, opts) {
1849
1980
  if (!opts.appendSupported || !cursor || cursor.dirty) return { mode: "replace" };
1850
1981
  if (!pendingReplayable(cursor, opts.now ?? Date.now())) return { mode: "replace" };
1851
1982
  if (cursor.bank !== opts.bank) return { mode: "replace" };
1852
- if (cursor.turns > turns.length) return { mode: "replace" };
1853
- if (fingerprintTurns(turns, cursor.turns) !== cursor.fingerprint) return { mode: "replace" };
1983
+ const seen = cursor.paths ?? [];
1984
+ const newFile = Boolean(opts.path && seen.length && !seen.includes(opts.path));
1985
+ const continues = cursor.turns <= turns.length && fingerprintTurns(turns, cursor.turns) === cursor.fingerprint;
1986
+ if (!continues) return newFile ? { mode: "append", fromTurn: 0 } : { mode: "replace" };
1854
1987
  if (cursor.turns === turns.length) return { mode: "skip" };
1855
1988
  return { mode: "append", fromTurn: cursor.turns };
1856
1989
  }
@@ -1885,7 +2018,7 @@ function renderSessionJsonl(refId, turns, baseTs) {
1885
2018
  }
1886
2019
  async function supportsAppend(client) {
1887
2020
  try {
1888
- return await client.supportsIdempotentRetain();
2021
+ return await client.supportsAppendRetain();
1889
2022
  } catch {
1890
2023
  return false;
1891
2024
  }
@@ -1919,6 +2052,7 @@ function serialize(cursors, sessionId, write2) {
1919
2052
  });
1920
2053
  return next;
1921
2054
  }
2055
+ var DEFAULT_RETAIN_CONTEXT = `conversation between the user and you (the coding agent): user turns are the user's words and decisions, assistant turns are yours. When an assistant turn says something is fixed, passes or works, record it as the agent's claim ("the agent reported X fixed"), not as an established fact.`;
1922
2056
  async function retainLiveSession(client, sessionId, turns, startTs, harness, opts = {}) {
1923
2057
  const cursors = opts.cursors;
1924
2058
  if (!cursors)
@@ -1930,20 +2064,36 @@ async function retainLiveSession(client, sessionId, turns, startTs, harness, opt
1930
2064
  harness,
1931
2065
  opts.stamp,
1932
2066
  void 0,
1933
- opts.retryUntil
2067
+ opts.retryUntil,
2068
+ opts.transcriptPath
1934
2069
  );
1935
2070
  return serialize(
1936
2071
  cursors,
1937
2072
  sessionId,
1938
- () => writeSession(client, sessionId, turns, startTs, harness, opts.stamp, cursors, opts.retryUntil)
2073
+ () => writeSession(
2074
+ client,
2075
+ sessionId,
2076
+ turns,
2077
+ startTs,
2078
+ harness,
2079
+ opts.stamp,
2080
+ cursors,
2081
+ opts.retryUntil,
2082
+ opts.transcriptPath
2083
+ )
1939
2084
  );
1940
2085
  }
1941
- async function writeSession(client, sessionId, turns, startTs, harness, stamp, cursors, retryUntil = Date.now() + DEFAULT_RETRY_WINDOW_MS) {
2086
+ async function writeSession(client, sessionId, turns, startTs, harness, stamp, cursors, retryUntil = Date.now() + DEFAULT_RETRY_WINDOW_MS, transcriptPath) {
1942
2087
  if (!turns.length) return;
1943
2088
  const refId = `conversation:${sessionId}`;
1944
2089
  const cursor = cursors?.read(sessionId);
1945
2090
  const appendSupported = Boolean(cursors) && (cursor?.appendSupported === true || await supportsAppend(client));
1946
- const plan = planRetain(turns, cursor, { appendSupported, bank: client.bank });
2091
+ const plan = planRetain(turns, cursor, {
2092
+ appendSupported,
2093
+ bank: client.bank,
2094
+ path: transcriptPath
2095
+ });
2096
+ const paths = plan.mode === "replace" ? transcriptPath ? [transcriptPath] : void 0 : advancePaths(cursor?.paths, transcriptPath);
1947
2097
  const outbox = plan.mode === "replace" ? [] : cursor?.pending ?? [];
1948
2098
  if (plan.mode === "skip" && !outbox.length) return;
1949
2099
  const opId = (mode, content) => uuidV5(`${client.bank}
@@ -1952,7 +2102,10 @@ ${mode}
1952
2102
  ${content}`);
1953
2103
  const submit = (content, operationId, append) => client.retain(
1954
2104
  content,
1955
- "coding agent session",
2105
+ // Configured context wins. Extraction reads this to decide whose claim a sentence is, so the
2106
+ // default names both speakers: the previous "coding agent session" said nothing about
2107
+ // authorship and let an assistant's proposal be recorded as the user's decision.
2108
+ stamp?.context ?? DEFAULT_RETAIN_CONTEXT,
1956
2109
  refId,
1957
2110
  // Configured tags first, built-ins last and deduped: `source:chat` and `harness:<id>` are what
1958
2111
  // the documents list filters and draws its agent logo from, so a template cannot displace them.
@@ -1982,6 +2135,7 @@ ${content}`);
1982
2135
  turns: turns.length,
1983
2136
  fingerprint: fingerprintTurns(turns, turns.length),
1984
2137
  bank: client.bank,
2138
+ ...paths ? { paths } : {},
1985
2139
  ...appendSupported ? { appendSupported: true } : {}
1986
2140
  };
1987
2141
  const stillOurs = () => {
@@ -2108,12 +2262,46 @@ function startDaemonDetached(cfg, harness, spawnFn = realSpawn2) {
2108
2262
  } catch {
2109
2263
  }
2110
2264
  }
2265
+ var coldStarts = /* @__PURE__ */ new Map();
2266
+ async function waitBounded(p, ms) {
2267
+ let timer;
2268
+ try {
2269
+ await Promise.race([
2270
+ p,
2271
+ new Promise((resolve3) => {
2272
+ timer = setTimeout(resolve3, Math.max(ms, 0));
2273
+ })
2274
+ ]);
2275
+ } finally {
2276
+ clearTimeout(timer);
2277
+ }
2278
+ }
2111
2279
  async function ensureDaemon(cfg, harness, opts = {}) {
2112
2280
  if (cfg.serverMode !== "daemon") return;
2113
2281
  if (await isServerHealthy(cfg.apiUrl)) return;
2114
2282
  if (!preflightDaemon(cfg, harness)) return;
2115
- startDaemonDetached(cfg, harness, opts.spawnFn);
2116
- await waitForHealth(cfg.apiUrl, opts.waitMs ?? 0);
2283
+ const waitMs = opts.waitMs ?? 0;
2284
+ const running = coldStarts.get(cfg.apiUrl);
2285
+ if (running) {
2286
+ const startedAt = Date.now();
2287
+ await waitBounded(
2288
+ running.catch(() => void 0),
2289
+ waitMs
2290
+ );
2291
+ const remaining = waitMs - (Date.now() - startedAt);
2292
+ if (remaining > 0) await waitForHealth(cfg.apiUrl, remaining);
2293
+ return;
2294
+ }
2295
+ const attempt = (async () => {
2296
+ startDaemonDetached(cfg, harness, opts.spawnFn);
2297
+ await waitForHealth(cfg.apiUrl, waitMs);
2298
+ })();
2299
+ coldStarts.set(cfg.apiUrl, attempt);
2300
+ try {
2301
+ await attempt;
2302
+ } finally {
2303
+ if (coldStarts.get(cfg.apiUrl) === attempt) coldStarts.delete(cfg.apiUrl);
2304
+ }
2117
2305
  }
2118
2306
  async function waitForHealth(baseUrl, budgetMs, pollMs = 1e3) {
2119
2307
  const deadline = Date.now() + budgetMs;
@@ -2168,7 +2356,8 @@ function resolversFor(ctx) {
2168
2356
  function buildRetainStamp(cfg, ctx) {
2169
2357
  const hasTags = Boolean(cfg.retainTags?.length);
2170
2358
  const hasMetadata = Boolean(cfg.retainMetadata && Object.keys(cfg.retainMetadata).length);
2171
- if (!hasTags && !hasMetadata) return { tags: [], metadata: {} };
2359
+ const hasContext = Boolean(cfg.retainContext?.trim());
2360
+ if (!hasTags && !hasMetadata && !hasContext) return { tags: [], metadata: {} };
2172
2361
  const base = resolversFor(ctx);
2173
2362
  const cache = /* @__PURE__ */ new Map();
2174
2363
  const resolvers = Object.fromEntries(
@@ -2192,7 +2381,8 @@ function buildRetainStamp(cfg, ctx) {
2192
2381
  for (const [key, value] of Object.entries(cfg.retainMetadata ?? {})) {
2193
2382
  metadata[key] = applyTemplate(value, resolvers, "retainMetadata");
2194
2383
  }
2195
- return { tags, metadata };
2384
+ const context = hasContext ? applyTemplate(cfg.retainContext, resolvers, "retainContext").trim() || void 0 : void 0;
2385
+ return { tags, metadata, context };
2196
2386
  }
2197
2387
 
2198
2388
  // src/core/jsonl.ts
@@ -2366,7 +2556,8 @@ async function buildRetain(args) {
2366
2556
  await retainLiveSession(client, sessionId, turns, startTs, harness, {
2367
2557
  cursors: args.cursors ?? fileCursorStore(harness),
2368
2558
  stamp: args.stamp,
2369
- retryUntil: args.retryUntil
2559
+ retryUntil: args.retryUntil,
2560
+ transcriptPath
2370
2561
  });
2371
2562
  diag(harness, "retain_ok", { ms: Date.now() - t0, turns: turns.length, session: sessionId });
2372
2563
  } catch (e) {
@@ -2500,15 +2691,246 @@ var NPM_VIEW_HARD_DEADLINE_MS = NPM_VIEW_TIMEOUT_MS + 1e3;
2500
2691
  var LOCK_STALE_MS = 10 * 60 * 1e3;
2501
2692
 
2502
2693
  // src/core/skill-sync.ts
2503
- import { cpSync, existsSync as existsSync5, readFileSync as readFileSync9 } from "fs";
2694
+ import { cpSync, existsSync as existsSync6, readFileSync as readFileSync9 } from "fs";
2504
2695
  import { homedir as homedir6 } from "os";
2505
- import { dirname as dirname10, join as join15 } from "path";
2696
+ import { dirname as dirname10, join as join16 } from "path";
2506
2697
  import { fileURLToPath as fileURLToPath5 } from "url";
2507
2698
 
2699
+ // src/core/skill-dirs.ts
2700
+ import { existsSync as existsSync5 } from "fs";
2701
+ import { join as join15 } from "path";
2702
+
2508
2703
  // src/core/legacy.ts
2509
- import { existsSync as existsSync6, readFileSync as readFileSync10 } from "fs";
2704
+ import { existsSync as existsSync7, readFileSync as readFileSync10 } from "fs";
2510
2705
  import { homedir as homedir7 } from "os";
2511
- import { join as join16, relative, isAbsolute as isAbsolute2 } from "path";
2706
+ import { join as join17, relative, isAbsolute as isAbsolute2 } from "path";
2707
+
2708
+ // src/core/traecode-mcp.ts
2709
+ import { execFileSync as execFileSync4 } from "child_process";
2710
+ import { existsSync as existsSync8, mkdirSync as mkdirSync6, readFileSync as readFileSync12, readdirSync as readdirSync2, rmSync as rmSync3, writeFileSync as writeFileSync4 } from "fs";
2711
+ import { homedir as homedir8 } from "os";
2712
+ import { dirname as dirname11, isAbsolute as isAbsolute3, join as join18 } from "path";
2713
+ import { fileURLToPath as fileURLToPath6 } from "url";
2714
+ var MCP_SERVER_NAME = "hindsight";
2715
+ var MCP_FILE_REL = join18(".trae", "mcp.json");
2716
+ function bundledDistDir() {
2717
+ const here = dirname11(fileURLToPath6(import.meta.url));
2718
+ return existsSync8(join18(here, "mcp-server.js")) ? here : join18(here, "..", "..", "dist");
2719
+ }
2720
+ function canon(value) {
2721
+ if (Array.isArray(value)) return `[${value.map(canon).join(",")}]`;
2722
+ if (value && typeof value === "object") {
2723
+ const entries = Object.entries(value).sort(
2724
+ ([a], [b]) => a < b ? -1 : a > b ? 1 : 0
2725
+ );
2726
+ return `{${entries.map(([k, v]) => `${JSON.stringify(k)}:${canon(v)}`).join(",")}}`;
2727
+ }
2728
+ return JSON.stringify(value);
2729
+ }
2730
+ var WORKSPACE_MCP_KEY = "trae.mcp.enableWorkspaceMcp";
2731
+ var HINT_MIN_INTERVAL_MS = 24 * 60 * 60 * 1e3;
2732
+ function traecodeUserDataDir(home) {
2733
+ const root = process.platform === "darwin" ? join18(home, "Library", "Application Support") : process.platform === "win32" ? process.env.APPDATA ?? join18(home, "AppData", "Roaming") : process.env.XDG_CONFIG_HOME ?? join18(home, ".config");
2734
+ for (const brand of ["Trae CN", "Trae"]) {
2735
+ const dir = join18(root, brand);
2736
+ if (existsSync8(dir)) return dir;
2737
+ }
2738
+ return join18(root, "Trae CN");
2739
+ }
2740
+ var traecodeUserSettingsPath = (home) => join18(traecodeUserDataDir(home), "User", "settings.json");
2741
+ var gateStateFileFor = (dist) => join18(dirname11(dist), ".workspace-mcp.json");
2742
+ function gateStateFile() {
2743
+ return gateStateFileFor(bundledDistDir());
2744
+ }
2745
+ function readGateState(opts = {}) {
2746
+ try {
2747
+ return JSON.parse(readFileSync12(opts.stateFile ?? gateStateFile(), "utf8"));
2748
+ } catch {
2749
+ return {};
2750
+ }
2751
+ }
2752
+ function workspaceMcpGateState(settingsPath) {
2753
+ let raw;
2754
+ try {
2755
+ raw = readFileSync12(settingsPath, "utf8");
2756
+ } catch {
2757
+ return "unknown";
2758
+ }
2759
+ try {
2760
+ const doc = JSON.parse(raw);
2761
+ return doc[WORKSPACE_MCP_KEY] === true ? "on" : "off";
2762
+ } catch {
2763
+ const hit = raw.match(new RegExp(`"${WORKSPACE_MCP_KEY}"\\s*:\\s*(true|false)`));
2764
+ return hit ? hit[1] === "true" ? "on" : "off" : "unknown";
2765
+ }
2766
+ }
2767
+ function workspaceMcpHint(opts = {}) {
2768
+ try {
2769
+ const settingsPath = traecodeUserSettingsPath(opts.home ?? homedir8());
2770
+ if (workspaceMcpGateState(settingsPath) === "on") return void 0;
2771
+ const now = opts.now ?? Date.now();
2772
+ const state = readGateState(opts);
2773
+ if (state.workspaceMcpEnabled) return void 0;
2774
+ if (typeof state.lastHint === "number" && now - state.lastHint < HINT_MIN_INTERVAL_MS) {
2775
+ return void 0;
2776
+ }
2777
+ writeFileSync4(
2778
+ opts.stateFile ?? gateStateFile(),
2779
+ JSON.stringify({ ...state, lastHint: now }, null, 2) + "\n"
2780
+ );
2781
+ return 'Hindsight MCP tools are hidden: TraeCode does not read per-repo MCP configs until workspace MCP is enabled. Turn it on once in Trae settings (search "enableWorkspaceMcp") or re-run `hindsight-coding-agents install traecode` \u2014 then reload this window.';
2782
+ } catch {
2783
+ return void 0;
2784
+ }
2785
+ }
2786
+ function gitignoreCovers(lines) {
2787
+ return lines.some((l) => {
2788
+ const t = l.trim();
2789
+ return t.includes(".trae");
2790
+ });
2791
+ }
2792
+ function ensureGitignored(repo) {
2793
+ const gitignore = join18(repo, ".gitignore");
2794
+ if (!existsSync8(gitignore)) return;
2795
+ const current2 = readFileSync12(gitignore, "utf8");
2796
+ if (gitignoreCovers(current2.split("\n"))) return;
2797
+ const addition = (current2.endsWith("\n") || current2 === "" ? "" : "\n") + "# hindsight MCP registration (machine-specific)\n.trae/mcp.json\n";
2798
+ writeFileSync4(gitignore, current2 + addition);
2799
+ }
2800
+ function ensureTraecodeWorkspaceMcp(cwd, opts = {}) {
2801
+ registerTraecodeWorkspaceMcp(cwd, opts);
2802
+ const seeded = ensureWorkspaceMcpEnabled(cwd, opts);
2803
+ return workspaceMcpHint(opts) ?? (seeded === "failed" ? workspaceEnableHint(opts) : void 0);
2804
+ }
2805
+ function registerTraecodeWorkspaceMcp(cwd, opts = {}) {
2806
+ try {
2807
+ const home = opts.home ?? homedir8();
2808
+ if (!cwd || !isAbsolute3(cwd) || dirname11(cwd) === cwd || cwd === home) return "skipped";
2809
+ const dist = opts.dist ?? bundledDistDir();
2810
+ const script = join18(dist, "mcp-server.js");
2811
+ if (!existsSync8(script)) return "skipped";
2812
+ const file = join18(cwd, MCP_FILE_REL);
2813
+ let doc = {};
2814
+ let exists = false;
2815
+ try {
2816
+ doc = JSON.parse(readFileSync12(file, "utf8"));
2817
+ exists = true;
2818
+ } catch {
2819
+ if (existsSync8(file)) return "skipped";
2820
+ }
2821
+ const servers = doc.mcpServers && typeof doc.mcpServers === "object" && !Array.isArray(doc.mcpServers) ? doc.mcpServers : doc.mcpServers = {};
2822
+ const entry = {
2823
+ command: "node",
2824
+ args: [script],
2825
+ env: { HINDSIGHT_MCP_HARNESS: "traecode", HINDSIGHT_MCP_PROJECT_CWD: cwd }
2826
+ };
2827
+ const existing = servers[MCP_SERVER_NAME];
2828
+ let merged;
2829
+ if (existing === void 0) {
2830
+ merged = entry;
2831
+ } else if (isOurMcpEntry(existing)) {
2832
+ const env = existing.env;
2833
+ merged = {
2834
+ ...existing,
2835
+ command: entry.command,
2836
+ args: entry.args,
2837
+ env: { ...env ?? {}, ...entry.env }
2838
+ };
2839
+ } else {
2840
+ diag("traecode", "workspace_mcp_foreign_entry", { cwd, file });
2841
+ return "skipped";
2842
+ }
2843
+ if (existing !== void 0 && canon(merged) === canon(existing)) return "current";
2844
+ servers[MCP_SERVER_NAME] = merged;
2845
+ mkdirSync6(dirname11(file), { recursive: true });
2846
+ writeFileSync4(file, JSON.stringify(doc, null, 2) + "\n");
2847
+ if (!exists) ensureGitignored(cwd);
2848
+ diag("traecode", "workspace_mcp_registered", { cwd, file });
2849
+ return "registered";
2850
+ } catch (e) {
2851
+ diag("traecode", "workspace_mcp_register_failed", {
2852
+ cwd,
2853
+ error: e instanceof Error ? e.message : String(e)
2854
+ });
2855
+ return "failed";
2856
+ }
2857
+ }
2858
+ var WORKSPACE_STORAGE_REL = join18("User", "workspaceStorage");
2859
+ var ENABLED_KEY_PREFIX = "icubeAgentExtension.enabled.mcp.config.ws0.";
2860
+ var SQLITE_TIMEOUT_MS = 5e3;
2861
+ var TRAECODE_WORKSPACE_ENABLED_KEY = ENABLED_KEY_PREFIX + MCP_SERVER_NAME;
2862
+ var traecodeWorkspaceStorageDir = (home) => join18(traecodeUserDataDir(home), WORKSPACE_STORAGE_REL);
2863
+ function findWorkspaceStorageDir(storage, repo) {
2864
+ let entries;
2865
+ try {
2866
+ entries = readdirSync2(storage);
2867
+ } catch {
2868
+ return void 0;
2869
+ }
2870
+ for (const name of entries) {
2871
+ try {
2872
+ const doc = JSON.parse(readFileSync12(join18(storage, name, "workspace.json"), "utf8"));
2873
+ if (typeof doc.folder !== "string") continue;
2874
+ let folder;
2875
+ try {
2876
+ folder = fileURLToPath6(doc.folder);
2877
+ } catch {
2878
+ folder = doc.folder;
2879
+ }
2880
+ if (folder === repo) return join18(storage, name);
2881
+ } catch {
2882
+ continue;
2883
+ }
2884
+ }
2885
+ return void 0;
2886
+ }
2887
+ function ensureWorkspaceMcpEnabled(cwd, opts = {}) {
2888
+ try {
2889
+ const home = opts.home ?? homedir8();
2890
+ if (!cwd || !isAbsolute3(cwd) || dirname11(cwd) === cwd || cwd === home) return "failed";
2891
+ const dir = findWorkspaceStorageDir(traecodeWorkspaceStorageDir(home), cwd);
2892
+ if (!dir) return "failed";
2893
+ const db = join18(dir, "state.vscdb");
2894
+ if (!existsSync8(db)) return "failed";
2895
+ const sqlite = opts.sqlite ?? execFileSync4;
2896
+ const run = (sql) => sqlite("sqlite3", [db, ".timeout 3000", sql], {
2897
+ encoding: "utf8",
2898
+ timeout: SQLITE_TIMEOUT_MS,
2899
+ windowsHide: true,
2900
+ stdio: ["ignore", "pipe", "pipe"]
2901
+ }).trim();
2902
+ if (run(`SELECT value FROM ItemTable WHERE key='${TRAECODE_WORKSPACE_ENABLED_KEY}';`) === "true") {
2903
+ return "on";
2904
+ }
2905
+ run(
2906
+ `INSERT OR REPLACE INTO ItemTable (key, value) VALUES ('${TRAECODE_WORKSPACE_ENABLED_KEY}', 'true');`
2907
+ );
2908
+ diag("traecode", "workspace_mcp_enabled_seeded", { cwd, db });
2909
+ return "seeded";
2910
+ } catch (e) {
2911
+ diag("traecode", "workspace_mcp_enabled_seed_failed", {
2912
+ cwd,
2913
+ error: e instanceof Error ? e.message : String(e)
2914
+ });
2915
+ return "failed";
2916
+ }
2917
+ }
2918
+ function workspaceEnableHint(opts = {}) {
2919
+ try {
2920
+ const now = opts.now ?? Date.now();
2921
+ const state = readGateState(opts);
2922
+ if (typeof state.lastEnableHint === "number" && now - state.lastEnableHint < HINT_MIN_INTERVAL_MS) {
2923
+ return void 0;
2924
+ }
2925
+ writeFileSync4(
2926
+ opts.stateFile ?? gateStateFile(),
2927
+ JSON.stringify({ ...state, lastEnableHint: now }, null, 2) + "\n"
2928
+ );
2929
+ return "Hindsight's MCP server stays disabled in this window: auto-enabling it failed here. Switch hindsight on for this workspace in Trae's MCP panel, then reload the window.";
2930
+ } catch {
2931
+ return void 0;
2932
+ }
2933
+ }
2512
2934
 
2513
2935
  // src/core/transcript-codex.ts
2514
2936
  function stampOf(line) {
@@ -2519,11 +2941,56 @@ function isSyntheticUserText(text) {
2519
2941
  return s.startsWith("# AGENTS.md instructions for ") || s.startsWith("<environment_context>");
2520
2942
  }
2521
2943
  function contentText(content) {
2522
- return (content || []).filter((c) => c && typeof c.text === "string").map((c) => c.text).join("\n");
2944
+ return (Array.isArray(content) ? content : []).filter((c) => c && typeof c.text === "string").map((c) => c.text).join("\n");
2945
+ }
2946
+ var startupKinds = /* @__PURE__ */ new Set([
2947
+ "agents_md.instructions",
2948
+ "environments.instructions",
2949
+ "environments.environment_context",
2950
+ "plugins.recommendations",
2951
+ "plugins.usage_instructions"
2952
+ ]);
2953
+ function fallbackUserText(payload) {
2954
+ const content = payload.content;
2955
+ const kinds = payload.internal_chat_message_metadata_passthrough?.content_item_kinds;
2956
+ if (Array.isArray(content) && Array.isArray(kinds) && kinds.length === content.length && kinds.every((kind) => typeof kind === "string" && kind.length > 0)) {
2957
+ return contentText(content.filter((_, index) => !startupKinds.has(kinds[index])));
2958
+ }
2959
+ const text = contentText(content);
2960
+ return isSyntheticUserText(stripInjectedMemory(text)) ? "" : text;
2523
2961
  }
2524
2962
  function isUserMessageEvent(line) {
2525
2963
  return line.type === "event_msg" && line.payload?.type === "item_completed" && line.payload.item?.type === "UserMessage";
2526
2964
  }
2965
+ var TOOL_ITEM_TYPES = /* @__PURE__ */ new Set(["McpToolCall", "CommandExecution"]);
2966
+ function isToolItemEvent(line) {
2967
+ return line.type === "event_msg" && line.payload?.type === "item_completed" && TOOL_ITEM_TYPES.has(line.payload.item?.type ?? "");
2968
+ }
2969
+ function parseArgs(raw) {
2970
+ if (typeof raw !== "string") return raw;
2971
+ try {
2972
+ return JSON.parse(raw);
2973
+ } catch {
2974
+ return void 0;
2975
+ }
2976
+ }
2977
+ var SHELL_RE = /(?:^|\/)(?:sh|bash|zsh|dash|ksh|fish)$/;
2978
+ function commandText(command) {
2979
+ if (typeof command === "string") return command;
2980
+ if (!Array.isArray(command) || !command.every((c) => typeof c === "string")) return "";
2981
+ const argv = command;
2982
+ if (argv.length === 3 && SHELL_RE.test(argv[0]) && /^-[a-z]*c$/.test(argv[1])) return argv[2];
2983
+ return argv.join(" ");
2984
+ }
2985
+ function toolItemAction(item) {
2986
+ if (item.type === "McpToolCall") {
2987
+ if (typeof item.tool !== "string" || !item.tool) return void 0;
2988
+ const name = typeof item.server === "string" && item.server ? `mcp__${item.server}__${item.tool}` : item.tool;
2989
+ return actionLine(name, parseArgs(item.arguments));
2990
+ }
2991
+ const command = commandText(item.command).trim();
2992
+ return command ? actionLine("exec_command", { command }) : void 0;
2993
+ }
2527
2994
  function readCodexTranscript(path) {
2528
2995
  const lines = [];
2529
2996
  for (const rawLine of readJsonl(path)) {
@@ -2537,6 +3004,7 @@ function readCodexTranscript(path) {
2537
3004
  }
2538
3005
  }
2539
3006
  const userFromEvents = lines.some(isUserMessageEvent);
3007
+ const actionsFromEvents = lines.some(isToolItemEvent);
2540
3008
  const turns = [];
2541
3009
  const push = (role, raw, stamp = {}) => {
2542
3010
  const text = stripInjectedMemory(raw).trim();
@@ -2547,16 +3015,24 @@ function readCodexTranscript(path) {
2547
3015
  push("user", contentText(line.payload?.item?.content), stampOf(line));
2548
3016
  continue;
2549
3017
  }
3018
+ if (isToolItemEvent(line)) {
3019
+ const action = toolItemAction(line.payload?.item ?? {});
3020
+ if (action) turns.push({ role: "action", content: action, ...stampOf(line) });
3021
+ continue;
3022
+ }
2550
3023
  if (line.type !== "response_item") continue;
2551
3024
  const p = line.payload;
2552
3025
  if (!p || typeof p !== "object") continue;
2553
3026
  if (p.type === "message") {
2554
- if (p.role === "assistant") push("assistant", contentText(p.content), stampOf(line));
2555
- else if (p.role === "user" && !userFromEvents) {
2556
- const text = contentText(p.content);
2557
- if (!isSyntheticUserText(stripInjectedMemory(text))) push("user", text, stampOf(line));
3027
+ if (p.role === "assistant") {
3028
+ if (p.channel === "analysis" || p.channel === "reasoning" || p.phase === "analysis" || p.phase === "reasoning")
3029
+ continue;
3030
+ push("assistant", contentText(p.content), stampOf(line));
3031
+ } else if (p.role === "user" && !userFromEvents) {
3032
+ push("user", fallbackUserText(p), stampOf(line));
2558
3033
  }
2559
3034
  } else if ((p.type === "function_call" || p.type === "custom_tool_call") && typeof p.name === "string") {
3035
+ if (actionsFromEvents && p.type === "custom_tool_call" && p.name === "exec") continue;
2560
3036
  const rawInput = p.type === "function_call" ? p.arguments : p.input;
2561
3037
  let input;
2562
3038
  try {
@@ -2657,19 +3133,19 @@ function readCopilotTranscript(path) {
2657
3133
  }
2658
3134
 
2659
3135
  // src/core/transcript-grok.ts
2660
- import { existsSync as existsSync7, readFileSync as readFileSync12, readdirSync as readdirSync2 } from "fs";
2661
- import { homedir as homedir8 } from "os";
2662
- import { join as join17 } from "path";
3136
+ import { existsSync as existsSync9, readFileSync as readFileSync13, readdirSync as readdirSync3 } from "fs";
3137
+ import { homedir as homedir9 } from "os";
3138
+ import { join as join19 } from "path";
2663
3139
  var CHAT_HISTORY = "chat_history.jsonl";
2664
- function grokTranscriptPath(cwd, sessionId, grokHome = process.env.GROK_HOME || join17(homedir8(), ".grok")) {
2665
- const sessionsDir = join17(grokHome, "sessions");
2666
- const direct = join17(sessionsDir, encodeURIComponent(cwd), sessionId, CHAT_HISTORY);
2667
- if (existsSync7(direct)) return direct;
3140
+ function grokTranscriptPath(cwd, sessionId, grokHome = process.env.GROK_HOME || join19(homedir9(), ".grok")) {
3141
+ const sessionsDir = join19(grokHome, "sessions");
3142
+ const direct = join19(sessionsDir, encodeURIComponent(cwd), sessionId, CHAT_HISTORY);
3143
+ if (existsSync9(direct)) return direct;
2668
3144
  try {
2669
- for (const candidate of readdirSync2(sessionsDir)) {
2670
- const directory = join17(sessionsDir, candidate);
2671
- if (readFileSync12(join17(directory, ".cwd"), "utf8").trim() === cwd) {
2672
- return join17(directory, sessionId, CHAT_HISTORY);
3145
+ for (const candidate of readdirSync3(sessionsDir)) {
3146
+ const directory = join19(sessionsDir, candidate);
3147
+ if (readFileSync13(join19(directory, ".cwd"), "utf8").trim() === cwd) {
3148
+ return join19(directory, sessionId, CHAT_HISTORY);
2673
3149
  }
2674
3150
  }
2675
3151
  } catch {
@@ -2704,12 +3180,12 @@ function readGrokTranscript(path) {
2704
3180
  }
2705
3181
 
2706
3182
  // src/core/transcript-devin.ts
2707
- import { existsSync as existsSync8 } from "fs";
3183
+ import { existsSync as existsSync10 } from "fs";
2708
3184
  import { createRequire } from "module";
2709
- import { homedir as homedir9 } from "os";
2710
- import { join as join18 } from "path";
2711
- function devinSessionDb(home = homedir9()) {
2712
- return join18(home, ".local", "share", "devin", "cli", "sessions.db");
3185
+ import { homedir as homedir10 } from "os";
3186
+ import { join as join20 } from "path";
3187
+ function devinSessionDb(home = homedir10()) {
3188
+ return join20(home, ".local", "share", "devin", "cli", "sessions.db");
2713
3189
  }
2714
3190
  function parseDevinMessages(nodes) {
2715
3191
  const messages = /* @__PURE__ */ new Map();
@@ -2746,7 +3222,7 @@ function readDevinTranscript(sessionId, dbPath = devinSessionDb()) {
2746
3222
  diag("devin-cli", "sqlite_unavailable", { node: process.version, dbPath });
2747
3223
  return [];
2748
3224
  }
2749
- if (!existsSync8(dbPath)) {
3225
+ if (!existsSync10(dbPath)) {
2750
3226
  diag("devin-cli", "session_db_missing", { dbPath });
2751
3227
  return [];
2752
3228
  }
@@ -3019,7 +3495,7 @@ function readDroidTranscript(path) {
3019
3495
  }
3020
3496
 
3021
3497
  // src/core/transcript-zcode.ts
3022
- import { readFileSync as readFileSync13 } from "fs";
3498
+ import { readFileSync as readFileSync14 } from "fs";
3023
3499
  function messageText(content) {
3024
3500
  if (typeof content === "string") return content.trim();
3025
3501
  if (!Array.isArray(content)) return "";
@@ -3029,7 +3505,7 @@ function readZcodeTranscript(path) {
3029
3505
  if (!path) return [];
3030
3506
  let body;
3031
3507
  try {
3032
- body = readFileSync13(path, "utf8");
3508
+ body = readFileSync14(path, "utf8");
3033
3509
  } catch {
3034
3510
  return [];
3035
3511
  }
@@ -3063,6 +3539,131 @@ function zcodeAssistantText(path) {
3063
3539
  return readZcodeTranscript(path).filter((turn) => turn.role === "assistant").at(-1)?.content ?? "";
3064
3540
  }
3065
3541
 
3542
+ // src/core/transcript-kimi.ts
3543
+ import { existsSync as existsSync11, readdirSync as readdirSync4 } from "fs";
3544
+ import { homedir as homedir11 } from "os";
3545
+ import { join as join21 } from "path";
3546
+ var HARNESS = "kimi-code";
3547
+ var SESSIONS_DIR = "sessions";
3548
+ var AGENTS_DIR = "agents";
3549
+ var WIRE_LOG = "wire.jsonl";
3550
+ var SESSION_PREFIX = "session_";
3551
+ var MAIN_AGENT = "main";
3552
+ var MAX_SESSION_CHARS = 32 * 1024 * 1024;
3553
+ function kimiSessionDir(sessionId, kimiHome = process.env.KIMI_CODE_HOME || join21(homedir11(), ".kimi-code")) {
3554
+ const name = sessionId.startsWith(SESSION_PREFIX) ? sessionId : `${SESSION_PREFIX}${sessionId}`;
3555
+ const sessions = join21(kimiHome, SESSIONS_DIR);
3556
+ try {
3557
+ for (const workspace of readdirSync4(sessions, { withFileTypes: true })) {
3558
+ if (!workspace.isDirectory()) continue;
3559
+ const candidate = join21(sessions, workspace.name, name);
3560
+ if (existsSync11(join21(candidate, AGENTS_DIR))) return candidate;
3561
+ }
3562
+ } catch {
3563
+ }
3564
+ diag(HARNESS, "session_dir_missing", { sessions, session: name });
3565
+ return void 0;
3566
+ }
3567
+ function stampOf2(event) {
3568
+ if (typeof event.time !== "number") return {};
3569
+ const at = new Date(event.time);
3570
+ return Number.isNaN(at.getTime()) ? {} : { timestamp: at.toISOString() };
3571
+ }
3572
+ function kimiPromptText(input) {
3573
+ if (!Array.isArray(input)) return "";
3574
+ return input.filter((block) => block?.type === "text" && typeof block.text === "string").map((block) => block.text).join("\n");
3575
+ }
3576
+ function readKimiWire(events) {
3577
+ const turns = [];
3578
+ let step;
3579
+ const flushStep = () => {
3580
+ if (!step) return;
3581
+ const content = stripInjectedMemory(step.texts.join("\n")).trim();
3582
+ if (content) turns.push({ role: "assistant", content, ...step.stamp });
3583
+ step = void 0;
3584
+ };
3585
+ for (const event of events || []) {
3586
+ if (!event || typeof event !== "object") continue;
3587
+ const stamp = stampOf2(event);
3588
+ if (event.type === "turn.prompt") {
3589
+ flushStep();
3590
+ if (event.origin?.kind !== "user") continue;
3591
+ const content = stripInjectedMemory(kimiPromptText(event.input)).trim();
3592
+ if (content) turns.push({ role: "user", content, ...stamp });
3593
+ continue;
3594
+ }
3595
+ if (event.type !== "context.append_loop_event") continue;
3596
+ const loop = event.event;
3597
+ if (!loop || typeof loop !== "object") continue;
3598
+ if (loop.type === "content.part") {
3599
+ if (loop.part?.type !== "text" || typeof loop.part.text !== "string") continue;
3600
+ const uuid = typeof loop.stepUuid === "string" ? loop.stepUuid : "";
3601
+ if (step && step.uuid !== uuid) flushStep();
3602
+ if (!step) step = { uuid, texts: [], stamp };
3603
+ step.texts.push(loop.part.text);
3604
+ } else if (loop.type === "tool.call") {
3605
+ flushStep();
3606
+ if (typeof loop.name !== "string" || !loop.name) continue;
3607
+ turns.push({ role: "action", content: actionLine(loop.name, loop.args), ...stamp });
3608
+ }
3609
+ }
3610
+ flushStep();
3611
+ return turns;
3612
+ }
3613
+ function agentIds(sessionDir) {
3614
+ try {
3615
+ return readdirSync4(join21(sessionDir, AGENTS_DIR), { withFileTypes: true }).filter((entry) => entry.isDirectory()).map((entry) => entry.name).sort(byAgentId);
3616
+ } catch {
3617
+ return [];
3618
+ }
3619
+ }
3620
+ function byAgentId(a, b) {
3621
+ if (a === b) return 0;
3622
+ if (a === MAIN_AGENT) return -1;
3623
+ if (b === MAIN_AGENT) return 1;
3624
+ const indexA = agentIndex(a);
3625
+ const indexB = agentIndex(b);
3626
+ return indexA === indexB ? a.localeCompare(b) : indexA - indexB;
3627
+ }
3628
+ function agentIndex(id) {
3629
+ const suffix = Number(id.slice(id.lastIndexOf("-") + 1));
3630
+ return Number.isFinite(suffix) ? suffix : Number.MAX_SAFE_INTEGER;
3631
+ }
3632
+ function parseEvent(rawLine) {
3633
+ const trimmed = rawLine.trim();
3634
+ if (!trimmed) return void 0;
3635
+ let parsed;
3636
+ try {
3637
+ parsed = JSON.parse(trimmed);
3638
+ } catch {
3639
+ return void 0;
3640
+ }
3641
+ return typeof parsed === "object" && parsed !== null ? parsed : void 0;
3642
+ }
3643
+ function readKimiTranscript(path) {
3644
+ const turns = [];
3645
+ let remaining = MAX_SESSION_CHARS;
3646
+ for (const agentId of agentIds(path)) {
3647
+ const wire = join21(path, AGENTS_DIR, agentId, WIRE_LOG);
3648
+ const events = [];
3649
+ for (const rawLine of readJsonl(wire)) {
3650
+ remaining -= rawLine.length;
3651
+ if (remaining < 0) break;
3652
+ const event = parseEvent(rawLine);
3653
+ if (event) events.push(event);
3654
+ }
3655
+ for (const turn of readKimiWire(events)) turns.push(turn);
3656
+ if (remaining < 0) {
3657
+ log.warn(HARNESS, "session exceeds the wire-log budget \u2014 later agents were not read", {
3658
+ sessionDir: path,
3659
+ stoppedAt: wire
3660
+ });
3661
+ break;
3662
+ }
3663
+ }
3664
+ return turns;
3665
+ }
3666
+
3066
3667
  // src/harness/hook-lifecycle.ts
3067
3668
  var cursorCwd = (ev) => ev.cwd ?? ev.workspace_root ?? (Array.isArray(ev.workspace_roots) ? ev.workspace_roots[0] : void 0);
3068
3669
  var claudePrompt = {
@@ -3141,7 +3742,7 @@ var copilotPrompt = {
3141
3742
  ${context}`.trim()
3142
3743
  })
3143
3744
  };
3144
- var devinCwd = () => process.env.DEVIN_PROJECT_DIR;
3745
+ var devinCwd = () => process.env.DEVIN_PROJECT_DIR || process.cwd();
3145
3746
  var devinPrompt = {
3146
3747
  harness: "devin-cli",
3147
3748
  requireCwd: true,
@@ -3168,6 +3769,7 @@ var standardSessionStart = (harness) => ({
3168
3769
  }
3169
3770
  })
3170
3771
  });
3772
+ var notGrokHosted = () => !process.env.GROK_HOOK_EVENT;
3171
3773
  var HOOK_HARNESSES = {
3172
3774
  "claude-code": {
3173
3775
  configStyle: "nested",
@@ -3176,11 +3778,12 @@ var HOOK_HARNESSES = {
3176
3778
  prompt: { event: "UserPromptSubmit", entry: "claude-hook.js", timeout: 30 },
3177
3779
  stop: { event: "Stop", entry: "claude-stop-hook.js", timeout: 60 }
3178
3780
  },
3179
- sessionStart: standardSessionStart("claude-code"),
3180
- prompt: claudePrompt,
3781
+ sessionStart: { ...standardSessionStart("claude-code"), accept: notGrokHosted },
3782
+ prompt: { ...claudePrompt, accept: notGrokHosted },
3181
3783
  retain: {
3182
3784
  hostTimeoutSec: 60,
3183
3785
  harness: "claude-code",
3786
+ accept: notGrokHosted,
3184
3787
  parse: (ev) => ({
3185
3788
  sessionId: ev.session_id,
3186
3789
  transcriptPath: ev.transcript_path,
@@ -3496,6 +4099,117 @@ var HOOK_HARNESSES = {
3496
4099
  assistantText: (ev) => (ev.responseText || zcodeAssistantText(ev.transcript_path) || ev.responsePreview || "").trim()
3497
4100
  }
3498
4101
  }
4102
+ },
4103
+ /**
4104
+ * TraeCode (TRAE CN's agent) also speaks Claude Code's hook protocol — `prompt`/`cwd`/`session_id`
4105
+ * in, `hookSpecificOutput.additionalContext` + `systemMessage` out — with registrations nested
4106
+ * under the top-level `hooks` key of `~/.trae-cn/hooks.json` (unlike Factory Droid, whose event
4107
+ * map IS the file) and a `version` field the host writes and expects.
4108
+ *
4109
+ * Like ZCode, what it does not have is a TRANSCRIPT: sessions live in an encrypted local DB or
4110
+ * the cloud and no `transcript_path` is ever supplied, so this is the second harness that retains
4111
+ * from the plugin's own journal (core/turn-journal.ts) — the prompt hook appends the user turn,
4112
+ * and Stop's `last_assistant_message` (the full reply) plays the role ZCode's `responseText`
4113
+ * plays: `journal.assistantText` closes the turn with it.
4114
+ */
4115
+ traecode: {
4116
+ configStyle: "nested",
4117
+ install: {
4118
+ sessionStart: { event: "SessionStart", entry: "traecode-sessionstart-hook.js", timeout: 30 },
4119
+ prompt: { event: "UserPromptSubmit", entry: "traecode-hook.js", timeout: 30 },
4120
+ stop: { event: "Stop", entry: "traecode-stop-hook.js", timeout: 60 }
4121
+ },
4122
+ sessionStart: {
4123
+ ...standardSessionStart("traecode"),
4124
+ // Trae launches USER-level MCP servers from the Electron process's cwd (home), where an
4125
+ // optInOnly config self-disables and the tools vanish. Each repo's own workspace file fixes
4126
+ // it — kept current here, once memory is confirmed live for the repo, along with the
4127
+ // workspace's per-server enable switch (seeded into Trae's storage DB,
4128
+ // core/traecode-mcp.ts). The returned hint (global gate off, or an unseedable switch)
4129
+ // rides the session banner.
4130
+ ensureMcpRegistration: (cwd) => ensureTraecodeWorkspaceMcp(cwd)
4131
+ },
4132
+ prompt: {
4133
+ ...claudePrompt,
4134
+ harness: "traecode",
4135
+ journalPrompt: true,
4136
+ // TraeCode's UserPromptSubmit payload carries `prompt` exactly like Claude Code's.
4137
+ parse: (ev) => ({
4138
+ prompt: ev.prompt,
4139
+ cwd: ev.cwd,
4140
+ sessionId: ev.session_id
4141
+ })
4142
+ },
4143
+ retain: {
4144
+ hostTimeoutSec: 60,
4145
+ harness: "traecode",
4146
+ // No transcriptPath: the journal supplies it (see `journal` below).
4147
+ parse: (ev) => ({
4148
+ sessionId: ev.session_id,
4149
+ cwd: ev.cwd
4150
+ }),
4151
+ journal: {
4152
+ // `last_assistant_message` is the full reply — TraeCode's `responseText`.
4153
+ assistantText: (ev) => (ev.last_assistant_message ?? "").trim()
4154
+ }
4155
+ }
4156
+ },
4157
+ "kimi-code": {
4158
+ // Kimi's ~/.kimi-code/config.toml takes a FLAT [[hooks]] array whose entries are validated by a
4159
+ // strict 4-key schema (event/matcher/command/timeout). Neither JSON style can express it, and a
4160
+ // fifth key drops EVERY hook in the file at warning severity, so its installer writes the block
4161
+ // itself (the grok-build pattern) rather than going through mergeHarnessHooks.
4162
+ configStyle: "toml-array",
4163
+ install: {
4164
+ // Timeouts are SECONDS here (integer 1-600, default 30) — the same unit as every other
4165
+ // supported host, and the opposite of qwen-code's identically named field.
4166
+ sessionStart: { event: "SessionStart", entry: "kimi-sessionstart-hook.js", timeout: 30 },
4167
+ prompt: { event: "UserPromptSubmit", entry: "kimi-hook.js", timeout: 30 },
4168
+ stop: { event: "Stop", entry: "kimi-stop-hook.js", timeout: 60 }
4169
+ },
4170
+ sessionStart: {
4171
+ harness: "kimi-code",
4172
+ parse: (ev) => ({
4173
+ cwd: ev.cwd,
4174
+ sessionId: ev.session_id
4175
+ }),
4176
+ // Kimi runs SessionStart hooks for their side effects only: it awaits the trigger and drops
4177
+ // the result, so nothing emitted here can reach the model or the terminal. Installed for the
4178
+ // seed/daemon/session-root work runSessionStartHook does, and silent like antigravity-cli's.
4179
+ emit: () => ({})
4180
+ },
4181
+ prompt: {
4182
+ harness: "kimi-code",
4183
+ parse: (ev) => ({
4184
+ // A block array, not a string — the same shape as the wire log's `turn.prompt.input`.
4185
+ prompt: kimiPromptText(ev.prompt),
4186
+ cwd: ev.cwd,
4187
+ sessionId: ev.session_id
4188
+ }),
4189
+ // Kimi has no additionalContext: a top-level `message` is the injection channel, which the
4190
+ // CLI wraps as <hook_result hook_event="UserPromptSubmit"> and appends to the conversation.
4191
+ // `notice` has no banner channel to reach (the copilot-cli precedent), but it cannot simply
4192
+ // be dropped: when a hook's stdout parses to JSON carrying no message, Kimi falls back to
4193
+ // injecting the RAW STDOUT, so an empty `{}` would put a literal "{}" in front of the model.
4194
+ // Emitting the notice on the notice-only turn is what keeps that from ever happening.
4195
+ emit: (context, notice) => ({ message: context || notice })
4196
+ },
4197
+ retain: {
4198
+ hostTimeoutSec: 60,
4199
+ harness: "kimi-code",
4200
+ parse: (ev) => {
4201
+ const sessionId = ev.session_id;
4202
+ return {
4203
+ sessionId,
4204
+ // Kimi's Stop payload carries no transcript path — its hook feature has no such field at
4205
+ // all — so resolve the session's own directory from the id, as grok-build does. The
4206
+ // reader takes that DIRECTORY and reads every agent's wire.jsonl beneath it.
4207
+ transcriptPath: sessionId ? kimiSessionDir(sessionId) : void 0,
4208
+ cwd: ev.cwd
4209
+ };
4210
+ },
4211
+ readTranscript: readKimiTranscript
4212
+ }
3499
4213
  }
3500
4214
  };
3501
4215
  var runHarnessRetain = (harness) => runRetainHook(HOOK_HARNESSES[harness].retain);