@vectorize-io/hindsight-coding-agents 0.5.4 → 0.5.5

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 (46) hide show
  1. package/README.md +5 -2
  2. package/dist/antigravity-hook.js +121 -11
  3. package/dist/antigravity-stop-hook.js +56 -8
  4. package/dist/claude-hook.js +121 -11
  5. package/dist/claude-sessionstart-hook.js +56 -8
  6. package/dist/claude-stop-hook.js +56 -8
  7. package/dist/cline.js +121 -11
  8. package/dist/codex-hook.js +121 -11
  9. package/dist/codex-sessionstart-hook.js +56 -8
  10. package/dist/codex-stop-hook.js +56 -8
  11. package/dist/copilot-hook.js +121 -11
  12. package/dist/copilot-sessionstart-hook.js +56 -8
  13. package/dist/copilot-stop-hook.js +56 -8
  14. package/dist/cursor-hook.js +121 -11
  15. package/dist/cursor-sessionstart-hook.js +56 -8
  16. package/dist/cursor-stop-hook.js +56 -8
  17. package/dist/dcode-hook.js +121 -11
  18. package/dist/dcode-sessionstart-hook.js +56 -8
  19. package/dist/dcode-stop-hook.js +56 -8
  20. package/dist/deepen.js +56 -8
  21. package/dist/devin-hook.js +121 -11
  22. package/dist/devin-sessionstart-hook.js +56 -8
  23. package/dist/devin-stop-hook.js +56 -8
  24. package/dist/droid-hook.js +121 -11
  25. package/dist/droid-sessionstart-hook.js +56 -8
  26. package/dist/droid-stop-hook.js +56 -8
  27. package/dist/dsh.js +121 -11
  28. package/dist/grok-hook.js +121 -11
  29. package/dist/grok-sessionstart-hook.js +56 -8
  30. package/dist/grok-stop-hook.js +56 -8
  31. package/dist/index.js +121 -11
  32. package/dist/kilo.js +121 -11
  33. package/dist/mcp-server.js +56 -8
  34. package/dist/opencode2.js +121 -11
  35. package/dist/pi.js +121 -11
  36. package/dist/prime-agent.js +121 -11
  37. package/dist/qwen-hook.js +121 -11
  38. package/dist/qwen-sessionstart-hook.js +56 -8
  39. package/dist/qwen-stop-hook.js +56 -8
  40. package/dist/status.js +56 -8
  41. package/dist/zcode-hook.js +121 -11
  42. package/dist/zcode-sessionstart-hook.js +56 -8
  43. package/dist/zcode-stop-hook.js +56 -8
  44. package/package.json +1 -1
  45. package/plugin.json +1 -1
  46. package/skill/SKILL.md +5 -2
package/dist/index.js CHANGED
@@ -679,6 +679,22 @@ var KnowledgePagesUnavailableError = class extends Error {
679
679
  }
680
680
  };
681
681
  var TERMINAL = /* @__PURE__ */ new Set(["completed", "failed", "cancelled", "error"]);
682
+ var ReflectError = class extends Error {
683
+ constructor(message, status, timedOut, options) {
684
+ super(message, options);
685
+ this.status = status;
686
+ this.timedOut = timedOut;
687
+ this.name = "ReflectError";
688
+ }
689
+ status;
690
+ timedOut;
691
+ /** A timeout or a 5xx means reflect's synthesis (the slow LLM path) broke, while the cheap
692
+ * retrieval endpoints may still answer — worth falling back. A 4xx will fail the same way on
693
+ * every endpoint (auth, missing bank), so it is not. */
694
+ get fallbackEligible() {
695
+ return this.timedOut || this.status !== void 0 && this.status >= 500;
696
+ }
697
+ };
682
698
  var DEFAULT_MAX_PARALLEL_RETAINS = 10;
683
699
  var POLL_CYCLE_MS = 5e3;
684
700
  var RETRY_AFTER_FLOOR_MS = 10 * 1e3;
@@ -762,11 +778,11 @@ var HindsightClient = class {
762
778
  return `${this.apiUrl}/v1/default/banks/${encodeURIComponent(this.bank)}${suffix}`;
763
779
  }
764
780
  /** `tolerate` adds statuses that are returned to the caller instead of thrown (404 always is). */
