@vectorize-io/hindsight-coding-agents 0.6.1 → 0.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (56) hide show
  1. package/README.md +314 -51
  2. package/dist/antigravity-hook.js +1039 -198
  3. package/dist/antigravity-statusline.js +185 -11
  4. package/dist/antigravity-stop-hook.js +1026 -163
  5. package/dist/claude-hook.js +1039 -198
  6. package/dist/claude-sessionstart-hook.js +1123 -190
  7. package/dist/claude-stop-hook.js +1026 -163
  8. package/dist/cline.js +749 -209
  9. package/dist/codex-hook.js +1039 -198
  10. package/dist/codex-sessionstart-hook.js +1123 -190
  11. package/dist/codex-stop-hook.js +1026 -163
  12. package/dist/copilot-hook.js +1039 -198
  13. package/dist/copilot-sessionstart-hook.js +1123 -190
  14. package/dist/copilot-stop-hook.js +1026 -163
  15. package/dist/cursor-hook.js +1039 -198
  16. package/dist/cursor-sessionstart-hook.js +1123 -190
  17. package/dist/cursor-stop-hook.js +1026 -163
  18. package/dist/daemon-start.js +154 -5
  19. package/dist/dcode-hook.js +1039 -198
  20. package/dist/dcode-sessionstart-hook.js +1123 -190
  21. package/dist/dcode-stop-hook.js +1026 -163
  22. package/dist/deepen.js +437 -105
  23. package/dist/devin-hook.js +1039 -198
  24. package/dist/devin-sessionstart-hook.js +1123 -190
  25. package/dist/devin-stop-hook.js +1026 -163
  26. package/dist/droid-hook.js +1039 -198
  27. package/dist/droid-sessionstart-hook.js +1123 -190
  28. package/dist/droid-stop-hook.js +1026 -163
  29. package/dist/dsh.js +750 -210
  30. package/dist/grok-hook.js +1039 -198
  31. package/dist/grok-sessionstart-hook.js +1123 -190
  32. package/dist/grok-stop-hook.js +1026 -163
  33. package/dist/hindsight-seed.js +157 -8
  34. package/dist/index.js +749 -209
  35. package/dist/installer.js +1233 -366
  36. package/dist/kilo.js +749 -209
  37. package/dist/kimi-hook.js +3909 -0
  38. package/dist/kimi-sessionstart-hook.js +4650 -0
  39. package/dist/kimi-stop-hook.js +4218 -0
  40. package/dist/mcp-server.js +373 -71
  41. package/dist/opencode2.js +778 -209
  42. package/dist/pi.js +754 -211
  43. package/dist/prime-agent.js +754 -211
  44. package/dist/qwen-hook.js +1039 -198
  45. package/dist/qwen-sessionstart-hook.js +1123 -190
  46. package/dist/qwen-stop-hook.js +1026 -163
  47. package/dist/status.js +333 -59
  48. package/dist/traecode-hook.js +3909 -0
  49. package/dist/traecode-sessionstart-hook.js +4650 -0
  50. package/dist/traecode-stop-hook.js +4218 -0
  51. package/dist/zcode-hook.js +1039 -198
  52. package/dist/zcode-sessionstart-hook.js +1123 -190
  53. package/dist/zcode-stop-hook.js +1026 -163
  54. package/package.json +15 -11
  55. package/plugin.json +1 -1
  56. package/skill/SKILL.md +241 -48
