@vectorize-io/hindsight-coding-agents 0.0.3 → 0.0.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.
@@ -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 {
@@ -1180,10 +1321,13 @@ function readGrokTranscript(path) {
1180
1321
  }
1181
1322
 
1182
1323
  // src/core/transcript-devin.ts
1183
- import { execFileSync as execFileSync4 } from "child_process";
1324
+ import { existsSync as existsSync5 } from "fs";
1325
+ import { createRequire } from "module";
1184
1326
  import { homedir as homedir6 } from "os";
1185
- import { join as join9 } from "path";
1186
- var sessionDb = join9(homedir6(), ".local", "share", "devin", "cli", "sessions.db");
1327
+ import { join as join10 } from "path";
1328
+ function devinSessionDb(home = homedir6()) {
1329
+ return join10(home, ".local", "share", "devin", "cli", "sessions.db");
1330
+ }
1187
1331
  function parseDevinMessages(nodes) {
1188
1332
  const messages = /* @__PURE__ */ new Map();
1189
1333
  for (const node of nodes) {
@@ -1204,23 +1348,41 @@ function parseDevinMessages(nodes) {
1204
1348
  }
1205
1349
  return [...messages.values()].sort((a, b) => a.index - b.index).map(({ role, content }) => ({ role, content }));
1206
1350
  }
1207
- function readDevinTranscript(sessionId) {
1208
- if (!sessionId) return [];
1351
+ var requireBuiltin = createRequire(import.meta.url);
1352
+ function loadSqlite() {
1209
1353
  try {
1210
- const quotedId = sessionId.replace(/'/g, "''");
1211
- const raw = execFileSync4(
1212
- "sqlite3",
1213
- [
1214
- "-json",
1215
- sessionDb,
1216
- `SELECT node_id, chat_message FROM message_nodes WHERE session_id = '${quotedId}' ORDER BY node_id`
1217
- ],
1218
- { encoding: "utf8", stdio: ["ignore", "pipe", "ignore"], timeout: 2e3 }
1219
- );
1220
- return parseDevinMessages(JSON.parse(raw));
1354
+ return requireBuiltin("node:sqlite").DatabaseSync;
1221
1355
  } catch {
1356
+ return void 0;
1357
+ }
1358
+ }
1359
+ function readDevinTranscript(sessionId, dbPath = devinSessionDb()) {
1360
+ if (!sessionId) return [];
1361
+ const Database = loadSqlite();
1362
+ if (!Database) {
1363
+ diag("devin-cli", "sqlite_unavailable", { node: process.version, dbPath });
1222
1364
  return [];
1223
1365
  }
1366
+ if (!existsSync5(dbPath)) {
1367
+ diag("devin-cli", "session_db_missing", { dbPath });
1368
+ return [];
1369
+ }
1370
+ let db;
1371
+ try {
1372
+ db = new Database(dbPath, { readOnly: true });
1373
+ const rows = db.prepare(
1374
+ "SELECT node_id, chat_message FROM message_nodes WHERE session_id = ? ORDER BY node_id"
1375
+ ).all(sessionId);
1376
+ return parseDevinMessages(rows);
1377
+ } catch (error) {
1378
+ diag("devin-cli", "session_db_read_failed", { dbPath, error: String(error) });
1379
+ return [];
1380
+ } finally {
1381
+ try {
1382
+ db?.close();
1383
+ } catch {
1384
+ }
1385
+ }
1224
1386
  }
1225
1387
 
1226
1388
  // src/harness/hook-lifecycle.ts