@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/opencode2.js CHANGED
@@ -15190,6 +15190,22 @@ var KnowledgePagesUnavailableError = class extends Error {
15190
15190
  }
15191
15191
  };
15192
15192
  var TERMINAL = /* @__PURE__ */ new Set(["completed", "failed", "cancelled", "error"]);
15193
+ var ReflectError = class extends Error {
15194
+ constructor(message, status, timedOut, options) {
15195
+ super(message, options);
15196
+ this.status = status;
15197
+ this.timedOut = timedOut;
15198
+ this.name = "ReflectError";
15199
+ }
15200
+ status;
15201
+ timedOut;
15202
+ /** A timeout or a 5xx means reflect's synthesis (the slow LLM path) broke, while the cheap
15203
+ * retrieval endpoints may still answer — worth falling back. A 4xx will fail the same way on
15204
+ * every endpoint (auth, missing bank), so it is not. */
15205
+ get fallbackEligible() {
15206
+ return this.timedOut || this.status !== void 0 && this.status >= 500;
15207
+ }
15208
+ };
15193
15209
  var DEFAULT_MAX_PARALLEL_RETAINS = 10;
15194
15210
  var POLL_CYCLE_MS = 5e3;
15195
15211
  var RETRY_AFTER_FLOOR_MS = 10 * 1e3;
@@ -15273,11 +15289,11 @@ var HindsightClient = class {
15273
15289
  return `${this.apiUrl}/v1/default/banks/${encodeURIComponent(this.bank)}${suffix}`;
15274
15290
  }
15275
15291
  /** `tolerate` adds statuses that are returned to the caller instead of thrown (404 always is). */