@@ -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;
@@ -352,13 +356,15 @@ var CONVERSATION_MISSION = `You are ingesting a developer conversation as a JSON
352
356
  var REFLECT_MISSION = "You are a debugging assistant with the project's past decisions in memory (git rationale and developer chats). Given a bug's SYMPTOM, find the past decision whose rationale explains the ROOT CAUSE \u2014 not one that merely shares vocabulary. Answer with the PRECISE fix: state the EXACT rule and the LITERAL values, identifiers, strings, numbers, or set members that were decided \u2014 quote them VERBATIM, never paraphrase, generalize, or omit them (give the actual decided value, not 'the project standard'). If memories CONFLICT on the same rule, the LATEST decision wins \u2014 prefer facts that explicitly amend or supersede an earlier one, state the superseded rule as no longer in effect, and never present it as the fix. Name the function/file to change and cite the REF-ID(s). If NOTHING in memory genuinely explains THIS symptom, say exactly that in one short sentence \u2014 a wrong-but-confident nearest match is worse than an honest miss; never stretch an unrelated decision to fit.";
353
357
  var DOCUMENT_MISSION = "You are ingesting a standalone document (notes, docs, or structural findings). Extract the concrete facts, concepts, and structure it describes.";
354
358
  var OBSERVATIONS_MISSION = "Consolidate durable knowledge about THIS codebase \u2014 recurring patterns, conventions, module responsibilities, and how components relate \u2014 from the ingested commits and conversations. Favor stable structural understanding over one-off details. When a new fact contradicts or supersedes an existing observation, UPDATE that observation to reflect the current state rather than creating a sibling alongside it; note that the rule was revised and when, so the superseded version is visible as history rather than as a competing claim.";
359
+ var RETAIN_EXTRACTION_MODES = ["concise", "verbose", "verbatim", "chunks"];
360
+ var DEFAULT_RETAIN_EXTRACTION_MODE = "concise";
355
361
  var RETAIN_STRATEGIES = {
356
- git: { retain_mission: GIT_MISSION, retain_extraction_mode: "verbose" },
362
+ git: { retain_mission: GIT_MISSION, retain_extraction_mode: DEFAULT_RETAIN_EXTRACTION_MODE },
357
363
  // ONE big aggregated document (last N commit messages, no diffs) -> a larger chunk size so it stays
358
364
  // in as few chunks as possible and the extractor sees the whole history arc at once.
359
365
  gitlog: {
360
366
  retain_mission: GITLOG_MISSION,
361
- retain_extraction_mode: "verbose",
367
+ retain_extraction_mode: DEFAULT_RETAIN_EXTRACTION_MODE,
362
368
  retain_chunk_size: 12e3
363
369
  },
364
370
  // ONE strategy for ALL developer conversations — backfilled decision chats and live working
@@ -369,15 +375,15 @@ var RETAIN_STRATEGIES = {
369
375
  // the consolidation layer.
370
376
  conversation: {
371
377
  retain_mission: CONVERSATION_MISSION,
372
- retain_extraction_mode: "verbose",
378
+ retain_extraction_mode: DEFAULT_RETAIN_EXTRACTION_MODE,
373
379
  retain_chunk_size: 12e3
374
380
  },
375
381
  // Structural documents (e.g. the codebase survey's ingested findings) aren't dialogue — the
376
- // chat strategy's "final decision vs rejected proposal" extraction doesn't apply. Verbose mode
377
- // with a bigger chunk size (documents can run long) captures the concrete facts/structure instead.
382
+ // chat strategy's "final decision vs rejected proposal" extraction doesn't apply. A bigger chunk
383
+ // size (documents can run long) keeps the concrete facts/structure together instead.
378
384
  document: {
379
385
  retain_mission: DOCUMENT_MISSION,
380
- retain_extraction_mode: "verbose",
386
+ retain_extraction_mode: DEFAULT_RETAIN_EXTRACTION_MODE,
381
387
  retain_chunk_size: 12e3
382
388
  },
383
389
  // Codebase-SURVEY lifecycle documents, ONE strategy with conditional rules: the survey's
@@ -450,9 +456,22 @@ var PAGE_TAXONOMY = [
450
456
  tags: ["knowledge:feature-work"]
451
457
  }
452
458
  ];
453
- function pagesFor(project) {
459
+ var PAGE_NAMES = PAGE_TAXONOMY.map((page) => page.name);
460
+ function pagesFor(project, pages = {}, customPages = {}) {
454
461
  const scope = pageScopeRule(project);
455
- return PAGE_TAXONOMY.map((page) => ({ ...page, source_query: page.source_query + scope }));
462
+ const byName = new Map(
463
+ Object.entries(pages).map(([name, override]) => [name.trim().toLowerCase(), override])
464
+ );
465
+ const out = [];
466
+ for (const page of PAGE_TAXONOMY) {
467
+ const override = byName.get(page.name.toLowerCase());
468
+ if (override === false) continue;
469
+ out.push({ ...page, source_query: (override?.source_query || page.source_query) + scope });
470
+ }
471
+ for (const [name, page] of Object.entries(customPages)) {
472
+ out.push({ name: name.trim(), source_query: page.source_query + scope, tags: page.tags ?? [] });
473
+ }
474
+ return out;
456
475
  }
457
476
  var PAGE_MAX_TOKENS = 4096;
458
477
  var PAGE_TAGS_MATCH = "all";
@@ -535,7 +554,7 @@ var CODING_BANK_TEMPLATE = {
535
554
  enable_observations: true,
536
555
  observations_mission: OBSERVATIONS_MISSION,
537
556
  retain_mission: GIT_MISSION,
538
- retain_extraction_mode: "verbose",
557
+ retain_extraction_mode: DEFAULT_RETAIN_EXTRACTION_MODE,
539
558
  retain_default_strategy: "git",
540
559
  retain_strategies: RETAIN_STRATEGIES,
541
560
  entity_labels: [KNOWLEDGE_LABELS],
@@ -543,12 +562,17 @@ var CODING_BANK_TEMPLATE = {
543
562
  }
544
563
  };
545
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
+ ];
546
570
  function isSet(v) {
547
571
  if (v === null || v === void 0) return false;
548
572
  if (typeof v === "string") return v.trim() !== "";
549
573
  return true;
550
574
  }
551
- function codingBankManifest(overrides) {
575
+ function codingBankManifest(overrides, mode = DEFAULT_RETAIN_EXTRACTION_MODE, defaults = {}) {
552
576
  const current2 = overrides ?? {};
553
577
  const template = CODING_BANK_TEMPLATE.bank;
554
578
  const bank = {};
@@ -557,20 +581,30 @@ function codingBankManifest(overrides) {
557
581
  bank.enable_observations = template.enable_observations;
558
582
  bank.observations_mission = template.observations_mission;
559
583
  bank.retain_mission = template.retain_mission;
560
- bank.retain_extraction_mode = template.retain_extraction_mode;
584
+ bank.retain_extraction_mode = mode;
561
585
  }
562
586
  if (!isSet(current2.retain_default_strategy))
563
587
  bank.retain_default_strategy = template.retain_default_strategy;
564
588
  if (!isSet(current2.entities_allow_free_form))
565
589
  bank.entities_allow_free_form = template.entities_allow_free_form;
566
590
  const strategies = current2.retain_strategies && typeof current2.retain_strategies === "object" ? current2.retain_strategies : {};
567
- const missing = Object.entries(template.retain_strategies).filter(([n]) => !(n in strategies));
568
- if (missing.length > 0)
569
- bank.retain_strategies = { ...strategies, ...Object.fromEntries(missing) };
591
+ const updates = {};
592
+ for (const [name, def] of Object.entries(template.retain_strategies)) {
593
+ const synced = def.retain_extraction_mode === "custom" ? {} : { retain_extraction_mode: mode };
594
+ const have = strategies[name];
595
+ if (!have || typeof have !== "object") updates[name] = { ...def, ...synced };
596
+ else if ("retain_extraction_mode" in synced && have.retain_extraction_mode !== mode)
597
+ updates[name] = { ...have, ...synced };
598
+ }
599
+ if (Object.keys(updates).length > 0) bank.retain_strategies = { ...strategies, ...updates };
570
600
  const labels = Array.isArray(current2.entity_labels) ? current2.entity_labels : [];
571
601
  const [knowledgeGroup] = template.entity_labels;
572
602
  if (!labels.some((g) => g?.key === knowledgeGroup.key))
573
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
+ }
574
608
  return Object.keys(bank).length > 0 ? { version: "1", bank } : void 0;
575
609
  }
576
610
 
@@ -606,6 +640,15 @@ async function pool(items, n, fn, onError, onProgress) {
606
640
  }
607
641
  await Promise.all(Array.from({ length: Math.min(n, items.length) }, worker));
608
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
+ }
609
652
 
610
653
  // src/core/hindsight.ts
611
654
  function resolveRetainScopes(tags, configured) {
@@ -638,6 +681,14 @@ var KnowledgePagesUnavailableError = class extends Error {
638
681
  this.name = "KnowledgePagesUnavailableError";
639
682
  }
640
683
  };
684
+ async function isEndpointMissing(r) {
685
+ try {
686
+ const j = await r.json();
687
+ return String(j?.detail ?? "").trim().toLowerCase() === "not found";
688
+ } catch {
689
+ return true;
690
+ }
691
+ }
641
692
  var TERMINAL = /* @__PURE__ */ new Set(["completed", "failed", "cancelled", "error"]);
642
693
  var ReflectError = class extends Error {
643
694
  constructor(message, status, timedOut, options) {
@@ -656,9 +707,28 @@ var ReflectError = class extends Error {
656
707
  }
657
708
  };
658
709
  var DEFAULT_MAX_PARALLEL_RETAINS = 10;
710
+ var DEFAULT_PAGE_SEARCH_LIMIT = 10;
711
+ var DEFAULT_RECALL_OPTIONS = {
712
+ types: ["observation"],
713
+ budget: "low",
714
+ max_tokens: 2e3,
715
+ include: { entities: null }
716
+ };
659
717
  var POLL_CYCLE_MS = 5e3;
660
718
  var RETRY_AFTER_FLOOR_MS = 10 * 1e3;
661
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
+ }
662
732
  var HindsightClient = class {
663
733
  apiUrl;
664
734
  /** The credential the NEXT request will sign with — NOT the one the config file holds. The two
@@ -676,6 +746,8 @@ var HindsightClient = class {
676
746
  log;
677
747
  maxParallelRetains;
678
748
  observationScopes;
749
+ pageSearchLimit;
750
+ recallOptions;
679
751
  constructor(o) {
680
752
  this.apiUrl = o.apiUrl.replace(/\/$/, "");
681
753
  this.token = o.apiToken;
@@ -686,13 +758,18 @@ var HindsightClient = class {
686
758
  });
687
759
  this.maxParallelRetains = o.maxParallelRetains || DEFAULT_MAX_PARALLEL_RETAINS;
688
760
  this.observationScopes = o.observationScopes ?? DEFAULT_OBSERVATION_SCOPES;
761
+ this.pageSearchLimit = o.pageSearchLimit || DEFAULT_PAGE_SEARCH_LIMIT;
762
+ this.recallOptions = { ...DEFAULT_RECALL_OPTIONS, ...o.recallOptions };
689
763
  }
690
764
  /** The credential in use, for diagnostics. Never log or report the VALUE — booleans only. */
691
765
  get apiToken() {
692
766
  return this.token;
693
767
  }
694
768
  headers() {
695
- const h = { "Content-Type": "application/json" };
769
+ const h = {
770
+ "Content-Type": "application/json",
771
+ "Accept-Encoding": "identity"
772
+ };
696
773
  if (this.token) h["Authorization"] = `Bearer ${this.token}`;
697
774
  return h;
698
775
  }
@@ -800,6 +877,23 @@ var HindsightClient = class {
800
877
  return false;
801
878
  }
802
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
+ }
803
897
  /**
804
898
  * Every document_id currently in the bank under a strategy tag (e.g. `source:git`), paginated into a
805
899
  * Set. Powers the incremental git-sync's "what's already ingested?" check — since git commits are stored
@@ -825,9 +919,28 @@ var HindsightClient = class {
825
919
  }
826
920
  return ids;
827
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
+ }
828
940
  /** Configure the bank: POST the coding bank manifest to /import (missions, retain strategies,
829
941
  * entity labels), then seed knowledge pages when the server supports them. Both halves are
830
- * idempotent and strictly ADDITIVE — nothing the bank already says is overwritten (#3927) — so
942
+ * idempotent and ADDITIVE — nothing the bank already says is overwritten (#3927), bar the
943
+ * extraction mode of the plugin's own strategies, which follows its config (#4560) — so
831
944
  * the deepen engine can re-run this every pass. Creates the bank if missing; legacy servers
832
945
  * continue with the template-only path.
833
946
  *
@@ -843,7 +956,11 @@ var HindsightClient = class {
843
956
  if (opts.manage === false) {
844
957
  this.log(`[bank] manageBankConfig: false \u2014 leaving ${this.bank}'s configuration alone`);
845
958
  } else {
846
- const manifest = codingBankManifest(opts.reset ? void 0 : await this.readBankOverrides());
959
+ const manifest = codingBankManifest(
960
+ opts.reset ? void 0 : await this.readBankOverrides(),
961
+ opts.extractionMode,
962
+ opts.defaults
963
+ );
847
964
  if (!manifest) {
848
965
  this.log(`[bank] ${this.bank} already carries the coding structure \u2014 nothing to apply`);
849
966
  } else {
@@ -851,7 +968,7 @@ var HindsightClient = class {
851
968
  this.log(`[bank] applied to ${this.bank}: ${Object.keys(manifest.bank).sort().join(", ")}`);
852
969
  }
853
970
  }
854
- await this.seedPages(opts.pageTrigger);
971
+ await this.seedPages(opts.pageTrigger, opts.pages, opts.customPages);
855
972
  }
856
973
  /**
857
974
  * This bank's own config OVERRIDES, or undefined when there are none to read.
@@ -967,20 +1084,22 @@ var HindsightClient = class {
967
1084
  }
968
1085
  }
969
1086
  /**
970
- * Raw recall restricted to consolidated observations — no LLM in the loop, so it still answers
971
- * when reflect's synthesis times out or 5xxs. Returns the observation texts in rank order.
1087
+ * Raw recall with no LLM in the loop, so it still answers when reflect's synthesis times out or
1088
+ * 5xxs. The body is `recallOptions` (consolidated observations by default) — a bank that grows
1089
+ * no observations widens it rather than getting nothing back. Returns the texts in rank order.
1090
+ *
1091
+ * The name predates `recallOptions` (the observation type used to be hardcoded here) and is
1092
+ * kept deliberately: this is the client's published surface, so renaming it would break
1093
+ * importers for a cosmetic gain. The doc above is the contract, not the name.
972
1094
  */
