@vectorize-io/hindsight-coding-agents 0.5.3 → 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 (48) hide show
  1. package/README.md +5 -2
  2. package/dist/antigravity-hook.js +185 -41
  3. package/dist/antigravity-stop-hook.js +114 -36
  4. package/dist/claude-hook.js +185 -41
  5. package/dist/claude-sessionstart-hook.js +292 -76
  6. package/dist/claude-stop-hook.js +114 -36
  7. package/dist/cline.js +331 -58
  8. package/dist/codex-hook.js +185 -41
  9. package/dist/codex-sessionstart-hook.js +292 -76
  10. package/dist/codex-stop-hook.js +114 -36
  11. package/dist/copilot-hook.js +185 -41
  12. package/dist/copilot-sessionstart-hook.js +292 -76
  13. package/dist/copilot-stop-hook.js +114 -36
  14. package/dist/cursor-hook.js +185 -41
  15. package/dist/cursor-sessionstart-hook.js +292 -76
  16. package/dist/cursor-stop-hook.js +114 -36
  17. package/dist/dcode-hook.js +185 -41
  18. package/dist/dcode-sessionstart-hook.js +292 -76
  19. package/dist/dcode-stop-hook.js +114 -36
  20. package/dist/deepen.js +93 -18
  21. package/dist/devin-hook.js +185 -41
  22. package/dist/devin-sessionstart-hook.js +292 -76
  23. package/dist/devin-stop-hook.js +114 -36
  24. package/dist/droid-hook.js +185 -41
  25. package/dist/droid-sessionstart-hook.js +292 -76
  26. package/dist/droid-stop-hook.js +114 -36
  27. package/dist/dsh.js +333 -60
  28. package/dist/grok-hook.js +185 -41
  29. package/dist/grok-sessionstart-hook.js +292 -76
  30. package/dist/grok-stop-hook.js +114 -36
  31. package/dist/index.js +333 -60
  32. package/dist/installer.js +1030 -268
  33. package/dist/kilo.js +333 -60
  34. package/dist/mcp-server.js +86 -11
  35. package/dist/opencode2.js +333 -60
  36. package/dist/pi.js +332 -59
  37. package/dist/prime-agent.js +332 -59
  38. package/dist/qwen-hook.js +185 -41
  39. package/dist/qwen-sessionstart-hook.js +292 -76
  40. package/dist/qwen-stop-hook.js +114 -36
  41. package/dist/status.js +84 -9
  42. package/dist/survey-supervisor.js +81 -0
  43. package/dist/zcode-hook.js +185 -41
  44. package/dist/zcode-sessionstart-hook.js +292 -76
  45. package/dist/zcode-stop-hook.js +114 -36
  46. package/package.json +2 -1
  47. package/plugin.json +1 -1
  48. package/skill/SKILL.md +5 -2
package/dist/grok-hook.js CHANGED
@@ -653,6 +653,22 @@ var KnowledgePagesUnavailableError = class extends Error {
653
653
  }
654
654
  };
655
655
  var TERMINAL = /* @__PURE__ */ new Set(["completed", "failed", "cancelled", "error"]);
656
+ var ReflectError = class extends Error {
657
+ constructor(message, status, timedOut, options) {
658
+ super(message, options);
659
+ this.status = status;
660
+ this.timedOut = timedOut;
661
+ this.name = "ReflectError";
662
+ }
663
+ status;
664
+ timedOut;
665
+ /** A timeout or a 5xx means reflect's synthesis (the slow LLM path) broke, while the cheap
666
+ * retrieval endpoints may still answer — worth falling back. A 4xx will fail the same way on
667
+ * every endpoint (auth, missing bank), so it is not. */
668
+ get fallbackEligible() {
669
+ return this.timedOut || this.status !== void 0 && this.status >= 500;
670
+ }
671
+ };
656
672
  var DEFAULT_MAX_PARALLEL_RETAINS = 10;
657
673
  var POLL_CYCLE_MS = 5e3;
658
674
  var RETRY_AFTER_FLOOR_MS = 10 * 1e3;
