@vectorize-io/hindsight-coding-agents 0.0.4 → 0.1.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.
@@ -106,10 +106,24 @@ function startBackgroundSeed(repoDir, opts = {}) {
106
106
 
107
107
  // src/core/config.ts
108
108
  var CONFIG_PATH = process.env.HINDSIGHT_CONFIG || join3(homedir2(), ".hindsight", "coding-agent.json");
109
+ var DEFAULT_DAEMON_PORT = 9077;
110
+ var DEFAULT_DAEMON_IDLE_TIMEOUT = 300;
111
+ var DEFAULT_DAEMON_PROFILE = "coding-agent";
109
112
  function resolveConfig(raw = {}) {
113
+ const serverMode = ["cloud", "self-hosted", "daemon"].includes(raw.serverMode) ? raw.serverMode : "cloud";
114
+ const apiPort = raw.apiPort || DEFAULT_DAEMON_PORT;
110
115
  return {
111
- apiUrl: raw.apiUrl ?? "https://api.hindsight.vectorize.io",
116
+ serverMode,
117
+ // Daemon mode resolves the URL HERE rather than at each call site: every entry point already
118
+ // builds its client from cfg.apiUrl, so collapsing the mode into that one field means the
119
+ // daemon needs no plumbing through eight separate constructors.
120
+ apiUrl: serverMode === "daemon" ? `http://127.0.0.1:${apiPort}` : raw.apiUrl ?? "https://api.hindsight.vectorize.io",
112
121
  apiToken: raw.apiToken || void 0,
122
+ apiPort,
123
+ daemonIdleTimeout: raw.daemonIdleTimeout ?? DEFAULT_DAEMON_IDLE_TIMEOUT,
124
+ daemonProfile: raw.daemonProfile || DEFAULT_DAEMON_PROFILE,
125
+ embedVersion: raw.embedVersion || void 0,
126
+ embedPackagePath: raw.embedPackagePath || void 0,
113
127
  bankId: raw.bankId,
114
128
  dynamicBankId: raw.dynamicBankId,
115
129
  bankIdTemplate: raw.bankIdTemplate,
@@ -155,8 +169,16 @@ function applyLayer(raw, layer, harness) {
155
169
  return out;
156
170
  }
157
171
  var ENV_KEYS = {
172
+ serverMode: "HINDSIGHT_SERVER_MODE",
158
173
  apiUrl: "HINDSIGHT_API_URL",
159
174
  apiToken: "HINDSIGHT_API_TOKEN",
175
+ // These four keep the names the old per-agent Claude Code plugin used, so a user migrating from
176
+ // it can carry their existing environment over unchanged.
177
+ apiPort: "HINDSIGHT_API_PORT",
178
+ daemonIdleTimeout: "HINDSIGHT_DAEMON_IDLE_TIMEOUT",
179
+ embedVersion: "HINDSIGHT_EMBED_VERSION",
180
+ embedPackagePath: "HINDSIGHT_EMBED_PACKAGE_PATH",
181
+ daemonProfile: "HINDSIGHT_DAEMON_PROFILE",
160
182
  bankId: "HINDSIGHT_BANK_ID",
161
183
  dynamicBankId: "HINDSIGHT_DYNAMIC_BANK_ID",
162
184
  bankIdTemplate: "HINDSIGHT_BANK_ID_TEMPLATE",
@@ -187,6 +209,8 @@ var ENV_BOOLEANS = /* @__PURE__ */ new Set([
187
209
  "codebaseSurvey"
188
210
  ]);
189
211
  var ENV_NUMBERS = /* @__PURE__ */ new Set([
212
+ "apiPort",
213
+ "daemonIdleTimeout",
190
214
  "retainEveryTurns",
191
215
  "reflectTimeoutMs",
192
216
  "pageRefreshEveryTurns",
@@ -860,6 +884,122 @@ function writeSessionCache(cacheFile, cache) {
860
884
  // src/core/retain-hook.ts
861
885
  import { readFileSync as readFileSync5 } from "fs";
862
886
 
887
+ // src/core/daemon.ts
888
+ import { execFileSync as execFileSync2, spawn as realSpawn2 } from "child_process";
889
+ import { dirname as dirname5, join as join6 } from "path";
890
+ import { fileURLToPath as fileURLToPath2 } from "url";
891
+ var DAEMON_WAIT_SESSION_START_MS = 12e3;
892
+ async function isServerHealthy(baseUrl, timeoutMs = 2e3) {
893
+ try {
894
+ const res = await fetch(`${baseUrl}/health`, { signal: AbortSignal.timeout(timeoutMs) });
895
+ return res.ok;
896
+ } catch {
897
+ return false;
898
+ }
899
+ }
900
+ function hasRustToolchain() {
901
+ if (process.platform !== "darwin") return true;
902
+ try {
903
+ execFileSync2("cargo", ["--version"], { stdio: "pipe", timeout: 1e4 });
904
+ return true;
905
+ } catch {
906
+ return false;
907
+ }
908
+ }
909
+ function hasUvx() {
910
+ try {
911
+ execFileSync2("uvx", ["--version"], { stdio: "pipe", timeout: 1e4 });
912
+ return true;
913
+ } catch {
914
+ return false;
915
+ }
916
+ }
917
+ var PROVIDER_PROBES = [
918
+ { provider: "openai", keyEnv: "OPENAI_API_KEY" },
919
+ { provider: "anthropic", keyEnv: "ANTHROPIC_API_KEY" },
920
+ { provider: "gemini", keyEnv: "GEMINI_API_KEY" },
921
+ { provider: "groq", keyEnv: "GROQ_API_KEY" }
922
+ ];
923
+ function detectLlm(env = process.env) {
924
+ const explicit = env.HINDSIGHT_API_LLM_PROVIDER?.trim();
925
+ if (explicit) {
926
+ return {
927
+ provider: explicit,
928
+ apiKey: env.HINDSIGHT_API_LLM_API_KEY?.trim() || void 0,
929
+ source: "HINDSIGHT_API_LLM_PROVIDER"
930
+ };
931
+ }
932
+ for (const probe of PROVIDER_PROBES) {
933
+ const key = env[probe.keyEnv]?.trim();
934
+ if (key) return { provider: probe.provider, apiKey: key, source: probe.keyEnv };
935
+ }
936
+ if (onPath("claude")) {
937
+ return { provider: "claude-code", source: "the Claude Code CLI on PATH (no API key needed)" };
938
+ }
939
+ return void 0;
940
+ }
941
+ function onPath(bin) {
942
+ try {
943
+ execFileSync2("which", [bin], { stdio: "pipe", timeout: 5e3 });
944
+ return true;
945
+ } catch {
946
+ return false;
947
+ }
948
+ }
949
+ function startDaemonDetached(cfg, harness, spawnFn = realSpawn2) {
950
+ try {
951
+ const starter = join6(dirname5(fileURLToPath2(import.meta.url)), "daemon-start.js");
952
+ const child = spawnFn("node", [starter, "--harness", harness], {
953
+ detached: true,
954
+ stdio: "ignore"
955
+ });
956
+ child.on("error", () => {
957
+ });
958
+ child.unref();
959
+ diag(harness, "daemon_start_spawned", { apiUrl: cfg.apiUrl });
960
+ } catch {
961
+ }
962
+ }
963
+ async function ensureDaemon(cfg, harness, opts = {}) {
964
+ if (cfg.serverMode !== "daemon") return;
965
+ if (await isServerHealthy(cfg.apiUrl)) return;
966
+ if (!preflightDaemon(cfg, harness)) return;
967
+ startDaemonDetached(cfg, harness, opts.spawnFn);
968
+ await waitForHealth(cfg.apiUrl, opts.waitMs ?? 0);
969
+ }
970
+ async function waitForHealth(baseUrl, budgetMs, pollMs = 1e3) {
971
+ const deadline = Date.now() + budgetMs;
972
+ while (Date.now() < deadline) {
973
+ await new Promise((r) => setTimeout(r, pollMs));
974
+ if (await isServerHealthy(baseUrl)) return true;
975
+ }
976
+ return false;
977
+ }
978
+ function preflightDaemon(cfg, harness) {
979
+ if (!hasUvx()) {
980
+ diag(harness, "daemon_uvx_missing", { apiUrl: cfg.apiUrl });
981
+ log.warn(harness, "daemon mode needs `uv` on PATH \u2014 see https://docs.astral.sh/uv/");
982
+ return false;
983
+ }
984
+ if (!hasRustToolchain()) {
985
+ diag(harness, "daemon_rust_missing", { platform: process.platform });
986
+ log.warn(
987
+ harness,
988
+ "daemon mode on macOS needs a current Rust toolchain (litellm ships no macOS wheel) \u2014 install from https://rustup.rs, then `rustup default stable && rustup update`"
989
+ );
990
+ return false;
991
+ }
992
+ if (!detectLlm()) {
993
+ diag(harness, "daemon_no_llm", {});
994
+ log.warn(
995
+ harness,
996
+ "daemon mode needs an LLM for fact extraction \u2014 set OPENAI_API_KEY (or ANTHROPIC_API_KEY / GEMINI_API_KEY / HINDSIGHT_API_LLM_PROVIDER), or install the Claude Code CLI"
997
+ );
998
+ return false;
999
+ }
1000
+ return true;
1001
+ }
1002
+
863
1003
  // src/core/transcript.ts
864
1004
  import { readFileSync as readFileSync4 } from "fs";
865
1005
 
@@ -902,10 +1042,10 @@ function actionLine(tool, input) {
902
1042
  import { readFileSync as readFileSync7 } from "fs";
903
1043
 
904
1044
  // src/core/git.ts
905
- import { execFileSync as execFileSync2 } from "child_process";
1045
+ import { execFileSync as execFileSync3 } from "child_process";
906
1046
  import { resolve } from "path";
907
1047
  function git(repo, ...args) {
908
- return execFileSync2("git", ["-C", repo, ...args], { encoding: "utf8", maxBuffer: 1 << 28 });
1048
+ return execFileSync3("git", ["-C", repo, ...args], { encoding: "utf8", maxBuffer: 1 << 28 });
909
1049
  }
910
1050
  function gitHeadSha(dir) {
911
1051
  try {
@@ -931,14 +1071,14 @@ function hasGitHistory(dir) {
931
1071
  }
932
1072
 
933
1073
  // src/core/status.ts
934
- import { execFileSync as execFileSync3 } from "child_process";
1074
+ import { execFileSync as execFileSync4 } from "child_process";
935
1075
 
936
1076
  // src/core/survey.ts
937
- import { spawn as realSpawn2 } from "child_process";
1077
+ import { spawn as realSpawn3 } from "child_process";
938
1078
  import { accessSync, constants, existsSync as existsSync2 } from "fs";
939
1079
  import { homedir as homedir3 } from "os";
940
- import { delimiter, dirname as dirname5, join as join6 } from "path";
941
- import { fileURLToPath as fileURLToPath2 } from "url";
1080
+ import { delimiter, dirname as dirname6, join as join7 } from "path";
1081
+ import { fileURLToPath as fileURLToPath3 } from "url";
942
1082
  var SURVEY_DOC_IDS = [
943
1083
  "repository-component-map",
944
1084
  "repository-core-concepts",
@@ -948,7 +1088,7 @@ var SURVEY_DOC_IDS = [
948
1088
  function resolveClaudeBin(explicit) {
949
1089
  if (explicit) return explicit;
950
1090
  if (process.env.HINDSIGHT_CLAUDE_BIN) return process.env.HINDSIGHT_CLAUDE_BIN;
951
- const nativeInstallPath = join6(homedir3(), ".claude", "local", "claude");
1091
+ const nativeInstallPath = join7(homedir3(), ".claude", "local", "claude");
952
1092
  try {
953
1093
  if (existsSync2(nativeInstallPath)) return nativeInstallPath;
954
1094
  } catch {
@@ -976,7 +1116,7 @@ function binExists(bin) {
976
1116
  for (const dir of (process.env.PATH || "").split(delimiter)) {
977
1117
  if (!dir) continue;
978
1118
  try {
979
- accessSync(join6(dir, bin), constants.X_OK);
1119
+ accessSync(join7(dir, bin), constants.X_OK);
980
1120
  return true;
981
1121
  } catch {
982
1122
  }
@@ -1083,9 +1223,9 @@ function buildSurveyPlan(harness, bin, repoDir, opts) {
1083
1223
  }
1084
1224
  function startCodebaseSurvey(repoDir, opts = {}) {
1085
1225
  try {
1086
- const spawnFn = opts.spawn ?? realSpawn2;
1226
+ const spawnFn = opts.spawn ?? realSpawn3;
1087
1227
  const exists = opts.exists ?? binExists;
1088
- const mcpServerPath = opts.mcpServerPath ?? join6(dirname5(fileURLToPath2(import.meta.url)), "mcp-server.js");
1228
+ const mcpServerPath = opts.mcpServerPath ?? join7(dirname6(fileURLToPath3(import.meta.url)), "mcp-server.js");
1089
1229
  const preferred = opts.harness ?? "claude-code";
1090
1230
  const order = [
1091
1231
  preferred,
@@ -1126,8 +1266,8 @@ var DEEPEN_DIFF_TARGET = 300;
1126
1266
  // src/core/skill-sync.ts
1127
1267
  import { cpSync, existsSync as existsSync3, readFileSync as readFileSync6 } from "fs";
1128
1268
  import { homedir as homedir4 } from "os";
1129
- import { dirname as dirname6, join as join7 } from "path";
1130
- import { fileURLToPath as fileURLToPath3 } from "url";
1269
+ import { dirname as dirname7, join as join8 } from "path";
1270
+ import { fileURLToPath as fileURLToPath4 } from "url";
1131
1271
  var SKILL_DIRS = {
1132
1272
  "claude-code": [".claude", "skills"],
1133
1273
  codex: [".agents", "skills"],
@@ -1136,17 +1276,17 @@ var SKILL_DIRS = {
1136
1276
  "cursor-cli": [".cursor", "skills"]
1137
1277
  };
1138
1278
  function packagedSkillDir() {
1139
- return join7(dirname6(fileURLToPath3(import.meta.url)), "..", "skill");
1279
+ return join8(dirname7(fileURLToPath4(import.meta.url)), "..", "skill");
1140
1280
  }
1141
1281
  function syncCompanionSkill(harness, opts = {}) {
1142
1282
  try {
1143
1283
  const parts = SKILL_DIRS[harness];
1144
1284
  if (!parts) return;
1145
1285
  const src = opts.srcDir ?? packagedSkillDir();
1146
- const srcMd = join7(src, "SKILL.md");
1286
+ const srcMd = join8(src, "SKILL.md");
1147
1287
  if (!existsSync3(srcMd)) return;
1148
- const dst = join7(opts.home ?? homedir4(), ...parts, "hindsight-coding-agent");
1149
- const dstMd = join7(dst, "SKILL.md");
1288
+ const dst = join8(opts.home ?? homedir4(), ...parts, "hindsight-coding-agent");
1289
+ const dstMd = join8(dst, "SKILL.md");
1150
1290
  if (!existsSync3(dstMd)) return;
1151
1291
  if (readFileSync6(srcMd, "utf8") !== readFileSync6(dstMd, "utf8")) {
1152
1292
  cpSync(src, dst, { recursive: true });
@@ -1173,9 +1313,9 @@ async function gitSyncNote(args) {
1173
1313
  const deepened = [...gitIds].filter((id) => id.startsWith("git:")).length;
1174
1314
  let target = DEEPEN_DIFF_TARGET;
1175
1315
  try {
1176
- const { execFileSync: execFileSync4 } = await import("child_process");
1316
+ const { execFileSync: execFileSync5 } = await import("child_process");
1177
1317
  const n = Number(
1178
- execFileSync4("git", ["-C", cwd, "rev-list", "--count", "HEAD"], { encoding: "utf8" }).trim()
1318
+ execFileSync5("git", ["-C", cwd, "rev-list", "--count", "HEAD"], { encoding: "utf8" }).trim()
1179
1319
  );
1180
1320
  if (n > 0) target = Math.min(DEEPEN_DIFF_TARGET, n);
1181
1321
  } catch {
@@ -1317,6 +1457,7 @@ async function runSessionStartHook(spec, makeClient = (o) => new HindsightClient
1317
1457
  cfg = resolved.cfg;
1318
1458
  const bankId = resolved.bankId;
1319
1459
  if (cfg.disabled) return;
1460
+ await ensureDaemon(cfg, harness, { waitMs: DAEMON_WAIT_SESSION_START_MS });
1320
1461
  const client = makeClient({ apiUrl: cfg.apiUrl, apiToken: cfg.apiToken, bank: bankId });
1321
1462
  const out = await buildSessionStartContext({ cwd, bankId, cfg, client, harness });
1322
1463
  if (out.deferInitialReflect && sessionId) {
@@ -1490,17 +1631,17 @@ function readCopilotTranscript(path) {
1490
1631
  // src/core/transcript-grok.ts
1491
1632
  import { existsSync as existsSync4, readFileSync as readFileSync12, readdirSync } from "fs";
1492
1633
  import { homedir as homedir5 } from "os";
1493
- import { join as join8 } from "path";
1634
+ import { join as join9 } from "path";
1494
1635
  var CHAT_HISTORY = "chat_history.jsonl";
1495
- function grokTranscriptPath(cwd, sessionId, grokHome = process.env.GROK_HOME || join8(homedir5(), ".grok")) {
1496
- const sessionsDir = join8(grokHome, "sessions");
1497
- const direct = join8(sessionsDir, encodeURIComponent(cwd), sessionId, CHAT_HISTORY);
1636
+ function grokTranscriptPath(cwd, sessionId, grokHome = process.env.GROK_HOME || join9(homedir5(), ".grok")) {
1637
+ const sessionsDir = join9(grokHome, "sessions");
1638
+ const direct = join9(sessionsDir, encodeURIComponent(cwd), sessionId, CHAT_HISTORY);
1498
1639
  if (existsSync4(direct)) return direct;
1499
1640
  try {
1500
1641
  for (const candidate of readdirSync(sessionsDir)) {
1501
- const directory = join8(sessionsDir, candidate);
1502
- if (readFileSync12(join8(directory, ".cwd"), "utf8").trim() === cwd) {
1503
- return join8(directory, sessionId, CHAT_HISTORY);
1642
+ const directory = join9(sessionsDir, candidate);
1643
+ if (readFileSync12(join9(directory, ".cwd"), "utf8").trim() === cwd) {
1644
+ return join9(directory, sessionId, CHAT_HISTORY);
1504
1645
  }
1505
1646
  }
1506
1647
  } catch {
@@ -1544,9 +1685,9 @@ function readGrokTranscript(path) {
1544
1685
  import { existsSync as existsSync5 } from "fs";
1545
1686
  import { createRequire } from "module";
1546
1687
  import { homedir as homedir6 } from "os";
1547
- import { join as join9 } from "path";
1688
+ import { join as join10 } from "path";
1548
1689
  function devinSessionDb(home = homedir6()) {
1549
- return join9(home, ".local", "share", "devin", "cli", "sessions.db");
1690
+ return join10(home, ".local", "share", "devin", "cli", "sessions.db");
1550
1691
  }
1551
1692
  function parseDevinMessages(nodes) {
1552
1693
  const messages = /* @__PURE__ */ new Map();
@@ -80,10 +80,24 @@ var DEFAULT_SEED_LIMIT = 300;
80
80
 
81
81
  // src/core/config.ts
82
82
  var CONFIG_PATH = process.env.HINDSIGHT_CONFIG || join3(homedir2(), ".hindsight", "coding-agent.json");
83
+ var DEFAULT_DAEMON_PORT = 9077;
84
+ var DEFAULT_DAEMON_IDLE_TIMEOUT = 300;
85
+ var DEFAULT_DAEMON_PROFILE = "coding-agent";
83
86
  function resolveConfig(raw = {}) {
87
+ const serverMode = ["cloud", "self-hosted", "daemon"].includes(raw.serverMode) ? raw.serverMode : "cloud";
88
+ const apiPort = raw.apiPort || DEFAULT_DAEMON_PORT;
84
89
  return {
85
- apiUrl: raw.apiUrl ?? "https://api.hindsight.vectorize.io",
90
+ serverMode,
91
+ // Daemon mode resolves the URL HERE rather than at each call site: every entry point already
92
+ // builds its client from cfg.apiUrl, so collapsing the mode into that one field means the
93
+ // daemon needs no plumbing through eight separate constructors.
94
+ apiUrl: serverMode === "daemon" ? `http://127.0.0.1:${apiPort}` : raw.apiUrl ?? "https://api.hindsight.vectorize.io",
86
95
  apiToken: raw.apiToken || void 0,
96
+ apiPort,
97
+ daemonIdleTimeout: raw.daemonIdleTimeout ?? DEFAULT_DAEMON_IDLE_TIMEOUT,
98
+ daemonProfile: raw.daemonProfile || DEFAULT_DAEMON_PROFILE,
99
+ embedVersion: raw.embedVersion || void 0,
100
+ embedPackagePath: raw.embedPackagePath || void 0,
87
101
  bankId: raw.bankId,
88
102
  dynamicBankId: raw.dynamicBankId,
89
103
  bankIdTemplate: raw.bankIdTemplate,
@@ -129,8 +143,16 @@ function applyLayer(raw, layer, harness) {
129
143
  return out;
130
144
  }
131
145
  var ENV_KEYS = {
146
+ serverMode: "HINDSIGHT_SERVER_MODE",
132
147
  apiUrl: "HINDSIGHT_API_URL",
133
148
  apiToken: "HINDSIGHT_API_TOKEN",
149
+ // These four keep the names the old per-agent Claude Code plugin used, so a user migrating from
150
+ // it can carry their existing environment over unchanged.
151
+ apiPort: "HINDSIGHT_API_PORT",
152
+ daemonIdleTimeout: "HINDSIGHT_DAEMON_IDLE_TIMEOUT",
153
+ embedVersion: "HINDSIGHT_EMBED_VERSION",
154
+ embedPackagePath: "HINDSIGHT_EMBED_PACKAGE_PATH",
155
+ daemonProfile: "HINDSIGHT_DAEMON_PROFILE",
134
156
  bankId: "HINDSIGHT_BANK_ID",
135
157
  dynamicBankId: "HINDSIGHT_DYNAMIC_BANK_ID",
136
158
  bankIdTemplate: "HINDSIGHT_BANK_ID_TEMPLATE",
@@ -161,6 +183,8 @@ var ENV_BOOLEANS = /* @__PURE__ */ new Set([
161
183
  "codebaseSurvey"
162
184
  ]);
163
185
  var ENV_NUMBERS = /* @__PURE__ */ new Set([
186
+ "apiPort",
187
+ "daemonIdleTimeout",
164
188
  "retainEveryTurns",
165
189
  "reflectTimeoutMs",
166
190
  "pageRefreshEveryTurns",
@@ -802,6 +826,122 @@ async function retainLiveSession(client, sessionId, turns, startTs, harness) {
802
826
  );
803
827
  }
804
828
 
829
+ // src/core/daemon.ts
830
+ import { execFileSync as execFileSync2, spawn as realSpawn2 } from "child_process";
831
+ import { dirname as dirname5, join as join6 } from "path";
832
+ import { fileURLToPath as fileURLToPath2 } from "url";
833
+ var DAEMON_WAIT_RETAIN_MS = 4e4;
834
+ async function isServerHealthy(baseUrl, timeoutMs = 2e3) {
835
+ try {
836
+ const res = await fetch(`${baseUrl}/health`, { signal: AbortSignal.timeout(timeoutMs) });
837
+ return res.ok;
838
+ } catch {
839
+ return false;
840
+ }
841
+ }
842
+ function hasRustToolchain() {
843
+ if (process.platform !== "darwin") return true;
844
+ try {
845
+ execFileSync2("cargo", ["--version"], { stdio: "pipe", timeout: 1e4 });
846
+ return true;
847
+ } catch {
848
+ return false;
849
+ }
850
+ }
851
+ function hasUvx() {
852
+ try {
853
+ execFileSync2("uvx", ["--version"], { stdio: "pipe", timeout: 1e4 });
854
+ return true;
855
+ } catch {
856
+ return false;
857
+ }
858
+ }
859
+ var PROVIDER_PROBES = [
860
+ { provider: "openai", keyEnv: "OPENAI_API_KEY" },
861
+ { provider: "anthropic", keyEnv: "ANTHROPIC_API_KEY" },
862
+ { provider: "gemini", keyEnv: "GEMINI_API_KEY" },
863
+ { provider: "groq", keyEnv: "GROQ_API_KEY" }
864
+ ];
865
+ function detectLlm(env = process.env) {
866
+ const explicit = env.HINDSIGHT_API_LLM_PROVIDER?.trim();
867
+ if (explicit) {
868
+ return {
869
+ provider: explicit,
870
+ apiKey: env.HINDSIGHT_API_LLM_API_KEY?.trim() || void 0,
871
+ source: "HINDSIGHT_API_LLM_PROVIDER"
872
+ };
873
+ }
874
+ for (const probe of PROVIDER_PROBES) {
875
+ const key = env[probe.keyEnv]?.trim();
876
+ if (key) return { provider: probe.provider, apiKey: key, source: probe.keyEnv };
877
+ }
878
+ if (onPath("claude")) {
879
+ return { provider: "claude-code", source: "the Claude Code CLI on PATH (no API key needed)" };
880
+ }
881
+ return void 0;
882
+ }
883
+ function onPath(bin) {
884
+ try {
885
+ execFileSync2("which", [bin], { stdio: "pipe", timeout: 5e3 });
886
+ return true;
887
+ } catch {
888
+ return false;
889
+ }
890
+ }
891
+ function startDaemonDetached(cfg, harness, spawnFn = realSpawn2) {
892
+ try {
893
+ const starter = join6(dirname5(fileURLToPath2(import.meta.url)), "daemon-start.js");
894
+ const child = spawnFn("node", [starter, "--harness", harness], {
895
+ detached: true,
896
+ stdio: "ignore"
897
+ });
898
+ child.on("error", () => {
899
+ });
900
+ child.unref();
901
+ diag(harness, "daemon_start_spawned", { apiUrl: cfg.apiUrl });
902
+ } catch {
903
+ }
904
+ }
905
+ async function ensureDaemon(cfg, harness, opts = {}) {
906
+ if (cfg.serverMode !== "daemon") return;
907
+ if (await isServerHealthy(cfg.apiUrl)) return;
908
+ if (!preflightDaemon(cfg, harness)) return;
909
+ startDaemonDetached(cfg, harness, opts.spawnFn);
910
+ await waitForHealth(cfg.apiUrl, opts.waitMs ?? 0);
911
+ }
912
+ async function waitForHealth(baseUrl, budgetMs, pollMs = 1e3) {
913
+ const deadline = Date.now() + budgetMs;
914
+ while (Date.now() < deadline) {
915
+ await new Promise((r) => setTimeout(r, pollMs));
916
+ if (await isServerHealthy(baseUrl)) return true;
917
+ }
918
+ return false;
919
+ }
920
+ function preflightDaemon(cfg, harness) {
921
+ if (!hasUvx()) {
922
+ diag(harness, "daemon_uvx_missing", { apiUrl: cfg.apiUrl });
923
+ log.warn(harness, "daemon mode needs `uv` on PATH \u2014 see https://docs.astral.sh/uv/");
924
+ return false;
925
+ }
926
+ if (!hasRustToolchain()) {
927
+ diag(harness, "daemon_rust_missing", { platform: process.platform });
928
+ log.warn(
929
+ harness,
930
+ "daemon mode on macOS needs a current Rust toolchain (litellm ships no macOS wheel) \u2014 install from https://rustup.rs, then `rustup default stable && rustup update`"
931
+ );
932
+ return false;
933
+ }
934
+ if (!detectLlm()) {
935
+ diag(harness, "daemon_no_llm", {});
936
+ log.warn(
937
+ harness,
938
+ "daemon mode needs an LLM for fact extraction \u2014 set OPENAI_API_KEY (or ANTHROPIC_API_KEY / GEMINI_API_KEY / HINDSIGHT_API_LLM_PROVIDER), or install the Claude Code CLI"
939
+ );
940
+ return false;
941
+ }
942
+ return true;
943
+ }
944
+
805
945
  // src/core/transcript.ts
806
946
  import { readFileSync as readFileSync4 } from "fs";
807
947
 
@@ -936,6 +1076,7 @@ async function runRetainHook(spec, makeClient = (o) => new HindsightClient(o)) {
936
1076
  cfg = resolved.cfg;
937
1077
  const bankId = resolved.bankId;
938
1078
  if (cfg.disabled) return;
1079
+ await ensureDaemon(cfg, spec.harness, { waitMs: DAEMON_WAIT_RETAIN_MS });
939
1080
  const client = makeClient({ apiUrl: cfg.apiUrl, apiToken: cfg.apiToken, bank: bankId });
940
1081
  await buildRetain({
941
1082
  harness: spec.harness,
@@ -950,24 +1091,24 @@ async function runRetainHook(spec, makeClient = (o) => new HindsightClient(o)) {
950
1091
  import { readFileSync as readFileSync7 } from "fs";
951
1092
 
952
1093
  // src/core/git.ts
953
- import { execFileSync as execFileSync2 } from "child_process";
1094
+ import { execFileSync as execFileSync3 } from "child_process";
954
1095
  import { resolve } from "path";
955
1096
 
956
1097
  // src/core/status.ts
957
- import { execFileSync as execFileSync3 } from "child_process";
1098
+ import { execFileSync as execFileSync4 } from "child_process";
958
1099
 
959
1100
  // src/core/survey.ts
960
- import { spawn as realSpawn2 } from "child_process";
1101
+ import { spawn as realSpawn3 } from "child_process";
961
1102
  import { accessSync, constants, existsSync as existsSync2 } from "fs";
962
1103
  import { homedir as homedir3 } from "os";
963
- import { delimiter, dirname as dirname5, join as join6 } from "path";
964
- import { fileURLToPath as fileURLToPath2 } from "url";
1104
+ import { delimiter, dirname as dirname6, join as join7 } from "path";
1105
+ import { fileURLToPath as fileURLToPath3 } from "url";
965
1106
 
966
1107
  // src/core/skill-sync.ts
967
1108
  import { cpSync, existsSync as existsSync3, readFileSync as readFileSync6 } from "fs";
968
1109
  import { homedir as homedir4 } from "os";
969
- import { dirname as dirname6, join as join7 } from "path";
970
- import { fileURLToPath as fileURLToPath3 } from "url";
1110
+ import { dirname as dirname7, join as join8 } from "path";
1111
+ import { fileURLToPath as fileURLToPath4 } from "url";
971
1112
 
972
1113
  // src/core/transcript-codex.ts
973
1114
  import { readFileSync as readFileSync8 } from "fs";
@@ -1129,17 +1270,17 @@ function readCopilotTranscript(path) {
1129
1270
  // src/core/transcript-grok.ts
1130
1271
  import { existsSync as existsSync4, readFileSync as readFileSync12, readdirSync } from "fs";
1131
1272
  import { homedir as homedir5 } from "os";
1132
- import { join as join8 } from "path";
1273
+ import { join as join9 } from "path";
1133
1274
  var CHAT_HISTORY = "chat_history.jsonl";
1134
- function grokTranscriptPath(cwd, sessionId, grokHome = process.env.GROK_HOME || join8(homedir5(), ".grok")) {
1135
- const sessionsDir = join8(grokHome, "sessions");
1136
- const direct = join8(sessionsDir, encodeURIComponent(cwd), sessionId, CHAT_HISTORY);
1275
+ function grokTranscriptPath(cwd, sessionId, grokHome = process.env.GROK_HOME || join9(homedir5(), ".grok")) {
1276
+ const sessionsDir = join9(grokHome, "sessions");
1277
+ const direct = join9(sessionsDir, encodeURIComponent(cwd), sessionId, CHAT_HISTORY);
1137
1278
  if (existsSync4(direct)) return direct;
1138
1279
  try {
1139
1280
  for (const candidate of readdirSync(sessionsDir)) {
1140
- const directory = join8(sessionsDir, candidate);
1141
- if (readFileSync12(join8(directory, ".cwd"), "utf8").trim() === cwd) {
1142
- return join8(directory, sessionId, CHAT_HISTORY);
1281
+ const directory = join9(sessionsDir, candidate);
1282
+ if (readFileSync12(join9(directory, ".cwd"), "utf8").trim() === cwd) {
1283
+ return join9(directory, sessionId, CHAT_HISTORY);
1143
1284
  }
1144
1285
  }
1145
1286
  } catch {
@@ -1183,9 +1324,9 @@ function readGrokTranscript(path) {
1183
1324
  import { existsSync as existsSync5 } from "fs";
1184
1325
  import { createRequire } from "module";
1185
1326
  import { homedir as homedir6 } from "os";
1186
- import { join as join9 } from "path";
1327
+ import { join as join10 } from "path";
1187
1328
  function devinSessionDb(home = homedir6()) {
1188
- return join9(home, ".local", "share", "devin", "cli", "sessions.db");
1329
+ return join10(home, ".local", "share", "devin", "cli", "sessions.db");
1189
1330
  }
1190
1331
  function parseDevinMessages(nodes) {
1191
1332
  const messages = /* @__PURE__ */ new Map();
@@ -49,10 +49,24 @@ function seedControl(command2, args) {
49
49
 
50
50
  // src/core/config.ts
51
51
  var CONFIG_PATH = process.env.HINDSIGHT_CONFIG || join2(homedir(), ".hindsight", "coding-agent.json");
52
+ var DEFAULT_DAEMON_PORT = 9077;
53
+ var DEFAULT_DAEMON_IDLE_TIMEOUT = 300;
54
+ var DEFAULT_DAEMON_PROFILE = "coding-agent";
52
55
  function resolveConfig(raw = {}) {
56
+ const serverMode = ["cloud", "self-hosted", "daemon"].includes(raw.serverMode) ? raw.serverMode : "cloud";
57
+ const apiPort = raw.apiPort || DEFAULT_DAEMON_PORT;
53
58
  return {
54
- apiUrl: raw.apiUrl ?? "https://api.hindsight.vectorize.io",
59
+ serverMode,
60
+ // Daemon mode resolves the URL HERE rather than at each call site: every entry point already
61
+ // builds its client from cfg.apiUrl, so collapsing the mode into that one field means the
62
+ // daemon needs no plumbing through eight separate constructors.
63
+ apiUrl: serverMode === "daemon" ? `http://127.0.0.1:${apiPort}` : raw.apiUrl ?? "https://api.hindsight.vectorize.io",
55
64
  apiToken: raw.apiToken || void 0,
65
+ apiPort,
66
+ daemonIdleTimeout: raw.daemonIdleTimeout ?? DEFAULT_DAEMON_IDLE_TIMEOUT,
67
+ daemonProfile: raw.daemonProfile || DEFAULT_DAEMON_PROFILE,
68
+ embedVersion: raw.embedVersion || void 0,
69
+ embedPackagePath: raw.embedPackagePath || void 0,
56
70
  bankId: raw.bankId,
57
71
  dynamicBankId: raw.dynamicBankId,
58
72
  bankIdTemplate: raw.bankIdTemplate,
@@ -98,8 +112,16 @@ function applyLayer(raw, layer, harness) {
98
112
  return out;
99
113
  }
100
114
  var ENV_KEYS = {
115
+ serverMode: "HINDSIGHT_SERVER_MODE",
101
116
  apiUrl: "HINDSIGHT_API_URL",
102
117
  apiToken: "HINDSIGHT_API_TOKEN",
118
+ // These four keep the names the old per-agent Claude Code plugin used, so a user migrating from
119
+ // it can carry their existing environment over unchanged.
120
+ apiPort: "HINDSIGHT_API_PORT",
121
+ daemonIdleTimeout: "HINDSIGHT_DAEMON_IDLE_TIMEOUT",
122
+ embedVersion: "HINDSIGHT_EMBED_VERSION",
123
+ embedPackagePath: "HINDSIGHT_EMBED_PACKAGE_PATH",
124
+ daemonProfile: "HINDSIGHT_DAEMON_PROFILE",
103
125
  bankId: "HINDSIGHT_BANK_ID",
104
126
  dynamicBankId: "HINDSIGHT_DYNAMIC_BANK_ID",
105
127
  bankIdTemplate: "HINDSIGHT_BANK_ID_TEMPLATE",
@@ -130,6 +152,8 @@ var ENV_BOOLEANS = /* @__PURE__ */ new Set([
130
152
  "codebaseSurvey"
131
153
  ]);
132
154
  var ENV_NUMBERS = /* @__PURE__ */ new Set([
155
+ "apiPort",
156
+ "daemonIdleTimeout",
133
157
  "retainEveryTurns",
134
158
  "reflectTimeoutMs",
135
159
  "pageRefreshEveryTurns",