973
1095
  async recallObservations(query, opts) {
974
1096
  const r = await this.req(
975
1097
  "POST",
976
1098
  this.bankUrl("/memories/recall"),
977
- {
978
- query,
979
- types: ["observation"],
980
- budget: "low",
981
- max_tokens: opts.maxTokens,
982
- include: { entities: null }
983
- },
1099
+ // `query` is applied AFTER the spread: everything else is the caller's to override, but a
1100
+ // config that could replace the goal with a fixed string would silently recall for the
1101
+ // wrong question on every turn.
1102
+ { ...this.recallOptions, query },
984
1103
  [],
985
1104
  opts.timeoutMs
986
1105
  );
@@ -988,6 +1107,19 @@ var HindsightClient = class {
988
1107
  const j = await r.json();
989
1108
  return (j.results ?? []).map((x) => (x.text ?? "").trim()).filter(Boolean);
990
1109
  }
1110
+ /**
1111
+ * Latch `knowledgePagesSupported = false` iff this response really means the endpoint is absent.
1112
+ * Returns whether it latched. A bank-not-found 404 is NOT a capability verdict — it is the
1113
+ * expected answer before the bank's first retain — so it must never cache a negative (#4607).
1114
+ *
1115
+ * Only 404 is tested: `req` throws on every other non-ok status it was not told to tolerate, so
1116
+ * the 405/501 this used to check for never reach a caller in the first place.
1117
+ */
1118
+ async pagesUnsupported(r) {
1119
+ if (r.status !== 404 || !await isEndpointMissing(r)) return false;
1120
+ this.knowledgePagesSupported = false;
1121
+ return true;
1122
+ }
991
1123
  /**
992
1124
  * The bank's knowledge-base tree (folders + pages, nested). The tree carries names, source
993
1125
  * queries and staleness but NOT synthesized content, so it is cheap enough to poll.
@@ -995,10 +1127,8 @@ var HindsightClient = class {
995
1127
  async tree() {
996
1128
  if (this.knowledgePagesSupported === false) throw new KnowledgePagesUnavailableError();
997
1129
  const r = await this.req("GET", this.bankUrl("/knowledge-base/tree"));
998
- if ([404, 405, 501].includes(r.status)) {
999
- this.knowledgePagesSupported = false;
1000
- throw new KnowledgePagesUnavailableError();
1001
- }
1130
+ if (await this.pagesUnsupported(r)) throw new KnowledgePagesUnavailableError();
1131
+ if (r.status === 404) return [];
1002
1132
  this.knowledgePagesSupported = true;
1003
1133
  try {
1004
1134
  return (await r.json()).roots ?? [];
@@ -1035,8 +1165,8 @@ var HindsightClient = class {
1035
1165
  return { items };
1036
1166
  }
1037
1167
  /**
1038
- * Read one knowledge page's synthesized content by knowledge-base id, as an OKF document
1039
- * (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
1040
1170
  * the page — that is 70-95% of the raw bytes and can blow past an MCP host's per-tool-result
1041
1171
  * token cap.
1042
1172
  */
@@ -1047,25 +1177,28 @@ var HindsightClient = class {
1047
1177
  this.bankUrl(`/knowledge-base/pages/${encodeURIComponent(pageId)}`)
1048
1178
  );
1049
1179
  if (r.status === 404) throw new Error(`knowledge page not found: ${pageId}`);
1050
- return await r.json();
1180
+ return shapePage(await r.json());
1051
1181
  }
1052
1182
  /** Hybrid (BM25 + vector, RRF-fused) server-side search over the bank's knowledge pages.
1053
1183
  * Returns page-level hits with a relevance snippet — the real search behind
1054
1184
  * hindsight_search_knowledge_pages. */