@@ -736,11 +752,11 @@ var HindsightClient = class {
736
752
  return `${this.apiUrl}/v1/default/banks/${encodeURIComponent(this.bank)}${suffix}`;
737
753
  }
738
754
  /** `tolerate` adds statuses that are returned to the caller instead of thrown (404 always is). */
739
- async req(method, url, body, tolerate = []) {
755
+ async req(method, url, body, tolerate = [], timeoutMs = 15e3) {
740
756
  const r = await this.fetchWithAuth(url, {
741
757
  method,
742
758
  body: body ? JSON.stringify(body) : void 0,
743
- signal: AbortSignal.timeout(15e3)
759
+ signal: AbortSignal.timeout(timeoutMs)
744
760
  });
745
761
  if (r.status === 429 && !tolerate.includes(429))
746
762
  throw new RateLimitedError(retryAfterMs(r.headers.get("retry-after")));
@@ -933,7 +949,7 @@ var HindsightClient = class {
933
949
  /**
934
950
  * Reflect: synthesized, root-cause answer over the bank. Bounded so a slow server never hangs a
935
951
  * caller — but `timeoutMs` is REQUIRED, deliberately: the right deadline differs by an order of
936
- * magnitude between the automatic hook (25s, to fit the host's window) and the agent-invoked
952
+ * magnitude between the automatic hook (20s, to fit the host's window) and the agent-invoked
937
953
  * tool (minutes, on a populated bank). This used to default to 120s, which silently overrode the
938
954
  * tool's configured window and aborted every high-budget synthesis mid-flight (#3590).
939
955
  */
@@ -946,13 +962,46 @@ var HindsightClient = class {
946
962
  body: JSON.stringify({ query, budget: opts.budget ?? "high" }),
947
963
  signal: ctrl.signal
948
964
  });
949
- if (!resp.ok) throw new Error(`reflect ${resp.status}${this.authHint(resp.status)}`);
965
+ if (!resp.ok)
966
+ throw new ReflectError(
967
+ `reflect ${resp.status} ${(await resp.text()).slice(0, 1e3)}${this.authHint(resp.status)}`,
968
+ resp.status,
969
+ false
970
+ );
950
971
  const data = await resp.json();
951
972
  return (data.text || "").trim();
973
+ } catch (e) {
974
+ if (ctrl.signal.aborted)
975
+ throw new ReflectError(`reflect timed out after ${opts.timeoutMs}ms`, void 0, true, {
976
+ cause: e
977
+ });
978
+ throw e;
952
979
  } finally {
953
980
  clearTimeout(timer);
954
981
  }
955
982
  }
983
+ /**
984
+ * Raw recall restricted to consolidated observations — no LLM in the loop, so it still answers
985
+ * when reflect's synthesis times out or 5xxs. Returns the observation texts in rank order.
986
+ */
987
+ async recallObservations(query, opts) {
988
+ const r = await this.req(
989
+ "POST",
990
+ this.bankUrl("/memories/recall"),
991
+ {
992
+ query,
993
+ types: ["observation"],
994
+ budget: "low",
995
+ max_tokens: opts.maxTokens,
996
+ include: { entities: null }
997
+ },
998
+ [],
999
+ opts.timeoutMs
1000
+ );
1001
+ if (r.status === 404) return [];
1002
+ const j = await r.json();
1003
+ return (j.results ?? []).map((x) => (x.text ?? "").trim()).filter(Boolean);
1004
+ }
956
1005
  /**
957
1006
  * The bank's knowledge-base tree (folders + pages, nested). The tree carries names, source
958
1007
  * queries and staleness but NOT synthesized content, so it is cheap enough to poll.
@@ -1017,10 +1066,16 @@ var HindsightClient = class {
1017
1066
  /** Hybrid (BM25 + vector, RRF-fused) server-side search over the bank's knowledge pages.
1018
1067
  * Returns page-level hits with a relevance snippet — the real search behind
1019
1068
  * hindsight_search_knowledge_pages. */