15276
- async req(method, url3, body, tolerate = []) {
15292
+ async req(method, url3, body, tolerate = [], timeoutMs = 15e3) {
15277
15293
  const r = await this.fetchWithAuth(url3, {
15278
15294
  method,
15279
15295
  body: body ? JSON.stringify(body) : void 0,
15280
- signal: AbortSignal.timeout(15e3)
15296
+ signal: AbortSignal.timeout(timeoutMs)
15281
15297
  });
15282
15298
  if (r.status === 429 && !tolerate.includes(429))
15283
15299
  throw new RateLimitedError(retryAfterMs(r.headers.get("retry-after")));
@@ -15470,7 +15486,7 @@ var HindsightClient = class {
15470
15486
  /**
15471
15487
  * Reflect: synthesized, root-cause answer over the bank. Bounded so a slow server never hangs a
15472
15488
  * caller — but `timeoutMs` is REQUIRED, deliberately: the right deadline differs by an order of
15473
- * magnitude between the automatic hook (25s, to fit the host's window) and the agent-invoked
15489
+ * magnitude between the automatic hook (20s, to fit the host's window) and the agent-invoked
15474
15490
  * tool (minutes, on a populated bank). This used to default to 120s, which silently overrode the
15475
15491
  * tool's configured window and aborted every high-budget synthesis mid-flight (#3590).
15476
15492
  */
@@ -15484,19 +15500,45 @@ var HindsightClient = class {
15484
15500
  signal: ctrl.signal
15485
15501
  });
15486
15502
  if (!resp.ok)
15487
- throw new Error(
15488
- `reflect ${resp.status} ${(await resp.text()).slice(0, 1e3)}${this.authHint(resp.status)}`
15503
+ throw new ReflectError(
15504
+ `reflect ${resp.status} ${(await resp.text()).slice(0, 1e3)}${this.authHint(resp.status)}`,
15505
+ resp.status,
15506
+ false
15489
15507
  );
15490
15508
  const data = await resp.json();
15491
15509
  return (data.text || "").trim();
15492
15510
  } catch (e) {
15493
15511
  if (ctrl.signal.aborted)
15494
- throw new Error(`reflect timed out after ${opts.timeoutMs}ms`, { cause: e });
15512
+ throw new ReflectError(`reflect timed out after ${opts.timeoutMs}ms`, void 0, true, {
15513
+ cause: e
15514
+ });
15495
15515
  throw e;
15496
15516
  } finally {
15497
15517
  clearTimeout(timer);
15498
15518
  }
15499
15519
  }
15520
+ /**
15521
+ * Raw recall restricted to consolidated observations — no LLM in the loop, so it still answers
15522
+ * when reflect's synthesis times out or 5xxs. Returns the observation texts in rank order.
15523
+ */
15524
+ async recallObservations(query, opts) {
15525
+ const r = await this.req(
15526
+ "POST",
15527
+ this.bankUrl("/memories/recall"),
15528
+ {
15529
+ query,
15530
+ types: ["observation"],
15531
+ budget: "low",
15532
+ max_tokens: opts.maxTokens,
15533
+ include: { entities: null }
15534
+ },
15535
+ [],
15536
+ opts.timeoutMs
15537
+ );
15538
+ if (r.status === 404) return [];
15539
+ const j = await r.json();
15540
+ return (j.results ?? []).map((x) => (x.text ?? "").trim()).filter(Boolean);
15541
+ }
15500
15542
  /**
15501
15543
  * The bank's knowledge-base tree (folders + pages, nested). The tree carries names, source
15502
15544
  * queries and staleness but NOT synthesized content, so it is cheap enough to poll.
@@ -15561,10 +15603,16 @@ var HindsightClient = class {
15561
15603
  /** Hybrid (BM25 + vector, RRF-fused) server-side search over the bank's knowledge pages.
15562
15604
  * Returns page-level hits with a relevance snippet — the real search behind
15563
15605
  * hindsight_search_knowledge_pages. */
15564
- async searchKnowledgePages(query, limit = 3) {
15606
+ async searchKnowledgePages(query, limit = 3, timeoutMs) {
15565
15607
  if (this.knowledgePagesSupported === false) throw new KnowledgePagesUnavailableError();
15566
15608
  const q = `?q=${encodeURIComponent(query)}&limit=${limit}`;
15567
- const r = await this.req("GET", this.bankUrl(`/knowledge-base/search${q}`));
15609
+ const r = await this.req(
15610
+ "GET",
15611
+ this.bankUrl(`/knowledge-base/search${q}`),
15612
+ void 0,
15613
+ [],
15614
+ timeoutMs
15615
+ );
15568
15616
  const j = await r.json();
15569
15617
  return (j.results ?? []).map((x) => ({
15570
15618
  id: x.id,
@@ -17481,6 +17529,15 @@ Report what this bank's history genuinely bears on that goal. Rendering rules, s
17481
17529
  - 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.
17482
17530
  - If the bank holds nothing that bears on the goal, say so in one line.`;
17483
17531
  }
17532
+ function formatPageFallback(hits) {
17533
+ 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) => {
17534
+ const snippet = h.snippet.replace(/\s+/g, " ").trim();
17535
+ return `- ${h.name} (${h.id})${snippet ? `: ${snippet}` : ""}`;
17536
+ }).join("\n");
17537
+ }
17538
+ function formatObservationFallback(observations) {
17539
+ 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");
17540
+ }
17484
17541
  function buildSystemInjection(memory) {
17485
17542
  return `<hindsight_memory>
17486
17543
  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.
@@ -17538,7 +17595,52 @@ function actionLine(tool2, input) {
17538
17595
  var JOURNAL_MAX_BYTES = 8 * 1024 * 1024;
17539
17596
 
17540
17597
  // src/core/hook.ts
17541
- var HOOK_REFLECT_CAP_MS = 25e3;
17598
+ var HOOK_REFLECT_CAP_MS = 2e4;
17599
+ var HOOK_FALLBACK_BUDGET_MS = 7e3;
17600
+ var FALLBACK_PAGE_LIMIT = 3;
17601
+ var FALLBACK_RECALL_MAX_TOKENS = 2e3;
17602
+ async function reflectFallback(harness, prompt, client) {
17603
+ const deadline = Date.now() + HOOK_FALLBACK_BUDGET_MS;
17604
+ const remaining = () => Math.max(deadline - Date.now(), 1);
17605
+ const query = prompt.slice(0, 500);
17606
+ let t0 = Date.now();
17607
+ try {
17608
+ const hits = await client.searchKnowledgePages(query, FALLBACK_PAGE_LIMIT, remaining());
17609
+ diag(harness, "reflect_fallback_pages", { ms: Date.now() - t0, count: hits.length });
17610
+ if (hits.length) {
17611
+ return { memory: formatPageFallback(hits), source: "knowledge_pages", count: hits.length };
17612
+ }
17613
+ } catch (e) {
17614
+ diag(harness, "reflect_fallback_pages_failed", {
17615
+ ms: Date.now() - t0,
17616
+ error: describeError(e)
17617
+ });
17618
+ }
17619
+ t0 = Date.now();
17620
+ try {
17621
+ const observations = await client.recallObservations(prompt.slice(0, 2e3), {
17622
+ maxTokens: FALLBACK_RECALL_MAX_TOKENS,
17623
+ timeoutMs: remaining()
17624
+ });
17625
+ diag(harness, "reflect_fallback_observations", {
17626
+ ms: Date.now() - t0,
17627
+ count: observations.length
17628
+ });
17629
+ if (observations.length) {
17630
+ return {
17631
+ memory: formatObservationFallback(observations),
17632
+ source: "observations",
17633
+ count: observations.length
17634
+ };
17635
+ }
17636
+ } catch (e) {
17637
+ diag(harness, "reflect_fallback_observations_failed", {
17638
+ ms: Date.now() - t0,
17639
+ error: describeError(e)
17640
+ });
17641
+ }
17642
+ return void 0;
17643
+ }
17542
17644
  async function buildHookOutput(args) {
17543
17645
  const { harness, prompt, cfg, client, cacheFile } = args;
17544
17646
  const cached3 = readSessionCache(cacheFile);
@@ -17546,6 +17648,7 @@ async function buildHookOutput(args) {
17546
17648
  let reflectAnswer = cached3.reflectAnswer;
17547
17649
  let reflectRanThisTurn = false;
17548
17650
  let reflectFailed = false;
17651
+ let fallback;
17549
17652
  const deferInitialReflect = cached3.deferInitialReflect === true;
17550
17653
  if (deferInitialReflect) {
17551
17654
  diag(harness, "reflect_deferred_new_bank", { query: prompt.slice(0, 80) });
@@ -17555,7 +17658,7 @@ async function buildHookOutput(args) {
17555
17658
  const timeoutMs = Math.min(cfg.reflectTimeoutMs, HOOK_REFLECT_CAP_MS);
17556
17659
  try {
17557
17660
  reflectAnswer = await client.reflect(buildReflectQuery(prompt), {
17558
- // Automatic reflection runs inside a hard 25s hook window. Hindsight's low budget is the
17661
+ // Automatic reflection runs inside a hard 20s slot of the hook window. Hindsight's low budget is the
17559
17662
  // supported default for bounded reflect calls; callers that explicitly invoke the MCP
17560
17663
  // tool still get the deeper high-budget path.
17561
17664
  budget: "low",
@@ -17583,6 +17686,10 @@ async function buildHookOutput(args) {
17583
17686
  error: describeError(e, 1500),
17584
17687
  query: prompt.slice(0, 80)
17585
17688
  });
17689
+ if (e instanceof ReflectError && e.fallbackEligible) {
17690
+ fallback = await reflectFallback(harness, prompt, client);
17691
+ if (fallback) reflectAnswer = fallback.memory;
17692
+ }
17586
17693
  }
17587
17694
  }
17588
17695
  const cadence = cfg.pageRefreshEveryTurns;
@@ -17616,7 +17723,10 @@ async function buildHookOutput(args) {
17616
17723
  }
17617
17724
  const kept = blocks.filter(Boolean);
17618
17725
  let notice;
17619
- if (reflectRanThisTurn && reflectAnswer) {
17726
+ if (fallback) {
17727
+ const what = fallback.source === "knowledge_pages" ? "knowledge page" : "observation";
17728
+ notice = `${brandWord()} \xB7 reflect unavailable \u2014 fell back to ${fallback.count} ${what}${fallback.count === 1 ? "" : "s"} (see ${diagFilePath()})`;
17729
+ } else if (reflectRanThisTurn && reflectAnswer) {
17620
17730
  const q = prompt.replace(/\s+/g, " ").trim();
17621
17731
  const excerpt = q.length > 48 ? `${q.slice(0, 48)}\u2026` : q;
17622
17732
  const preview = reflectAnswer.replace(/\s+/g, " ").trim();
package/dist/pi.js CHANGED
@@ -15190,6 +15190,22 @@ var KnowledgePagesUnavailableError = class extends Error {
15190
15190
  }
15191
15191
  };
15192
15192
  var TERMINAL = /* @__PURE__ */ new Set(["completed", "failed", "cancelled", "error"]);
15193
+ var ReflectError = class extends Error {
15194
+ constructor(message, status, timedOut, options) {
15195
+ super(message, options);
15196
+ this.status = status;
15197
+ this.timedOut = timedOut;
15198
+ this.name = "ReflectError";
15199
+ }
15200
+ status;
15201
+ timedOut;
15202
+ /** A timeout or a 5xx means reflect's synthesis (the slow LLM path) broke, while the cheap
15203
+ * retrieval endpoints may still answer — worth falling back. A 4xx will fail the same way on
15204
+ * every endpoint (auth, missing bank), so it is not. */
15205
+ get fallbackEligible() {
15206
+ return this.timedOut || this.status !== void 0 && this.status >= 500;
15207
+ }
15208
+ };
15193
15209
  var DEFAULT_MAX_PARALLEL_RETAINS = 10;
15194
15210
  var POLL_CYCLE_MS = 5e3;
15195
15211
  var RETRY_AFTER_FLOOR_MS = 10 * 1e3;
@@ -15273,11 +15289,11 @@ var HindsightClient = class {
15273
15289
  return `${this.apiUrl}/v1/default/banks/${encodeURIComponent(this.bank)}${suffix}`;
15274
15290
  }
15275
15291
  /** `tolerate` adds statuses that are returned to the caller instead of thrown (404 always is). */
15276
- async req(method, url2, body, tolerate = []) {
15292
+ async req(method, url2, body, tolerate = [], timeoutMs = 15e3) {
15277
15293
  const r = await this.fetchWithAuth(url2, {
15278
15294
  method,
15279
15295
  body: body ? JSON.stringify(body) : void 0,
15280
- signal: AbortSignal.timeout(15e3)
15296
+ signal: AbortSignal.timeout(timeoutMs)
15281
15297
  });
15282
15298
  if (r.status === 429 && !tolerate.includes(429))
15283
15299
  throw new RateLimitedError(retryAfterMs(r.headers.get("retry-after")));
@@ -15470,7 +15486,7 @@ var HindsightClient = class {
15470
15486
  /**
15471
15487
  * Reflect: synthesized, root-cause answer over the bank. Bounded so a slow server never hangs a
15472
15488
  * caller — but `timeoutMs` is REQUIRED, deliberately: the right deadline differs by an order of
15473
- * magnitude between the automatic hook (25s, to fit the host's window) and the agent-invoked
15489
+ * magnitude between the automatic hook (20s, to fit the host's window) and the agent-invoked
15474
15490
  * tool (minutes, on a populated bank). This used to default to 120s, which silently overrode the
15475
15491
  * tool's configured window and aborted every high-budget synthesis mid-flight (#3590).
15476
15492
  */
@@ -15484,19 +15500,45 @@ var HindsightClient = class {
15484
15500
  signal: ctrl.signal
15485
15501
  });
15486
15502
  if (!resp.ok)
15487
- throw new Error(
15488
- `reflect ${resp.status} ${(await resp.text()).slice(0, 1e3)}${this.authHint(resp.status)}`
15503
+ throw new ReflectError(
15504
+ `reflect ${resp.status} ${(await resp.text()).slice(0, 1e3)}${this.authHint(resp.status)}`,
15505
+ resp.status,
15506
+ false
15489
15507
  );
15490
15508
  const data = await resp.json();
15491
15509
  return (data.text || "").trim();
15492
15510
  } catch (e) {
15493
15511
  if (ctrl.signal.aborted)
15494
- throw new Error(`reflect timed out after ${opts.timeoutMs}ms`, { cause: e });
15512
+ throw new ReflectError(`reflect timed out after ${opts.timeoutMs}ms`, void 0, true, {
15513
+ cause: e
15514
+ });
15495
15515
  throw e;
15496
15516
  } finally {
15497
15517
  clearTimeout(timer);
15498
15518
  }
15499
15519
  }
15520
+ /**
15521
+ * Raw recall restricted to consolidated observations — no LLM in the loop, so it still answers
15522
+ * when reflect's synthesis times out or 5xxs. Returns the observation texts in rank order.
15523
+ */
15524
+ async recallObservations(query, opts) {
15525
+ const r = await this.req(
15526
+ "POST",
15527
+ this.bankUrl("/memories/recall"),
15528
+ {
15529
+ query,
15530
+ types: ["observation"],
15531
+ budget: "low",
15532
+ max_tokens: opts.maxTokens,
15533
+ include: { entities: null }
15534
+ },
15535
+ [],
15536
+ opts.timeoutMs
15537
+ );
15538
+ if (r.status === 404) return [];
15539
+ const j = await r.json();
15540
+ return (j.results ?? []).map((x) => (x.text ?? "").trim()).filter(Boolean);
15541
+ }
15500
15542
  /**
15501
15543
  * The bank's knowledge-base tree (folders + pages, nested). The tree carries names, source
15502
15544
  * queries and staleness but NOT synthesized content, so it is cheap enough to poll.
@@ -15561,10 +15603,16 @@ var HindsightClient = class {
15561
15603
  /** Hybrid (BM25 + vector, RRF-fused) server-side search over the bank's knowledge pages.
15562
15604
  * Returns page-level hits with a relevance snippet — the real search behind
15563
15605
  * hindsight_search_knowledge_pages. */
15564
- async searchKnowledgePages(query, limit = 3) {
15606
+ async searchKnowledgePages(query, limit = 3, timeoutMs) {
15565
15607
  if (this.knowledgePagesSupported === false) throw new KnowledgePagesUnavailableError();
15566
15608
  const q = `?q=${encodeURIComponent(query)}&limit=${limit}`;
15567
- const r = await this.req("GET", this.bankUrl(`/knowledge-base/search${q}`));
15609
+ const r = await this.req(
15610
+ "GET",
15611
+ this.bankUrl(`/knowledge-base/search${q}`),
15612
+ void 0,
15613
+ [],
15614
+ timeoutMs
15615
+ );
15568
15616
  const j = await r.json();
15569
15617
  return (j.results ?? []).map((x) => ({
15570
15618
  id: x.id,
@@ -17481,6 +17529,15 @@ Report what this bank's history genuinely bears on that goal. Rendering rules, s
17481
17529
  - 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.
17482
17530
  - If the bank holds nothing that bears on the goal, say so in one line.`;
17483
17531
  }
17532
+ function formatPageFallback(hits) {
17533
+ 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) => {
17534
+ const snippet = h.snippet.replace(/\s+/g, " ").trim();
17535
+ return `- ${h.name} (${h.id})${snippet ? `: ${snippet}` : ""}`;
17536
+ }).join("\n");
17537
+ }
17538
+ function formatObservationFallback(observations) {
17539
+ 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");
17540
+ }
17484
17541
  function buildSystemInjection(memory) {
17485
17542
  return `<hindsight_memory>
17486
17543
  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.
@@ -17538,7 +17595,52 @@ function actionLine(tool, input) {
17538
17595
  var JOURNAL_MAX_BYTES = 8 * 1024 * 1024;
17539
17596
 
17540
17597
  // src/core/hook.ts
17541
- var HOOK_REFLECT_CAP_MS = 25e3;
17598
+ var HOOK_REFLECT_CAP_MS = 2e4;
17599
+ var HOOK_FALLBACK_BUDGET_MS = 7e3;
17600
+ var FALLBACK_PAGE_LIMIT = 3;
17601
+ var FALLBACK_RECALL_MAX_TOKENS = 2e3;
17602
+ async function reflectFallback(harness, prompt, client) {
17603
+ const deadline = Date.now() + HOOK_FALLBACK_BUDGET_MS;
17604
+ const remaining = () => Math.max(deadline - Date.now(), 1);
17605
+ const query = prompt.slice(0, 500);
17606
+ let t0 = Date.now();
17607
+ try {
17608
+ const hits = await client.searchKnowledgePages(query, FALLBACK_PAGE_LIMIT, remaining());
17609
+ diag(harness, "reflect_fallback_pages", { ms: Date.now() - t0, count: hits.length });
17610
+ if (hits.length) {
17611
+ return { memory: formatPageFallback(hits), source: "knowledge_pages", count: hits.length };
17612
+ }
17613
+ } catch (e) {
17614
+ diag(harness, "reflect_fallback_pages_failed", {
17615
+ ms: Date.now() - t0,
17616
+ error: describeError(e)
17617
+ });
17618
+ }
17619
+ t0 = Date.now();
17620
+ try {
17621
+ const observations = await client.recallObservations(prompt.slice(0, 2e3), {
17622
+ maxTokens: FALLBACK_RECALL_MAX_TOKENS,
17623
+ timeoutMs: remaining()
17624
+ });
17625
+ diag(harness, "reflect_fallback_observations", {
17626
+ ms: Date.now() - t0,
17627
+ count: observations.length
17628
+ });
17629
+ if (observations.length) {
17630
+ return {
17631
+ memory: formatObservationFallback(observations),
17632
+ source: "observations",
17633
+ count: observations.length
17634
+ };
17635
+ }
17636
+ } catch (e) {
17637
+ diag(harness, "reflect_fallback_observations_failed", {
17638
+ ms: Date.now() - t0,
17639
+ error: describeError(e)
17640
+ });
17641
+ }
17642
+ return void 0;
17643
+ }
17542
17644
  async function buildHookOutput(args) {
17543
17645
  const { harness, prompt, cfg, client, cacheFile } = args;
17544
17646
  const cached2 = readSessionCache(cacheFile);
@@ -17546,6 +17648,7 @@ async function buildHookOutput(args) {
17546
17648
  let reflectAnswer = cached2.reflectAnswer;
17547
17649
  let reflectRanThisTurn = false;
17548
17650
  let reflectFailed = false;
17651
+ let fallback;
17549
17652
  const deferInitialReflect = cached2.deferInitialReflect === true;
17550
17653
  if (deferInitialReflect) {
17551
17654
  diag(harness, "reflect_deferred_new_bank", { query: prompt.slice(0, 80) });
@@ -17555,7 +17658,7 @@ async function buildHookOutput(args) {
17555
17658
  const timeoutMs = Math.min(cfg.reflectTimeoutMs, HOOK_REFLECT_CAP_MS);
17556
17659
  try {
17557
17660
  reflectAnswer = await client.reflect(buildReflectQuery(prompt), {
17558
- // Automatic reflection runs inside a hard 25s hook window. Hindsight's low budget is the
17661
+ // Automatic reflection runs inside a hard 20s slot of the hook window. Hindsight's low budget is the
17559
17662
  // supported default for bounded reflect calls; callers that explicitly invoke the MCP
17560
17663
  // tool still get the deeper high-budget path.
17561
17664
  budget: "low",
@@ -17583,6 +17686,10 @@ async function buildHookOutput(args) {
17583
17686
  error: describeError(e, 1500),
17584
17687
  query: prompt.slice(0, 80)
17585
17688
  });
17689
+ if (e instanceof ReflectError && e.fallbackEligible) {
17690
+ fallback = await reflectFallback(harness, prompt, client);
17691
+ if (fallback) reflectAnswer = fallback.memory;
17692
+ }
17586
17693
  }
17587
17694
  }
17588
17695
  const cadence = cfg.pageRefreshEveryTurns;
@@ -17616,7 +17723,10 @@ async function buildHookOutput(args) {
17616
17723
  }
17617
17724
  const kept = blocks.filter(Boolean);
17618
17725
  let notice;
17619
- if (reflectRanThisTurn && reflectAnswer) {
17726
+ if (fallback) {
17727
+ const what = fallback.source === "knowledge_pages" ? "knowledge page" : "observation";
17728
+ notice = `${brandWord()} \xB7 reflect unavailable \u2014 fell back to ${fallback.count} ${what}${fallback.count === 1 ? "" : "s"} (see ${diagFilePath()})`;
17729
+ } else if (reflectRanThisTurn && reflectAnswer) {
17620
17730
  const q = prompt.replace(/\s+/g, " ").trim();
17621
17731
  const excerpt = q.length > 48 ? `${q.slice(0, 48)}\u2026` : q;
17622
17732
  const preview = reflectAnswer.replace(/\s+/g, " ").trim();
@@ -15190,6 +15190,22 @@ var KnowledgePagesUnavailableError = class extends Error {
15190
15190
  }
15191
15191
  };
15192
15192
  var TERMINAL = /* @__PURE__ */ new Set(["completed", "failed", "cancelled", "error"]);
15193
+ var ReflectError = class extends Error {
15194
+ constructor(message, status, timedOut, options) {
15195
+ super(message, options);
15196
+ this.status = status;
15197
+ this.timedOut = timedOut;
15198
+ this.name = "ReflectError";
15199
+ }
15200
+ status;
15201
+ timedOut;
15202
+ /** A timeout or a 5xx means reflect's synthesis (the slow LLM path) broke, while the cheap
15203
+ * retrieval endpoints may still answer — worth falling back. A 4xx will fail the same way on
15204
+ * every endpoint (auth, missing bank), so it is not. */
15205
+ get fallbackEligible() {
15206
+ return this.timedOut || this.status !== void 0 && this.status >= 500;
15207
+ }
15208
+ };
15193
15209
  var DEFAULT_MAX_PARALLEL_RETAINS = 10;
15194
15210
  var POLL_CYCLE_MS = 5e3;
15195
15211
  var RETRY_AFTER_FLOOR_MS = 10 * 1e3;
@@ -15273,11 +15289,11 @@ var HindsightClient = class {
15273
15289
  return `${this.apiUrl}/v1/default/banks/${encodeURIComponent(this.bank)}${suffix}`;
15274
15290
  }
15275
15291
  /** `tolerate` adds statuses that are returned to the caller instead of thrown (404 always is). */
15276
- async req(method, url2, body, tolerate = []) {
15292
+ async req(method, url2, body, tolerate = [], timeoutMs = 15e3) {
15277
15293
  const r = await this.fetchWithAuth(url2, {
15278
15294
  method,
15279
15295
  body: body ? JSON.stringify(body) : void 0,
15280
- signal: AbortSignal.timeout(15e3)
15296
+ signal: AbortSignal.timeout(timeoutMs)
15281
15297
  });
15282
15298
  if (r.status === 429 && !tolerate.includes(429))
15283
15299
  throw new RateLimitedError(retryAfterMs(r.headers.get("retry-after")));
@@ -15470,7 +15486,7 @@ var HindsightClient = class {
15470
15486
  /**
15471
15487
  * Reflect: synthesized, root-cause answer over the bank. Bounded so a slow server never hangs a
15472
15488
  * caller — but `timeoutMs` is REQUIRED, deliberately: the right deadline differs by an order of
15473
- * magnitude between the automatic hook (25s, to fit the host's window) and the agent-invoked
15489
+ * magnitude between the automatic hook (20s, to fit the host's window) and the agent-invoked
15474
15490
  * tool (minutes, on a populated bank). This used to default to 120s, which silently overrode the
15475
15491
  * tool's configured window and aborted every high-budget synthesis mid-flight (#3590).
15476
15492
  */
@@ -15484,19 +15500,45 @@ var HindsightClient = class {
15484
15500
  signal: ctrl.signal
15485
15501
  });
15486
15502
  if (!resp.ok)
15487
- throw new Error(
15488
- `reflect ${resp.status} ${(await resp.text()).slice(0, 1e3)}${this.authHint(resp.status)}`
15503
+ throw new ReflectError(
15504
+ `reflect ${resp.status} ${(await resp.text()).slice(0, 1e3)}${this.authHint(resp.status)}`,
15505
+ resp.status,
15506
+ false
15489
15507
  );
15490
15508
  const data = await resp.json();
15491
15509
  return (data.text || "").trim();
15492
15510
  } catch (e) {
15493
15511
  if (ctrl.signal.aborted)
15494
- throw new Error(`reflect timed out after ${opts.timeoutMs}ms`, { cause: e });
15512
+ throw new ReflectError(`reflect timed out after ${opts.timeoutMs}ms`, void 0, true, {
15513
+ cause: e
15514
+ });
15495
15515
  throw e;
15496
15516
  } finally {
15497
15517
  clearTimeout(timer);
15498
15518
  }
15499
15519
  }
15520
+ /**
15521
+ * Raw recall restricted to consolidated observations — no LLM in the loop, so it still answers
15522
+ * when reflect's synthesis times out or 5xxs. Returns the observation texts in rank order.
15523
+ */
15524
+ async recallObservations(query, opts) {
15525
+ const r = await this.req(
15526
+ "POST",
15527
+ this.bankUrl("/memories/recall"),
15528
+ {
15529
+ query,
15530
+ types: ["observation"],
15531
+ budget: "low",
15532
+ max_tokens: opts.maxTokens,
15533
+ include: { entities: null }
15534
+ },
15535
+ [],
15536
+ opts.timeoutMs
15537
+ );
15538
+ if (r.status === 404) return [];
15539
+ const j = await r.json();
15540
+ return (j.results ?? []).map((x) => (x.text ?? "").trim()).filter(Boolean);
15541
+ }
15500
15542
  /**
15501
15543
  * The bank's knowledge-base tree (folders + pages, nested). The tree carries names, source
15502
15544
  * queries and staleness but NOT synthesized content, so it is cheap enough to poll.
@@ -15561,10 +15603,16 @@ var HindsightClient = class {
15561
15603
  /** Hybrid (BM25 + vector, RRF-fused) server-side search over the bank's knowledge pages.
15562
15604
  * Returns page-level hits with a relevance snippet — the real search behind
15563
15605
  * hindsight_search_knowledge_pages. */
15564
- async searchKnowledgePages(query, limit = 3) {
15606
+ async searchKnowledgePages(query, limit = 3, timeoutMs) {
15565
15607
  if (this.knowledgePagesSupported === false) throw new KnowledgePagesUnavailableError();
15566
15608
  const q = `?q=${encodeURIComponent(query)}&limit=${limit}`;
15567
- const r = await this.req("GET", this.bankUrl(`/knowledge-base/search${q}`));
15609
+ const r = await this.req(
15610
+ "GET",
15611
+ this.bankUrl(`/knowledge-base/search${q}`),
15612
+ void 0,
15613
+ [],
15614
+ timeoutMs
15615
+ );
15568
15616
  const j = await r.json();
15569
15617
  return (j.results ?? []).map((x) => ({
15570
15618
  id: x.id,
@@ -17481,6 +17529,15 @@ Report what this bank's history genuinely bears on that goal. Rendering rules, s
17481
17529
  - 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.
17482
17530
  - If the bank holds nothing that bears on the goal, say so in one line.`;
17483
17531
  }
17532
+ function formatPageFallback(hits) {
17533
+ 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) => {
17534
+ const snippet = h.snippet.replace(/\s+/g, " ").trim();
17535
+ return `- ${h.name} (${h.id})${snippet ? `: ${snippet}` : ""}`;
17536
+ }).join("\n");
17537
+ }
17538
+ function formatObservationFallback(observations) {
17539
+ 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");
17540
+ }
17484
17541
  function buildSystemInjection(memory) {
17485
17542
  return `<hindsight_memory>
17486
17543
  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.
@@ -17538,7 +17595,52 @@ function actionLine(tool, input) {
17538
17595
  var JOURNAL_MAX_BYTES = 8 * 1024 * 1024;
17539
17596
 
17540
17597
  // src/core/hook.ts
17541
- var HOOK_REFLECT_CAP_MS = 25e3;
17598
+ var HOOK_REFLECT_CAP_MS = 2e4;
17599
+ var HOOK_FALLBACK_BUDGET_MS = 7e3;
17600
+ var FALLBACK_PAGE_LIMIT = 3;
17601
+ var FALLBACK_RECALL_MAX_TOKENS = 2e3;
17602
+ async function reflectFallback(harness, prompt, client) {
17603
+ const deadline = Date.now() + HOOK_FALLBACK_BUDGET_MS;
17604
+ const remaining = () => Math.max(deadline - Date.now(), 1);
17605
+ const query = prompt.slice(0, 500);
17606
+ let t0 = Date.now();
17607
+ try {
17608
+ const hits = await client.searchKnowledgePages(query, FALLBACK_PAGE_LIMIT, remaining());
17609
+ diag(harness, "reflect_fallback_pages", { ms: Date.now() - t0, count: hits.length });
17610
+ if (hits.length) {
17611
+ return { memory: formatPageFallback(hits), source: "knowledge_pages", count: hits.length };
17612
+ }
17613
+ } catch (e) {
17614
+ diag(harness, "reflect_fallback_pages_failed", {
17615
+ ms: Date.now() - t0,
17616
+ error: describeError(e)
17617
+ });
17618
+ }
17619
+ t0 = Date.now();
17620
+ try {
17621
+ const observations = await client.recallObservations(prompt.slice(0, 2e3), {
17622
+ maxTokens: FALLBACK_RECALL_MAX_TOKENS,
17623
+ timeoutMs: remaining()
17624
+ });
17625
+ diag(harness, "reflect_fallback_observations", {
17626
+ ms: Date.now() - t0,
17627
+ count: observations.length
17628
+ });
17629
+ if (observations.length) {
17630
+ return {
17631
+ memory: formatObservationFallback(observations),
17632
+ source: "observations",
17633
+ count: observations.length
17634
+ };
17635
+ }
17636
+ } catch (e) {
17637
+ diag(harness, "reflect_fallback_observations_failed", {
17638
+ ms: Date.now() - t0,
17639
+ error: describeError(e)
17640
+ });
17641
+ }
17642
+ return void 0;
17643
+ }
17542
17644
  async function buildHookOutput(args) {
17543
17645
  const { harness, prompt, cfg, client, cacheFile } = args;
17544
17646
  const cached2 = readSessionCache(cacheFile);
@@ -17546,6 +17648,7 @@ async function buildHookOutput(args) {
17546
17648
  let reflectAnswer = cached2.reflectAnswer;
17547
17649
  let reflectRanThisTurn = false;
17548
17650
  let reflectFailed = false;
17651
+ let fallback;
17549
17652
  const deferInitialReflect = cached2.deferInitialReflect === true;
17550
17653
  if (deferInitialReflect) {
17551
17654
  diag(harness, "reflect_deferred_new_bank", { query: prompt.slice(0, 80) });
@@ -17555,7 +17658,7 @@ async function buildHookOutput(args) {
17555
17658
  const timeoutMs = Math.min(cfg.reflectTimeoutMs, HOOK_REFLECT_CAP_MS);
17556
17659
  try {
17557
17660
  reflectAnswer = await client.reflect(buildReflectQuery(prompt), {
17558
- // Automatic reflection runs inside a hard 25s hook window. Hindsight's low budget is the
17661
+ // Automatic reflection runs inside a hard 20s slot of the hook window. Hindsight's low budget is the
17559
17662
  // supported default for bounded reflect calls; callers that explicitly invoke the MCP
17560
17663
  // tool still get the deeper high-budget path.
17561
17664
  budget: "low",
@@ -17583,6 +17686,10 @@ async function buildHookOutput(args) {
17583
17686
  error: describeError(e, 1500),
17584
17687
  query: prompt.slice(0, 80)
17585
17688
  });
17689
+ if (e instanceof ReflectError && e.fallbackEligible) {
17690
+ fallback = await reflectFallback(harness, prompt, client);
17691
+ if (fallback) reflectAnswer = fallback.memory;
17692
+ }
17586
17693
  }
17587
17694
  }
17588
17695
  const cadence = cfg.pageRefreshEveryTurns;
@@ -17616,7 +17723,10 @@ async function buildHookOutput(args) {
17616
17723
  }
17617
17724
  const kept = blocks.filter(Boolean);
17618
17725
  let notice;
17619
- if (reflectRanThisTurn && reflectAnswer) {
17726
+ if (fallback) {
17727
+ const what = fallback.source === "knowledge_pages" ? "knowledge page" : "observation";
17728
+ notice = `${brandWord()} \xB7 reflect unavailable \u2014 fell back to ${fallback.count} ${what}${fallback.count === 1 ? "" : "s"} (see ${diagFilePath()})`;
17729
+ } else if (reflectRanThisTurn && reflectAnswer) {
17620
17730
  const q = prompt.replace(/\s+/g, " ").trim();
17621
17731
  const excerpt = q.length > 48 ? `${q.slice(0, 48)}\u2026` : q;
17622
17732
  const preview = reflectAnswer.replace(/\s+/g, " ").trim();