1055
- async searchKnowledgePages(query, limit = 3, timeoutMs) {
1185
+ async searchKnowledgePages(query, opts = {}) {
1056
1186
  if (this.knowledgePagesSupported === false) throw new KnowledgePagesUnavailableError();
1057
- const q = `?q=${encodeURIComponent(query)}&limit=${limit}`;
1187
+ const q = `?q=${encodeURIComponent(query)}&limit=${opts.limit ?? this.pageSearchLimit}`;
1058
1188
  const r = await this.req(
1059
1189
  "GET",
1060
1190
  this.bankUrl(`/knowledge-base/search${q}`),
1061
1191
  void 0,
1062
1192
  [],
1063
- timeoutMs
1193
+ opts.timeoutMs
1064
1194
  );
1195
+ if (await this.pagesUnsupported(r)) throw new KnowledgePagesUnavailableError();
1196
+ if (r.status === 404) return [];
1065
1197
  const j = await r.json();
1066
1198
  return (j.results ?? []).map((x) => ({
1067
1199
  id: x.id,
1068
1200
  name: x.name,
1201
+ ...x.source_query ? { source_query: x.source_query } : {},
1069
1202
  snippet: x.snippet ?? "",
1070
1203
  score: x.score ?? 0
1071
1204
  }));
@@ -1081,8 +1214,8 @@ var HindsightClient = class {
1081
1214
  * `source_query` re-syncs onto the live page instead of orphaning its synthesized content —
1082
1215
  * which is how `pageScopeRule`'s repo name reaches banks seeded by an earlier version.
1083
1216
  */
1084
- async seedPages(pageTrigger = buildPageTrigger()) {
1085
- const pages = pagesFor(this.project ?? this.bank);
1217
+ async seedPages(pageTrigger = buildPageTrigger(), pagesConfig = {}, customPages = {}) {
1218
+ const pages = pagesFor(this.project ?? this.bank, pagesConfig, customPages);
1086
1219
  const existing = /* @__PURE__ */ new Map();
1087
1220
  let roots;
1088
1221
  try {
@@ -1099,6 +1232,7 @@ var HindsightClient = class {
1099
1232
  }
1100
1233
  let created = 0;
1101
1234
  let updated = 0;
1235
+ let vanished = 0;
1102
1236
  for (const page of pages) {
1103
1237
  const hit = existing.get(page.name.toLowerCase());
1104
1238
  const body = {
@@ -1112,13 +1246,16 @@ var HindsightClient = class {
1112
1246
  };
1113
1247
  if (!hit) {
1114
1248
  const r = await this.req("POST", this.bankUrl("/knowledge-base/pages"), body, [409]);
1115
- if ([404, 405, 501].includes(r.status)) {
1116
- this.knowledgePagesSupported = false;
1249
+ if (await this.pagesUnsupported(r)) {
1117
1250
  this.log(
1118
1251
  `[bank] knowledge pages unavailable on ${this.apiUrl}; continuing without pages`
1119
1252
  );
1120
1253
  return;
1121
1254
  }
1255
+ if (r.status === 404) {
1256
+ this.log(`[bank] ${this.bank} does not exist yet; pages seed on the next session`);
1257
+ return;
1258
+ }
1122
1259
  if (r.status !== 409) created++;
1123
1260
  } else {
1124
1261
  const sourceDrift = hit.description !== page.source_query;
@@ -1128,6 +1265,9 @@ var HindsightClient = class {
1128
1265
  if (sourceDrift) {
1129
1266
  patch.source_query = page.source_query;
1130
1267
  patch.tags = page.tags;
1268
+ this.log(
1269
+ `[bank] re-syncing "${page.name}" to its configured source_query \u2014 set pages[${JSON.stringify(page.name)}].source_query to keep your own wording`
1270
+ );
1131
1271
  }
1132
1272
  if (triggerDrift) patch.trigger = pageTriggerPatch(body.trigger);
1133
1273
  const r = await this.req(
@@ -1135,19 +1275,22 @@ var HindsightClient = class {
1135
1275
  this.bankUrl(`/knowledge-base/nodes/${encodeURIComponent(hit.id)}`),
1136
1276
  patch
1137
1277
  );
1138
- if ([404, 405, 501].includes(r.status)) {
1139
- this.knowledgePagesSupported = false;
1278
+ if (await this.pagesUnsupported(r)) {
1140
1279
  this.log(
1141
1280
  `[bank] knowledge pages unavailable on ${this.apiUrl}; continuing without pages`
1142
1281
  );
1143
1282
  return;
1144
1283
  }
1284
+ if (r.status === 404) {
1285
+ vanished++;
1286
+ continue;
1287
+ }
1145
1288
  updated++;
1146
1289
  }
1147
1290
  }
1148
1291
  const initiatives = await this.resyncInitiativeTriggers(roots, pageTrigger);
1149
1292
  this.log(
1150
- `[bank] knowledge pages seeded on ${this.bank} (scoped to ${this.project ?? this.bank}): ${created} created, ${updated} re-synced, ${pages.length - created - updated} unchanged` + (initiatives ? `, ${initiatives} initiative pages re-synced` : "")
1293
+ `[bank] knowledge pages seeded on ${this.bank} (scoped to ${this.project ?? this.bank}): ${created} created, ${updated} re-synced, ${pages.length - created - updated - vanished} unchanged` + (vanished ? `, ${vanished} deleted under us` : "") + (initiatives ? `, ${initiatives} initiative pages re-synced` : "")
1151
1294
  );
1152
1295
  }
1153
1296
  /**
@@ -1176,7 +1319,7 @@ var HindsightClient = class {
1176
1319
  this.bankUrl(`/knowledge-base/nodes/${encodeURIComponent(page.id)}`),
1177
1320
  { trigger: pageTriggerPatch(desired) }
1178
1321
  );
1179
- if ([404, 405, 501].includes(r.status)) break;
1322
+ if (r.status === 404) continue;
1180
1323
  updated++;
1181
1324
  }
1182
1325
  return updated;
@@ -1268,7 +1411,65 @@ function resolvePageTrigger(raw) {
1268
1411
  );
1269
1412
  return { type: "cron", cron: DEFAULT_PAGE_TRIGGER_CRON };
1270
1413
  }
1414
+ function resolvePages(raw) {
1415
+ const value = raw;
1416
+ if (!value || typeof value !== "object" || Array.isArray(value)) return {};
1417
+ const out = {};
1418
+ for (const [name, entry] of Object.entries(value)) {
1419
+ if (!PAGE_NAMES.some((known) => known.toLowerCase() === name.trim().toLowerCase())) {
1420
+ log.warn(
1421
+ "config",
1422
+ `ignoring pages[${JSON.stringify(name)}] \u2014 no seeded page has that name; expected one of: ${PAGE_NAMES.join(", ")}`
1423
+ );
1424
+ continue;
1425
+ }
1426
+ if (entry === false) {
1427
+ out[name] = false;
1428
+ continue;
1429
+ }
1430
+ const query = entry && typeof entry === "object" && !Array.isArray(entry) ? entry.source_query : void 0;
1431
+ if (typeof query === "string" && query.trim()) {
1432
+ out[name] = { source_query: query };
1433
+ continue;
1434
+ }
1435
+ log.warn(
1436
+ "config",
1437
+ `ignoring pages[${JSON.stringify(name)}]=${JSON.stringify(entry)} \u2014 expected false, or {"source_query": "<your question>"}`
1438
+ );
1439
+ }
1440
+ return out;
1441
+ }
1442
+ function resolveCustomPages(raw) {
1443
+ const value = raw;
1444
+ if (!value || typeof value !== "object" || Array.isArray(value)) return {};
1445
+ const out = {};
1446
+ for (const [rawName, entry] of Object.entries(value)) {
1447
+ const name = rawName.trim();
1448
+ if (!name) continue;
1449
+ if (PAGE_NAMES.some((known) => known.toLowerCase() === name.toLowerCase())) {
1450
+ log.warn(
1451
+ "config",
1452
+ `ignoring customPages[${JSON.stringify(rawName)}] \u2014 that is a seeded page; reword it under \`pages\` instead`
1453
+ );
1454
+ continue;
1455
+ }
1456
+ const query = entry && typeof entry === "object" && !Array.isArray(entry) ? entry.source_query : void 0;
1457
+ if (typeof query !== "string" || !query.trim()) {
1458
+ log.warn(
1459
+ "config",
1460
+ `ignoring customPages[${JSON.stringify(rawName)}]=${JSON.stringify(entry)} \u2014 expected {"source_query": "<your question>"}`
1461
+ );
1462
+ continue;
1463
+ }
1464
+ const rawTags = entry.tags;
1465
+ const tags = Array.isArray(rawTags) ? rawTags.filter((t) => typeof t === "string" && t.trim() !== "") : [];
1466
+ out[name] = tags.length ? { source_query: query, tags } : { source_query: query };
1467
+ }
1468
+ return out;
1469
+ }
1470
+ var DEFAULT_REFLECT_TIMEOUT_MS = 2e4;
1271
1471
  var DEFAULT_REFLECT_TOOL_TIMEOUT_MS = 33e4;
1472
+ var DEFAULT_INJECT_TIMEOUT_MS = 7e3;
1272
1473
  var REFLECT_BUDGETS = ["low", "mid", "high"];
1273
1474
  function resolveReflectBudget(raw) {
1274
1475
  const value = raw.reflectBudget;
@@ -1295,6 +1496,31 @@ function resolveObservationScopes(raw) {
1295
1496
  }
1296
1497
  return DEFAULT_OBSERVATION_SCOPES;
1297
1498
  }
1499
+ function resolveDefaultBankConfig(raw) {
1500
+ const value = raw;
1501
+ if (!value || typeof value !== "object" || Array.isArray(value)) return {};
1502
+ const out = {};
1503
+ for (const [key, v] of Object.entries(value)) {
1504
+ if (PLUGIN_GOVERNED_BANK_FIELDS.includes(key)) {
1505
+ log.warn(
1506
+ "config",
1507
+ `ignoring defaultBankConfig.${key} \u2014 the plugin manages this field itself` + (key === "retain_extraction_mode" ? " (set retainExtractionMode instead)" : "")
1508
+ );
1509
+ continue;
1510
+ }
1511
+ out[key] = v;
1512
+ }
1513
+ return out;
1514
+ }
1515
+ var AUTO_INJECT_MODES = ["reflect", "pages", "recall", "none"];
1516
+ function resolveAutoInject(raw) {
1517
+ if (raw.autoReflect !== void 0) {
1518
+ const replacement = raw.autoReflect === false ? "none" : "reflect";
1519
+ log.warn("config", `autoReflect is deprecated \u2014 use autoInject: "${replacement}" instead`);
1520
+ }
1521
+ if (AUTO_INJECT_MODES.includes(raw.autoInject)) return raw.autoInject;
1522
+ return raw.autoReflect === false ? "none" : "reflect";
1523
+ }
1298
1524
  function resolveConfig(raw = {}) {
1299
1525
  const serverMode = ["cloud", "self-hosted", "daemon"].includes(raw.serverMode) ? raw.serverMode : "cloud";
1300
1526
  const apiPort = raw.apiPort || DEFAULT_DAEMON_PORT;
@@ -1324,17 +1550,31 @@ function resolveConfig(raw = {}) {
1324
1550
  retainSessions: raw.retainSessions ?? true,
1325
1551
  // write sessions back by default, every harness
1326
1552
  manageBankConfig: raw.manageBankConfig ?? true,
1553
+ retainExtractionMode: RETAIN_EXTRACTION_MODES.includes(raw.retainExtractionMode) ? raw.retainExtractionMode : DEFAULT_RETAIN_EXTRACTION_MODE,
1554
+ defaultBankConfig: resolveDefaultBankConfig(raw.defaultBankConfig),
1327
1555
  maxParallelRetains: raw.maxParallelRetains || 10,
1328
- reflectTimeoutMs: raw.reflectTimeoutMs || 12e4,
1556
+ reflectTimeoutMs: raw.reflectTimeoutMs || DEFAULT_REFLECT_TIMEOUT_MS,
1329
1557
  // Inherit an explicitly-raised reflectTimeoutMs (that is what users reaching for a longer
1330
1558
  // reflect already set), but never let it LOWER the tool below the default — a short window is
1331
1559
  // set to bound the automatic hook, not to cut off a call the agent is waiting on.
1332
1560
  reflectToolTimeoutMs: raw.reflectToolTimeoutMs || Math.max(raw.reflectTimeoutMs || 0, DEFAULT_REFLECT_TOOL_TIMEOUT_MS),
1561
+ injectTimeoutMs: raw.injectTimeoutMs || DEFAULT_INJECT_TIMEOUT_MS,
1333
1562
  reflectBudget: resolveReflectBudget(raw),
1334
- autoReflect: raw.autoReflect ?? true,
1335
- pageRefreshEveryTurns: raw.pageRefreshEveryTurns || 10,
1563
+ autoInject: resolveAutoInject(raw),
1564
+ pageSearchLimit: raw.pageSearchLimit || DEFAULT_PAGE_SEARCH_LIMIT,
1565
+ // Same shape as retainMetadata: an object, or nothing. An array would spread into numeric
1566
+ // keys and reach the API as garbage, so it is rejected like any other non-object.
1567
+ recallOptions: raw.recallOptions && typeof raw.recallOptions === "object" && !Array.isArray(raw.recallOptions) ? { ...raw.recallOptions } : {},
1568
+ toolGuideExtra: typeof raw.toolGuideExtra === "string" && raw.toolGuideExtra.trim() ? raw.toolGuideExtra : void 0,
1569
+ // Every turn, not every tenth. The guide is what tells the agent WHEN to reach for memory, and
1570
+ // at a cadence of 10 a normal session is told once, on turn 1, and never again. Measured over
1571
+ // 40 real Claude Code turns, moving this from 10 to 1 took searches from 15% of turns to 32.5%
1572
+ // with no wording change at all. The cost is the guide's ~2KB re-sent per turn, which caches.
1573
+ pageRefreshEveryTurns: raw.pageRefreshEveryTurns || 1,
1336
1574
  pageTriggerType: pageTrigger.type,
1337
1575
  pageTriggerCron: pageTrigger.cron,
1576
+ pages: resolvePages(raw.pages),
1577
+ customPages: resolveCustomPages(raw.customPages),
1338
1578
  autoSeed: raw.autoSeed ?? true,
1339
1579
  seedLimit: raw.seedLimit || DEFAULT_SEED_LIMIT,
1340
1580
  codebaseSurvey: raw.codebaseSurvey ?? true,
@@ -1345,11 +1585,15 @@ function resolveConfig(raw = {}) {
1345
1585
  // Hostile input is a config typo, not an attack: keep only string entries so a stray number or
1346
1586
  // nested object cannot reach the API as a tag and fail the whole retain.
1347
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,
1348
1591
  retainMetadata: raw.retainMetadata && typeof raw.retainMetadata === "object" ? Object.fromEntries(
1349
1592
  Object.entries(raw.retainMetadata).filter(([, v]) => typeof v === "string")
1350
1593
  ) : {},
1351
1594
  observationScopes: resolveObservationScopes(raw.observationScopes),
1352
1595
  banks: raw.banks && typeof raw.banks === "object" ? raw.banks : {},
1596
+ paths: raw.paths && typeof raw.paths === "object" ? raw.paths : {},
1353
1597
  logLevel: ["debug", "info", "warn", "error"].includes(raw.logLevel) ? raw.logLevel : "info",
1354
1598
  autoUpdate: raw.autoUpdate ?? true
1355
1599
  };
@@ -1366,7 +1610,12 @@ function readRaw(path) {
1366
1610
  }
1367
1611
  function mergeRaw(a, b) {
1368
1612
  const { harnesses: _drop, ...flat } = b;
1369
- 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
+ };
1370
1619
  }
1371
1620
  function applyLayer(raw, layer, harness) {
1372
1621
  let out = mergeRaw(raw, layer);
@@ -1397,7 +1646,11 @@ var ENV_KEYS = {
1397
1646
  maxParallelRetains: "HINDSIGHT_MAX_PARALLEL_RETAINS",
1398
1647
  reflectTimeoutMs: "HINDSIGHT_REFLECT_TIMEOUT_MS",
1399
1648
  reflectToolTimeoutMs: "HINDSIGHT_REFLECT_TOOL_TIMEOUT_MS",
1649
+ injectTimeoutMs: "HINDSIGHT_INJECT_TIMEOUT_MS",
1400
1650
  reflectBudget: "HINDSIGHT_REFLECT_BUDGET",
1651
+ autoInject: "HINDSIGHT_AUTO_INJECT",
1652
+ pageSearchLimit: "HINDSIGHT_PAGE_SEARCH_LIMIT",
1653
+ toolGuideExtra: "HINDSIGHT_TOOL_GUIDE_EXTRA",
1401
1654
  autoReflect: "HINDSIGHT_AUTO_REFLECT",
1402
1655
  pageRefreshEveryTurns: "HINDSIGHT_PAGE_REFRESH_EVERY_TURNS",
1403
1656
  pageTriggerType: "HINDSIGHT_PAGE_TRIGGER_TYPE",
@@ -1417,7 +1670,8 @@ var ENV_KEYS = {
1417
1670
  // Comma-separated, e.g. HINDSIGHT_RETAIN_TAGS="project:{gitProject},env:work". A LIST rather than
1418
1671
  // a map, so it flattens cleanly; its sibling retainMetadata stays file-only for the reason above.
1419
1672
  retainTags: "HINDSIGHT_RETAIN_TAGS",
1420
- manageBankConfig: "HINDSIGHT_MANAGE_BANK_CONFIG"
1673
+ manageBankConfig: "HINDSIGHT_MANAGE_BANK_CONFIG",
1674
+ retainExtractionMode: "HINDSIGHT_RETAIN_EXTRACTION_MODE"
1421
1675
  };
1422
1676
  var ENV_BOOLEANS = /* @__PURE__ */ new Set([
1423
1677
  "dynamicBankId",
@@ -1438,6 +1692,8 @@ var ENV_NUMBERS = /* @__PURE__ */ new Set([
1438
1692
  "maxParallelRetains",
1439
1693
  "reflectTimeoutMs",
1440
1694
  "reflectToolTimeoutMs",
1695
+ "injectTimeoutMs",
1696
+ "pageSearchLimit",
1441
1697
  "pageRefreshEveryTurns",
1442
1698
  "seedLimit",
1443
1699
  "surveyBudgetUsd",
@@ -1485,15 +1741,25 @@ var BANK_OVERRIDE_EXCLUDED = [
1485
1741
  function applyBankConfig(cfg, resolvedId, directory) {
1486
1742
  if (directory !== void 0 && !isOptedIn(cfg, directory))
1487
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
+ }
1488
1749
  const section = cfg.banks[resolvedId];
1489
1750
  if (!section) return { cfg, bankId: resolvedId };
1490
- const safe = { ...section };
1491
- for (const k of BANK_OVERRIDE_EXCLUDED) delete safe[k];
1492
- delete safe.banks;
1751
+ const safe = overrideFields(section);
1493
1752
  const bankId = typeof safe.bank === "string" && safe.bank ? safe.bank : resolvedId;
1494
1753
  delete safe.bank;
1495
1754
  return { cfg: { ...cfg, ...resolvePartial(cfg, safe) }, bankId };
1496
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
+ }
1497
1763
  function resolvePartial(cfg, patch) {
1498
1764
  const full = resolveConfig(patch);
1499
1765
  const out = {};
@@ -1501,6 +1767,17 @@ function resolvePartial(cfg, patch) {
1501
1767
  if (key in full)
1502
1768
  out[key] = full[key];
1503
1769
  }
1770
+ if ("autoReflect" in patch && !("autoInject" in patch)) out.autoInject = full.autoInject;
1771
+ if ("serverMode" in patch || "apiUrl" in patch || "apiPort" in patch) {
1772
+ const conn = resolveConfig({
1773
+ serverMode: patch.serverMode ?? cfg.serverMode,
1774
+ apiPort: patch.apiPort ?? cfg.apiPort,
1775
+ apiUrl: patch.apiUrl ?? (cfg.serverMode === "daemon" ? void 0 : cfg.apiUrl)
1776
+ });
1777
+ out.serverMode = conn.serverMode;
1778
+ out.apiUrl = conn.apiUrl;
1779
+ out.apiPort = conn.apiPort;
1780
+ }
1504
1781
  return out;
1505
1782
  }
1506
1783
 
@@ -1682,6 +1959,11 @@ import { readFileSync as readFileSync7 } from "fs";
1682
1959
  import { createHash as createHash2 } from "crypto";
1683
1960
  var PENDING_MAX_AGE_MS = 12 * 60 * 60 * 1e3;
1684
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
+ }
1685
1967
  function pendingReplayable(cursor, now) {
1686
1968
  const pending = cursor.pending ?? [];
1687
1969
  if (!pending.length) return true;
@@ -1698,8 +1980,10 @@ function planRetain(turns, cursor, opts) {
1698
1980
  if (!opts.appendSupported || !cursor || cursor.dirty) return { mode: "replace" };
1699
1981
  if (!pendingReplayable(cursor, opts.now ?? Date.now())) return { mode: "replace" };
1700
1982
  if (cursor.bank !== opts.bank) return { mode: "replace" };
1701
- if (cursor.turns > turns.length) return { mode: "replace" };
1702
- 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" };
1703
1987
  if (cursor.turns === turns.length) return { mode: "skip" };
1704
1988
  return { mode: "append", fromTurn: cursor.turns };
1705
1989
  }
@@ -1734,7 +2018,7 @@ function renderSessionJsonl(refId, turns, baseTs) {
1734
2018
  }
1735
2019
  async function supportsAppend(client) {
1736
2020
  try {
1737
- return await client.supportsIdempotentRetain();
2021
+ return await client.supportsAppendRetain();
1738
2022
  } catch {
1739
2023
  return false;
1740
2024
  }
@@ -1768,6 +2052,7 @@ function serialize(cursors, sessionId, write2) {
1768
2052
  });
1769
2053
  return next;
1770
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.`;
1771
2056
  async function retainLiveSession(client, sessionId, turns, startTs, harness, opts = {}) {
1772
2057
  const cursors = opts.cursors;
1773
2058
  if (!cursors)
@@ -1779,20 +2064,36 @@ async function retainLiveSession(client, sessionId, turns, startTs, harness, opt
1779
2064
  harness,
1780
2065
  opts.stamp,
1781
2066
  void 0,
1782
- opts.retryUntil
2067
+ opts.retryUntil,
2068
+ opts.transcriptPath
1783
2069
  );
1784
2070
  return serialize(
1785
2071
  cursors,
1786
2072
  sessionId,
1787
- () => 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
+ )
1788
2084
  );
1789
2085
  }
1790
- 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) {
1791
2087
  if (!turns.length) return;
1792
2088
  const refId = `conversation:${sessionId}`;
1793
- const appendSupported = Boolean(cursors) && await supportsAppend(client);
1794
2089
  const cursor = cursors?.read(sessionId);
1795
- const plan = planRetain(turns, cursor, { appendSupported, bank: client.bank });
2090
+ const appendSupported = Boolean(cursors) && (cursor?.appendSupported === true || await supportsAppend(client));
2091
+ const plan = planRetain(turns, cursor, {
2092
+ appendSupported,
2093
+ bank: client.bank,
2094
+ path: transcriptPath
2095
+ });
2096
+ const paths = plan.mode === "replace" ? transcriptPath ? [transcriptPath] : void 0 : advancePaths(cursor?.paths, transcriptPath);
1796
2097
  const outbox = plan.mode === "replace" ? [] : cursor?.pending ?? [];
1797
2098
  if (plan.mode === "skip" && !outbox.length) return;
1798
2099
  const opId = (mode, content) => uuidV5(`${client.bank}
@@ -1801,7 +2102,10 @@ ${mode}
1801
2102
  ${content}`);
1802
2103
  const submit = (content, operationId, append) => client.retain(
1803
2104
  content,
1804
- "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,
1805
2109
  refId,
1806
2110
  // Configured tags first, built-ins last and deduped: `source:chat` and `harness:<id>` are what
1807
2111
  // the documents list filters and draws its agent logo from, so a template cannot displace them.
@@ -1830,7 +2134,9 @@ ${content}`);
1830
2134
  const next = {
1831
2135
  turns: turns.length,
1832
2136
  fingerprint: fingerprintTurns(turns, turns.length),
1833
- bank: client.bank
2137
+ bank: client.bank,
2138
+ ...paths ? { paths } : {},
2139
+ ...appendSupported ? { appendSupported: true } : {}
1834
2140
  };
1835
2141
  const stillOurs = () => {
1836
2142
  if (!cursors) return true;
@@ -1956,12 +2262,46 @@ function startDaemonDetached(cfg, harness, spawnFn = realSpawn2) {
1956
2262
  } catch {
1957
2263
  }
1958
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
+ }
1959
2279
  async function ensureDaemon(cfg, harness, opts = {}) {
1960
2280
  if (cfg.serverMode !== "daemon") return;
1961
2281
  if (await isServerHealthy(cfg.apiUrl)) return;
1962
2282
  if (!preflightDaemon(cfg, harness)) return;
1963
- startDaemonDetached(cfg, harness, opts.spawnFn);
1964
- 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
+ }
1965
2305
  }
1966
2306
  async function waitForHealth(baseUrl, budgetMs, pollMs = 1e3) {
1967
2307
  const deadline = Date.now() + budgetMs;
@@ -2016,7 +2356,8 @@ function resolversFor(ctx) {
2016
2356
  function buildRetainStamp(cfg, ctx) {
2017
2357
  const hasTags = Boolean(cfg.retainTags?.length);
2018
2358
  const hasMetadata = Boolean(cfg.retainMetadata && Object.keys(cfg.retainMetadata).length);
2019
- if (!hasTags && !hasMetadata) return { tags: [], metadata: {} };
2359
+ const hasContext = Boolean(cfg.retainContext?.trim());
2360
+ if (!hasTags && !hasMetadata && !hasContext) return { tags: [], metadata: {} };
2020
2361
  const base = resolversFor(ctx);
2021
2362
  const cache = /* @__PURE__ */ new Map();
2022
2363
  const resolvers = Object.fromEntries(
@@ -2040,35 +2381,15 @@ function buildRetainStamp(cfg, ctx) {
2040
2381
  for (const [key, value] of Object.entries(cfg.retainMetadata ?? {})) {
2041
2382
  metadata[key] = applyTemplate(value, resolvers, "retainMetadata");
2042
2383
  }
2043
- return { tags, metadata };
2384
+ const context = hasContext ? applyTemplate(cfg.retainContext, resolvers, "retainContext").trim() || void 0 : void 0;
2385
+ return { tags, metadata, context };
2044
2386
  }
2045
2387
 
2046
2388
  // src/core/jsonl.ts
2047
- import { closeSync, openSync, readSync, statSync as statSync3 } from "fs";
2389
+ import { closeSync, openSync, readSync } from "fs";
2048
2390
  import { StringDecoder } from "string_decoder";
2049
2391
  var CHUNK_BYTES = 64 * 1024;
2050
- var MAX_TRANSCRIPT_BYTES = 32 * 1024 * 1024;
2051
- function readJsonlTail(path, opts) {
2052
- const maxBytes = opts.maxBytes ?? MAX_TRANSCRIPT_BYTES;
2053
- let size;
2054
- try {
2055
- size = statSync3(path).size;
2056
- } catch {
2057
- return { lines: emptyLines(), skippedBytes: 0 };
2058
- }
2059
- const skippedBytes = size > maxBytes ? size - maxBytes : 0;
2060
- if (skippedBytes > 0) {
2061
- log.warn(opts.scope, "transcript too large \u2014 retaining the most recent portion only", {
2062
- path,
2063
- sizeBytes: size,
2064
- skippedBytes
2065
- });
2066
- }
2067
- return { lines: streamLines(path, skippedBytes), skippedBytes };
2068
- }
2069
- function* emptyLines() {
2070
- }
2071
- function* streamLines(path, start) {
2392
+ function* readJsonl(path) {
2072
2393
  let fd;
2073
2394
  try {
2074
2395
  fd = openSync(path, "r");
@@ -2079,8 +2400,7 @@ function* streamLines(path, start) {
2079
2400
  const buffer = Buffer.allocUnsafe(CHUNK_BYTES);
2080
2401
  const decoder = new StringDecoder("utf8");
2081
2402
  let pending = "";
2082
- let position = start > 0 ? start - 1 : 0;
2083
- let dropPartial = start > 0;
2403
+ let position = 0;
2084
2404
  for (; ; ) {
2085
2405
  const bytesRead = readSync(fd, buffer, 0, buffer.length, position);
2086
2406
  if (bytesRead <= 0) break;
@@ -2088,17 +2408,12 @@ function* streamLines(path, start) {
2088
2408
  pending += decoder.write(buffer.subarray(0, bytesRead));
2089
2409
  let newline;
2090
2410
  while ((newline = pending.indexOf("\n")) !== -1) {
2091
- const line = pending.slice(0, newline);
2411
+ yield pending.slice(0, newline);
2092
2412
  pending = pending.slice(newline + 1);
2093
- if (dropPartial) {
2094
- dropPartial = false;
2095
- continue;
2096
- }
2097
- yield line;
2098
2413
  }
2099
2414
  }
2100
2415
  pending += decoder.end();
2101
- if (pending && !dropPartial) yield pending;
2416
+ if (pending) yield pending;
2102
2417
  } finally {
2103
2418
  closeSync(fd);
2104
2419
  }
@@ -2130,7 +2445,7 @@ function renderLine(content, type) {
2130
2445
  }
2131
2446
  function readClaudeTranscript(path) {
2132
2447
  const turns = [];
2133
- for (const rawLine of readJsonlTail(path, { scope: "claude-code" }).lines) {
2448
+ for (const rawLine of readJsonl(path)) {
2134
2449
  const trimmed = rawLine.trim();
2135
2450
  if (!trimmed) continue;
2136
2451
  let parsed;
@@ -2185,7 +2500,8 @@ function summarizeTurns(turns) {
2185
2500
  function recordUsage(args) {
2186
2501
  const summary = summarizeTurns(args.turns);
2187
2502
  const finished = args.lastTurnComplete ? summary : summary.slice(0, -1);
2188
- const from = args.cursors.read(args.sessionId) ?? 0;
2503
+ const recorded = args.cursors.read(args.sessionId) ?? 0;
2504
+ const from = args.reviseLastTurn ? Math.max(0, recorded - 1) : recorded;
2189
2505
  if (finished.length <= from) return;
2190
2506
  const ts = (/* @__PURE__ */ new Date()).toISOString();
2191
2507
  const lines = finished.slice(from).map(
@@ -2228,7 +2544,11 @@ async function buildRetain(args) {
2228
2544
  bankId: args.bankId ?? "",
2229
2545
  turns,
2230
2546
  cursors: args.usageCursors ?? fileUsageCursorStore(harness),
2231
- lastTurnComplete: true
2547
+ lastTurnComplete: true,
2548
+ // The host has usually not flushed this turn's final reply yet — and that is
2549
+ // the message carrying the credit line. Re-emit the previous turn so the next
2550
+ // Stop, reading a complete transcript, corrects it. See recordUsage.
2551
+ reviseLastTurn: true
2232
2552
  });
2233
2553
  const startTs = turns[0]?.timestamp ?? (/* @__PURE__ */ new Date()).toISOString();
2234
2554
  const t0 = Date.now();
@@ -2236,7 +2556,8 @@ async function buildRetain(args) {
2236
2556
  await retainLiveSession(client, sessionId, turns, startTs, harness, {
2237
2557
  cursors: args.cursors ?? fileCursorStore(harness),
2238
2558
  stamp: args.stamp,
2239
- retryUntil: args.retryUntil
2559
+ retryUntil: args.retryUntil,
2560
+ transcriptPath
2240
2561
  });
2241
2562
  diag(harness, "retain_ok", { ms: Date.now() - t0, turns: turns.length, session: sessionId });
2242
2563
  } catch (e) {
@@ -2344,7 +2665,7 @@ import {
2344
2665
  renameSync as renameSync3,
2345
2666
  rmdirSync,
2346
2667
  rmSync as rmSync2,
2347
- statSync as statSync4,
2668
+ statSync as statSync3,
2348
2669
  unlinkSync,
2349
2670
  utimesSync,
2350
2671
  writeFileSync as writeFileSync2
@@ -2365,57 +2686,361 @@ import { homedir as homedir5, tmpdir as tmpdir4 } from "os";
2365
2686
  import { dirname as dirname9, join as join14 } from "path";
2366
2687
  import { fileURLToPath as fileURLToPath4 } from "url";
2367
2688
  var CHECK_INTERVAL_MS = 24 * 60 * 60 * 1e3;
2689
+ var NPM_VIEW_TIMEOUT_MS = 5e3;
2690
+ var NPM_VIEW_HARD_DEADLINE_MS = NPM_VIEW_TIMEOUT_MS + 1e3;
2368
2691
  var LOCK_STALE_MS = 10 * 60 * 1e3;
2369
2692
 
2370
2693
  // src/core/skill-sync.ts
2371
- import { cpSync, existsSync as existsSync5, readFileSync as readFileSync9 } from "fs";
2694
+ import { cpSync, existsSync as existsSync6, readFileSync as readFileSync9 } from "fs";
2372
2695
  import { homedir as homedir6 } from "os";
2373
- import { dirname as dirname10, join as join15 } from "path";
2696
+ import { dirname as dirname10, join as join16 } from "path";
2374
2697
  import { fileURLToPath as fileURLToPath5 } from "url";
2375
2698
 
2699
+ // src/core/skill-dirs.ts
2700
+ import { existsSync as existsSync5 } from "fs";
2701
+ import { join as join15 } from "path";
2702
+
2376
2703
  // src/core/legacy.ts
2377
- import { existsSync as existsSync6, readFileSync as readFileSync10 } from "fs";
2704
+ import { existsSync as existsSync7, readFileSync as readFileSync10 } from "fs";
2378
2705
  import { homedir as homedir7 } from "os";
2379
- 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
+ }
2380
2934
 
2381
2935
  // src/core/transcript-codex.ts
2936
+ function stampOf(line) {
2937
+ return typeof line.timestamp === "string" && line.timestamp ? { timestamp: line.timestamp } : {};
2938
+ }
2382
2939
  function isSyntheticUserText(text) {
2383
2940
  const s = text.trimStart();
2384
2941
  return s.startsWith("# AGENTS.md instructions for ") || s.startsWith("<environment_context>");
2385
2942
  }
2386
- function messageText(payload) {
2387
- return (payload.content || []).filter((c) => c && typeof c.text === "string").map((c) => c.text).join("\n");
2943
+ function contentText(content) {
2944
+ return (Array.isArray(content) ? content : []).filter((c) => c && typeof c.text === "string").map((c) => c.text).join("\n");
2945
+ }
2946
+ var startupKinds = /* @__PURE__ */ new Set([
2947
+ "agents_md.instructions",
2948
+ "environments.instructions",
2949
+ "environments.environment_context",
2950
+ "plugins.recommendations",
2951
+ "plugins.usage_instructions"
2952
+ ]);
2953
+ function fallbackUserText(payload) {
2954
+ const content = payload.content;
2955
+ const kinds = payload.internal_chat_message_metadata_passthrough?.content_item_kinds;
2956
+ if (Array.isArray(content) && Array.isArray(kinds) && kinds.length === content.length && kinds.every((kind) => typeof kind === "string" && kind.length > 0)) {
2957
+ return contentText(content.filter((_, index) => !startupKinds.has(kinds[index])));
2958
+ }
2959
+ const text = contentText(content);
2960
+ return isSyntheticUserText(stripInjectedMemory(text)) ? "" : text;
2961
+ }
2962
+ function isUserMessageEvent(line) {
2963
+ return line.type === "event_msg" && line.payload?.type === "item_completed" && line.payload.item?.type === "UserMessage";
2964
+ }
2965
+ var TOOL_ITEM_TYPES = /* @__PURE__ */ new Set(["McpToolCall", "CommandExecution"]);
2966
+ function isToolItemEvent(line) {
2967
+ return line.type === "event_msg" && line.payload?.type === "item_completed" && TOOL_ITEM_TYPES.has(line.payload.item?.type ?? "");
2968
+ }
2969
+ function parseArgs(raw) {
2970
+ if (typeof raw !== "string") return raw;
2971
+ try {
2972
+ return JSON.parse(raw);
2973
+ } catch {
2974
+ return void 0;
2975
+ }
2976
+ }
2977
+ var SHELL_RE = /(?:^|\/)(?:sh|bash|zsh|dash|ksh|fish)$/;
2978
+ function commandText(command) {
2979
+ if (typeof command === "string") return command;
2980
+ if (!Array.isArray(command) || !command.every((c) => typeof c === "string")) return "";
2981
+ const argv = command;
2982
+ if (argv.length === 3 && SHELL_RE.test(argv[0]) && /^-[a-z]*c$/.test(argv[1])) return argv[2];
2983
+ return argv.join(" ");
2984
+ }
2985
+ function toolItemAction(item) {
2986
+ if (item.type === "McpToolCall") {
2987
+ if (typeof item.tool !== "string" || !item.tool) return void 0;
2988
+ const name = typeof item.server === "string" && item.server ? `mcp__${item.server}__${item.tool}` : item.tool;
2989
+ return actionLine(name, parseArgs(item.arguments));
2990
+ }
2991
+ const command = commandText(item.command).trim();
2992
+ return command ? actionLine("exec_command", { command }) : void 0;
2388
2993
  }
2389
2994
  function readCodexTranscript(path) {
2390
- const turns = [];
2391
- for (const rawLine of readJsonlTail(path, { scope: "codex" }).lines) {
2995
+ const lines = [];
2996
+ for (const rawLine of readJsonl(path)) {
2392
2997
  const trimmed = rawLine.trim();
2393
2998
  if (!trimmed) continue;
2394
- let parsed;
2395
2999
  try {
2396
- parsed = JSON.parse(trimmed);
3000
+ const parsed = JSON.parse(trimmed);
3001
+ if (typeof parsed === "object" && parsed !== null) lines.push(parsed);
2397
3002
  } catch {
2398
3003
  continue;
2399
3004
  }
2400
- if (typeof parsed !== "object" || parsed === null) continue;
2401
- const line = parsed;
3005
+ }
3006
+ const userFromEvents = lines.some(isUserMessageEvent);
3007
+ const actionsFromEvents = lines.some(isToolItemEvent);
3008
+ const turns = [];
3009
+ const push = (role, raw, stamp = {}) => {
3010
+ const text = stripInjectedMemory(raw).trim();
3011
+ if (text) turns.push({ role, content: text, ...stamp });
3012
+ };
3013
+ for (const line of lines) {
3014
+ if (isUserMessageEvent(line)) {
3015
+ push("user", contentText(line.payload?.item?.content), stampOf(line));
3016
+ continue;
3017
+ }
3018
+ if (isToolItemEvent(line)) {
3019
+ const action = toolItemAction(line.payload?.item ?? {});
3020
+ if (action) turns.push({ role: "action", content: action, ...stampOf(line) });
3021
+ continue;
3022
+ }
2402
3023
  if (line.type !== "response_item") continue;
2403
3024
  const p = line.payload;
2404
3025
  if (!p || typeof p !== "object") continue;
2405
3026
  if (p.type === "message") {
2406
- if (p.role !== "user" && p.role !== "assistant") continue;
2407
- const text = stripInjectedMemory(messageText(p)).trim();
2408
- if (!text) continue;
2409
- if (p.role === "user" && isSyntheticUserText(text)) continue;
2410
- turns.push({ role: p.role, content: text });
2411
- } else if (p.type === "function_call" && typeof p.name === "string") {
3027
+ if (p.role === "assistant") {
3028
+ if (p.channel === "analysis" || p.channel === "reasoning" || p.phase === "analysis" || p.phase === "reasoning")
3029
+ continue;
3030
+ push("assistant", contentText(p.content), stampOf(line));
3031
+ } else if (p.role === "user" && !userFromEvents) {
3032
+ push("user", fallbackUserText(p), stampOf(line));
3033
+ }
3034
+ } else if ((p.type === "function_call" || p.type === "custom_tool_call") && typeof p.name === "string") {
3035
+ if (actionsFromEvents && p.type === "custom_tool_call" && p.name === "exec") continue;
3036
+ const rawInput = p.type === "function_call" ? p.arguments : p.input;
2412
3037
  let input;
2413
3038
  try {
2414
- input = JSON.parse(p.arguments || "");
3039
+ input = JSON.parse(rawInput || "");
2415
3040
  } catch {
2416
3041
  input = void 0;
2417
3042
  }
2418
- turns.push({ role: "action", content: actionLine(p.name, input) });
3043
+ turns.push({ role: "action", content: actionLine(p.name, input), ...stampOf(line) });
2419
3044
  }
2420
3045
  }
2421
3046
  return turns;
@@ -2432,7 +3057,7 @@ function textFrom(content) {
2432
3057
  }
2433
3058
  function readCursorTranscript(path) {
2434
3059
  const turns = [];
2435
- for (const rawLine of readJsonlTail(path, { scope: "cursor-cli" }).lines) {
3060
+ for (const rawLine of readJsonl(path)) {
2436
3061
  let parsed;
2437
3062
  try {
2438
3063
  parsed = JSON.parse(rawLine);
@@ -2471,7 +3096,7 @@ function readCursorTranscript(path) {
2471
3096
  function readAntigravityTranscript(path) {
2472
3097
  if (!path) return [];
2473
3098
  const turns = [];
2474
- for (const line of readJsonlTail(path, { scope: "antigravity-cli" }).lines) {
3099
+ for (const line of readJsonl(path)) {
2475
3100
  try {
2476
3101
  const event = JSON.parse(line);
2477
3102
  const role = event.role ?? event.message?.role ?? event.type;
@@ -2494,7 +3119,7 @@ function readAntigravityTranscript(path) {
2494
3119
  // src/core/transcript-copilot.ts
2495
3120
  function readCopilotTranscript(path) {
2496
3121
  const turns = [];
2497
- for (const rawLine of readJsonlTail(path, { scope: "copilot-cli" }).lines) {
3122
+ for (const rawLine of readJsonl(path)) {
2498
3123
  try {
2499
3124
  const event = JSON.parse(rawLine);
2500
3125
  const role = event.type === "user.message" ? "user" : event.type === "assistant.message" ? "assistant" : void 0;
@@ -2508,19 +3133,19 @@ function readCopilotTranscript(path) {
2508
3133
  }
2509
3134
 
2510
3135
  // src/core/transcript-grok.ts
2511
- import { existsSync as existsSync7, readFileSync as readFileSync12, readdirSync as readdirSync2 } from "fs";
2512
- import { homedir as homedir8 } from "os";
2513
- 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";
2514
3139
  var CHAT_HISTORY = "chat_history.jsonl";
2515
- function grokTranscriptPath(cwd, sessionId, grokHome = process.env.GROK_HOME || join17(homedir8(), ".grok")) {
2516
- const sessionsDir = join17(grokHome, "sessions");
2517
- const direct = join17(sessionsDir, encodeURIComponent(cwd), sessionId, CHAT_HISTORY);
2518
- 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;
2519
3144
  try {
2520
- for (const candidate of readdirSync2(sessionsDir)) {
2521
- const directory = join17(sessionsDir, candidate);
2522
- if (readFileSync12(join17(directory, ".cwd"), "utf8").trim() === cwd) {
2523
- 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);
2524
3149
  }
2525
3150
  }
2526
3151
  } catch {
@@ -2529,7 +3154,7 @@ function grokTranscriptPath(cwd, sessionId, grokHome = process.env.GROK_HOME ||
2529
3154
  }
2530
3155
  function readGrokTranscript(path) {
2531
3156
  const turns = [];
2532
- for (const rawLine of readJsonlTail(path, { scope: "grok-build" }).lines) {
3157
+ for (const rawLine of readJsonl(path)) {
2533
3158
  try {
2534
3159
  const event = JSON.parse(rawLine);
2535
3160
  if (event.type !== "user" && event.type !== "assistant") continue;
@@ -2555,12 +3180,12 @@ function readGrokTranscript(path) {
2555
3180
  }
2556
3181
 
2557
3182
  // src/core/transcript-devin.ts
2558
- import { existsSync as existsSync8 } from "fs";
3183
+ import { existsSync as existsSync10 } from "fs";
2559
3184
  import { createRequire } from "module";
2560
- import { homedir as homedir9 } from "os";
2561
- import { join as join18 } from "path";
2562
- function devinSessionDb(home = homedir9()) {
2563
- 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");
2564
3189
  }
2565
3190
  function parseDevinMessages(nodes) {
2566
3191
  const messages = /* @__PURE__ */ new Map();
@@ -2597,7 +3222,7 @@ function readDevinTranscript(sessionId, dbPath = devinSessionDb()) {
2597
3222
  diag("devin-cli", "sqlite_unavailable", { node: process.version, dbPath });
2598
3223
  return [];
2599
3224
  }
2600
- if (!existsSync8(dbPath)) {
3225
+ if (!existsSync10(dbPath)) {
2601
3226
  diag("devin-cli", "session_db_missing", { dbPath });
2602
3227
  return [];
2603
3228
  }
@@ -2621,7 +3246,7 @@ function readDevinTranscript(sessionId, dbPath = devinSessionDb()) {
2621
3246
 
2622
3247
  // src/core/transcript-dcode.ts
2623
3248
  var BLOCK_JOIN = "\n";
2624
- function contentText(content) {
3249
+ function contentText2(content) {
2625
3250
  if (typeof content === "string") return content;
2626
3251
  if (!Array.isArray(content)) return "";
2627
3252
  return content.flatMap((block) => {
@@ -2714,11 +3339,11 @@ function dcodeAssistantText(raw) {
2714
3339
  const parsed = readPyValue(trimmed, 0);
2715
3340
  if (!parsed || readPyValue(trimmed, parsed.end) !== null) return "";
2716
3341
  if (!Array.isArray(parsed.value)) return "";
2717
- return contentText(parsed.value);
3342
+ return contentText2(parsed.value);
2718
3343
  }
2719
3344
  function readDcodeTranscript(path) {
2720
3345
  const turns = [];
2721
- for (const rawLine of readJsonlTail(path, { scope: "dcode" }).lines) {
3346
+ for (const rawLine of readJsonl(path)) {
2722
3347
  if (!rawLine.trim()) continue;
2723
3348
  let parsed;
2724
3349
  try {
@@ -2732,7 +3357,7 @@ function readDcodeTranscript(path) {
2732
3357
  const role = record.role;
2733
3358
  const stamp = typeof record.timestamp === "string" && record.timestamp ? { timestamp: record.timestamp } : {};
2734
3359
  if (role === "user" || role === "assistant") {
2735
- const text = stripInjectedMemory(contentText(record.content)).trim();
3360
+ const text = stripInjectedMemory(contentText2(record.content)).trim();
2736
3361
  if (text) turns.push({ role, content: text, ...stamp });
2737
3362
  } else if (role === "tool" && typeof record.name === "string" && record.name.trim()) {
2738
3363
  turns.push({ role: "action", content: actionLine(record.name, record.content), ...stamp });
@@ -2793,7 +3418,7 @@ function readQwenTranscript(path) {
2793
3418
  return turns;
2794
3419
  }
2795
3420
  function collectQwenTurns(path, turns) {
2796
- for (const rawLine of readJsonlTail(path, { scope: "qwen-code" }).lines) {
3421
+ for (const rawLine of readJsonl(path)) {
2797
3422
  const trimmed = rawLine.trim();
2798
3423
  if (!trimmed) continue;
2799
3424
  let parsed;
@@ -2848,7 +3473,7 @@ function renderContent(content, role) {
2848
3473
  }
2849
3474
  function readDroidTranscript(path) {
2850
3475
  const turns = [];
2851
- for (const rawLine of readJsonlTail(path, { scope: "factory-droid" }).lines) {
3476
+ for (const rawLine of readJsonl(path)) {
2852
3477
  if (!rawLine.trim()) continue;
2853
3478
  let parsed;
2854
3479
  try {
@@ -2870,8 +3495,8 @@ function readDroidTranscript(path) {
2870
3495
  }
2871
3496
 
2872
3497
  // src/core/transcript-zcode.ts
2873
- import { readFileSync as readFileSync13 } from "fs";
2874
- function messageText2(content) {
3498
+ import { readFileSync as readFileSync14 } from "fs";
3499
+ function messageText(content) {
2875
3500
  if (typeof content === "string") return content.trim();
2876
3501
  if (!Array.isArray(content)) return "";
2877
3502
  return content.filter((block) => block && typeof block === "object" && typeof block.text === "string").map((block) => block.text.trim()).filter(Boolean).join("\n").trim();
@@ -2880,7 +3505,7 @@ function readZcodeTranscript(path) {
2880
3505
  if (!path) return [];
2881
3506
  let body;
2882
3507
  try {
2883
- body = readFileSync13(path, "utf8");
3508
+ body = readFileSync14(path, "utf8");
2884
3509
  } catch {
2885
3510
  return [];
2886
3511
  }
@@ -2899,7 +3524,7 @@ function readZcodeTranscript(path) {
2899
3524
  const message = typeof record.message === "object" && record.message !== null ? record.message : void 0;
2900
3525
  const role = typeof message?.role === "string" ? message.role : record.type;
2901
3526
  if (role !== "user" && role !== "assistant") continue;
2902
- const content = stripInjectedMemory(messageText2(message?.content)).trim();
3527
+ const content = stripInjectedMemory(messageText(message?.content)).trim();
2903
3528
  if (!content) continue;
2904
3529
  turns.push({
2905
3530
  role,
@@ -2914,6 +3539,131 @@ function zcodeAssistantText(path) {
2914
3539
  return readZcodeTranscript(path).filter((turn) => turn.role === "assistant").at(-1)?.content ?? "";
2915
3540
  }
2916
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
+
2917
3667
  // src/harness/hook-lifecycle.ts
2918
3668
  var cursorCwd = (ev) => ev.cwd ?? ev.workspace_root ?? (Array.isArray(ev.workspace_roots) ? ev.workspace_roots[0] : void 0);
2919
3669
  var claudePrompt = {
@@ -2992,7 +3742,7 @@ var copilotPrompt = {
2992
3742
  ${context}`.trim()
2993
3743
  })
2994
3744
  };
2995
- var devinCwd = () => process.env.DEVIN_PROJECT_DIR;
3745
+ var devinCwd = () => process.env.DEVIN_PROJECT_DIR || process.cwd();
2996
3746
  var devinPrompt = {
2997
3747
  harness: "devin-cli",
2998
3748
  requireCwd: true,
@@ -3019,6 +3769,7 @@ var standardSessionStart = (harness) => ({
3019
3769
  }
3020
3770
  })
3021
3771
  });
3772
+ var notGrokHosted = () => !process.env.GROK_HOOK_EVENT;
3022
3773
  var HOOK_HARNESSES = {
3023
3774
  "claude-code": {
3024
3775
  configStyle: "nested",
@@ -3027,11 +3778,12 @@ var HOOK_HARNESSES = {
3027
3778
  prompt: { event: "UserPromptSubmit", entry: "claude-hook.js", timeout: 30 },
3028
3779
  stop: { event: "Stop", entry: "claude-stop-hook.js", timeout: 60 }
3029
3780
  },
3030
- sessionStart: standardSessionStart("claude-code"),
3031
- prompt: claudePrompt,
3781
+ sessionStart: { ...standardSessionStart("claude-code"), accept: notGrokHosted },
3782
+ prompt: { ...claudePrompt, accept: notGrokHosted },
3032
3783
  retain: {
3033
3784
  hostTimeoutSec: 60,
3034
3785
  harness: "claude-code",
3786
+ accept: notGrokHosted,
3035
3787
  parse: (ev) => ({
3036
3788
  sessionId: ev.session_id,
3037
3789
  transcriptPath: ev.transcript_path,
@@ -3252,7 +4004,7 @@ var HOOK_HARNESSES = {
3252
4004
  // `detached` and terminates the whole process TREE on timeout, so the retain is genuinely lost
3253
4005
  // rather than merely orphaned. `retain.hostTimeoutSec` below stays SECONDS, as its name says;
3254
4006
  // these two numbers are the same budget in different units for this harness alone.
3255
- // The prompt timeout must also stay above core/hook.ts's HOOK_REFLECT_CAP_MS (25_000).
4007
+ // The prompt timeout must also stay above core/config.ts's DEFAULT_REFLECT_TIMEOUT_MS.
3256
4008
  install: {
3257
4009
  sessionStart: { event: "SessionStart", entry: "qwen-sessionstart-hook.js", timeout: 3e4 },
3258
4010
  prompt: { event: "UserPromptSubmit", entry: "qwen-hook.js", timeout: 3e4 },
@@ -3314,7 +4066,7 @@ var HOOK_HARNESSES = {
3314
4066
  zcode: {
3315
4067
  configStyle: "process",
3316
4068
  // ZCode's `timeoutMs`, so MILLISECONDS — see the qwen-code note above for the same trap. The
3317
- // prompt budget must stay above core/hook.ts's HOOK_REFLECT_CAP_MS (25_000).
4069
+ // prompt budget must stay above core/config.ts's DEFAULT_REFLECT_TIMEOUT_MS.
3318
4070
  timeoutUnit: "milliseconds",
3319
4071
  install: {
3320
4072
  sessionStart: { event: "SessionStart", entry: "zcode-sessionstart-hook.js", timeout: 3e4 },
@@ -3347,6 +4099,117 @@ var HOOK_HARNESSES = {
3347
4099
  assistantText: (ev) => (ev.responseText || zcodeAssistantText(ev.transcript_path) || ev.responsePreview || "").trim()
3348
4100
  }
3349
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
+ }
3350
4213
  }
3351
4214
  };
3352
4215
  var runHarnessRetain = (harness) => runRetainHook(HOOK_HARNESSES[harness].retain);