@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
@@ -53,6 +53,20 @@ var log = {
53
53
  warn: (scope, msg, extra) => write("warn", scope, msg, extra),
54
54
  error: (scope, msg, extra) => write("error", scope, msg, extra)
55
55
  };
56
+ function describeError(value, maxChars = 200) {
57
+ const parts = [];
58
+ const seen = /* @__PURE__ */ new Set();
59
+ let current2 = value;
60
+ while (current2 && !seen.has(current2)) {
61
+ seen.add(current2);
62
+ const error = current2;
63
+ const text = typeof error.message === "string" ? error.message : String(current2);
64
+ const withCode = error.code ? `${text} (${String(error.code)})` : text;
65
+ if (withCode && parts.at(-1) !== withCode) parts.push(withCode);
66
+ current2 = error.cause;
67
+ }
68
+ return (parts.join(": ") || String(value)).slice(0, maxChars);
69
+ }
56
70
 
57
71
  // src/core/diag.ts
58
72
  function diagFilePath() {
@@ -256,13 +270,13 @@ function isWithin(directory, configured) {
256
270
  function mapLookup(map, directory) {
257
271
  const cwd = normalize(directory);
258
272
  let best;
259
- for (const [dir, bank] of Object.entries(map)) {
273
+ for (const [dir, value] of Object.entries(map)) {
260
274
  const p = configuredDir(dir);
261
275
  if (isWithin(cwd, p)) {
262
- if (!best || p.length > best.len) best = { len: p.length, bank };
276
+ if (!best || p.length > best.len) best = { len: p.length, value };
263
277
  }
264
278
  }
265
- return best?.bank;
279
+ return best?.value;
266
280
  }
267
281
  function lookupDirectories(config, directory, sessionRoot = "") {
268
282
  const directories = [normalize(directory)];
@@ -286,6 +300,10 @@ function isOptedIn(config, directory) {
286
300
  const pathMap = config.mapPathToBank;
287
301
  return Boolean(pathMap && directories.some((candidate) => mapLookup(pathMap, candidate)));
288
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
+ }
289
307
  function mappedBank(config, directory, sessionRoot) {
290
308
  const pathMap = config.mapPathToBank;
291
309
  if (!directory || !pathMap) return void 0;
@@ -365,13 +383,15 @@ var CONVERSATION_MISSION = `You are ingesting a developer conversation as a JSON
365
383
  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.";
366
384
  var DOCUMENT_MISSION = "You are ingesting a standalone document (notes, docs, or structural findings). Extract the concrete facts, concepts, and structure it describes.";
367
385
  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.";
386
+ var RETAIN_EXTRACTION_MODES = ["concise", "verbose", "verbatim", "chunks"];
387
+ var DEFAULT_RETAIN_EXTRACTION_MODE = "concise";
368
388
  var RETAIN_STRATEGIES = {
369
- git: { retain_mission: GIT_MISSION, retain_extraction_mode: "verbose" },
389
+ git: { retain_mission: GIT_MISSION, retain_extraction_mode: DEFAULT_RETAIN_EXTRACTION_MODE },
370
390
  // ONE big aggregated document (last N commit messages, no diffs) -> a larger chunk size so it stays
371
391
  // in as few chunks as possible and the extractor sees the whole history arc at once.
372
392
  gitlog: {
373
393
  retain_mission: GITLOG_MISSION,
374
- retain_extraction_mode: "verbose",
394
+ retain_extraction_mode: DEFAULT_RETAIN_EXTRACTION_MODE,
375
395
  retain_chunk_size: 12e3
376
396
  },
377
397
  // ONE strategy for ALL developer conversations — backfilled decision chats and live working
@@ -382,15 +402,15 @@ var RETAIN_STRATEGIES = {
382
402
  // the consolidation layer.
383
403
  conversation: {
384
404
  retain_mission: CONVERSATION_MISSION,
385
- retain_extraction_mode: "verbose",
405
+ retain_extraction_mode: DEFAULT_RETAIN_EXTRACTION_MODE,
386
406
  retain_chunk_size: 12e3
387
407
  },
388
408
  // Structural documents (e.g. the codebase survey's ingested findings) aren't dialogue — the
389
- // chat strategy's "final decision vs rejected proposal" extraction doesn't apply. Verbose mode
390
- // with a bigger chunk size (documents can run long) captures the concrete facts/structure instead.
409
+ // chat strategy's "final decision vs rejected proposal" extraction doesn't apply. A bigger chunk
410
+ // size (documents can run long) keeps the concrete facts/structure together instead.
391
411
  document: {
392
412
  retain_mission: DOCUMENT_MISSION,
393
- retain_extraction_mode: "verbose",
413
+ retain_extraction_mode: DEFAULT_RETAIN_EXTRACTION_MODE,
394
414
  retain_chunk_size: 12e3
395
415
  },
396
416
  // Codebase-SURVEY lifecycle documents, ONE strategy with conditional rules: the survey's
@@ -463,9 +483,22 @@ var PAGE_TAXONOMY = [
463
483
  tags: ["knowledge:feature-work"]
464
484
  }
465
485
  ];
466
- function pagesFor(project) {
486
+ var PAGE_NAMES = PAGE_TAXONOMY.map((page) => page.name);
487
+ function pagesFor(project, pages = {}, customPages = {}) {
467
488
  const scope = pageScopeRule(project);
468
- return PAGE_TAXONOMY.map((page) => ({ ...page, source_query: page.source_query + scope }));
489
+ const byName = new Map(
490
+ Object.entries(pages).map(([name, override]) => [name.trim().toLowerCase(), override])
491
+ );
492
+ const out = [];
493
+ for (const page of PAGE_TAXONOMY) {
494
+ const override = byName.get(page.name.toLowerCase());
495
+ if (override === false) continue;
496
+ out.push({ ...page, source_query: (override?.source_query || page.source_query) + scope });
497
+ }
498
+ for (const [name, page] of Object.entries(customPages)) {
499
+ out.push({ name: name.trim(), source_query: page.source_query + scope, tags: page.tags ?? [] });
500
+ }
501
+ return out;
469
502
  }
470
503
  var PAGE_MAX_TOKENS = 4096;
471
504
  var PAGE_TAGS_MATCH = "all";
@@ -548,7 +581,7 @@ var CODING_BANK_TEMPLATE = {
548
581
  enable_observations: true,
549
582
  observations_mission: OBSERVATIONS_MISSION,
550
583
  retain_mission: GIT_MISSION,
551
- retain_extraction_mode: "verbose",
584
+ retain_extraction_mode: DEFAULT_RETAIN_EXTRACTION_MODE,
552
585
  retain_default_strategy: "git",
553
586
  retain_strategies: RETAIN_STRATEGIES,
554
587
  entity_labels: [KNOWLEDGE_LABELS],
@@ -556,12 +589,17 @@ var CODING_BANK_TEMPLATE = {
556
589
  }
557
590
  };
558
591
  var MISSION_FIELDS = ["reflect_mission", "retain_mission", "observations_mission"];
592
+ var PLUGIN_GOVERNED_BANK_FIELDS = [
593
+ "retain_strategies",
594
+ "entity_labels",
595
+ "retain_extraction_mode"
596
+ ];
559
597
  function isSet(v) {
560
598
  if (v === null || v === void 0) return false;
561
599
  if (typeof v === "string") return v.trim() !== "";
562
600
  return true;
563
601
  }
564
- function codingBankManifest(overrides) {
602
+ function codingBankManifest(overrides, mode = DEFAULT_RETAIN_EXTRACTION_MODE, defaults = {}) {
565
603
  const current2 = overrides ?? {};
566
604
  const template = CODING_BANK_TEMPLATE.bank;
567
605
  const bank = {};
@@ -570,20 +608,30 @@ function codingBankManifest(overrides) {
570
608
  bank.enable_observations = template.enable_observations;
571
609
  bank.observations_mission = template.observations_mission;
572
610
  bank.retain_mission = template.retain_mission;
573
- bank.retain_extraction_mode = template.retain_extraction_mode;
611
+ bank.retain_extraction_mode = mode;
574
612
  }
575
613
  if (!isSet(current2.retain_default_strategy))
576
614
  bank.retain_default_strategy = template.retain_default_strategy;
577
615
  if (!isSet(current2.entities_allow_free_form))
578
616
  bank.entities_allow_free_form = template.entities_allow_free_form;
579
617
  const strategies = current2.retain_strategies && typeof current2.retain_strategies === "object" ? current2.retain_strategies : {};
580
- const missing = Object.entries(template.retain_strategies).filter(([n]) => !(n in strategies));
581
- if (missing.length > 0)
582
- bank.retain_strategies = { ...strategies, ...Object.fromEntries(missing) };
618
+ const updates = {};
619
+ for (const [name, def] of Object.entries(template.retain_strategies)) {
620
+ const synced = def.retain_extraction_mode === "custom" ? {} : { retain_extraction_mode: mode };
621
+ const have = strategies[name];
622
+ if (!have || typeof have !== "object") updates[name] = { ...def, ...synced };
623
+ else if ("retain_extraction_mode" in synced && have.retain_extraction_mode !== mode)
624
+ updates[name] = { ...have, ...synced };
625
+ }
626
+ if (Object.keys(updates).length > 0) bank.retain_strategies = { ...strategies, ...updates };
583
627
  const labels = Array.isArray(current2.entity_labels) ? current2.entity_labels : [];
584
628
  const [knowledgeGroup] = template.entity_labels;
585
629
  if (!labels.some((g) => g?.key === knowledgeGroup.key))
586
630
  bank.entity_labels = [...labels, knowledgeGroup];
631
+ for (const [key, value] of Object.entries(defaults)) {
632
+ if (PLUGIN_GOVERNED_BANK_FIELDS.includes(key) || !isSet(value) || isSet(current2[key])) continue;
633
+ bank[key] = value;
634
+ }
587
635
  return Object.keys(bank).length > 0 ? { version: "1", bank } : void 0;
588
636
  }
589
637
 
@@ -638,6 +686,15 @@ async function pool(items, n, fn, onError, onProgress) {
638
686
  }
639
687
  await Promise.all(Array.from({ length: Math.min(n, items.length) }, worker));
640
688
  }
689
+ function isOurMcpEntry(entry) {
690
+ if (!entry || typeof entry !== "object") return false;
691
+ const candidate = entry;
692
+ if (candidate.command !== "node" || !Array.isArray(candidate.args)) return false;
693
+ const script = candidate.args[0];
694
+ if (typeof script !== "string") return false;
695
+ const parts = script.replaceAll("\\", "/").split("/").filter(Boolean);
696
+ return parts.at(-1) === "mcp-server.js" && parts.at(-2) === "dist" && (parts.at(-3) === "coding-agents" || parts.at(-3) === "hindsight-coding-agents");
697
+ }
641
698
 
642
699
  // src/core/hindsight.ts
643
700
  function resolveRetainScopes(tags, configured) {
@@ -670,6 +727,14 @@ var KnowledgePagesUnavailableError = class extends Error {
670
727
  this.name = "KnowledgePagesUnavailableError";
671
728
  }
672
729
  };
730
+ async function isEndpointMissing(r) {
731
+ try {
732
+ const j = await r.json();
733
+ return String(j?.detail ?? "").trim().toLowerCase() === "not found";
734
+ } catch {
735
+ return true;
736
+ }
737
+ }
673
738
  var TERMINAL = /* @__PURE__ */ new Set(["completed", "failed", "cancelled", "error"]);
674
739
  var ReflectError = class extends Error {
675
740
  constructor(message, status, timedOut, options) {
@@ -688,9 +753,28 @@ var ReflectError = class extends Error {
688
753
  }
689
754
  };
690
755
  var DEFAULT_MAX_PARALLEL_RETAINS = 10;
756
+ var DEFAULT_PAGE_SEARCH_LIMIT = 10;
757
+ var DEFAULT_RECALL_OPTIONS = {
758
+ types: ["observation"],
759
+ budget: "low",
760
+ max_tokens: 2e3,
761
+ include: { entities: null }
762
+ };
691
763
  var POLL_CYCLE_MS = 5e3;
692
764
  var RETRY_AFTER_FLOOR_MS = 10 * 1e3;
693
765
  var RETRY_AFTER_CEILING_MS = 60 * 1e3;
766
+ function shapePage(page) {
767
+ const p = page ?? {};
768
+ const body = typeof p.body === "string" && p.body.trim() ? p.body : p.markdown;
769
+ return {
770
+ id: p.id,
771
+ name: p.name,
772
+ ...p.description ? { description: p.description } : {},
773
+ ...Array.isArray(p.tags) && p.tags.length ? { tags: p.tags } : {},
774
+ ...p.timestamp ? { last_updated_at: p.timestamp } : {},
775
+ body
776
+ };
777
+ }
694
778
  var HindsightClient = class {
695
779
  apiUrl;
696
780
  /** The credential the NEXT request will sign with — NOT the one the config file holds. The two
@@ -708,6 +792,8 @@ var HindsightClient = class {
708
792
  log;
709
793
  maxParallelRetains;
710
794
  observationScopes;
795
+ pageSearchLimit;
796
+ recallOptions;
711
797
  constructor(o) {
712
798
  this.apiUrl = o.apiUrl.replace(/\/$/, "");
713
799
  this.token = o.apiToken;
@@ -718,13 +804,18 @@ var HindsightClient = class {
718
804
  });
719
805
  this.maxParallelRetains = o.maxParallelRetains || DEFAULT_MAX_PARALLEL_RETAINS;
720
806
  this.observationScopes = o.observationScopes ?? DEFAULT_OBSERVATION_SCOPES;
807
+ this.pageSearchLimit = o.pageSearchLimit || DEFAULT_PAGE_SEARCH_LIMIT;
808
+ this.recallOptions = { ...DEFAULT_RECALL_OPTIONS, ...o.recallOptions };
721
809
  }
722
810
  /** The credential in use, for diagnostics. Never log or report the VALUE — booleans only. */
723
811
  get apiToken() {
724
812
  return this.token;
725
813
  }
726
814
  headers() {
727
- const h = { "Content-Type": "application/json" };
815
+ const h = {
816
+ "Content-Type": "application/json",
817
+ "Accept-Encoding": "identity"
818
+ };
728
819
  if (this.token) h["Authorization"] = `Bearer ${this.token}`;
729
820
  return h;
730
821
  }
@@ -832,6 +923,23 @@ var HindsightClient = class {
832
923
  return false;
833
924
  }
834
925
  }
926
+ /**
927
+ * Whether a session write-back may use `update_mode="append"`: the server must dedupe by
928
+ * `operation_id` AND the bank must keep document text, or the server rejects the append in the
929
+ * background (#4613). Only an explicit `store_document_text: false` answers "no" — an unreachable
930
+ * or unparseable config assumes the default (stored), so a flaky probe never downgrades appends.
931
+ */
932
+ async supportsAppendRetain() {
933
+ if (!await this.supportsIdempotentRetain()) return false;
934
+ try {
935
+ const r = await this.req("GET", this.bankUrl("/config"));
936
+ if (!r.ok) return true;
937
+ const j = await r.json();
938
+ return j.config?.store_document_text !== false;
939
+ } catch {
940
+ return true;
941
+ }
942
+ }
835
943
  /**
836
944
  * Every document_id currently in the bank under a strategy tag (e.g. `source:git`), paginated into a
837
945
  * Set. Powers the incremental git-sync's "what's already ingested?" check — since git commits are stored
@@ -857,9 +965,28 @@ var HindsightClient = class {
857
965
  }
858
966
  return ids;
859
967
  }
968
+ /**
969
+ * The tags on one document, or undefined when the bank holds none with that id. Read from the
970
+ * document LISTING narrowed by `q` (a substring match on the id, so the exact id is picked out of
971
+ * the page) rather than GET /documents/{id}, which also sends the document's full text: the
972
+ * caller, the git-log freshness check on SessionStart, reads a ~100k-character document for one tag.
973
+ */
974
+ async documentTags(documentId) {
975
+ const limit = 100;
976
+ for (let offset = 0; ; offset += limit) {
977
+ const q = `?q=${encodeURIComponent(documentId)}&limit=${limit}&offset=${offset}`;
978
+ const r = await this.req("GET", this.bankUrl(`/documents${q}`));
979
+ const j = await r.json();
980
+ const items = j.items ?? [];
981
+ const hit = items.find((it) => it.id === documentId);
982
+ if (hit) return hit.tags ?? [];
983
+ if (items.length < limit || offset + limit >= (j.total ?? 0)) return void 0;
984
+ }
985
+ }
860
986
  /** Configure the bank: POST the coding bank manifest to /import (missions, retain strategies,
861
987
  * entity labels), then seed knowledge pages when the server supports them. Both halves are
862
- * idempotent and strictly ADDITIVE — nothing the bank already says is overwritten (#3927) — so
988
+ * idempotent and ADDITIVE — nothing the bank already says is overwritten (#3927), bar the
989
+ * extraction mode of the plugin's own strategies, which follows its config (#4560) — so
863
990
  * the deepen engine can re-run this every pass. Creates the bank if missing; legacy servers
864
991
  * continue with the template-only path.
865
992
  *
@@ -875,7 +1002,11 @@ var HindsightClient = class {
875
1002
  if (opts.manage === false) {
876
1003
  this.log(`[bank] manageBankConfig: false \u2014 leaving ${this.bank}'s configuration alone`);
877
1004
  } else {
878
- const manifest = codingBankManifest(opts.reset ? void 0 : await this.readBankOverrides());
1005
+ const manifest = codingBankManifest(
1006
+ opts.reset ? void 0 : await this.readBankOverrides(),
1007
+ opts.extractionMode,
1008
+ opts.defaults
1009
+ );
879
1010
  if (!manifest) {
880
1011
  this.log(`[bank] ${this.bank} already carries the coding structure \u2014 nothing to apply`);
881
1012
  } else {
@@ -883,7 +1014,7 @@ var HindsightClient = class {
883
1014
  this.log(`[bank] applied to ${this.bank}: ${Object.keys(manifest.bank).sort().join(", ")}`);
884
1015
  }
885
1016
  }
886
- await this.seedPages(opts.pageTrigger);
1017
+ await this.seedPages(opts.pageTrigger, opts.pages, opts.customPages);
887
1018
  }
888
1019
  /**
889
1020
  * This bank's own config OVERRIDES, or undefined when there are none to read.
@@ -999,20 +1130,22 @@ var HindsightClient = class {
999
1130
  }
1000
1131
  }
1001
1132
  /**
1002
- * Raw recall restricted to consolidated observations — no LLM in the loop, so it still answers
1003
- * when reflect's synthesis times out or 5xxs. Returns the observation texts in rank order.
1133
+ * Raw recall with no LLM in the loop, so it still answers when reflect's synthesis times out or
1134
+ * 5xxs. The body is `recallOptions` (consolidated observations by default) — a bank that grows
1135
+ * no observations widens it rather than getting nothing back. Returns the texts in rank order.
1136
+ *
1137
+ * The name predates `recallOptions` (the observation type used to be hardcoded here) and is
1138
+ * kept deliberately: this is the client's published surface, so renaming it would break
1139
+ * importers for a cosmetic gain. The doc above is the contract, not the name.
1004
1140
  */
1005
1141
  async recallObservations(query, opts) {
1006
1142
  const r = await this.req(
1007
1143
  "POST",
1008
1144
  this.bankUrl("/memories/recall"),
1009
- {
1010
- query,
1011
- types: ["observation"],
1012
- budget: "low",
1013
- max_tokens: opts.maxTokens,
1014
- include: { entities: null }
1015
- },
1145
+ // `query` is applied AFTER the spread: everything else is the caller's to override, but a
1146
+ // config that could replace the goal with a fixed string would silently recall for the
1147
+ // wrong question on every turn.
1148
+ { ...this.recallOptions, query },
1016
1149
  [],
1017
1150
  opts.timeoutMs
1018
1151
  );
@@ -1020,6 +1153,19 @@ var HindsightClient = class {
1020
1153
  const j = await r.json();
1021
1154
  return (j.results ?? []).map((x) => (x.text ?? "").trim()).filter(Boolean);
1022
1155
  }
1156
+ /**
1157
+ * Latch `knowledgePagesSupported = false` iff this response really means the endpoint is absent.
1158
+ * Returns whether it latched. A bank-not-found 404 is NOT a capability verdict — it is the
1159
+ * expected answer before the bank's first retain — so it must never cache a negative (#4607).
1160
+ *
1161
+ * Only 404 is tested: `req` throws on every other non-ok status it was not told to tolerate, so
1162
+ * the 405/501 this used to check for never reach a caller in the first place.
1163
+ */
1164
+ async pagesUnsupported(r) {
1165
+ if (r.status !== 404 || !await isEndpointMissing(r)) return false;
1166
+ this.knowledgePagesSupported = false;
1167
+ return true;
1168
+ }
1023
1169
  /**
1024
1170
  * The bank's knowledge-base tree (folders + pages, nested). The tree carries names, source
1025
1171
  * queries and staleness but NOT synthesized content, so it is cheap enough to poll.
@@ -1027,10 +1173,8 @@ var HindsightClient = class {
1027
1173
  async tree() {
1028
1174
  if (this.knowledgePagesSupported === false) throw new KnowledgePagesUnavailableError();
1029
1175
  const r = await this.req("GET", this.bankUrl("/knowledge-base/tree"));
1030
- if ([404, 405, 501].includes(r.status)) {
1031
- this.knowledgePagesSupported = false;
1032
- throw new KnowledgePagesUnavailableError();
1033
- }
1176
+ if (await this.pagesUnsupported(r)) throw new KnowledgePagesUnavailableError();
1177
+ if (r.status === 404) return [];
1034
1178
  this.knowledgePagesSupported = true;
1035
1179
  try {
1036
1180
  return (await r.json()).roots ?? [];
@@ -1067,8 +1211,8 @@ var HindsightClient = class {
1067
1211
  return { items };
1068
1212
  }
1069
1213
  /**
1070
- * Read one knowledge page's synthesized content by knowledge-base id, as an OKF document
1071
- * (YAML frontmatter + markdown body). The endpoint omits the internal reflect trace that built
1214
+ * Read one knowledge page's synthesized content by knowledge-base id, shaped by `shapePage` so
1215
+ * the body arrives once. The endpoint omits the internal reflect trace that built
1072
1216
  * the page — that is 70-95% of the raw bytes and can blow past an MCP host's per-tool-result
1073
1217
  * token cap.
1074
1218
  */
@@ -1079,25 +1223,28 @@ var HindsightClient = class {
1079
1223
  this.bankUrl(`/knowledge-base/pages/${encodeURIComponent(pageId)}`)
1080
1224
  );
1081
1225
  if (r.status === 404) throw new Error(`knowledge page not found: ${pageId}`);
1082
- return await r.json();
1226
+ return shapePage(await r.json());
1083
1227
  }
1084
1228
  /** Hybrid (BM25 + vector, RRF-fused) server-side search over the bank's knowledge pages.
1085
1229
  * Returns page-level hits with a relevance snippet — the real search behind
1086
1230
  * hindsight_search_knowledge_pages. */
1087
- async searchKnowledgePages(query, limit = 3, timeoutMs) {
1231
+ async searchKnowledgePages(query, opts = {}) {
1088
1232
  if (this.knowledgePagesSupported === false) throw new KnowledgePagesUnavailableError();
1089
- const q = `?q=${encodeURIComponent(query)}&limit=${limit}`;
1233
+ const q = `?q=${encodeURIComponent(query)}&limit=${opts.limit ?? this.pageSearchLimit}`;
1090
1234
  const r = await this.req(
1091
1235
  "GET",
1092
1236
  this.bankUrl(`/knowledge-base/search${q}`),
1093
1237
  void 0,
1094
1238
  [],
1095
- timeoutMs
1239
+ opts.timeoutMs
1096
1240
  );
1241
+ if (await this.pagesUnsupported(r)) throw new KnowledgePagesUnavailableError();
1242
+ if (r.status === 404) return [];
1097
1243
  const j = await r.json();
1098
1244
  return (j.results ?? []).map((x) => ({
1099
1245
  id: x.id,
1100
1246
  name: x.name,
1247
+ ...x.source_query ? { source_query: x.source_query } : {},
1101
1248
  snippet: x.snippet ?? "",
1102
1249
  score: x.score ?? 0
1103
1250
  }));
@@ -1113,8 +1260,8 @@ var HindsightClient = class {
1113
1260
  * `source_query` re-syncs onto the live page instead of orphaning its synthesized content —
1114
1261
  * which is how `pageScopeRule`'s repo name reaches banks seeded by an earlier version.
1115
1262
  */
1116
- async seedPages(pageTrigger = buildPageTrigger()) {
1117
- const pages = pagesFor(this.project ?? this.bank);
1263
+ async seedPages(pageTrigger = buildPageTrigger(), pagesConfig = {}, customPages = {}) {
1264
+ const pages = pagesFor(this.project ?? this.bank, pagesConfig, customPages);
1118
1265
  const existing = /* @__PURE__ */ new Map();
1119
1266
  let roots;
1120
1267
  try {
@@ -1131,6 +1278,7 @@ var HindsightClient = class {
1131
1278
  }
1132
1279
  let created = 0;
1133
1280
  let updated = 0;
1281
+ let vanished = 0;
1134
1282
  for (const page of pages) {
1135
1283
  const hit = existing.get(page.name.toLowerCase());
1136
1284
  const body = {
@@ -1144,13 +1292,16 @@ var HindsightClient = class {
1144
1292
  };
1145
1293
  if (!hit) {
1146
1294
  const r = await this.req("POST", this.bankUrl("/knowledge-base/pages"), body, [409]);
1147
- if ([404, 405, 501].includes(r.status)) {
1148
- this.knowledgePagesSupported = false;
1295
+ if (await this.pagesUnsupported(r)) {
1149
1296
  this.log(
1150
1297
  `[bank] knowledge pages unavailable on ${this.apiUrl}; continuing without pages`
1151
1298
  );
1152
1299
  return;
1153
1300
  }
1301
+ if (r.status === 404) {
1302
+ this.log(`[bank] ${this.bank} does not exist yet; pages seed on the next session`);
1303
+ return;
1304
+ }
1154
1305
  if (r.status !== 409) created++;
1155
1306
  } else {
1156
1307
  const sourceDrift = hit.description !== page.source_query;
@@ -1160,6 +1311,9 @@ var HindsightClient = class {
1160
1311
  if (sourceDrift) {
1161
1312
  patch.source_query = page.source_query;
1162
1313
  patch.tags = page.tags;
1314
+ this.log(
1315
+ `[bank] re-syncing "${page.name}" to its configured source_query \u2014 set pages[${JSON.stringify(page.name)}].source_query to keep your own wording`
1316
+ );
1163
1317
  }
1164
1318
  if (triggerDrift) patch.trigger = pageTriggerPatch(body.trigger);
1165
1319
  const r = await this.req(
@@ -1167,19 +1321,22 @@ var HindsightClient = class {
1167
1321
  this.bankUrl(`/knowledge-base/nodes/${encodeURIComponent(hit.id)}`),
1168
1322
  patch
1169
1323
  );
1170
- if ([404, 405, 501].includes(r.status)) {
1171
- this.knowledgePagesSupported = false;
1324
+ if (await this.pagesUnsupported(r)) {
1172
1325
  this.log(
1173
1326
  `[bank] knowledge pages unavailable on ${this.apiUrl}; continuing without pages`
1174
1327
  );
1175
1328
  return;
1176
1329
  }
1330
+ if (r.status === 404) {
1331
+ vanished++;
1332
+ continue;
1333
+ }
1177
1334
  updated++;
1178
1335
  }
1179
1336
  }
1180
1337
  const initiatives = await this.resyncInitiativeTriggers(roots, pageTrigger);
1181
1338
  this.log(
1182
- `[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` : "")
1339
+ `[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` : "")
1183
1340
  );
1184
1341
  }
1185
1342
  /**
@@ -1208,7 +1365,7 @@ var HindsightClient = class {
1208
1365
  this.bankUrl(`/knowledge-base/nodes/${encodeURIComponent(page.id)}`),
1209
1366
  { trigger: pageTriggerPatch(desired) }
1210
1367
  );
1211
- if ([404, 405, 501].includes(r.status)) break;
1368
+ if (r.status === 404) continue;
1212
1369
  updated++;
1213
1370
  }
1214
1371
  return updated;
@@ -1300,7 +1457,65 @@ function resolvePageTrigger(raw) {
1300
1457
  );
1301
1458
  return { type: "cron", cron: DEFAULT_PAGE_TRIGGER_CRON };
1302
1459
  }
1460
+ function resolvePages(raw) {
1461
+ const value = raw;
1462
+ if (!value || typeof value !== "object" || Array.isArray(value)) return {};
1463
+ const out = {};
1464
+ for (const [name, entry] of Object.entries(value)) {
1465
+ if (!PAGE_NAMES.some((known) => known.toLowerCase() === name.trim().toLowerCase())) {
1466
+ log.warn(
1467
+ "config",
1468
+ `ignoring pages[${JSON.stringify(name)}] \u2014 no seeded page has that name; expected one of: ${PAGE_NAMES.join(", ")}`
1469
+ );
1470
+ continue;
1471
+ }
1472
+ if (entry === false) {
1473
+ out[name] = false;
1474
+ continue;
1475
+ }
1476
+ const query = entry && typeof entry === "object" && !Array.isArray(entry) ? entry.source_query : void 0;
1477
+ if (typeof query === "string" && query.trim()) {
1478
+ out[name] = { source_query: query };
1479
+ continue;
1480
+ }
1481
+ log.warn(
1482
+ "config",
1483
+ `ignoring pages[${JSON.stringify(name)}]=${JSON.stringify(entry)} \u2014 expected false, or {"source_query": "<your question>"}`
1484
+ );
1485
+ }
1486
+ return out;
1487
+ }
1488
+ function resolveCustomPages(raw) {
1489
+ const value = raw;
1490
+ if (!value || typeof value !== "object" || Array.isArray(value)) return {};
1491
+ const out = {};
1492
+ for (const [rawName, entry] of Object.entries(value)) {
1493
+ const name = rawName.trim();
1494
+ if (!name) continue;
1495
+ if (PAGE_NAMES.some((known) => known.toLowerCase() === name.toLowerCase())) {
1496
+ log.warn(
1497
+ "config",
1498
+ `ignoring customPages[${JSON.stringify(rawName)}] \u2014 that is a seeded page; reword it under \`pages\` instead`
1499
+ );
1500
+ continue;
1501
+ }
1502
+ const query = entry && typeof entry === "object" && !Array.isArray(entry) ? entry.source_query : void 0;
1503
+ if (typeof query !== "string" || !query.trim()) {
1504
+ log.warn(
1505
+ "config",
1506
+ `ignoring customPages[${JSON.stringify(rawName)}]=${JSON.stringify(entry)} \u2014 expected {"source_query": "<your question>"}`
1507
+ );
1508
+ continue;
1509
+ }
1510
+ const rawTags = entry.tags;
1511
+ const tags = Array.isArray(rawTags) ? rawTags.filter((t) => typeof t === "string" && t.trim() !== "") : [];
1512
+ out[name] = tags.length ? { source_query: query, tags } : { source_query: query };
1513
+ }
1514
+ return out;
1515
+ }
1516
+ var DEFAULT_REFLECT_TIMEOUT_MS = 2e4;
1303
1517
  var DEFAULT_REFLECT_TOOL_TIMEOUT_MS = 33e4;
1518
+ var DEFAULT_INJECT_TIMEOUT_MS = 7e3;
1304
1519
  var REFLECT_BUDGETS = ["low", "mid", "high"];
1305
1520
  function resolveReflectBudget(raw) {
1306
1521
  const value = raw.reflectBudget;
@@ -1327,6 +1542,31 @@ function resolveObservationScopes(raw) {
1327
1542
  }
1328
1543
  return DEFAULT_OBSERVATION_SCOPES;
1329
1544
  }
1545
+ function resolveDefaultBankConfig(raw) {
1546
+ const value = raw;
1547
+ if (!value || typeof value !== "object" || Array.isArray(value)) return {};
1548
+ const out = {};
1549
+ for (const [key, v] of Object.entries(value)) {
1550
+ if (PLUGIN_GOVERNED_BANK_FIELDS.includes(key)) {
1551
+ log.warn(
1552
+ "config",
1553
+ `ignoring defaultBankConfig.${key} \u2014 the plugin manages this field itself` + (key === "retain_extraction_mode" ? " (set retainExtractionMode instead)" : "")
1554
+ );
1555
+ continue;
1556
+ }
1557
+ out[key] = v;
1558
+ }
1559
+ return out;
1560
+ }
1561
+ var AUTO_INJECT_MODES = ["reflect", "pages", "recall", "none"];
1562
+ function resolveAutoInject(raw) {
1563
+ if (raw.autoReflect !== void 0) {
1564
+ const replacement = raw.autoReflect === false ? "none" : "reflect";
1565
+ log.warn("config", `autoReflect is deprecated \u2014 use autoInject: "${replacement}" instead`);
1566
+ }
1567
+ if (AUTO_INJECT_MODES.includes(raw.autoInject)) return raw.autoInject;
1568
+ return raw.autoReflect === false ? "none" : "reflect";
1569
+ }
1330
1570
  function resolveConfig(raw = {}) {
1331
1571
  const serverMode = ["cloud", "self-hosted", "daemon"].includes(raw.serverMode) ? raw.serverMode : "cloud";
1332
1572
  const apiPort = raw.apiPort || DEFAULT_DAEMON_PORT;
@@ -1356,17 +1596,31 @@ function resolveConfig(raw = {}) {
1356
1596
  retainSessions: raw.retainSessions ?? true,
1357
1597
  // write sessions back by default, every harness
1358
1598
  manageBankConfig: raw.manageBankConfig ?? true,
1599
+ retainExtractionMode: RETAIN_EXTRACTION_MODES.includes(raw.retainExtractionMode) ? raw.retainExtractionMode : DEFAULT_RETAIN_EXTRACTION_MODE,
1600
+ defaultBankConfig: resolveDefaultBankConfig(raw.defaultBankConfig),
1359
1601
  maxParallelRetains: raw.maxParallelRetains || 10,
1360
- reflectTimeoutMs: raw.reflectTimeoutMs || 12e4,
1602
+ reflectTimeoutMs: raw.reflectTimeoutMs || DEFAULT_REFLECT_TIMEOUT_MS,
1361
1603
  // Inherit an explicitly-raised reflectTimeoutMs (that is what users reaching for a longer
1362
1604
  // reflect already set), but never let it LOWER the tool below the default — a short window is
1363
1605
  // set to bound the automatic hook, not to cut off a call the agent is waiting on.
1364
1606
  reflectToolTimeoutMs: raw.reflectToolTimeoutMs || Math.max(raw.reflectTimeoutMs || 0, DEFAULT_REFLECT_TOOL_TIMEOUT_MS),
1607
+ injectTimeoutMs: raw.injectTimeoutMs || DEFAULT_INJECT_TIMEOUT_MS,
1365
1608
  reflectBudget: resolveReflectBudget(raw),
1366
- autoReflect: raw.autoReflect ?? true,
1367
- pageRefreshEveryTurns: raw.pageRefreshEveryTurns || 10,
1609
+ autoInject: resolveAutoInject(raw),
1610
+ pageSearchLimit: raw.pageSearchLimit || DEFAULT_PAGE_SEARCH_LIMIT,
1611
+ // Same shape as retainMetadata: an object, or nothing. An array would spread into numeric
1612
+ // keys and reach the API as garbage, so it is rejected like any other non-object.
1613
+ recallOptions: raw.recallOptions && typeof raw.recallOptions === "object" && !Array.isArray(raw.recallOptions) ? { ...raw.recallOptions } : {},
1614
+ toolGuideExtra: typeof raw.toolGuideExtra === "string" && raw.toolGuideExtra.trim() ? raw.toolGuideExtra : void 0,
1615
+ // Every turn, not every tenth. The guide is what tells the agent WHEN to reach for memory, and
1616
+ // at a cadence of 10 a normal session is told once, on turn 1, and never again. Measured over
1617
+ // 40 real Claude Code turns, moving this from 10 to 1 took searches from 15% of turns to 32.5%
1618
+ // with no wording change at all. The cost is the guide's ~2KB re-sent per turn, which caches.
1619
+ pageRefreshEveryTurns: raw.pageRefreshEveryTurns || 1,
1368
1620
  pageTriggerType: pageTrigger.type,
1369
1621
  pageTriggerCron: pageTrigger.cron,
1622
+ pages: resolvePages(raw.pages),
1623
+ customPages: resolveCustomPages(raw.customPages),
1370
1624
  autoSeed: raw.autoSeed ?? true,
1371
1625
  seedLimit: raw.seedLimit || DEFAULT_SEED_LIMIT,
1372
1626
  codebaseSurvey: raw.codebaseSurvey ?? true,
@@ -1377,11 +1631,15 @@ function resolveConfig(raw = {}) {
1377
1631
  // Hostile input is a config typo, not an attack: keep only string entries so a stray number or
1378
1632
  // nested object cannot reach the API as a tag and fail the whole retain.
1379
1633
  retainTags: Array.isArray(raw.retainTags) ? raw.retainTags.filter((t) => typeof t === "string" && t.trim() !== "") : [],
1634
+ // Undefined, not "", when unset or blank: the retain call distinguishes "not configured" (use
1635
+ // the built-in default) from a configured value, and an empty context would strip the default.
1636
+ retainContext: typeof raw.retainContext === "string" && raw.retainContext.trim() !== "" ? raw.retainContext : void 0,
1380
1637
  retainMetadata: raw.retainMetadata && typeof raw.retainMetadata === "object" ? Object.fromEntries(
1381
1638
  Object.entries(raw.retainMetadata).filter(([, v]) => typeof v === "string")
1382
1639
  ) : {},
1383
1640
  observationScopes: resolveObservationScopes(raw.observationScopes),
1384
1641
  banks: raw.banks && typeof raw.banks === "object" ? raw.banks : {},
1642
+ paths: raw.paths && typeof raw.paths === "object" ? raw.paths : {},
1385
1643
  logLevel: ["debug", "info", "warn", "error"].includes(raw.logLevel) ? raw.logLevel : "info",
1386
1644
  autoUpdate: raw.autoUpdate ?? true
1387
1645
  };
@@ -1398,7 +1656,12 @@ function readRaw(path) {
1398
1656
  }
1399
1657
  function mergeRaw(a, b) {
1400
1658
  const { harnesses: _drop, ...flat } = b;
1401
- return { ...a, ...flat, banks: { ...a.banks ?? {}, ...b.banks ?? {} } };
1659
+ return {
1660
+ ...a,
1661
+ ...flat,
1662
+ banks: { ...a.banks ?? {}, ...b.banks ?? {} },
1663
+ paths: { ...a.paths ?? {}, ...b.paths ?? {} }
1664
+ };
1402
1665
  }
1403
1666
  function applyLayer(raw, layer, harness) {
1404
1667
  let out = mergeRaw(raw, layer);
@@ -1429,7 +1692,11 @@ var ENV_KEYS = {
1429
1692
  maxParallelRetains: "HINDSIGHT_MAX_PARALLEL_RETAINS",
1430
1693
  reflectTimeoutMs: "HINDSIGHT_REFLECT_TIMEOUT_MS",
1431
1694
  reflectToolTimeoutMs: "HINDSIGHT_REFLECT_TOOL_TIMEOUT_MS",
1695
+ injectTimeoutMs: "HINDSIGHT_INJECT_TIMEOUT_MS",
1432
1696
  reflectBudget: "HINDSIGHT_REFLECT_BUDGET",
1697
+ autoInject: "HINDSIGHT_AUTO_INJECT",
1698
+ pageSearchLimit: "HINDSIGHT_PAGE_SEARCH_LIMIT",
1699
+ toolGuideExtra: "HINDSIGHT_TOOL_GUIDE_EXTRA",
1433
1700
  autoReflect: "HINDSIGHT_AUTO_REFLECT",
1434
1701
  pageRefreshEveryTurns: "HINDSIGHT_PAGE_REFRESH_EVERY_TURNS",
1435
1702
  pageTriggerType: "HINDSIGHT_PAGE_TRIGGER_TYPE",
@@ -1449,7 +1716,8 @@ var ENV_KEYS = {
1449
1716
  // Comma-separated, e.g. HINDSIGHT_RETAIN_TAGS="project:{gitProject},env:work". A LIST rather than
1450
1717
  // a map, so it flattens cleanly; its sibling retainMetadata stays file-only for the reason above.
1451
1718
  retainTags: "HINDSIGHT_RETAIN_TAGS",
1452
- manageBankConfig: "HINDSIGHT_MANAGE_BANK_CONFIG"
1719
+ manageBankConfig: "HINDSIGHT_MANAGE_BANK_CONFIG",
1720
+ retainExtractionMode: "HINDSIGHT_RETAIN_EXTRACTION_MODE"
1453
1721
  };
1454
1722
  var ENV_BOOLEANS = /* @__PURE__ */ new Set([
1455
1723
  "dynamicBankId",
@@ -1470,6 +1738,8 @@ var ENV_NUMBERS = /* @__PURE__ */ new Set([
1470
1738
  "maxParallelRetains",
1471
1739
  "reflectTimeoutMs",
1472
1740
  "reflectToolTimeoutMs",
1741
+ "injectTimeoutMs",
1742
+ "pageSearchLimit",
1473
1743
  "pageRefreshEveryTurns",
1474
1744
  "seedLimit",
1475
1745
  "surveyBudgetUsd",
@@ -1517,15 +1787,25 @@ var BANK_OVERRIDE_EXCLUDED = [
1517
1787
  function applyBankConfig(cfg, resolvedId, directory) {
1518
1788
  if (directory !== void 0 && !isOptedIn(cfg, directory))
1519
1789
  return { cfg: { ...cfg, disabled: true }, bankId: resolvedId };
1790
+ const byPath = directory === void 0 ? void 0 : pathSection(cfg, cfg.paths, directory);
1791
+ if (byPath) {
1792
+ const { bank: _rename, ...rest } = overrideFields(byPath);
1793
+ cfg = { ...cfg, ...resolvePartial(cfg, rest) };
1794
+ }
1520
1795
  const section = cfg.banks[resolvedId];
1521
1796
  if (!section) return { cfg, bankId: resolvedId };
1522
- const safe = { ...section };
1523
- for (const k of BANK_OVERRIDE_EXCLUDED) delete safe[k];
1524
- delete safe.banks;
1797
+ const safe = overrideFields(section);
1525
1798
  const bankId = typeof safe.bank === "string" && safe.bank ? safe.bank : resolvedId;
1526
1799
  delete safe.bank;
1527
1800
  return { cfg: { ...cfg, ...resolvePartial(cfg, safe) }, bankId };
1528
1801
  }
1802
+ function overrideFields(section) {
1803
+ const safe = { ...section };
1804
+ for (const k of BANK_OVERRIDE_EXCLUDED) delete safe[k];
1805
+ delete safe.banks;
1806
+ delete safe.paths;
1807
+ return safe;
1808
+ }
1529
1809
  function resolvePartial(cfg, patch) {
1530
1810
  const full = resolveConfig(patch);
1531
1811
  const out = {};
@@ -1533,6 +1813,17 @@ function resolvePartial(cfg, patch) {
1533
1813
  if (key in full)
1534
1814
  out[key] = full[key];
1535
1815
  }
1816
+ if ("autoReflect" in patch && !("autoInject" in patch)) out.autoInject = full.autoInject;
1817
+ if ("serverMode" in patch || "apiUrl" in patch || "apiPort" in patch) {
1818
+ const conn = resolveConfig({
1819
+ serverMode: patch.serverMode ?? cfg.serverMode,
1820
+ apiPort: patch.apiPort ?? cfg.apiPort,
1821
+ apiUrl: patch.apiUrl ?? (cfg.serverMode === "daemon" ? void 0 : cfg.apiUrl)
1822
+ });
1823
+ out.serverMode = conn.serverMode;
1824
+ out.apiUrl = conn.apiUrl;
1825
+ out.apiPort = conn.apiPort;
1826
+ }
1536
1827
  return out;
1537
1828
  }
1538
1829
 
@@ -1562,21 +1853,31 @@ function parsePageList(raw) {
1562
1853
  }
1563
1854
  return out;
1564
1855
  }
1565
- function roster(pages) {
1566
- return pages.map((p) => `- ${p.title} (${p.id})`).join("\n");
1567
- }
1568
- var TOOL_GUIDE = `- hindsight_search_knowledge_pages(query) \u2014 FIRST STOP for any question the project's accumulated knowledge might answer (components, conventions, past decisions, initiatives): search the knowledge pages and credit results visibly with a markdown blockquote so it renders as a callout, exactly: "> \u{1F9E0} **From Hindsight memory (<page>)** \u2014 <the specific facts you drew on>".
1856
+ var EMPTY_STATE = "No knowledge pages yet \u2014 Hindsight is still learning this repo; they'll appear as it processes.";
1857
+ function indexLine(pages) {
1858
+ const count = pages.length === 1 ? "1 knowledge page covers" : `${pages.length} knowledge pages cover`;
1859
+ return `${count} this repository \u2014 architecture, conventions, past decisions and in-flight initiatives. They are deliberately NOT listed here: call hindsight_search_knowledge_pages(query) to find the ones that bear on the current turn, then hindsight_read_knowledge_page(<id>) on anything the results show is worth reading in full.`;
1860
+ }
1861
+ var TOOL_GUIDE = `- hindsight_search_knowledge_pages(query) \u2014 FIRST STOP, and the way IN to everything below. The code shows what is true today but not what was decided or why; memory shows what was decided or said back then but not whether it still holds. Work built from either alone goes wrong: from code alone it quietly re-litigates settled questions, from memory alone it acts on stale claims. Search BEFORE you act whenever the turn is one of these \u2014 they are the ones that go wrong silently:
1862
+ \u2022 the user reports a bug or a wrong response (the intended behaviour, and the status code or value it should return, may already have been decided);
1863
+ \u2022 you are about to write or change a test (what this project expects a change to ship with, and how it asserts, is a convention, not a preference);
1864
+ \u2022 you are implementing something new, or two parts have to fit together;
1865
+ \u2022 the user asks why something is the way it is, or what is left to do;
1866
+ \u2022 you are about to commit, and need to know what the change was supposed to honour.
1867
+ It ranks the pages by relevance and returns the matching passage, which a page title cannot tell you. What it returns is a past record, not a live reading: a claim that something was fixed, passes, or works is what someone said then \u2014 check it against the code before you rely on it, and say so when the two disagree.
1868
+ CREDITING IS NOT OPTIONAL AND NOT A JUDGEMENT CALL. If you called this tool and anything it returned reached your reply \u2014 quoted, paraphrased, or merely confirming what you were about to say \u2014 open that part with a markdown blockquote, exactly: "> \u{1F9E0} **From Hindsight memory (<page>)** \u2014 <the specific facts you drew on>". Rewriting a snippet in your own words does not make it yours. A search that turned up nothing useful needs no mention at all \u2014 just carry on.
1569
1869
  - hindsight_list_knowledge_pages / hindsight_read_knowledge_page \u2014 BEFORE substantial work, list the pages and read the relevant ones to ground yourself in this repo's architecture, conventions, and past decisions instead of re-deriving them from the code; follow any [[page:<id>]] links you see.
1570
1870
  - hindsight_reflect(query) \u2014 when pages are too shallow and you need the WHY: deep reasoning over the repo's full memory for the past decision and exact values that explain a behavior or bug (slower \u2014 use deliberately, and credit results with a blockquote header "> \u{1F9E0} **From Hindsight memory** \u2014 <summary>").
1571
1871
  - hindsight_capture_initiative(title, summary) \u2014 right after the user approves a plan or finishes brainstorming a new feature/capability and you are about to start implementing (BEFORE you write any code), call this to record it as a tracked page; then call it AGAIN with relates_to_page_id set to that page whenever the goal, scope, or rationale materially changes mid-work, so the page tracks the current plan and not the opening one. Skip bug fixes, small tweaks, chores, and trivial course-corrections.
1572
1872
  - hindsight_ingest_document(title, content) \u2014 save an external document or durable notes/findings you want remembered (not the current conversation \u2014 that is captured automatically at session end).`;
1573
1873
  var PAGES_FIRST_ON_GOALS = "- The user just set a NEW task or goal \u2192 search the knowledge pages FIRST with hindsight_search_knowledge_pages. No synthesis is injected automatically in this configuration; call hindsight_reflect only when those pages are too shallow and deeper reasoning is needed.\n";
1574
1874
  function toolGuide(opts) {
1575
- return (opts?.reflectOnNewGoals ? PAGES_FIRST_ON_GOALS : "") + TOOL_GUIDE;
1875
+ const extra = opts?.extra?.trim();
1876
+ return (opts?.reflectOnNewGoals ? PAGES_FIRST_ON_GOALS : "") + TOOL_GUIDE + (extra ? `
1877
+ ${extra}` : "");
1576
1878
  }
1577
1879
  function buildKnowledgePreamble(pages, opts) {
1578
- const body = pages.length ? `Knowledge pages currently in this repository:
1579
- ${roster(pages)}` : "No knowledge pages yet \u2014 Hindsight is still learning this repo; they'll appear as it processes.";
1880
+ const body = pages.length ? indexLine(pages) : EMPTY_STATE;
1580
1881
  return `<hindsight_knowledge>
1581
1882
  This repository has a Hindsight memory + knowledge base (curated, continuously-updated pages plus the raw memory behind them). The tools below are registered, but you must actually CALL them at the right moments:
1582
1883
  ${toolGuide(opts)}
@@ -1774,12 +2075,46 @@ function startDaemonDetached(cfg, harness, spawnFn = realSpawn2) {
1774
2075
  } catch {
1775
2076
  }
1776
2077
  }
2078
+ var coldStarts = /* @__PURE__ */ new Map();
2079
+ async function waitBounded(p, ms) {
2080
+ let timer;
2081
+ try {
2082
+ await Promise.race([
2083
+ p,
2084
+ new Promise((resolve3) => {
2085
+ timer = setTimeout(resolve3, Math.max(ms, 0));
2086
+ })
2087
+ ]);
2088
+ } finally {
2089
+ clearTimeout(timer);
2090
+ }
2091
+ }
1777
2092
  async function ensureDaemon(cfg, harness, opts = {}) {
1778
2093
  if (cfg.serverMode !== "daemon") return;
1779
2094
  if (await isServerHealthy(cfg.apiUrl)) return;
1780
2095
  if (!preflightDaemon(cfg, harness)) return;
1781
- startDaemonDetached(cfg, harness, opts.spawnFn);
1782
- await waitForHealth(cfg.apiUrl, opts.waitMs ?? 0);
2096
+ const waitMs = opts.waitMs ?? 0;
2097
+ const running = coldStarts.get(cfg.apiUrl);
2098
+ if (running) {
2099
+ const startedAt = Date.now();
2100
+ await waitBounded(
2101
+ running.catch(() => void 0),
2102
+ waitMs
2103
+ );
2104
+ const remaining = waitMs - (Date.now() - startedAt);
2105
+ if (remaining > 0) await waitForHealth(cfg.apiUrl, remaining);
2106
+ return;
2107
+ }
2108
+ const attempt = (async () => {
2109
+ startDaemonDetached(cfg, harness, opts.spawnFn);
2110
+ await waitForHealth(cfg.apiUrl, waitMs);
2111
+ })();
2112
+ coldStarts.set(cfg.apiUrl, attempt);
2113
+ try {
2114
+ await attempt;
2115
+ } finally {
2116
+ if (coldStarts.get(cfg.apiUrl) === attempt) coldStarts.delete(cfg.apiUrl);
2117
+ }
1783
2118
  }
1784
2119
  async function waitForHealth(baseUrl, budgetMs, pollMs = 1e3) {
1785
2120
  const deadline = Date.now() + budgetMs;
@@ -1834,7 +2169,8 @@ function resolversFor(ctx) {
1834
2169
  function buildRetainStamp(cfg, ctx) {
1835
2170
  const hasTags = Boolean(cfg.retainTags?.length);
1836
2171
  const hasMetadata = Boolean(cfg.retainMetadata && Object.keys(cfg.retainMetadata).length);
1837
- if (!hasTags && !hasMetadata) return { tags: [], metadata: {} };
2172
+ const hasContext = Boolean(cfg.retainContext?.trim());
2173
+ if (!hasTags && !hasMetadata && !hasContext) return { tags: [], metadata: {} };
1838
2174
  const base = resolversFor(ctx);
1839
2175
  const cache = /* @__PURE__ */ new Map();
1840
2176
  const resolvers = Object.fromEntries(
@@ -1858,35 +2194,15 @@ function buildRetainStamp(cfg, ctx) {
1858
2194
  for (const [key, value] of Object.entries(cfg.retainMetadata ?? {})) {
1859
2195
  metadata[key] = applyTemplate(value, resolvers, "retainMetadata");
1860
2196
  }
1861
- return { tags, metadata };
2197
+ const context = hasContext ? applyTemplate(cfg.retainContext, resolvers, "retainContext").trim() || void 0 : void 0;
2198
+ return { tags, metadata, context };
1862
2199
  }
1863
2200
 
1864
2201
  // src/core/jsonl.ts
1865
- import { closeSync, openSync, readSync, statSync as statSync3 } from "fs";
2202
+ import { closeSync, openSync, readSync } from "fs";
1866
2203
  import { StringDecoder } from "string_decoder";
1867
2204
  var CHUNK_BYTES = 64 * 1024;
1868
- var MAX_TRANSCRIPT_BYTES = 32 * 1024 * 1024;
1869
- function readJsonlTail(path, opts) {
1870
- const maxBytes = opts.maxBytes ?? MAX_TRANSCRIPT_BYTES;
1871
- let size;
1872
- try {
1873
- size = statSync3(path).size;
1874
- } catch {
1875
- return { lines: emptyLines(), skippedBytes: 0 };
1876
- }
1877
- const skippedBytes = size > maxBytes ? size - maxBytes : 0;
1878
- if (skippedBytes > 0) {
1879
- log.warn(opts.scope, "transcript too large \u2014 retaining the most recent portion only", {
1880
- path,
1881
- sizeBytes: size,
1882
- skippedBytes
1883
- });
1884
- }
1885
- return { lines: streamLines(path, skippedBytes), skippedBytes };
1886
- }
1887
- function* emptyLines() {
1888
- }
1889
- function* streamLines(path, start) {
2205
+ function* readJsonl(path) {
1890
2206
  let fd;
1891
2207
  try {
1892
2208
  fd = openSync(path, "r");
@@ -1897,8 +2213,7 @@ function* streamLines(path, start) {
1897
2213
  const buffer = Buffer.allocUnsafe(CHUNK_BYTES);
1898
2214
  const decoder = new StringDecoder("utf8");
1899
2215
  let pending = "";
1900
- let position = start > 0 ? start - 1 : 0;
1901
- let dropPartial = start > 0;
2216
+ let position = 0;
1902
2217
  for (; ; ) {
1903
2218
  const bytesRead = readSync(fd, buffer, 0, buffer.length, position);
1904
2219
  if (bytesRead <= 0) break;
@@ -1906,17 +2221,12 @@ function* streamLines(path, start) {
1906
2221
  pending += decoder.write(buffer.subarray(0, bytesRead));
1907
2222
  let newline;
1908
2223
  while ((newline = pending.indexOf("\n")) !== -1) {
1909
- const line = pending.slice(0, newline);
2224
+ yield pending.slice(0, newline);
1910
2225
  pending = pending.slice(newline + 1);
1911
- if (dropPartial) {
1912
- dropPartial = false;
1913
- continue;
1914
- }
1915
- yield line;
1916
2226
  }
1917
2227
  }
1918
2228
  pending += decoder.end();
1919
- if (pending && !dropPartial) yield pending;
2229
+ if (pending) yield pending;
1920
2230
  } finally {
1921
2231
  closeSync(fd);
1922
2232
  }
@@ -1932,11 +2242,15 @@ import { readFileSync as readFileSync11 } from "fs";
1932
2242
  // src/core/git.ts
1933
2243
  import { execFileSync as execFileSync2 } from "child_process";
1934
2244
  import { resolve as resolve2 } from "path";
2245
+ var GITLOG_HEAD = "gitlog-head:";
1935
2246
  function git(repo, ...args) {
1936
2247
  return execFileSync2("git", ["-C", repo, ...args], {
1937
2248
  encoding: "utf8",
1938
2249
  maxBuffer: 1 << 28,
1939
- windowsHide: true
2250
+ windowsHide: true,
2251
+ // execFileSync otherwise forwards failed git stderr into the host's TUI,
2252
+ // even when callers catch the error. Keep diagnostics on the error instead.
2253
+ stdio: ["ignore", "pipe", "pipe"]
1940
2254
  });
1941
2255
  }
1942
2256
  function repoNameOf(repo) {
@@ -1950,6 +2264,7 @@ function gitHeadSha(dir) {
1950
2264
  }
1951
2265
  }
1952
2266
  function commitsSince(dir, sinceSha) {
2267
+ if (!/^[0-9a-f]{40}(?:[0-9a-f]{24})?$/.test(sinceSha)) return null;
1953
2268
  try {
1954
2269
  const n = Number.parseInt(git(dir, "rev-list", "--count", `${sinceSha}..HEAD`).trim(), 10);
1955
2270
  return Number.isFinite(n) ? n : null;
@@ -1964,6 +2279,15 @@ function hasGitHistory(dir) {
1964
2279
  return false;
1965
2280
  }
1966
2281
  }
2282
+ async function gitLogIsCurrent(client, repo, head) {
2283
+ const canonical2 = `gitlog:${repoNameOf(repo)}`;
2284
+ if ((await client.listDocumentIds(`${GITLOG_HEAD}${head}`, "all_strict")).has(canonical2))
2285
+ return true;
2286
+ const tags = await client.documentTags?.(canonical2) ?? [];
2287
+ return tags.some(
2288
+ (tag) => tag.startsWith(GITLOG_HEAD) && commitsSince(repo, tag.slice(GITLOG_HEAD.length)) === 0
2289
+ );
2290
+ }
1967
2291
 
1968
2292
  // src/core/status.ts
1969
2293
  import { execFileSync as execFileSync3 } from "child_process";
@@ -1995,7 +2319,7 @@ import {
1995
2319
  renameSync as renameSync3,
1996
2320
  rmdirSync,
1997
2321
  rmSync as rmSync2,
1998
- statSync as statSync4,
2322
+ statSync as statSync3,
1999
2323
  unlinkSync,
2000
2324
  utimesSync,
2001
2325
  writeFileSync as writeFileSync2
@@ -2032,7 +2356,7 @@ function reclaimIfStale(directory, staleMs) {
2032
2356
  return true;
2033
2357
  }
2034
2358
  if (owners.length !== 1) return false;
2035
- const age = Date.now() - statSync4(join12(directory, owners[0])).mtimeMs;
2359
+ const age = Date.now() - statSync3(join12(directory, owners[0])).mtimeMs;
2036
2360
  if (Math.abs(age) <= staleMs) return false;
2037
2361
  releaseLease({ directory, owner: owners[0] });
2038
2362
  return true;
@@ -2269,8 +2593,10 @@ import { homedir as homedir5, tmpdir as tmpdir4 } from "os";
2269
2593
  import { dirname as dirname9, join as join14 } from "path";
2270
2594
  import { fileURLToPath as fileURLToPath4 } from "url";
2271
2595
  var PACKAGE_NAME = "@vectorize-io/hindsight-coding-agents";
2596
+ var RELEASE_RE = /^\d+\.\d+\.\d+(?:-[0-9A-Za-z.]+)?$/;
2272
2597
  var CHECK_INTERVAL_MS = 24 * 60 * 60 * 1e3;
2273
- var FETCH_TIMEOUT_MS = 5e3;
2598
+ var NPM_VIEW_TIMEOUT_MS = 5e3;
2599
+ var NPM_VIEW_HARD_DEADLINE_MS = NPM_VIEW_TIMEOUT_MS + 1e3;
2274
2600
  function stateFile(runtimeDir) {
2275
2601
  return join14(runtimeDir, ".update-check.json");
2276
2602
  }
@@ -2377,17 +2703,53 @@ function stampCheck(file, now, latest) {
2377
2703
  } catch {
2378
2704
  }
2379
2705
  }
2380
- async function latestVersion(fetchImpl) {
2381
- try {
2382
- const r = await fetchImpl(`https://registry.npmjs.org/${PACKAGE_NAME}/latest`, {
2383
- signal: AbortSignal.timeout(FETCH_TIMEOUT_MS)
2384
- });
2385
- if (!r.ok) return "";
2386
- const body = await r.json();
2387
- return typeof body.version === "string" ? body.version : "";
2388
- } catch {
2389
- return "";
2390
- }
2706
+ async function npmViewVersion(pkg, spawnImpl = realSpawn5) {
2707
+ return new Promise((resolve3) => {
2708
+ let out = "";
2709
+ let settled = false;
2710
+ let deadline;
2711
+ const done = (v, reason) => {
2712
+ if (settled) return;
2713
+ settled = true;
2714
+ if (deadline) clearTimeout(deadline);
2715
+ if (reason) log.info("auto-update", `version check failed: ${reason}`);
2716
+ resolve3(v);
2717
+ };
2718
+ try {
2719
+ const child = spawnImpl("npm", ["view", pkg, "version", "--json"], {
2720
+ timeout: NPM_VIEW_TIMEOUT_MS,
2721
+ stdio: ["ignore", "pipe", "ignore"],
2722
+ windowsHide: true
2723
+ });
2724
+ child.stdout?.setEncoding("utf8");
2725
+ child.stdout?.on("data", (d) => {
2726
+ out += d;
2727
+ });
2728
+ child.stdout?.on("error", (e) => done("", describeError(e)));
2729
+ child.on("error", (e) => done("", describeError(e)));
2730
+ child.on("close", (code, signal) => {
2731
+ if (code !== 0) return done("", `npm view exited ${code ?? signal}`);
2732
+ try {
2733
+ const v = JSON.parse(out.trim());
2734
+ if (typeof v !== "string")
2735
+ return done("", `unparsable npm output: ${out.trim().slice(0, 80)}`);
2736
+ if (!RELEASE_RE.test(v)) return done("", `not a release: ${v.slice(0, 40)}`);
2737
+ done(v);
2738
+ } catch {
2739
+ done("", `unparsable npm output: ${out.trim().slice(0, 80)}`);
2740
+ }
2741
+ });
2742
+ deadline = setTimeout(() => {
2743
+ try {
2744
+ child.kill("SIGKILL");
2745
+ } catch {
2746
+ }
2747
+ done("", "npm view never exited \u2014 hard deadline");
2748
+ }, NPM_VIEW_HARD_DEADLINE_MS);
2749
+ } catch (e) {
2750
+ done("", describeError(e));
2751
+ }
2752
+ });
2391
2753
  }
2392
2754
  async function maybeAutoUpdate(cfg, opts = {}) {
2393
2755
  try {
@@ -2407,15 +2769,16 @@ async function maybeAutoUpdate(cfg, opts = {}) {
2407
2769
  stampCheck(file, now, "");
2408
2770
  return "";
2409
2771
  }
2410
- if (!(opts.binOnPath ?? binOnPath)("npx")) {
2411
- log.info("auto-update", "npx is not on PATH \u2014 skipping the update check");
2772
+ const binOk = opts.binOnPath ?? binOnPath;
2773
+ if (!binOk("npx") || !binOk("npm")) {
2774
+ log.info("auto-update", "npx/npm is not on PATH \u2014 skipping the update check");
2412
2775
  stampCheck(file, now, "");
2413
2776
  return "";
2414
2777
  }
2415
2778
  const lock = opts.lockFile ?? lockFile();
2416
2779
  if (!acquireUpdateLock(lock, now)) return "";
2417
2780
  try {
2418
- const latest = await latestVersion(opts.fetch ?? fetch);
2781
+ const latest = await (opts.npmView ?? npmViewVersion)(PACKAGE_NAME);
2419
2782
  stampCheck(file, now, latest);
2420
2783
  if (!latest || !isNewer(latest, current2)) {
2421
2784
  releaseUpdateLock(lock);
@@ -2448,12 +2811,14 @@ async function maybeAutoUpdate(cfg, opts = {}) {
2448
2811
  }
2449
2812
 
2450
2813
  // src/core/skill-sync.ts
2451
- import { cpSync, existsSync as existsSync5, readFileSync as readFileSync9 } from "fs";
2814
+ import { cpSync, existsSync as existsSync6, readFileSync as readFileSync9 } from "fs";
2452
2815
  import { homedir as homedir6 } from "os";
2453
- import { dirname as dirname10, join as join15 } from "path";
2816
+ import { dirname as dirname10, join as join16 } from "path";
2454
2817
  import { fileURLToPath as fileURLToPath5 } from "url";
2455
2818
 
2456
2819
  // src/core/skill-dirs.ts
2820
+ import { existsSync as existsSync5 } from "fs";
2821
+ import { join as join15 } from "path";
2457
2822
  var SKILL_DIRS = {
2458
2823
  "claude-code": [".claude", "skills"],
2459
2824
  // Codex and dsh share the agentskills-standard root; uninstalling either removes the one copy.
@@ -2466,6 +2831,8 @@ var SKILL_DIRS = {
2466
2831
  "cline-cli": [".cline", "data", "settings", "skills"],
2467
2832
  "qwen-code": [".qwen", "skills"],
2468
2833
  // Qwen's user-level skills root (Storage.getUserSkillsDirs)
2834
+ // Kimi Code's user-level skills root, alongside its config.toml and mcp.json.
2835
+ "kimi-code": [".kimi-code", "skills"],
2469
2836
  "factory-droid": [".factory", "skills"],
2470
2837
  // Droid's user-level skills root
2471
2838
  // ZCode scans TWO user roots by default (its resolveDefaultSkillRoots): `~/.zcode/skills` and the
@@ -2473,28 +2840,48 @@ var SKILL_DIRS = {
2473
2840
  // skill removal is by fixed directory name, so installing into the shared root would make
2474
2841
  // `uninstall zcode` take Codex's and dsh's copy with it.
2475
2842
  zcode: [".zcode", "skills"],
2843
+ // TraeCode's user-level skills root, resolved per edition by traecodeDotDir below — like ZCode's
2844
+ // its own, never the shared agentskills root other hosts install into.
2845
+ traecode: [".trae-cn", "skills"],
2476
2846
  // The pi family reads the shared ~/.agents/skills too, but writes its OWN root: skill removal is
2477
2847
  // by fixed directory name, so installing to the shared one would make `uninstall pi` take Codex's
2478
2848
  // and dsh's copy with it.
2479
2849
  pi: [".pi", "agent", "skills"],
2480
2850
  "prime-agent": [".prime", "agent", "skills"]
2481
2851
  };
2852
+ var TRAE_DOT_DIRS = [".trae-cn", ".trae"];
2853
+ var traecodeDotDirName = (home, exists = existsSync5) => {
2854
+ for (const dir of TRAE_DOT_DIRS) {
2855
+ if (exists(join15(home, dir))) return dir;
2856
+ }
2857
+ return ".trae-cn";
2858
+ };
2859
+ var resolveSkillDirs = (harness, home) => {
2860
+ const parts = SKILL_DIRS[harness];
2861
+ if (harness === "traecode" && parts) {
2862
+ return [traecodeDotDirName(home), ...parts.slice(1)];
2863
+ }
2864
+ return parts;
2865
+ };
2482
2866
 
2483
2867
  // src/core/skill-sync.ts
2484
2868
  function packagedSkillDir() {
2485
- return join15(dirname10(fileURLToPath5(import.meta.url)), "..", "skill");
2869
+ const here = dirname10(fileURLToPath5(import.meta.url));
2870
+ const dist = join16(here, "..", "skill");
2871
+ return existsSync6(join16(dist, "SKILL.md")) ? dist : join16(here, "..", "..", "skill");
2486
2872
  }
2487
2873
  function syncCompanionSkill(harness, opts = {}) {
2488
2874
  try {
2489
- const parts = SKILL_DIRS[harness];
2875
+ const parts = resolveSkillDirs(harness, opts.home ?? homedir6());
2490
2876
  if (!parts) return;
2491
2877
  const src = opts.srcDir ?? packagedSkillDir();
2492
- const srcMd = join15(src, "SKILL.md");
2493
- if (!existsSync5(srcMd)) return;
2494
- const dst = join15(opts.home ?? homedir6(), ...parts, "hindsight-coding-agent");
2495
- const dstMd = join15(dst, "SKILL.md");
2496
- if (!existsSync5(dstMd)) return;
2497
- if (readFileSync9(srcMd, "utf8") !== readFileSync9(dstMd, "utf8")) {
2878
+ const srcMd = join16(src, "SKILL.md");
2879
+ if (!existsSync6(srcMd)) return;
2880
+ const dst = join16(opts.home ?? homedir6(), ...parts, "hindsight-coding-agent");
2881
+ const dstMd = join16(dst, "SKILL.md");
2882
+ const installed = existsSync6(dstMd);
2883
+ if (!installed && !opts.install) return;
2884
+ if (!installed || readFileSync9(srcMd, "utf8") !== readFileSync9(dstMd, "utf8")) {
2498
2885
  cpSync(src, dst, { recursive: true });
2499
2886
  }
2500
2887
  } catch {
@@ -2502,15 +2889,15 @@ function syncCompanionSkill(harness, opts = {}) {
2502
2889
  }
2503
2890
 
2504
2891
  // src/core/legacy.ts
2505
- import { existsSync as existsSync6, readFileSync as readFileSync10 } from "fs";
2892
+ import { existsSync as existsSync7, readFileSync as readFileSync10 } from "fs";
2506
2893
  import { homedir as homedir7 } from "os";
2507
- import { join as join16, relative, isAbsolute as isAbsolute2 } from "path";
2894
+ import { join as join17, relative, isAbsolute as isAbsolute2 } from "path";
2508
2895
  var LEGACY_CLAUDE_PLUGIN = "hindsight-memory";
2509
- function detectLegacyClaudePlugin(cwd, claudeDir = join16(homedir7(), ".claude")) {
2510
- const registry = readJson(join16(claudeDir, "plugins", "installed_plugins.json"));
2896
+ function detectLegacyClaudePlugin(cwd, claudeDir = join17(homedir7(), ".claude")) {
2897
+ const registry = readJson(join17(claudeDir, "plugins", "installed_plugins.json"));
2511
2898
  const plugins = registry?.plugins;
2512
2899
  if (!plugins || typeof plugins !== "object") return void 0;
2513
- const enabled = readJson(join16(claudeDir, "settings.json"))?.enabledPlugins;
2900
+ const enabled = readJson(join17(claudeDir, "settings.json"))?.enabledPlugins;
2514
2901
  for (const [key, raw] of Object.entries(plugins)) {
2515
2902
  if (key.split("@")[0] !== LEGACY_CLAUDE_PLUGIN) continue;
2516
2903
  if (enabled && enabled[key] === false) continue;
@@ -2550,17 +2937,19 @@ async function gitSyncNote(args) {
2550
2937
  if (mode === "none" || cold) return void 0;
2551
2938
  const head = gitHeadSha(cwd);
2552
2939
  if (!head) return void 0;
2553
- const gitlogCurrent = await client.listDocumentIds(`gitlog-head:${head}`, "all_strict").then((s) => s.has(`gitlog:${repoNameOf(cwd)}`)).catch(() => void 0);
2940
+ const gitlogCurrent = await gitLogIsCurrent(client, cwd, head).catch(() => void 0);
2554
2941
  if (gitlogCurrent === void 0) return void 0;
2555
2942
  if (mode === "message") return gitlogCurrent ? "git in sync" : "catching up on new commits";
2556
2943
  const deepened = [...gitIds].filter((id) => id.startsWith("git:")).length;
2557
2944
  let target = DEEPEN_DIFF_TARGET;
2558
2945
  try {
2559
- const { execFileSync: execFileSync4 } = await import("child_process");
2946
+ const { execFileSync: execFileSync5 } = await import("child_process");
2560
2947
  const n = Number(
2561
- execFileSync4("git", ["-C", cwd, "rev-list", "--count", "HEAD"], {
2948
+ execFileSync5("git", ["-C", cwd, "rev-list", "--count", "HEAD"], {
2562
2949
  encoding: "utf8",
2563
- windowsHide: true
2950
+ windowsHide: true,
2951
+ stdio: ["ignore", "pipe", "pipe"]
2952
+ // do not corrupt the host banner on a late git failure
2564
2953
  }).trim()
2565
2954
  );
2566
2955
  if (n > 0) target = Math.min(DEEPEN_DIFF_TARGET, n);
@@ -2673,7 +3062,10 @@ async function buildSessionStartContext(args) {
2673
3062
  diag(harness, "knowledge_pages_unavailable", { bank: bankId });
2674
3063
  }
2675
3064
  }
2676
- const additionalContext = buildKnowledgePreamble(pages, { reflectOnNewGoals: !cfg.autoReflect });
3065
+ const additionalContext = buildKnowledgePreamble(pages, {
3066
+ reflectOnNewGoals: cfg.autoInject !== "reflect",
3067
+ extra: cfg.toolGuideExtra
3068
+ });
2677
3069
  const deferInitialReflect = cold === true || pageListKnown && pages.length === 0;
2678
3070
  let gitNote;
2679
3071
  if (gitDocIds) {
@@ -2705,6 +3097,7 @@ async function runSessionStartHook(spec, makeClient = (o) => new HindsightClient
2705
3097
  } catch {
2706
3098
  return;
2707
3099
  }
3100
+ if (spec.accept && !spec.accept(ev)) return;
2708
3101
  const { harness } = spec;
2709
3102
  const { cwd: rawCwd, sessionId } = spec.parse(ev);
2710
3103
  const cwd = rawCwd || process.cwd();
@@ -2720,6 +3113,7 @@ async function runSessionStartHook(spec, makeClient = (o) => new HindsightClient
2720
3113
  cfg = resolved2.cfg;
2721
3114
  const bankId = resolved2.bankId;
2722
3115
  if (cfg.disabled) return;
3116
+ const mcpHint = spec.ensureMcpRegistration?.(cwd);
2723
3117
  await ensureDaemon(cfg, harness, { waitMs: DAEMON_WAIT_SESSION_START_MS });
2724
3118
  const client = makeClient({
2725
3119
  apiUrl: cfg.apiUrl,
@@ -2729,6 +3123,9 @@ async function runSessionStartHook(spec, makeClient = (o) => new HindsightClient
2729
3123
  observationScopes: cfg.observationScopes
2730
3124
  });
2731
3125
  const out = await buildSessionStartContext({ cwd, sessionRoot, bankId, cfg, client, harness });
3126
+ if (mcpHint)
3127
+ out.systemMessage = out.systemMessage ? `${out.systemMessage}
3128
+ ${mcpHint}` : mcpHint;
2732
3129
  if (out.deferInitialReflect && sessionId) {
2733
3130
  writeSessionCache(sessionCacheFile(harness, sessionId), { deferInitialReflect: true });
2734
3131
  }
@@ -2740,44 +3137,342 @@ async function runSessionStartHook(spec, makeClient = (o) => new HindsightClient
2740
3137
  }
2741
3138
  }
2742
3139
 
3140
+ // src/core/traecode-mcp.ts
3141
+ import { execFileSync as execFileSync4 } from "child_process";
3142
+ import { existsSync as existsSync8, mkdirSync as mkdirSync6, readFileSync as readFileSync12, readdirSync as readdirSync2, rmSync as rmSync3, writeFileSync as writeFileSync4 } from "fs";
3143
+ import { homedir as homedir8 } from "os";
3144
+ import { dirname as dirname11, isAbsolute as isAbsolute3, join as join18 } from "path";
3145
+ import { fileURLToPath as fileURLToPath6 } from "url";
3146
+ var MCP_SERVER_NAME = "hindsight";
3147
+ var MCP_FILE_REL = join18(".trae", "mcp.json");
3148
+ function bundledDistDir() {
3149
+ const here = dirname11(fileURLToPath6(import.meta.url));
3150
+ return existsSync8(join18(here, "mcp-server.js")) ? here : join18(here, "..", "..", "dist");
3151
+ }
3152
+ function canon(value) {
3153
+ if (Array.isArray(value)) return `[${value.map(canon).join(",")}]`;
3154
+ if (value && typeof value === "object") {
3155
+ const entries = Object.entries(value).sort(
3156
+ ([a], [b]) => a < b ? -1 : a > b ? 1 : 0
3157
+ );
3158
+ return `{${entries.map(([k, v]) => `${JSON.stringify(k)}:${canon(v)}`).join(",")}}`;
3159
+ }
3160
+ return JSON.stringify(value);
3161
+ }
3162
+ var WORKSPACE_MCP_KEY = "trae.mcp.enableWorkspaceMcp";
3163
+ var HINT_MIN_INTERVAL_MS = 24 * 60 * 60 * 1e3;
3164
+ function traecodeUserDataDir(home) {
3165
+ const root = process.platform === "darwin" ? join18(home, "Library", "Application Support") : process.platform === "win32" ? process.env.APPDATA ?? join18(home, "AppData", "Roaming") : process.env.XDG_CONFIG_HOME ?? join18(home, ".config");
3166
+ for (const brand of ["Trae CN", "Trae"]) {
3167
+ const dir = join18(root, brand);
3168
+ if (existsSync8(dir)) return dir;
3169
+ }
3170
+ return join18(root, "Trae CN");
3171
+ }
3172
+ var traecodeUserSettingsPath = (home) => join18(traecodeUserDataDir(home), "User", "settings.json");
3173
+ var gateStateFileFor = (dist) => join18(dirname11(dist), ".workspace-mcp.json");
3174
+ function gateStateFile() {
3175
+ return gateStateFileFor(bundledDistDir());
3176
+ }
3177
+ function readGateState(opts = {}) {
3178
+ try {
3179
+ return JSON.parse(readFileSync12(opts.stateFile ?? gateStateFile(), "utf8"));
3180
+ } catch {
3181
+ return {};
3182
+ }
3183
+ }
3184
+ function workspaceMcpGateState(settingsPath) {
3185
+ let raw;
3186
+ try {
3187
+ raw = readFileSync12(settingsPath, "utf8");
3188
+ } catch {
3189
+ return "unknown";
3190
+ }
3191
+ try {
3192
+ const doc = JSON.parse(raw);
3193
+ return doc[WORKSPACE_MCP_KEY] === true ? "on" : "off";
3194
+ } catch {
3195
+ const hit = raw.match(new RegExp(`"${WORKSPACE_MCP_KEY}"\\s*:\\s*(true|false)`));
3196
+ return hit ? hit[1] === "true" ? "on" : "off" : "unknown";
3197
+ }
3198
+ }
3199
+ function workspaceMcpHint(opts = {}) {
3200
+ try {
3201
+ const settingsPath = traecodeUserSettingsPath(opts.home ?? homedir8());
3202
+ if (workspaceMcpGateState(settingsPath) === "on") return void 0;
3203
+ const now = opts.now ?? Date.now();
3204
+ const state = readGateState(opts);
3205
+ if (state.workspaceMcpEnabled) return void 0;
3206
+ if (typeof state.lastHint === "number" && now - state.lastHint < HINT_MIN_INTERVAL_MS) {
3207
+ return void 0;
3208
+ }
3209
+ writeFileSync4(
3210
+ opts.stateFile ?? gateStateFile(),
3211
+ JSON.stringify({ ...state, lastHint: now }, null, 2) + "\n"
3212
+ );
3213
+ return 'Hindsight MCP tools are hidden: TraeCode does not read per-repo MCP configs until workspace MCP is enabled. Turn it on once in Trae settings (search "enableWorkspaceMcp") or re-run `hindsight-coding-agents install traecode` \u2014 then reload this window.';
3214
+ } catch {
3215
+ return void 0;
3216
+ }
3217
+ }
3218
+ function gitignoreCovers(lines) {
3219
+ return lines.some((l) => {
3220
+ const t = l.trim();
3221
+ return t.includes(".trae");
3222
+ });
3223
+ }
3224
+ function ensureGitignored(repo) {
3225
+ const gitignore = join18(repo, ".gitignore");
3226
+ if (!existsSync8(gitignore)) return;
3227
+ const current2 = readFileSync12(gitignore, "utf8");
3228
+ if (gitignoreCovers(current2.split("\n"))) return;
3229
+ const addition = (current2.endsWith("\n") || current2 === "" ? "" : "\n") + "# hindsight MCP registration (machine-specific)\n.trae/mcp.json\n";
3230
+ writeFileSync4(gitignore, current2 + addition);
3231
+ }
3232
+ function ensureTraecodeWorkspaceMcp(cwd, opts = {}) {
3233
+ registerTraecodeWorkspaceMcp(cwd, opts);
3234
+ const seeded = ensureWorkspaceMcpEnabled(cwd, opts);
3235
+ return workspaceMcpHint(opts) ?? (seeded === "failed" ? workspaceEnableHint(opts) : void 0);
3236
+ }
3237
+ function registerTraecodeWorkspaceMcp(cwd, opts = {}) {
3238
+ try {
3239
+ const home = opts.home ?? homedir8();
3240
+ if (!cwd || !isAbsolute3(cwd) || dirname11(cwd) === cwd || cwd === home) return "skipped";
3241
+ const dist = opts.dist ?? bundledDistDir();
3242
+ const script = join18(dist, "mcp-server.js");
3243
+ if (!existsSync8(script)) return "skipped";
3244
+ const file = join18(cwd, MCP_FILE_REL);
3245
+ let doc = {};
3246
+ let exists = false;
3247
+ try {
3248
+ doc = JSON.parse(readFileSync12(file, "utf8"));
3249
+ exists = true;
3250
+ } catch {
3251
+ if (existsSync8(file)) return "skipped";
3252
+ }
3253
+ const servers = doc.mcpServers && typeof doc.mcpServers === "object" && !Array.isArray(doc.mcpServers) ? doc.mcpServers : doc.mcpServers = {};
3254
+ const entry = {
3255
+ command: "node",
3256
+ args: [script],
3257
+ env: { HINDSIGHT_MCP_HARNESS: "traecode", HINDSIGHT_MCP_PROJECT_CWD: cwd }
3258
+ };
3259
+ const existing = servers[MCP_SERVER_NAME];
3260
+ let merged;
3261
+ if (existing === void 0) {
3262
+ merged = entry;
3263
+ } else if (isOurMcpEntry(existing)) {
3264
+ const env = existing.env;
3265
+ merged = {
3266
+ ...existing,
3267
+ command: entry.command,
3268
+ args: entry.args,
3269
+ env: { ...env ?? {}, ...entry.env }
3270
+ };
3271
+ } else {
3272
+ diag("traecode", "workspace_mcp_foreign_entry", { cwd, file });
3273
+ return "skipped";
3274
+ }
3275
+ if (existing !== void 0 && canon(merged) === canon(existing)) return "current";
3276
+ servers[MCP_SERVER_NAME] = merged;
3277
+ mkdirSync6(dirname11(file), { recursive: true });
3278
+ writeFileSync4(file, JSON.stringify(doc, null, 2) + "\n");
3279
+ if (!exists) ensureGitignored(cwd);
3280
+ diag("traecode", "workspace_mcp_registered", { cwd, file });
3281
+ return "registered";
3282
+ } catch (e) {
3283
+ diag("traecode", "workspace_mcp_register_failed", {
3284
+ cwd,
3285
+ error: e instanceof Error ? e.message : String(e)
3286
+ });
3287
+ return "failed";
3288
+ }
3289
+ }
3290
+ var WORKSPACE_STORAGE_REL = join18("User", "workspaceStorage");
3291
+ var ENABLED_KEY_PREFIX = "icubeAgentExtension.enabled.mcp.config.ws0.";
3292
+ var SQLITE_TIMEOUT_MS = 5e3;
3293
+ var TRAECODE_WORKSPACE_ENABLED_KEY = ENABLED_KEY_PREFIX + MCP_SERVER_NAME;
3294
+ var traecodeWorkspaceStorageDir = (home) => join18(traecodeUserDataDir(home), WORKSPACE_STORAGE_REL);
3295
+ function findWorkspaceStorageDir(storage, repo) {
3296
+ let entries;
3297
+ try {
3298
+ entries = readdirSync2(storage);
3299
+ } catch {
3300
+ return void 0;
3301
+ }
3302
+ for (const name of entries) {
3303
+ try {
3304
+ const doc = JSON.parse(readFileSync12(join18(storage, name, "workspace.json"), "utf8"));
3305
+ if (typeof doc.folder !== "string") continue;
3306
+ let folder;
3307
+ try {
3308
+ folder = fileURLToPath6(doc.folder);
3309
+ } catch {
3310
+ folder = doc.folder;
3311
+ }
3312
+ if (folder === repo) return join18(storage, name);
3313
+ } catch {
3314
+ continue;
3315
+ }
3316
+ }
3317
+ return void 0;
3318
+ }
3319
+ function ensureWorkspaceMcpEnabled(cwd, opts = {}) {
3320
+ try {
3321
+ const home = opts.home ?? homedir8();
3322
+ if (!cwd || !isAbsolute3(cwd) || dirname11(cwd) === cwd || cwd === home) return "failed";
3323
+ const dir = findWorkspaceStorageDir(traecodeWorkspaceStorageDir(home), cwd);
3324
+ if (!dir) return "failed";
3325
+ const db = join18(dir, "state.vscdb");
3326
+ if (!existsSync8(db)) return "failed";
3327
+ const sqlite = opts.sqlite ?? execFileSync4;
3328
+ const run = (sql) => sqlite("sqlite3", [db, ".timeout 3000", sql], {
3329
+ encoding: "utf8",
3330
+ timeout: SQLITE_TIMEOUT_MS,
3331
+ windowsHide: true,
3332
+ stdio: ["ignore", "pipe", "pipe"]
3333
+ }).trim();
3334
+ if (run(`SELECT value FROM ItemTable WHERE key='${TRAECODE_WORKSPACE_ENABLED_KEY}';`) === "true") {
3335
+ return "on";
3336
+ }
3337
+ run(
3338
+ `INSERT OR REPLACE INTO ItemTable (key, value) VALUES ('${TRAECODE_WORKSPACE_ENABLED_KEY}', 'true');`
3339
+ );
3340
+ diag("traecode", "workspace_mcp_enabled_seeded", { cwd, db });
3341
+ return "seeded";
3342
+ } catch (e) {
3343
+ diag("traecode", "workspace_mcp_enabled_seed_failed", {
3344
+ cwd,
3345
+ error: e instanceof Error ? e.message : String(e)
3346
+ });
3347
+ return "failed";
3348
+ }
3349
+ }
3350
+ function workspaceEnableHint(opts = {}) {
3351
+ try {
3352
+ const now = opts.now ?? Date.now();
3353
+ const state = readGateState(opts);
3354
+ if (typeof state.lastEnableHint === "number" && now - state.lastEnableHint < HINT_MIN_INTERVAL_MS) {
3355
+ return void 0;
3356
+ }
3357
+ writeFileSync4(
3358
+ opts.stateFile ?? gateStateFile(),
3359
+ JSON.stringify({ ...state, lastEnableHint: now }, null, 2) + "\n"
3360
+ );
3361
+ return "Hindsight's MCP server stays disabled in this window: auto-enabling it failed here. Switch hindsight on for this workspace in Trae's MCP panel, then reload the window.";
3362
+ } catch {
3363
+ return void 0;
3364
+ }
3365
+ }
3366
+
2743
3367
  // src/core/transcript-codex.ts
3368
+ function stampOf(line) {
3369
+ return typeof line.timestamp === "string" && line.timestamp ? { timestamp: line.timestamp } : {};
3370
+ }
2744
3371
  function isSyntheticUserText(text) {
2745
3372
  const s = text.trimStart();
2746
3373
  return s.startsWith("# AGENTS.md instructions for ") || s.startsWith("<environment_context>");
2747
3374
  }
2748
- function messageText(payload) {
2749
- return (payload.content || []).filter((c) => c && typeof c.text === "string").map((c) => c.text).join("\n");
3375
+ function contentText(content) {
3376
+ return (Array.isArray(content) ? content : []).filter((c) => c && typeof c.text === "string").map((c) => c.text).join("\n");
3377
+ }
3378
+ var startupKinds = /* @__PURE__ */ new Set([
3379
+ "agents_md.instructions",
3380
+ "environments.instructions",
3381
+ "environments.environment_context",
3382
+ "plugins.recommendations",
3383
+ "plugins.usage_instructions"
3384
+ ]);
3385
+ function fallbackUserText(payload) {
3386
+ const content = payload.content;
3387
+ const kinds = payload.internal_chat_message_metadata_passthrough?.content_item_kinds;
3388
+ if (Array.isArray(content) && Array.isArray(kinds) && kinds.length === content.length && kinds.every((kind) => typeof kind === "string" && kind.length > 0)) {
3389
+ return contentText(content.filter((_, index) => !startupKinds.has(kinds[index])));
3390
+ }
3391
+ const text = contentText(content);
3392
+ return isSyntheticUserText(stripInjectedMemory(text)) ? "" : text;
3393
+ }
3394
+ function isUserMessageEvent(line) {
3395
+ return line.type === "event_msg" && line.payload?.type === "item_completed" && line.payload.item?.type === "UserMessage";
3396
+ }
3397
+ var TOOL_ITEM_TYPES = /* @__PURE__ */ new Set(["McpToolCall", "CommandExecution"]);
3398
+ function isToolItemEvent(line) {
3399
+ return line.type === "event_msg" && line.payload?.type === "item_completed" && TOOL_ITEM_TYPES.has(line.payload.item?.type ?? "");
3400
+ }
3401
+ function parseArgs(raw) {
3402
+ if (typeof raw !== "string") return raw;
3403
+ try {
3404
+ return JSON.parse(raw);
3405
+ } catch {
3406
+ return void 0;
3407
+ }
3408
+ }
3409
+ var SHELL_RE = /(?:^|\/)(?:sh|bash|zsh|dash|ksh|fish)$/;
3410
+ function commandText(command) {
3411
+ if (typeof command === "string") return command;
3412
+ if (!Array.isArray(command) || !command.every((c) => typeof c === "string")) return "";
3413
+ const argv = command;
3414
+ if (argv.length === 3 && SHELL_RE.test(argv[0]) && /^-[a-z]*c$/.test(argv[1])) return argv[2];
3415
+ return argv.join(" ");
3416
+ }
3417
+ function toolItemAction(item) {
3418
+ if (item.type === "McpToolCall") {
3419
+ if (typeof item.tool !== "string" || !item.tool) return void 0;
3420
+ const name = typeof item.server === "string" && item.server ? `mcp__${item.server}__${item.tool}` : item.tool;
3421
+ return actionLine(name, parseArgs(item.arguments));
3422
+ }
3423
+ const command = commandText(item.command).trim();
3424
+ return command ? actionLine("exec_command", { command }) : void 0;
2750
3425
  }
2751
3426
  function readCodexTranscript(path) {
2752
- const turns = [];
2753
- for (const rawLine of readJsonlTail(path, { scope: "codex" }).lines) {
3427
+ const lines = [];
3428
+ for (const rawLine of readJsonl(path)) {
2754
3429
  const trimmed = rawLine.trim();
2755
3430
  if (!trimmed) continue;
2756
- let parsed;
2757
3431
  try {
2758
- parsed = JSON.parse(trimmed);
3432
+ const parsed = JSON.parse(trimmed);
3433
+ if (typeof parsed === "object" && parsed !== null) lines.push(parsed);
2759
3434
  } catch {
2760
3435
  continue;
2761
3436
  }
2762
- if (typeof parsed !== "object" || parsed === null) continue;
2763
- const line = parsed;
3437
+ }
3438
+ const userFromEvents = lines.some(isUserMessageEvent);
3439
+ const actionsFromEvents = lines.some(isToolItemEvent);
3440
+ const turns = [];
3441
+ const push = (role, raw, stamp = {}) => {
3442
+ const text = stripInjectedMemory(raw).trim();
3443
+ if (text) turns.push({ role, content: text, ...stamp });
3444
+ };
3445
+ for (const line of lines) {
3446
+ if (isUserMessageEvent(line)) {
3447
+ push("user", contentText(line.payload?.item?.content), stampOf(line));
3448
+ continue;
3449
+ }
3450
+ if (isToolItemEvent(line)) {
3451
+ const action = toolItemAction(line.payload?.item ?? {});
3452
+ if (action) turns.push({ role: "action", content: action, ...stampOf(line) });
3453
+ continue;
3454
+ }
2764
3455
  if (line.type !== "response_item") continue;
2765
3456
  const p = line.payload;
2766
3457
  if (!p || typeof p !== "object") continue;
2767
3458
  if (p.type === "message") {
2768
- if (p.role !== "user" && p.role !== "assistant") continue;
2769
- const text = stripInjectedMemory(messageText(p)).trim();
2770
- if (!text) continue;
2771
- if (p.role === "user" && isSyntheticUserText(text)) continue;
2772
- turns.push({ role: p.role, content: text });
2773
- } else if (p.type === "function_call" && typeof p.name === "string") {
3459
+ if (p.role === "assistant") {
3460
+ if (p.channel === "analysis" || p.channel === "reasoning" || p.phase === "analysis" || p.phase === "reasoning")
3461
+ continue;
3462
+ push("assistant", contentText(p.content), stampOf(line));
3463
+ } else if (p.role === "user" && !userFromEvents) {
3464
+ push("user", fallbackUserText(p), stampOf(line));
3465
+ }
3466
+ } else if ((p.type === "function_call" || p.type === "custom_tool_call") && typeof p.name === "string") {
3467
+ if (actionsFromEvents && p.type === "custom_tool_call" && p.name === "exec") continue;
3468
+ const rawInput = p.type === "function_call" ? p.arguments : p.input;
2774
3469
  let input;
2775
3470
  try {
2776
- input = JSON.parse(p.arguments || "");
3471
+ input = JSON.parse(rawInput || "");
2777
3472
  } catch {
2778
3473
  input = void 0;
2779
3474
  }
2780
- turns.push({ role: "action", content: actionLine(p.name, input) });
3475
+ turns.push({ role: "action", content: actionLine(p.name, input), ...stampOf(line) });
2781
3476
  }
2782
3477
  }
2783
3478
  return turns;
@@ -2794,7 +3489,7 @@ function textFrom(content) {
2794
3489
  }
2795
3490
  function readCursorTranscript(path) {
2796
3491
  const turns = [];
2797
- for (const rawLine of readJsonlTail(path, { scope: "cursor-cli" }).lines) {
3492
+ for (const rawLine of readJsonl(path)) {
2798
3493
  let parsed;
2799
3494
  try {
2800
3495
  parsed = JSON.parse(rawLine);
@@ -2833,7 +3528,7 @@ function readCursorTranscript(path) {
2833
3528
  function readAntigravityTranscript(path) {
2834
3529
  if (!path) return [];
2835
3530
  const turns = [];
2836
- for (const line of readJsonlTail(path, { scope: "antigravity-cli" }).lines) {
3531
+ for (const line of readJsonl(path)) {
2837
3532
  try {
2838
3533
  const event = JSON.parse(line);
2839
3534
  const role = event.role ?? event.message?.role ?? event.type;
@@ -2856,7 +3551,7 @@ function readAntigravityTranscript(path) {
2856
3551
  // src/core/transcript-copilot.ts
2857
3552
  function readCopilotTranscript(path) {
2858
3553
  const turns = [];
2859
- for (const rawLine of readJsonlTail(path, { scope: "copilot-cli" }).lines) {
3554
+ for (const rawLine of readJsonl(path)) {
2860
3555
  try {
2861
3556
  const event = JSON.parse(rawLine);
2862
3557
  const role = event.type === "user.message" ? "user" : event.type === "assistant.message" ? "assistant" : void 0;
@@ -2870,19 +3565,19 @@ function readCopilotTranscript(path) {
2870
3565
  }
2871
3566
 
2872
3567
  // src/core/transcript-grok.ts
2873
- import { existsSync as existsSync7, readFileSync as readFileSync12, readdirSync as readdirSync2 } from "fs";
2874
- import { homedir as homedir8 } from "os";
2875
- import { join as join17 } from "path";
3568
+ import { existsSync as existsSync9, readFileSync as readFileSync13, readdirSync as readdirSync3 } from "fs";
3569
+ import { homedir as homedir9 } from "os";
3570
+ import { join as join19 } from "path";
2876
3571
  var CHAT_HISTORY = "chat_history.jsonl";
2877
- function grokTranscriptPath(cwd, sessionId, grokHome = process.env.GROK_HOME || join17(homedir8(), ".grok")) {
2878
- const sessionsDir = join17(grokHome, "sessions");
2879
- const direct = join17(sessionsDir, encodeURIComponent(cwd), sessionId, CHAT_HISTORY);
2880
- if (existsSync7(direct)) return direct;
2881
- try {
2882
- for (const candidate of readdirSync2(sessionsDir)) {
2883
- const directory = join17(sessionsDir, candidate);
2884
- if (readFileSync12(join17(directory, ".cwd"), "utf8").trim() === cwd) {
2885
- return join17(directory, sessionId, CHAT_HISTORY);
3572
+ function grokTranscriptPath(cwd, sessionId, grokHome = process.env.GROK_HOME || join19(homedir9(), ".grok")) {
3573
+ const sessionsDir = join19(grokHome, "sessions");
3574
+ const direct = join19(sessionsDir, encodeURIComponent(cwd), sessionId, CHAT_HISTORY);
3575
+ if (existsSync9(direct)) return direct;
3576
+ try {
3577
+ for (const candidate of readdirSync3(sessionsDir)) {
3578
+ const directory = join19(sessionsDir, candidate);
3579
+ if (readFileSync13(join19(directory, ".cwd"), "utf8").trim() === cwd) {
3580
+ return join19(directory, sessionId, CHAT_HISTORY);
2886
3581
  }
2887
3582
  }
2888
3583
  } catch {
@@ -2891,7 +3586,7 @@ function grokTranscriptPath(cwd, sessionId, grokHome = process.env.GROK_HOME ||
2891
3586
  }
2892
3587
  function readGrokTranscript(path) {
2893
3588
  const turns = [];
2894
- for (const rawLine of readJsonlTail(path, { scope: "grok-build" }).lines) {
3589
+ for (const rawLine of readJsonl(path)) {
2895
3590
  try {
2896
3591
  const event = JSON.parse(rawLine);
2897
3592
  if (event.type !== "user" && event.type !== "assistant") continue;
@@ -2917,12 +3612,12 @@ function readGrokTranscript(path) {
2917
3612
  }
2918
3613
 
2919
3614
  // src/core/transcript-devin.ts
2920
- import { existsSync as existsSync8 } from "fs";
3615
+ import { existsSync as existsSync10 } from "fs";
2921
3616
  import { createRequire } from "module";
2922
- import { homedir as homedir9 } from "os";
2923
- import { join as join18 } from "path";
2924
- function devinSessionDb(home = homedir9()) {
2925
- return join18(home, ".local", "share", "devin", "cli", "sessions.db");
3617
+ import { homedir as homedir10 } from "os";
3618
+ import { join as join20 } from "path";
3619
+ function devinSessionDb(home = homedir10()) {
3620
+ return join20(home, ".local", "share", "devin", "cli", "sessions.db");
2926
3621
  }
2927
3622
  function parseDevinMessages(nodes) {
2928
3623
  const messages = /* @__PURE__ */ new Map();
@@ -2959,7 +3654,7 @@ function readDevinTranscript(sessionId, dbPath = devinSessionDb()) {
2959
3654
  diag("devin-cli", "sqlite_unavailable", { node: process.version, dbPath });
2960
3655
  return [];
2961
3656
  }
2962
- if (!existsSync8(dbPath)) {
3657
+ if (!existsSync10(dbPath)) {
2963
3658
  diag("devin-cli", "session_db_missing", { dbPath });
2964
3659
  return [];
2965
3660
  }
@@ -2983,7 +3678,7 @@ function readDevinTranscript(sessionId, dbPath = devinSessionDb()) {
2983
3678
 
2984
3679
  // src/core/transcript-dcode.ts
2985
3680
  var BLOCK_JOIN = "\n";
2986
- function contentText(content) {
3681
+ function contentText2(content) {
2987
3682
  if (typeof content === "string") return content;
2988
3683
  if (!Array.isArray(content)) return "";
2989
3684
  return content.flatMap((block) => {
@@ -3076,11 +3771,11 @@ function dcodeAssistantText(raw) {
3076
3771
  const parsed = readPyValue(trimmed, 0);
3077
3772
  if (!parsed || readPyValue(trimmed, parsed.end) !== null) return "";
3078
3773
  if (!Array.isArray(parsed.value)) return "";
3079
- return contentText(parsed.value);
3774
+ return contentText2(parsed.value);
3080
3775
  }
3081
3776
  function readDcodeTranscript(path) {
3082
3777
  const turns = [];
3083
- for (const rawLine of readJsonlTail(path, { scope: "dcode" }).lines) {
3778
+ for (const rawLine of readJsonl(path)) {
3084
3779
  if (!rawLine.trim()) continue;
3085
3780
  let parsed;
3086
3781
  try {
@@ -3094,7 +3789,7 @@ function readDcodeTranscript(path) {
3094
3789
  const role = record.role;
3095
3790
  const stamp = typeof record.timestamp === "string" && record.timestamp ? { timestamp: record.timestamp } : {};
3096
3791
  if (role === "user" || role === "assistant") {
3097
- const text = stripInjectedMemory(contentText(record.content)).trim();
3792
+ const text = stripInjectedMemory(contentText2(record.content)).trim();
3098
3793
  if (text) turns.push({ role, content: text, ...stamp });
3099
3794
  } else if (role === "tool" && typeof record.name === "string" && record.name.trim()) {
3100
3795
  turns.push({ role: "action", content: actionLine(record.name, record.content), ...stamp });
@@ -3155,7 +3850,7 @@ function readQwenTranscript(path) {
3155
3850
  return turns;
3156
3851
  }
3157
3852
  function collectQwenTurns(path, turns) {
3158
- for (const rawLine of readJsonlTail(path, { scope: "qwen-code" }).lines) {
3853
+ for (const rawLine of readJsonl(path)) {
3159
3854
  const trimmed = rawLine.trim();
3160
3855
  if (!trimmed) continue;
3161
3856
  let parsed;
@@ -3210,7 +3905,7 @@ function renderContent(content, role) {
3210
3905
  }
3211
3906
  function readDroidTranscript(path) {
3212
3907
  const turns = [];
3213
- for (const rawLine of readJsonlTail(path, { scope: "factory-droid" }).lines) {
3908
+ for (const rawLine of readJsonl(path)) {
3214
3909
  if (!rawLine.trim()) continue;
3215
3910
  let parsed;
3216
3911
  try {
@@ -3232,8 +3927,8 @@ function readDroidTranscript(path) {
3232
3927
  }
3233
3928
 
3234
3929
  // src/core/transcript-zcode.ts
3235
- import { readFileSync as readFileSync13 } from "fs";
3236
- function messageText2(content) {
3930
+ import { readFileSync as readFileSync14 } from "fs";
3931
+ function messageText(content) {
3237
3932
  if (typeof content === "string") return content.trim();
3238
3933
  if (!Array.isArray(content)) return "";
3239
3934
  return content.filter((block) => block && typeof block === "object" && typeof block.text === "string").map((block) => block.text.trim()).filter(Boolean).join("\n").trim();
@@ -3242,7 +3937,7 @@ function readZcodeTranscript(path) {
3242
3937
  if (!path) return [];
3243
3938
  let body;
3244
3939
  try {
3245
- body = readFileSync13(path, "utf8");
3940
+ body = readFileSync14(path, "utf8");
3246
3941
  } catch {
3247
3942
  return [];
3248
3943
  }
@@ -3261,7 +3956,7 @@ function readZcodeTranscript(path) {
3261
3956
  const message = typeof record.message === "object" && record.message !== null ? record.message : void 0;
3262
3957
  const role = typeof message?.role === "string" ? message.role : record.type;
3263
3958
  if (role !== "user" && role !== "assistant") continue;
3264
- const content = stripInjectedMemory(messageText2(message?.content)).trim();
3959
+ const content = stripInjectedMemory(messageText(message?.content)).trim();
3265
3960
  if (!content) continue;
3266
3961
  turns.push({
3267
3962
  role,
@@ -3276,6 +3971,131 @@ function zcodeAssistantText(path) {
3276
3971
  return readZcodeTranscript(path).filter((turn) => turn.role === "assistant").at(-1)?.content ?? "";
3277
3972
  }
3278
3973
 
3974
+ // src/core/transcript-kimi.ts
3975
+ import { existsSync as existsSync11, readdirSync as readdirSync4 } from "fs";
3976
+ import { homedir as homedir11 } from "os";
3977
+ import { join as join21 } from "path";
3978
+ var HARNESS = "kimi-code";
3979
+ var SESSIONS_DIR = "sessions";
3980
+ var AGENTS_DIR = "agents";
3981
+ var WIRE_LOG = "wire.jsonl";
3982
+ var SESSION_PREFIX = "session_";
3983
+ var MAIN_AGENT = "main";
3984
+ var MAX_SESSION_CHARS = 32 * 1024 * 1024;
3985
+ function kimiSessionDir(sessionId, kimiHome = process.env.KIMI_CODE_HOME || join21(homedir11(), ".kimi-code")) {
3986
+ const name = sessionId.startsWith(SESSION_PREFIX) ? sessionId : `${SESSION_PREFIX}${sessionId}`;
3987
+ const sessions = join21(kimiHome, SESSIONS_DIR);
3988
+ try {
3989
+ for (const workspace of readdirSync4(sessions, { withFileTypes: true })) {
3990
+ if (!workspace.isDirectory()) continue;
3991
+ const candidate = join21(sessions, workspace.name, name);
3992
+ if (existsSync11(join21(candidate, AGENTS_DIR))) return candidate;
3993
+ }
3994
+ } catch {
3995
+ }
3996
+ diag(HARNESS, "session_dir_missing", { sessions, session: name });
3997
+ return void 0;
3998
+ }
3999
+ function stampOf2(event) {
4000
+ if (typeof event.time !== "number") return {};
4001
+ const at = new Date(event.time);
4002
+ return Number.isNaN(at.getTime()) ? {} : { timestamp: at.toISOString() };
4003
+ }
4004
+ function kimiPromptText(input) {
4005
+ if (!Array.isArray(input)) return "";
4006
+ return input.filter((block) => block?.type === "text" && typeof block.text === "string").map((block) => block.text).join("\n");
4007
+ }
4008
+ function readKimiWire(events) {
4009
+ const turns = [];
4010
+ let step;
4011
+ const flushStep = () => {
4012
+ if (!step) return;
4013
+ const content = stripInjectedMemory(step.texts.join("\n")).trim();
4014
+ if (content) turns.push({ role: "assistant", content, ...step.stamp });
4015
+ step = void 0;
4016
+ };
4017
+ for (const event of events || []) {
4018
+ if (!event || typeof event !== "object") continue;
4019
+ const stamp = stampOf2(event);
4020
+ if (event.type === "turn.prompt") {
4021
+ flushStep();
4022
+ if (event.origin?.kind !== "user") continue;
4023
+ const content = stripInjectedMemory(kimiPromptText(event.input)).trim();
4024
+ if (content) turns.push({ role: "user", content, ...stamp });
4025
+ continue;
4026
+ }
4027
+ if (event.type !== "context.append_loop_event") continue;
4028
+ const loop = event.event;
4029
+ if (!loop || typeof loop !== "object") continue;
4030
+ if (loop.type === "content.part") {
4031
+ if (loop.part?.type !== "text" || typeof loop.part.text !== "string") continue;
4032
+ const uuid = typeof loop.stepUuid === "string" ? loop.stepUuid : "";
4033
+ if (step && step.uuid !== uuid) flushStep();
4034
+ if (!step) step = { uuid, texts: [], stamp };
4035
+ step.texts.push(loop.part.text);
4036
+ } else if (loop.type === "tool.call") {
4037
+ flushStep();
4038
+ if (typeof loop.name !== "string" || !loop.name) continue;
4039
+ turns.push({ role: "action", content: actionLine(loop.name, loop.args), ...stamp });
4040
+ }
4041
+ }
4042
+ flushStep();
4043
+ return turns;
4044
+ }
4045
+ function agentIds(sessionDir) {
4046
+ try {
4047
+ return readdirSync4(join21(sessionDir, AGENTS_DIR), { withFileTypes: true }).filter((entry) => entry.isDirectory()).map((entry) => entry.name).sort(byAgentId);
4048
+ } catch {
4049
+ return [];
4050
+ }
4051
+ }
4052
+ function byAgentId(a, b) {
4053
+ if (a === b) return 0;
4054
+ if (a === MAIN_AGENT) return -1;
4055
+ if (b === MAIN_AGENT) return 1;
4056
+ const indexA = agentIndex(a);
4057
+ const indexB = agentIndex(b);
4058
+ return indexA === indexB ? a.localeCompare(b) : indexA - indexB;
4059
+ }
4060
+ function agentIndex(id) {
4061
+ const suffix = Number(id.slice(id.lastIndexOf("-") + 1));
4062
+ return Number.isFinite(suffix) ? suffix : Number.MAX_SAFE_INTEGER;
4063
+ }
4064
+ function parseEvent(rawLine) {
4065
+ const trimmed = rawLine.trim();
4066
+ if (!trimmed) return void 0;
4067
+ let parsed;
4068
+ try {
4069
+ parsed = JSON.parse(trimmed);
4070
+ } catch {
4071
+ return void 0;
4072
+ }
4073
+ return typeof parsed === "object" && parsed !== null ? parsed : void 0;
4074
+ }
4075
+ function readKimiTranscript(path) {
4076
+ const turns = [];
4077
+ let remaining = MAX_SESSION_CHARS;
4078
+ for (const agentId of agentIds(path)) {
4079
+ const wire = join21(path, AGENTS_DIR, agentId, WIRE_LOG);
4080
+ const events = [];
4081
+ for (const rawLine of readJsonl(wire)) {
4082
+ remaining -= rawLine.length;
4083
+ if (remaining < 0) break;
4084
+ const event = parseEvent(rawLine);
4085
+ if (event) events.push(event);
4086
+ }
4087
+ for (const turn of readKimiWire(events)) turns.push(turn);
4088
+ if (remaining < 0) {
4089
+ log.warn(HARNESS, "session exceeds the wire-log budget \u2014 later agents were not read", {
4090
+ sessionDir: path,
4091
+ stoppedAt: wire
4092
+ });
4093
+ break;
4094
+ }
4095
+ }
4096
+ return turns;
4097
+ }
4098
+
3279
4099
  // src/harness/hook-lifecycle.ts
3280
4100
  var cursorCwd = (ev) => ev.cwd ?? ev.workspace_root ?? (Array.isArray(ev.workspace_roots) ? ev.workspace_roots[0] : void 0);
3281
4101
  var claudePrompt = {
@@ -3354,7 +4174,7 @@ var copilotPrompt = {
3354
4174
  ${context}`.trim()
3355
4175
  })
3356
4176
  };
3357
- var devinCwd = () => process.env.DEVIN_PROJECT_DIR;
4177
+ var devinCwd = () => process.env.DEVIN_PROJECT_DIR || process.cwd();
3358
4178
  var devinPrompt = {
3359
4179
  harness: "devin-cli",
3360
4180
  requireCwd: true,
@@ -3381,6 +4201,7 @@ var standardSessionStart = (harness) => ({
3381
4201
  }
3382
4202
  })
3383
4203
  });
4204
+ var notGrokHosted = () => !process.env.GROK_HOOK_EVENT;
3384
4205
  var HOOK_HARNESSES = {
3385
4206
  "claude-code": {
3386
4207
  configStyle: "nested",
@@ -3389,11 +4210,12 @@ var HOOK_HARNESSES = {
3389
4210
  prompt: { event: "UserPromptSubmit", entry: "claude-hook.js", timeout: 30 },
3390
4211
  stop: { event: "Stop", entry: "claude-stop-hook.js", timeout: 60 }
3391
4212
  },
3392
- sessionStart: standardSessionStart("claude-code"),
3393
- prompt: claudePrompt,
4213
+ sessionStart: { ...standardSessionStart("claude-code"), accept: notGrokHosted },
4214
+ prompt: { ...claudePrompt, accept: notGrokHosted },
3394
4215
  retain: {
3395
4216
  hostTimeoutSec: 60,
3396
4217
  harness: "claude-code",
4218
+ accept: notGrokHosted,
3397
4219
  parse: (ev) => ({
3398
4220
  sessionId: ev.session_id,
3399
4221
  transcriptPath: ev.transcript_path,
@@ -3614,7 +4436,7 @@ var HOOK_HARNESSES = {
3614
4436
  // `detached` and terminates the whole process TREE on timeout, so the retain is genuinely lost
3615
4437
  // rather than merely orphaned. `retain.hostTimeoutSec` below stays SECONDS, as its name says;
3616
4438
  // these two numbers are the same budget in different units for this harness alone.
3617
- // The prompt timeout must also stay above core/hook.ts's HOOK_REFLECT_CAP_MS (25_000).
4439
+ // The prompt timeout must also stay above core/config.ts's DEFAULT_REFLECT_TIMEOUT_MS.
3618
4440
  install: {
3619
4441
  sessionStart: { event: "SessionStart", entry: "qwen-sessionstart-hook.js", timeout: 3e4 },
3620
4442
  prompt: { event: "UserPromptSubmit", entry: "qwen-hook.js", timeout: 3e4 },
@@ -3676,7 +4498,7 @@ var HOOK_HARNESSES = {
3676
4498
  zcode: {
3677
4499
  configStyle: "process",
3678
4500
  // ZCode's `timeoutMs`, so MILLISECONDS — see the qwen-code note above for the same trap. The
3679
- // prompt budget must stay above core/hook.ts's HOOK_REFLECT_CAP_MS (25_000).
4501
+ // prompt budget must stay above core/config.ts's DEFAULT_REFLECT_TIMEOUT_MS.
3680
4502
  timeoutUnit: "milliseconds",
3681
4503
  install: {
3682
4504
  sessionStart: { event: "SessionStart", entry: "zcode-sessionstart-hook.js", timeout: 3e4 },
@@ -3709,6 +4531,117 @@ var HOOK_HARNESSES = {
3709
4531
  assistantText: (ev) => (ev.responseText || zcodeAssistantText(ev.transcript_path) || ev.responsePreview || "").trim()
3710
4532
  }
3711
4533
  }
4534
+ },
4535
+ /**
4536
+ * TraeCode (TRAE CN's agent) also speaks Claude Code's hook protocol — `prompt`/`cwd`/`session_id`
4537
+ * in, `hookSpecificOutput.additionalContext` + `systemMessage` out — with registrations nested
4538
+ * under the top-level `hooks` key of `~/.trae-cn/hooks.json` (unlike Factory Droid, whose event
4539
+ * map IS the file) and a `version` field the host writes and expects.
4540
+ *
4541
+ * Like ZCode, what it does not have is a TRANSCRIPT: sessions live in an encrypted local DB or
4542
+ * the cloud and no `transcript_path` is ever supplied, so this is the second harness that retains
4543
+ * from the plugin's own journal (core/turn-journal.ts) — the prompt hook appends the user turn,
4544
+ * and Stop's `last_assistant_message` (the full reply) plays the role ZCode's `responseText`
4545
+ * plays: `journal.assistantText` closes the turn with it.
4546
+ */
4547
+ traecode: {
4548
+ configStyle: "nested",
4549
+ install: {
4550
+ sessionStart: { event: "SessionStart", entry: "traecode-sessionstart-hook.js", timeout: 30 },
4551
+ prompt: { event: "UserPromptSubmit", entry: "traecode-hook.js", timeout: 30 },
4552
+ stop: { event: "Stop", entry: "traecode-stop-hook.js", timeout: 60 }
4553
+ },
4554
+ sessionStart: {
4555
+ ...standardSessionStart("traecode"),
4556
+ // Trae launches USER-level MCP servers from the Electron process's cwd (home), where an
4557
+ // optInOnly config self-disables and the tools vanish. Each repo's own workspace file fixes
4558
+ // it — kept current here, once memory is confirmed live for the repo, along with the
4559
+ // workspace's per-server enable switch (seeded into Trae's storage DB,
4560
+ // core/traecode-mcp.ts). The returned hint (global gate off, or an unseedable switch)
4561
+ // rides the session banner.
4562
+ ensureMcpRegistration: (cwd) => ensureTraecodeWorkspaceMcp(cwd)
4563
+ },
4564
+ prompt: {
4565
+ ...claudePrompt,
4566
+ harness: "traecode",
4567
+ journalPrompt: true,
4568
+ // TraeCode's UserPromptSubmit payload carries `prompt` exactly like Claude Code's.
4569
+ parse: (ev) => ({
4570
+ prompt: ev.prompt,
4571
+ cwd: ev.cwd,
4572
+ sessionId: ev.session_id
4573
+ })
4574
+ },
4575
+ retain: {
4576
+ hostTimeoutSec: 60,
4577
+ harness: "traecode",
4578
+ // No transcriptPath: the journal supplies it (see `journal` below).
4579
+ parse: (ev) => ({
4580
+ sessionId: ev.session_id,
4581
+ cwd: ev.cwd
4582
+ }),
4583
+ journal: {
4584
+ // `last_assistant_message` is the full reply — TraeCode's `responseText`.
4585
+ assistantText: (ev) => (ev.last_assistant_message ?? "").trim()
4586
+ }
4587
+ }
4588
+ },
4589
+ "kimi-code": {
4590
+ // Kimi's ~/.kimi-code/config.toml takes a FLAT [[hooks]] array whose entries are validated by a
4591
+ // strict 4-key schema (event/matcher/command/timeout). Neither JSON style can express it, and a
4592
+ // fifth key drops EVERY hook in the file at warning severity, so its installer writes the block
4593
+ // itself (the grok-build pattern) rather than going through mergeHarnessHooks.
4594
+ configStyle: "toml-array",
4595
+ install: {
4596
+ // Timeouts are SECONDS here (integer 1-600, default 30) — the same unit as every other
4597
+ // supported host, and the opposite of qwen-code's identically named field.
4598
+ sessionStart: { event: "SessionStart", entry: "kimi-sessionstart-hook.js", timeout: 30 },
4599
+ prompt: { event: "UserPromptSubmit", entry: "kimi-hook.js", timeout: 30 },
4600
+ stop: { event: "Stop", entry: "kimi-stop-hook.js", timeout: 60 }
4601
+ },
4602
+ sessionStart: {
4603
+ harness: "kimi-code",
4604
+ parse: (ev) => ({
4605
+ cwd: ev.cwd,
4606
+ sessionId: ev.session_id
4607
+ }),
4608
+ // Kimi runs SessionStart hooks for their side effects only: it awaits the trigger and drops
4609
+ // the result, so nothing emitted here can reach the model or the terminal. Installed for the
4610
+ // seed/daemon/session-root work runSessionStartHook does, and silent like antigravity-cli's.
4611
+ emit: () => ({})
4612
+ },
4613
+ prompt: {
4614
+ harness: "kimi-code",
4615
+ parse: (ev) => ({
4616
+ // A block array, not a string — the same shape as the wire log's `turn.prompt.input`.
4617
+ prompt: kimiPromptText(ev.prompt),
4618
+ cwd: ev.cwd,
4619
+ sessionId: ev.session_id
4620
+ }),
4621
+ // Kimi has no additionalContext: a top-level `message` is the injection channel, which the
4622
+ // CLI wraps as <hook_result hook_event="UserPromptSubmit"> and appends to the conversation.
4623
+ // `notice` has no banner channel to reach (the copilot-cli precedent), but it cannot simply
4624
+ // be dropped: when a hook's stdout parses to JSON carrying no message, Kimi falls back to
4625
+ // injecting the RAW STDOUT, so an empty `{}` would put a literal "{}" in front of the model.
4626
+ // Emitting the notice on the notice-only turn is what keeps that from ever happening.
4627
+ emit: (context, notice) => ({ message: context || notice })
4628
+ },
4629
+ retain: {
4630
+ hostTimeoutSec: 60,
4631
+ harness: "kimi-code",
4632
+ parse: (ev) => {
4633
+ const sessionId = ev.session_id;
4634
+ return {
4635
+ sessionId,
4636
+ // Kimi's Stop payload carries no transcript path — its hook feature has no such field at
4637
+ // all — so resolve the session's own directory from the id, as grok-build does. The
4638
+ // reader takes that DIRECTORY and reads every agent's wire.jsonl beneath it.
4639
+ transcriptPath: sessionId ? kimiSessionDir(sessionId) : void 0,
4640
+ cwd: ev.cwd
4641
+ };
4642
+ },
4643
+ readTranscript: readKimiTranscript
4644
+ }
3712
4645
  }
3713
4646
  };
3714
4647
  var runHarnessSessionStart = (harness) => runSessionStartHook(HOOK_HARNESSES[harness].sessionStart);