1020
- async searchKnowledgePages(query, limit = 3) {
1069
+ async searchKnowledgePages(query, limit = 3, timeoutMs) {
1021
1070
  if (this.knowledgePagesSupported === false) throw new KnowledgePagesUnavailableError();
1022
1071
  const q = `?q=${encodeURIComponent(query)}&limit=${limit}`;
1023
- const r = await this.req("GET", this.bankUrl(`/knowledge-base/search${q}`));
1072
+ const r = await this.req(
1073
+ "GET",
1074
+ this.bankUrl(`/knowledge-base/search${q}`),
1075
+ void 0,
1076
+ [],
1077
+ timeoutMs
1078
+ );
1024
1079
  const j = await r.json();
1025
1080
  return (j.results ?? []).map((x) => ({
1026
1081
  id: x.id,
@@ -1493,6 +1548,15 @@ Report what this bank's history genuinely bears on that goal. Rendering rules, s
1493
1548
  - 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.
1494
1549
  - If the bank holds nothing that bears on the goal, say so in one line.`;
1495
1550
  }
1551
+ function formatPageFallback(hits) {
1552
+ 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) => {
1553
+ const snippet = h.snippet.replace(/\s+/g, " ").trim();
1554
+ return `- ${h.name} (${h.id})${snippet ? `: ${snippet}` : ""}`;
1555
+ }).join("\n");
1556
+ }
1557
+ function formatObservationFallback(observations) {
1558
+ 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");
1559
+ }
1496
1560
  function buildSystemInjection(memory) {
1497
1561
  return `<hindsight_memory>
1498
1562
  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.
@@ -1688,7 +1752,52 @@ function readJournalTranscript(path) {
1688
1752
  }
1689
1753
 
1690
1754
  // src/core/hook.ts
1691
- var HOOK_REFLECT_CAP_MS = 25e3;
1755
+ var HOOK_REFLECT_CAP_MS = 2e4;
1756
+ var HOOK_FALLBACK_BUDGET_MS = 7e3;
1757
+ var FALLBACK_PAGE_LIMIT = 3;
1758
+ var FALLBACK_RECALL_MAX_TOKENS = 2e3;
1759
+ async function reflectFallback(harness, prompt, client) {
1760
+ const deadline = Date.now() + HOOK_FALLBACK_BUDGET_MS;
1761
+ const remaining = () => Math.max(deadline - Date.now(), 1);
1762
+ const query = prompt.slice(0, 500);
1763
+ let t0 = Date.now();
1764
+ try {
1765
+ const hits = await client.searchKnowledgePages(query, FALLBACK_PAGE_LIMIT, remaining());
1766
+ diag(harness, "reflect_fallback_pages", { ms: Date.now() - t0, count: hits.length });
1767
+ if (hits.length) {
1768
+ return { memory: formatPageFallback(hits), source: "knowledge_pages", count: hits.length };
1769
+ }
1770
+ } catch (e) {
1771
+ diag(harness, "reflect_fallback_pages_failed", {
1772
+ ms: Date.now() - t0,
1773
+ error: describeError(e)
1774
+ });
1775
+ }
1776
+ t0 = Date.now();
1777
+ try {
1778
+ const observations = await client.recallObservations(prompt.slice(0, 2e3), {
1779
+ maxTokens: FALLBACK_RECALL_MAX_TOKENS,
1780
+ timeoutMs: remaining()
1781
+ });
1782
+ diag(harness, "reflect_fallback_observations", {
1783
+ ms: Date.now() - t0,
1784
+ count: observations.length
1785
+ });
1786
+ if (observations.length) {
1787
+ return {
1788
+ memory: formatObservationFallback(observations),
1789
+ source: "observations",
1790
+ count: observations.length
1791
+ };
1792
+ }
1793
+ } catch (e) {
1794
+ diag(harness, "reflect_fallback_observations_failed", {
1795
+ ms: Date.now() - t0,
1796
+ error: describeError(e)
1797
+ });
1798
+ }
1799
+ return void 0;
1800
+ }
1692
1801
  async function buildHookOutput(args) {
1693
1802
  const { harness, prompt, cfg, client, cacheFile } = args;
1694
1803
  const cached = readSessionCache(cacheFile);
@@ -1696,19 +1805,21 @@ async function buildHookOutput(args) {
1696
1805
  let reflectAnswer = cached.reflectAnswer;
1697
1806
  let reflectRanThisTurn = false;
1698
1807
  let reflectFailed = false;
1808
+ let fallback;
1699
1809
  const deferInitialReflect = cached.deferInitialReflect === true;
1700
1810
  if (deferInitialReflect) {
1701
1811
  diag(harness, "reflect_deferred_new_bank", { query: prompt.slice(0, 80) });
1702
1812
  } else if (cfg.autoReflect && reflectAnswer === void 0) {
1703
1813
  reflectRanThisTurn = true;
1704
1814
  const t0 = Date.now();
1815
+ const timeoutMs = Math.min(cfg.reflectTimeoutMs, HOOK_REFLECT_CAP_MS);
1705
1816
  try {
1706
1817
  reflectAnswer = await client.reflect(buildReflectQuery(prompt), {
1707
- // Automatic reflection runs inside a hard 25s hook window. Hindsight's low budget is the
1818
+ // Automatic reflection runs inside a hard 20s slot of the hook window. Hindsight's low budget is the
1708
1819
  // supported default for bounded reflect calls; callers that explicitly invoke the MCP
1709
1820
  // tool still get the deeper high-budget path.
1710
1821
  budget: "low",
1711
- timeoutMs: Math.min(cfg.reflectTimeoutMs, HOOK_REFLECT_CAP_MS)
1822
+ timeoutMs
1712
1823
  });
1713
1824
  diag(harness, reflectAnswer ? "reflect_ok" : "reflect_empty", {
1714
1825
  ms: Date.now() - t0,
@@ -1726,9 +1837,16 @@ async function buildHookOutput(args) {
1726
1837
  });
1727
1838
  diag(harness, "reflect_failed", {
1728
1839
  ms: Date.now() - t0,
1729
- error: describeError(e),
1840
+ bank: client.bank,
1841
+ timeoutMs,
1842
+ // Wider than describeError's default: the server's error body is the useful part.
1843
+ error: describeError(e, 1500),
1730
1844
  query: prompt.slice(0, 80)
1731
1845
  });
1846
+ if (e instanceof ReflectError && e.fallbackEligible) {
1847
+ fallback = await reflectFallback(harness, prompt, client);
1848
+ if (fallback) reflectAnswer = fallback.memory;
1849
+ }
1732
1850
  }
1733
1851
  }
1734
1852
  const cadence = cfg.pageRefreshEveryTurns;
@@ -1762,7 +1880,10 @@ async function buildHookOutput(args) {
1762
1880
  }
1763
1881
  const kept = blocks.filter(Boolean);
1764
1882
  let notice;
1765
- if (reflectRanThisTurn && reflectAnswer) {
1883
+ if (fallback) {
1884
+ const what = fallback.source === "knowledge_pages" ? "knowledge page" : "observation";
1885
+ notice = `${brandWord()} \xB7 reflect unavailable \u2014 fell back to ${fallback.count} ${what}${fallback.count === 1 ? "" : "s"} (see ${diagFilePath()})`;
1886
+ } else if (reflectRanThisTurn && reflectAnswer) {
1766
1887
  const q = prompt.replace(/\s+/g, " ").trim();
1767
1888
  const excerpt = q.length > 48 ? `${q.slice(0, 48)}\u2026` : q;
1768
1889
  const preview = reflectAnswer.replace(/\s+/g, " ").trim();
@@ -1905,7 +2026,7 @@ function* streamLines(path, start) {
1905
2026
  }
1906
2027
 
1907
2028
  // src/core/session-start.ts
1908
- import { readFileSync as readFileSync9 } from "fs";
2029
+ import { readFileSync as readFileSync10 } from "fs";
1909
2030
 
1910
2031
  // src/core/git.ts
1911
2032
  import { execFileSync as execFileSync2 } from "child_process";
@@ -1915,24 +2036,42 @@ import { resolve as resolve2 } from "path";
1915
2036
  import { execFileSync as execFileSync3 } from "child_process";
1916
2037
 
1917
2038
  // src/core/survey.ts
1918
- import { spawn as realSpawn3 } from "child_process";
2039
+ import { spawn as realSpawn4 } from "child_process";
2040
+ import { createHash as createHash4 } from "crypto";
1919
2041
  import { existsSync as existsSync3 } from "fs";
1920
- import { homedir as homedir3 } from "os";
1921
- import { dirname as dirname8, join as join10 } from "path";
2042
+ import { homedir as homedir3, tmpdir as tmpdir4 } from "os";
2043
+ import { dirname as dirname8, join as join11 } from "path";
1922
2044
  import { fileURLToPath as fileURLToPath3 } from "url";
1923
2045
 
2046
+ // src/core/survey-lease.ts
2047
+ import { spawn as realSpawn3 } from "child_process";
2048
+ import { randomUUID } from "crypto";
2049
+ import {
2050
+ mkdirSync as mkdirSync4,
2051
+ mkdtempSync,
2052
+ readdirSync,
2053
+ renameSync as renameSync2,
2054
+ rmdirSync,
2055
+ rmSync as rmSync2,
2056
+ statSync as statSync3,
2057
+ unlinkSync,
2058
+ utimesSync,
2059
+ writeFileSync as writeFileSync2
2060
+ } from "fs";
2061
+ import { join as join10 } from "path";
2062
+
1924
2063
  // src/core/auto-update.ts
1925
- import { spawn as realSpawn4 } from "child_process";
2064
+ import { spawn as realSpawn5 } from "child_process";
1926
2065
  import {
1927
2066
  existsSync as existsSync4,
1928
- mkdirSync as mkdirSync4,
2067
+ mkdirSync as mkdirSync5,
1929
2068
  readFileSync as readFileSync7,
1930
2069
  realpathSync as realpathSync2,
1931
- unlinkSync,
1932
- writeFileSync as writeFileSync2
2070
+ unlinkSync as unlinkSync2,
2071
+ writeFileSync as writeFileSync3
1933
2072
  } from "fs";
1934
- import { homedir as homedir4, tmpdir as tmpdir4 } from "os";
1935
- import { dirname as dirname9, join as join11 } from "path";
2073
+ import { homedir as homedir4, tmpdir as tmpdir5 } from "os";
2074
+ import { dirname as dirname9, join as join12 } from "path";
1936
2075
  import { fileURLToPath as fileURLToPath4 } from "url";
1937
2076
  var CHECK_INTERVAL_MS = 24 * 60 * 60 * 1e3;
1938
2077
  var LOCK_STALE_MS = 10 * 60 * 1e3;
@@ -1940,9 +2079,14 @@ var LOCK_STALE_MS = 10 * 60 * 1e3;
1940
2079
  // src/core/skill-sync.ts
1941
2080
  import { cpSync, existsSync as existsSync5, readFileSync as readFileSync8 } from "fs";
1942
2081
  import { homedir as homedir5 } from "os";
1943
- import { dirname as dirname10, join as join12 } from "path";
2082
+ import { dirname as dirname10, join as join13 } from "path";
1944
2083
  import { fileURLToPath as fileURLToPath5 } from "url";
1945
2084
 
2085
+ // src/core/legacy.ts
2086
+ import { existsSync as existsSync6, readFileSync as readFileSync9 } from "fs";
2087
+ import { homedir as homedir6 } from "os";
2088
+ import { join as join14, relative, isAbsolute as isAbsolute2 } from "path";
2089
+
1946
2090
  // src/core/transcript-codex.ts
1947
2091
  function isSyntheticUserText(text) {
1948
2092
  const s = text.trimStart();
@@ -2073,19 +2217,19 @@ function readCopilotTranscript(path) {
2073
2217
  }
2074
2218
 
2075
2219
  // src/core/transcript-grok.ts
2076
- import { existsSync as existsSync6, readFileSync as readFileSync10, readdirSync } from "fs";
2077
- import { homedir as homedir6 } from "os";
2078
- import { join as join13 } from "path";
2220
+ import { existsSync as existsSync7, readFileSync as readFileSync11, readdirSync as readdirSync2 } from "fs";
2221
+ import { homedir as homedir7 } from "os";
2222
+ import { join as join15 } from "path";
2079
2223
  var CHAT_HISTORY = "chat_history.jsonl";
2080
- function grokTranscriptPath(cwd, sessionId, grokHome = process.env.GROK_HOME || join13(homedir6(), ".grok")) {
2081
- const sessionsDir = join13(grokHome, "sessions");
2082
- const direct = join13(sessionsDir, encodeURIComponent(cwd), sessionId, CHAT_HISTORY);
2083
- if (existsSync6(direct)) return direct;
2224
+ function grokTranscriptPath(cwd, sessionId, grokHome = process.env.GROK_HOME || join15(homedir7(), ".grok")) {
2225
+ const sessionsDir = join15(grokHome, "sessions");
2226
+ const direct = join15(sessionsDir, encodeURIComponent(cwd), sessionId, CHAT_HISTORY);
2227
+ if (existsSync7(direct)) return direct;
2084
2228
  try {
2085
- for (const candidate of readdirSync(sessionsDir)) {
2086
- const directory = join13(sessionsDir, candidate);
2087
- if (readFileSync10(join13(directory, ".cwd"), "utf8").trim() === cwd) {
2088
- return join13(directory, sessionId, CHAT_HISTORY);
2229
+ for (const candidate of readdirSync2(sessionsDir)) {
2230
+ const directory = join15(sessionsDir, candidate);
2231
+ if (readFileSync11(join15(directory, ".cwd"), "utf8").trim() === cwd) {
2232
+ return join15(directory, sessionId, CHAT_HISTORY);
2089
2233
  }
2090
2234
  }
2091
2235
  } catch {
@@ -2120,12 +2264,12 @@ function readGrokTranscript(path) {
2120
2264
  }
2121
2265
 
2122
2266
  // src/core/transcript-devin.ts
2123
- import { existsSync as existsSync7 } from "fs";
2267
+ import { existsSync as existsSync8 } from "fs";
2124
2268
  import { createRequire } from "module";
2125
- import { homedir as homedir7 } from "os";
2126
- import { join as join14 } from "path";
2127
- function devinSessionDb(home = homedir7()) {
2128
- return join14(home, ".local", "share", "devin", "cli", "sessions.db");
2269
+ import { homedir as homedir8 } from "os";
2270
+ import { join as join16 } from "path";
2271
+ function devinSessionDb(home = homedir8()) {
2272
+ return join16(home, ".local", "share", "devin", "cli", "sessions.db");
2129
2273
  }
2130
2274
  function parseDevinMessages(nodes) {
2131
2275
  const messages = /* @__PURE__ */ new Map();
@@ -2162,7 +2306,7 @@ function readDevinTranscript(sessionId, dbPath = devinSessionDb()) {
2162
2306
  diag("devin-cli", "sqlite_unavailable", { node: process.version, dbPath });
2163
2307
  return [];
2164
2308
  }
2165
- if (!existsSync7(dbPath)) {
2309
+ if (!existsSync8(dbPath)) {
2166
2310
  diag("devin-cli", "session_db_missing", { dbPath });
2167
2311
  return [];
2168
2312
  }
@@ -2435,7 +2579,7 @@ function readDroidTranscript(path) {
2435
2579
  }
2436
2580
 
2437
2581
  // src/core/transcript-zcode.ts
2438
- import { readFileSync as readFileSync11 } from "fs";
2582
+ import { readFileSync as readFileSync12 } from "fs";
2439
2583
  function messageText2(content) {
2440
2584
  if (typeof content === "string") return content.trim();
2441
2585
  if (!Array.isArray(content)) return "";
@@ -2445,7 +2589,7 @@ function readZcodeTranscript(path) {
2445
2589
  if (!path) return [];
2446
2590
  let body;
2447
2591
  try {
2448
- body = readFileSync11(path, "utf8");
2592
+ body = readFileSync12(path, "utf8");
2449
2593
  } catch {
2450
2594
  return [];
2451
2595
  }