765
- async req(method, url3, body, tolerate = []) {
781
+ async req(method, url3, body, tolerate = [], timeoutMs = 15e3) {
766
782
  const r = await this.fetchWithAuth(url3, {
767
783
  method,
768
784
  body: body ? JSON.stringify(body) : void 0,
769
- signal: AbortSignal.timeout(15e3)
785
+ signal: AbortSignal.timeout(timeoutMs)
770
786
  });
771
787
  if (r.status === 429 && !tolerate.includes(429))
772
788
  throw new RateLimitedError(retryAfterMs(r.headers.get("retry-after")));
@@ -959,7 +975,7 @@ var HindsightClient = class {
959
975
  /**
960
976
  * Reflect: synthesized, root-cause answer over the bank. Bounded so a slow server never hangs a
961
977
  * caller — but `timeoutMs` is REQUIRED, deliberately: the right deadline differs by an order of
962
- * magnitude between the automatic hook (25s, to fit the host's window) and the agent-invoked
978
+ * magnitude between the automatic hook (20s, to fit the host's window) and the agent-invoked
963
979
  * tool (minutes, on a populated bank). This used to default to 120s, which silently overrode the
964
980
  * tool's configured window and aborted every high-budget synthesis mid-flight (#3590).
965
981
  */
@@ -973,19 +989,45 @@ var HindsightClient = class {
973
989
  signal: ctrl.signal
974
990
  });
975
991
  if (!resp.ok)
976
- throw new Error(
977
- `reflect ${resp.status} ${(await resp.text()).slice(0, 1e3)}${this.authHint(resp.status)}`
992
+ throw new ReflectError(
993
+ `reflect ${resp.status} ${(await resp.text()).slice(0, 1e3)}${this.authHint(resp.status)}`,
994
+ resp.status,
995
+ false
978
996
  );
979
997
  const data = await resp.json();
980
998
  return (data.text || "").trim();
981
999
  } catch (e) {
982
1000
  if (ctrl.signal.aborted)
983
- throw new Error(`reflect timed out after ${opts.timeoutMs}ms`, { cause: e });
1001
+ throw new ReflectError(`reflect timed out after ${opts.timeoutMs}ms`, void 0, true, {
1002
+ cause: e
1003
+ });
984
1004
  throw e;
985
1005
  } finally {
986
1006
  clearTimeout(timer);
987
1007
  }
988
1008
  }
1009
+ /**
1010
+ * Raw recall restricted to consolidated observations — no LLM in the loop, so it still answers
1011
+ * when reflect's synthesis times out or 5xxs. Returns the observation texts in rank order.
1012
+ */
1013
+ async recallObservations(query, opts) {
1014
+ const r = await this.req(
1015
+ "POST",
1016
+ this.bankUrl("/memories/recall"),
1017
+ {
1018
+ query,
1019
+ types: ["observation"],
1020
+ budget: "low",
1021
+ max_tokens: opts.maxTokens,
1022
+ include: { entities: null }
1023
+ },
1024
+ [],
1025
+ opts.timeoutMs
1026
+ );
1027
+ if (r.status === 404) return [];
1028
+ const j = await r.json();
1029
+ return (j.results ?? []).map((x) => (x.text ?? "").trim()).filter(Boolean);
1030
+ }
989
1031
  /**
990
1032
  * The bank's knowledge-base tree (folders + pages, nested). The tree carries names, source
991
1033
  * queries and staleness but NOT synthesized content, so it is cheap enough to poll.
@@ -1050,10 +1092,16 @@ var HindsightClient = class {
1050
1092
  /** Hybrid (BM25 + vector, RRF-fused) server-side search over the bank's knowledge pages.
1051
1093
  * Returns page-level hits with a relevance snippet — the real search behind
1052
1094
  * hindsight_search_knowledge_pages. */
1053
- async searchKnowledgePages(query, limit = 3) {
1095
+ async searchKnowledgePages(query, limit = 3, timeoutMs) {
1054
1096
  if (this.knowledgePagesSupported === false) throw new KnowledgePagesUnavailableError();
1055
1097
  const q = `?q=${encodeURIComponent(query)}&limit=${limit}`;
1056
- const r = await this.req("GET", this.bankUrl(`/knowledge-base/search${q}`));
1098
+ const r = await this.req(
1099
+ "GET",
1100
+ this.bankUrl(`/knowledge-base/search${q}`),
1101
+ void 0,
1102
+ [],
1103
+ timeoutMs
1104
+ );
1057
1105
  const j = await r.json();
1058
1106
  return (j.results ?? []).map((x) => ({
1059
1107
  id: x.id,
@@ -17495,6 +17543,15 @@ Report what this bank's history genuinely bears on that goal. Rendering rules, s
17495
17543
  - Do not connect unrelated episodes into one narrative; if two facts are not explicitly linked in the record, report them separately or leave the weaker one out.
17496
17544
  - If the bank holds nothing that bears on the goal, say so in one line.`;
17497
17545
  }
17546
+ function formatPageFallback(hits) {
17547
+ return "(Hindsight's synthesis was unavailable this turn; these knowledge pages matched the goal by search. Read one with hindsight_read_knowledge_page(<id>) if it looks relevant.)\n" + hits.map((h) => {
17548
+ const snippet = h.snippet.replace(/\s+/g, " ").trim();
17549
+ return `- ${h.name} (${h.id})${snippet ? `: ${snippet}` : ""}`;
17550
+ }).join("\n");
17551
+ }
17552
+ function formatObservationFallback(observations) {
17553
+ return "(Hindsight's synthesis was unavailable this turn; these consolidated observations were recalled from the bank for the goal, unsynthesized.)\n" + observations.map((o) => `- ${o.replace(/\s+/g, " ").trim()}`).join("\n");
17554
+ }
17498
17555
  function buildSystemInjection(memory) {
17499
17556
  return `<hindsight_memory>
17500
17557
  Automatically retrieved by Hindsight from THIS repository's own history (git rationale and past developer sessions) \u2014 real memory, but retrieval is heuristic: it may or may not bear on the current task.
@@ -17552,7 +17609,52 @@ function actionLine(tool2, input) {
17552
17609
  var JOURNAL_MAX_BYTES = 8 * 1024 * 1024;
17553
17610
 
17554
17611
  // src/core/hook.ts
17555
- var HOOK_REFLECT_CAP_MS = 25e3;
17612
+ var HOOK_REFLECT_CAP_MS = 2e4;
17613
+ var HOOK_FALLBACK_BUDGET_MS = 7e3;
17614
+ var FALLBACK_PAGE_LIMIT = 3;
17615
+ var FALLBACK_RECALL_MAX_TOKENS = 2e3;
17616
+ async function reflectFallback(harness, prompt, client) {
17617
+ const deadline = Date.now() + HOOK_FALLBACK_BUDGET_MS;
17618
+ const remaining = () => Math.max(deadline - Date.now(), 1);
17619
+ const query = prompt.slice(0, 500);
17620
+ let t0 = Date.now();
17621
+ try {
17622
+ const hits = await client.searchKnowledgePages(query, FALLBACK_PAGE_LIMIT, remaining());
17623
+ diag(harness, "reflect_fallback_pages", { ms: Date.now() - t0, count: hits.length });
17624
+ if (hits.length) {
17625
+ return { memory: formatPageFallback(hits), source: "knowledge_pages", count: hits.length };
17626
+ }
17627
+ } catch (e) {
17628
+ diag(harness, "reflect_fallback_pages_failed", {
17629
+ ms: Date.now() - t0,
17630
+ error: describeError(e)
17631
+ });
17632
+ }
17633
+ t0 = Date.now();
17634
+ try {
17635
+ const observations = await client.recallObservations(prompt.slice(0, 2e3), {
17636
+ maxTokens: FALLBACK_RECALL_MAX_TOKENS,
17637
+ timeoutMs: remaining()
17638
+ });
17639
+ diag(harness, "reflect_fallback_observations", {
17640
+ ms: Date.now() - t0,
17641
+ count: observations.length
17642
+ });
17643
+ if (observations.length) {
17644
+ return {
17645
+ memory: formatObservationFallback(observations),
17646
+ source: "observations",
17647
+ count: observations.length
17648
+ };
17649
+ }
17650
+ } catch (e) {
17651
+ diag(harness, "reflect_fallback_observations_failed", {
17652
+ ms: Date.now() - t0,
17653
+ error: describeError(e)
17654
+ });
17655
+ }
17656
+ return void 0;
17657
+ }
17556
17658
  async function buildHookOutput(args) {
17557
17659
  const { harness, prompt, cfg, client, cacheFile } = args;
17558
17660
  const cached3 = readSessionCache(cacheFile);
@@ -17560,6 +17662,7 @@ async function buildHookOutput(args) {
17560
17662
  let reflectAnswer = cached3.reflectAnswer;
17561
17663
  let reflectRanThisTurn = false;
17562
17664
  let reflectFailed = false;
17665
+ let fallback;
17563
17666
  const deferInitialReflect = cached3.deferInitialReflect === true;
17564
17667
  if (deferInitialReflect) {
17565
17668
  diag(harness, "reflect_deferred_new_bank", { query: prompt.slice(0, 80) });
@@ -17569,7 +17672,7 @@ async function buildHookOutput(args) {
17569
17672
  const timeoutMs = Math.min(cfg.reflectTimeoutMs, HOOK_REFLECT_CAP_MS);
17570
17673
  try {
17571
17674
  reflectAnswer = await client.reflect(buildReflectQuery(prompt), {
17572
- // Automatic reflection runs inside a hard 25s hook window. Hindsight's low budget is the
17675
+ // Automatic reflection runs inside a hard 20s slot of the hook window. Hindsight's low budget is the
17573
17676
  // supported default for bounded reflect calls; callers that explicitly invoke the MCP
17574
17677
  // tool still get the deeper high-budget path.
17575
17678
  budget: "low",
@@ -17597,6 +17700,10 @@ async function buildHookOutput(args) {
17597
17700
  error: describeError(e, 1500),
17598
17701
  query: prompt.slice(0, 80)
17599
17702
  });
17703
+ if (e instanceof ReflectError && e.fallbackEligible) {
17704
+ fallback = await reflectFallback(harness, prompt, client);
17705
+ if (fallback) reflectAnswer = fallback.memory;
17706
+ }
17600
17707
  }
17601
17708
  }
17602
17709
  const cadence = cfg.pageRefreshEveryTurns;
@@ -17630,7 +17737,10 @@ async function buildHookOutput(args) {
17630
17737
  }
17631
17738
  const kept = blocks.filter(Boolean);
17632
17739
  let notice;
17633
- if (reflectRanThisTurn && reflectAnswer) {
17740
+ if (fallback) {
17741
+ const what = fallback.source === "knowledge_pages" ? "knowledge page" : "observation";
17742
+ notice = `${brandWord()} \xB7 reflect unavailable \u2014 fell back to ${fallback.count} ${what}${fallback.count === 1 ? "" : "s"} (see ${diagFilePath()})`;
17743
+ } else if (reflectRanThisTurn && reflectAnswer) {
17634
17744
  const q = prompt.replace(/\s+/g, " ").trim();
17635
17745
  const excerpt = q.length > 48 ? `${q.slice(0, 48)}\u2026` : q;
17636
17746
  const preview = reflectAnswer.replace(/\s+/g, " ").trim();
package/dist/kilo.js CHANGED
@@ -679,6 +679,22 @@ var KnowledgePagesUnavailableError = class extends Error {
679
679
  }
680
680
  };
681
681
  var TERMINAL = /* @__PURE__ */ new Set(["completed", "failed", "cancelled", "error"]);
682
+ var ReflectError = class extends Error {
683
+ constructor(message, status, timedOut, options) {
684
+ super(message, options);
685
+ this.status = status;
686
+ this.timedOut = timedOut;
687
+ this.name = "ReflectError";
688
+ }
689
+ status;
690
+ timedOut;
691
+ /** A timeout or a 5xx means reflect's synthesis (the slow LLM path) broke, while the cheap
692
+ * retrieval endpoints may still answer — worth falling back. A 4xx will fail the same way on
693
+ * every endpoint (auth, missing bank), so it is not. */
694
+ get fallbackEligible() {
695
+ return this.timedOut || this.status !== void 0 && this.status >= 500;
696
+ }
697
+ };
682
698
  var DEFAULT_MAX_PARALLEL_RETAINS = 10;
683
699
  var POLL_CYCLE_MS = 5e3;
684
700
  var RETRY_AFTER_FLOOR_MS = 10 * 1e3;
@@ -762,11 +778,11 @@ var HindsightClient = class {
762
778
  return `${this.apiUrl}/v1/default/banks/${encodeURIComponent(this.bank)}${suffix}`;
763
779
  }
764
780
  /** `tolerate` adds statuses that are returned to the caller instead of thrown (404 always is). */
765
- async req(method, url3, body, tolerate = []) {
781
+ async req(method, url3, body, tolerate = [], timeoutMs = 15e3) {
766
782
  const r = await this.fetchWithAuth(url3, {
767
783
  method,
768
784
  body: body ? JSON.stringify(body) : void 0,
769
- signal: AbortSignal.timeout(15e3)
785
+ signal: AbortSignal.timeout(timeoutMs)
770
786
  });
771
787
  if (r.status === 429 && !tolerate.includes(429))
772
788
  throw new RateLimitedError(retryAfterMs(r.headers.get("retry-after")));
@@ -959,7 +975,7 @@ var HindsightClient = class {
959
975
  /**
960
976
  * Reflect: synthesized, root-cause answer over the bank. Bounded so a slow server never hangs a
961
977
  * caller — but `timeoutMs` is REQUIRED, deliberately: the right deadline differs by an order of
962
- * magnitude between the automatic hook (25s, to fit the host's window) and the agent-invoked
978
+ * magnitude between the automatic hook (20s, to fit the host's window) and the agent-invoked
963
979
  * tool (minutes, on a populated bank). This used to default to 120s, which silently overrode the
964
980
  * tool's configured window and aborted every high-budget synthesis mid-flight (#3590).
965
981
  */
@@ -973,19 +989,45 @@ var HindsightClient = class {
973
989
  signal: ctrl.signal
974
990
  });
975
991
  if (!resp.ok)
976
- throw new Error(
977
- `reflect ${resp.status} ${(await resp.text()).slice(0, 1e3)}${this.authHint(resp.status)}`
992
+ throw new ReflectError(
993
+ `reflect ${resp.status} ${(await resp.text()).slice(0, 1e3)}${this.authHint(resp.status)}`,
994
+ resp.status,
995
+ false
978
996
  );
979
997
  const data = await resp.json();
980
998
  return (data.text || "").trim();
981
999
  } catch (e) {
982
1000
  if (ctrl.signal.aborted)
983
- throw new Error(`reflect timed out after ${opts.timeoutMs}ms`, { cause: e });
1001
+ throw new ReflectError(`reflect timed out after ${opts.timeoutMs}ms`, void 0, true, {
1002
+ cause: e
1003
+ });
984
1004
  throw e;
985
1005
  } finally {
986
1006
  clearTimeout(timer);
987
1007
  }
988
1008
  }
1009
+ /**
1010
+ * Raw recall restricted to consolidated observations — no LLM in the loop, so it still answers
1011
+ * when reflect's synthesis times out or 5xxs. Returns the observation texts in rank order.
1012
+ */
1013
+ async recallObservations(query, opts) {
1014
+ const r = await this.req(
1015
+ "POST",
1016
+ this.bankUrl("/memories/recall"),
1017
+ {
1018
+ query,
1019
+ types: ["observation"],
1020
+ budget: "low",
1021
+ max_tokens: opts.maxTokens,
1022
+ include: { entities: null }
1023
+ },
1024
+ [],
1025
+ opts.timeoutMs
1026
+ );
1027
+ if (r.status === 404) return [];
1028
+ const j = await r.json();
1029
+ return (j.results ?? []).map((x) => (x.text ?? "").trim()).filter(Boolean);
1030
+ }
989
1031
  /**
990
1032
  * The bank's knowledge-base tree (folders + pages, nested). The tree carries names, source
991
1033
  * queries and staleness but NOT synthesized content, so it is cheap enough to poll.
@@ -1050,10 +1092,16 @@ var HindsightClient = class {
1050
1092
  /** Hybrid (BM25 + vector, RRF-fused) server-side search over the bank's knowledge pages.
1051
1093
  * Returns page-level hits with a relevance snippet — the real search behind
1052
1094
  * hindsight_search_knowledge_pages. */
1053
- async searchKnowledgePages(query, limit = 3) {
1095
+ async searchKnowledgePages(query, limit = 3, timeoutMs) {
1054
1096
  if (this.knowledgePagesSupported === false) throw new KnowledgePagesUnavailableError();
1055
1097
  const q = `?q=${encodeURIComponent(query)}&limit=${limit}`;
1056
- const r = await this.req("GET", this.bankUrl(`/knowledge-base/search${q}`));
1098
+ const r = await this.req(
1099
+ "GET",
1100
+ this.bankUrl(`/knowledge-base/search${q}`),
1101
+ void 0,
1102
+ [],
1103
+ timeoutMs
1104
+ );
1057
1105
  const j = await r.json();
1058
1106
  return (j.results ?? []).map((x) => ({
1059
1107
  id: x.id,
@@ -17495,6 +17543,15 @@ Report what this bank's history genuinely bears on that goal. Rendering rules, s
17495
17543
  - Do not connect unrelated episodes into one narrative; if two facts are not explicitly linked in the record, report them separately or leave the weaker one out.
17496
17544
  - If the bank holds nothing that bears on the goal, say so in one line.`;
17497
17545
  }
17546
+ function formatPageFallback(hits) {
17547
+ return "(Hindsight's synthesis was unavailable this turn; these knowledge pages matched the goal by search. Read one with hindsight_read_knowledge_page(<id>) if it looks relevant.)\n" + hits.map((h) => {
17548
+ const snippet = h.snippet.replace(/\s+/g, " ").trim();
17549
+ return `- ${h.name} (${h.id})${snippet ? `: ${snippet}` : ""}`;
17550
+ }).join("\n");
17551
+ }
17552
+ function formatObservationFallback(observations) {
17553
+ return "(Hindsight's synthesis was unavailable this turn; these consolidated observations were recalled from the bank for the goal, unsynthesized.)\n" + observations.map((o) => `- ${o.replace(/\s+/g, " ").trim()}`).join("\n");
17554
+ }
17498
17555
  function buildSystemInjection(memory) {
17499
17556
  return `<hindsight_memory>
17500
17557
  Automatically retrieved by Hindsight from THIS repository's own history (git rationale and past developer sessions) \u2014 real memory, but retrieval is heuristic: it may or may not bear on the current task.
@@ -17552,7 +17609,52 @@ function actionLine(tool2, input) {
17552
17609
  var JOURNAL_MAX_BYTES = 8 * 1024 * 1024;
17553
17610
 
17554
17611
  // src/core/hook.ts
17555
- var HOOK_REFLECT_CAP_MS = 25e3;
17612
+ var HOOK_REFLECT_CAP_MS = 2e4;
17613
+ var HOOK_FALLBACK_BUDGET_MS = 7e3;
17614
+ var FALLBACK_PAGE_LIMIT = 3;
17615
+ var FALLBACK_RECALL_MAX_TOKENS = 2e3;
17616
+ async function reflectFallback(harness, prompt, client) {
17617
+ const deadline = Date.now() + HOOK_FALLBACK_BUDGET_MS;
17618
+ const remaining = () => Math.max(deadline - Date.now(), 1);
17619
+ const query = prompt.slice(0, 500);
17620
+ let t0 = Date.now();
17621
+ try {
17622
+ const hits = await client.searchKnowledgePages(query, FALLBACK_PAGE_LIMIT, remaining());
17623
+ diag(harness, "reflect_fallback_pages", { ms: Date.now() - t0, count: hits.length });
17624
+ if (hits.length) {
17625
+ return { memory: formatPageFallback(hits), source: "knowledge_pages", count: hits.length };
17626
+ }
17627
+ } catch (e) {
17628
+ diag(harness, "reflect_fallback_pages_failed", {
17629
+ ms: Date.now() - t0,
17630
+ error: describeError(e)
17631
+ });
17632
+ }
17633
+ t0 = Date.now();
17634
+ try {
17635
+ const observations = await client.recallObservations(prompt.slice(0, 2e3), {
17636
+ maxTokens: FALLBACK_RECALL_MAX_TOKENS,
17637
+ timeoutMs: remaining()
17638
+ });
17639
+ diag(harness, "reflect_fallback_observations", {
17640
+ ms: Date.now() - t0,
17641
+ count: observations.length
17642
+ });
17643
+ if (observations.length) {
17644
+ return {
17645
+ memory: formatObservationFallback(observations),
17646
+ source: "observations",
17647
+ count: observations.length
17648
+ };
17649
+ }
17650
+ } catch (e) {
17651
+ diag(harness, "reflect_fallback_observations_failed", {
17652
+ ms: Date.now() - t0,
17653
+ error: describeError(e)
17654
+ });
17655
+ }
17656
+ return void 0;
17657
+ }
17556
17658
  async function buildHookOutput(args) {
17557
17659
  const { harness, prompt, cfg, client, cacheFile } = args;
17558
17660
  const cached3 = readSessionCache(cacheFile);
@@ -17560,6 +17662,7 @@ async function buildHookOutput(args) {
17560
17662
  let reflectAnswer = cached3.reflectAnswer;
17561
17663
  let reflectRanThisTurn = false;
17562
17664
  let reflectFailed = false;
17665
+ let fallback;
17563
17666
  const deferInitialReflect = cached3.deferInitialReflect === true;
17564
17667
  if (deferInitialReflect) {
17565
17668
  diag(harness, "reflect_deferred_new_bank", { query: prompt.slice(0, 80) });
@@ -17569,7 +17672,7 @@ async function buildHookOutput(args) {
17569
17672
  const timeoutMs = Math.min(cfg.reflectTimeoutMs, HOOK_REFLECT_CAP_MS);
17570
17673
  try {
17571
17674
  reflectAnswer = await client.reflect(buildReflectQuery(prompt), {
17572
- // Automatic reflection runs inside a hard 25s hook window. Hindsight's low budget is the
17675
+ // Automatic reflection runs inside a hard 20s slot of the hook window. Hindsight's low budget is the
17573
17676
  // supported default for bounded reflect calls; callers that explicitly invoke the MCP
17574
17677
  // tool still get the deeper high-budget path.
17575
17678
  budget: "low",
@@ -17597,6 +17700,10 @@ async function buildHookOutput(args) {
17597
17700
  error: describeError(e, 1500),
17598
17701
  query: prompt.slice(0, 80)
17599
17702
  });
17703
+ if (e instanceof ReflectError && e.fallbackEligible) {
17704
+ fallback = await reflectFallback(harness, prompt, client);
17705
+ if (fallback) reflectAnswer = fallback.memory;
17706
+ }
17600
17707
  }
17601
17708
  }
17602
17709
  const cadence = cfg.pageRefreshEveryTurns;
@@ -17630,7 +17737,10 @@ async function buildHookOutput(args) {
17630
17737
  }
17631
17738
  const kept = blocks.filter(Boolean);
17632
17739
  let notice;
17633
- if (reflectRanThisTurn && reflectAnswer) {
17740
+ if (fallback) {
17741
+ const what = fallback.source === "knowledge_pages" ? "knowledge page" : "observation";
17742
+ notice = `${brandWord()} \xB7 reflect unavailable \u2014 fell back to ${fallback.count} ${what}${fallback.count === 1 ? "" : "s"} (see ${diagFilePath()})`;
17743
+ } else if (reflectRanThisTurn && reflectAnswer) {
17634
17744
  const q = prompt.replace(/\s+/g, " ").trim();
17635
17745
  const excerpt = q.length > 48 ? `${q.slice(0, 48)}\u2026` : q;
17636
17746
  const preview = reflectAnswer.replace(/\s+/g, " ").trim();
@@ -31887,6 +31887,22 @@ var KnowledgePagesUnavailableError = class extends Error {
31887
31887
  }
31888
31888
  };
31889
31889
  var TERMINAL = /* @__PURE__ */ new Set(["completed", "failed", "cancelled", "error"]);
31890
+ var ReflectError = class extends Error {
31891
+ constructor(message, status, timedOut, options) {
31892
+ super(message, options);
31893
+ this.status = status;
31894
+ this.timedOut = timedOut;
31895
+ this.name = "ReflectError";
31896
+ }
31897
+ status;
31898
+ timedOut;
31899
+ /** A timeout or a 5xx means reflect's synthesis (the slow LLM path) broke, while the cheap
31900
+ * retrieval endpoints may still answer — worth falling back. A 4xx will fail the same way on
31901
+ * every endpoint (auth, missing bank), so it is not. */
31902
+ get fallbackEligible() {
31903
+ return this.timedOut || this.status !== void 0 && this.status >= 500;
31904
+ }
31905
+ };
31890
31906
  var DEFAULT_MAX_PARALLEL_RETAINS = 10;
31891
31907
  var POLL_CYCLE_MS = 5e3;
31892
31908
  var RETRY_AFTER_FLOOR_MS = 10 * 1e3;
@@ -31970,11 +31986,11 @@ var HindsightClient = class {
31970
31986
  return `${this.apiUrl}/v1/default/banks/${encodeURIComponent(this.bank)}${suffix}`;
31971
31987
  }
31972
31988
  /** `tolerate` adds statuses that are returned to the caller instead of thrown (404 always is). */
31973
- async req(method, url2, body, tolerate = []) {
31989
+ async req(method, url2, body, tolerate = [], timeoutMs = 15e3) {
31974
31990
  const r = await this.fetchWithAuth(url2, {
31975
31991
  method,
31976
31992
  body: body ? JSON.stringify(body) : void 0,
31977
- signal: AbortSignal.timeout(15e3)
31993
+ signal: AbortSignal.timeout(timeoutMs)
31978
31994
  });
31979
31995
  if (r.status === 429 && !tolerate.includes(429))
31980
31996
  throw new RateLimitedError(retryAfterMs(r.headers.get("retry-after")));
@@ -32167,7 +32183,7 @@ var HindsightClient = class {
32167
32183
  /**
32168
32184
  * Reflect: synthesized, root-cause answer over the bank. Bounded so a slow server never hangs a
32169
32185
  * caller — but `timeoutMs` is REQUIRED, deliberately: the right deadline differs by an order of
32170
- * magnitude between the automatic hook (25s, to fit the host's window) and the agent-invoked
32186
+ * magnitude between the automatic hook (20s, to fit the host's window) and the agent-invoked
32171
32187
  * tool (minutes, on a populated bank). This used to default to 120s, which silently overrode the
32172
32188
  * tool's configured window and aborted every high-budget synthesis mid-flight (#3590).
32173
32189
  */
@@ -32181,19 +32197,45 @@ var HindsightClient = class {
32181
32197
  signal: ctrl.signal
32182
32198
  });
32183
32199
  if (!resp.ok)
32184
- throw new Error(
32185
- `reflect ${resp.status} ${(await resp.text()).slice(0, 1e3)}${this.authHint(resp.status)}`
32200
+ throw new ReflectError(
32201
+ `reflect ${resp.status} ${(await resp.text()).slice(0, 1e3)}${this.authHint(resp.status)}`,
32202
+ resp.status,
32203
+ false
32186
32204
  );
32187
32205
  const data = await resp.json();
32188
32206
  return (data.text || "").trim();
32189
32207
  } catch (e) {
32190
32208
  if (ctrl.signal.aborted)
32191
- throw new Error(`reflect timed out after ${opts.timeoutMs}ms`, { cause: e });
32209
+ throw new ReflectError(`reflect timed out after ${opts.timeoutMs}ms`, void 0, true, {
32210
+ cause: e
32211
+ });
32192
32212
  throw e;
32193
32213
  } finally {
32194
32214
  clearTimeout(timer);
32195
32215
  }
32196
32216
  }
32217
+ /**
32218
+ * Raw recall restricted to consolidated observations — no LLM in the loop, so it still answers
32219
+ * when reflect's synthesis times out or 5xxs. Returns the observation texts in rank order.
32220
+ */
32221
+ async recallObservations(query, opts) {
32222
+ const r = await this.req(
32223
+ "POST",
32224
+ this.bankUrl("/memories/recall"),
32225
+ {
32226
+ query,
32227
+ types: ["observation"],
32228
+ budget: "low",
32229
+ max_tokens: opts.maxTokens,
32230
+ include: { entities: null }
32231
+ },
32232
+ [],
32233
+ opts.timeoutMs
32234
+ );
32235
+ if (r.status === 404) return [];
32236
+ const j = await r.json();
32237
+ return (j.results ?? []).map((x) => (x.text ?? "").trim()).filter(Boolean);
32238
+ }
32197
32239
  /**
32198
32240
  * The bank's knowledge-base tree (folders + pages, nested). The tree carries names, source
32199
32241
  * queries and staleness but NOT synthesized content, so it is cheap enough to poll.
@@ -32258,10 +32300,16 @@ var HindsightClient = class {
32258
32300
  /** Hybrid (BM25 + vector, RRF-fused) server-side search over the bank's knowledge pages.
32259
32301
  * Returns page-level hits with a relevance snippet — the real search behind
32260
32302
  * hindsight_search_knowledge_pages. */
32261
- async searchKnowledgePages(query, limit = 3) {
32303
+ async searchKnowledgePages(query, limit = 3, timeoutMs) {
32262
32304
  if (this.knowledgePagesSupported === false) throw new KnowledgePagesUnavailableError();
32263
32305
  const q = `?q=${encodeURIComponent(query)}&limit=${limit}`;
32264
- const r = await this.req("GET", this.bankUrl(`/knowledge-base/search${q}`));
32306
+ const r = await this.req(
32307
+ "GET",
32308
+ this.bankUrl(`/knowledge-base/search${q}`),
32309
+ void 0,
32310
+ [],
32311
+ timeoutMs
32312
+ );
32265
32313
  const j = await r.json();
32266
32314
  return (j.results ?? []).map((x) => ({
32267
32315
  id: x.id,