@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.
@@ -0,0 +1,626 @@
1
+ #!/usr/bin/env node
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropNames = Object.getOwnPropertyNames;
4
+ var __esm = (fn, res) => function __init() {
5
+ return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
6
+ };
7
+ var __export = (target, all) => {
8
+ for (var name in all)
9
+ __defProp(target, name, { get: all[name], enumerable: true });
10
+ };
11
+
12
+ // node_modules/@vectorize-io/hindsight-all/dist/index.js
13
+ var dist_exports = {};
14
+ __export(dist_exports, {
15
+ HindsightServer: () => HindsightServer,
16
+ consoleLogger: () => consoleLogger,
17
+ getEmbedCommand: () => getEmbedCommand,
18
+ silentLogger: () => silentLogger
19
+ });
20
+ import { spawn } from "child_process";
21
+ function getEmbedCommand(opts = {}) {
22
+ if (opts.embedPackagePath) {
23
+ return ["uv", "run", "--directory", opts.embedPackagePath, "hindsight-embed"];
24
+ }
25
+ const version = opts.embedVersion && opts.embedVersion.length > 0 ? opts.embedVersion : "latest";
26
+ return ["uvx", `hindsight-embed@${version}`];
27
+ }
28
+ var silentLogger, consoleLogger, DEFAULT_PORT, DEFAULT_HOST, DEFAULT_PROFILE, DEFAULT_READY_TIMEOUT_MS, DEFAULT_READY_POLL_INTERVAL_MS, HindsightServer;
29
+ var init_dist = __esm({
30
+ "node_modules/@vectorize-io/hindsight-all/dist/index.js"() {
31
+ "use strict";
32
+ silentLogger = {
33
+ debug: () => {
34
+ },
35
+ info: () => {
36
+ },
37
+ warn: () => {
38
+ },
39
+ error: () => {
40
+ }
41
+ };
42
+ consoleLogger = {
43
+ debug: (msg) => console.debug(msg),
44
+ info: (msg) => console.log(msg),
45
+ warn: (msg) => console.warn(msg),
46
+ error: (msg) => console.error(msg)
47
+ };
48
+ DEFAULT_PORT = 8888;
49
+ DEFAULT_HOST = "127.0.0.1";
50
+ DEFAULT_PROFILE = "default";
51
+ DEFAULT_READY_TIMEOUT_MS = 3e4;
52
+ DEFAULT_READY_POLL_INTERVAL_MS = 1e3;
53
+ HindsightServer = class {
54
+ profile;
55
+ port;
56
+ host;
57
+ baseUrl;
58
+ embedVersion;
59
+ embedPackagePath;
60
+ userEnv;
61
+ extraProfileCreateArgs;
62
+ extraDaemonStartArgs;
63
+ platformCpuWorkaround;
64
+ readyTimeoutMs;
65
+ readyPollIntervalMs;
66
+ logger;
67
+ constructor(opts = {}) {
68
+ this.profile = opts.profile ?? DEFAULT_PROFILE;
69
+ this.port = opts.port ?? DEFAULT_PORT;
70
+ this.host = opts.host ?? DEFAULT_HOST;
71
+ this.baseUrl = `http://${this.host}:${this.port}`;
72
+ this.embedVersion = opts.embedVersion;
73
+ this.embedPackagePath = opts.embedPackagePath;
74
+ this.userEnv = opts.env ?? {};
75
+ this.extraProfileCreateArgs = opts.extraProfileCreateArgs ?? [];
76
+ this.extraDaemonStartArgs = opts.extraDaemonStartArgs ?? [];
77
+ this.platformCpuWorkaround = opts.platformCpuWorkaround ?? process.platform === "darwin";
78
+ this.readyTimeoutMs = opts.readyTimeoutMs ?? DEFAULT_READY_TIMEOUT_MS;
79
+ this.readyPollIntervalMs = opts.readyPollIntervalMs ?? DEFAULT_READY_POLL_INTERVAL_MS;
80
+ this.logger = opts.logger ?? silentLogger;
81
+ }
82
+ /** The base URL the daemon listens on (`http://host:port`). */
83
+ getBaseUrl() {
84
+ return this.baseUrl;
85
+ }
86
+ /** The profile name this server operates on. */
87
+ getProfile() {
88
+ return this.profile;
89
+ }
90
+ /**
91
+ * Ensure the daemon is configured and running. Idempotent — the underlying
92
+ * `profile create --merge` and `daemon start` commands tolerate re-runs.
93
+ */
94
+ async start() {
95
+ this.logger.info(`[hindsight] starting daemon for profile "${this.profile}"`);
96
+ const env = this.buildEnv();
97
+ await this.configureProfile(env);
98
+ await this.startDaemon(env);
99
+ await this.waitForReady();
100
+ this.logger.info(`[hindsight] daemon ready at ${this.baseUrl}`);
101
+ }
102
+ /** Stop the daemon. Never throws — logs and resolves even on failure. */
103
+ async stop() {
104
+ this.logger.info(`[hindsight] stopping daemon for profile "${this.profile}"`);
105
+ const [cmd, ...baseArgs] = getEmbedCommand({
106
+ embedVersion: this.embedVersion,
107
+ embedPackagePath: this.embedPackagePath
108
+ });
109
+ const args = [...baseArgs, "daemon", "--profile", this.profile, "stop"];
110
+ const child = spawn(cmd, args, { stdio: "pipe" });
111
+ this.pipeOutput(child, "daemon.stop");
112
+ await new Promise((resolve) => {
113
+ const timeout = setTimeout(() => {
114
+ this.logger.warn(`[hindsight] daemon stop timed out after 5s`);
115
+ resolve();
116
+ }, 5e3);
117
+ child.on("exit", () => {
118
+ clearTimeout(timeout);
119
+ this.logger.info(`[hindsight] daemon stopped`);
120
+ resolve();
121
+ });
122
+ child.on("error", (err) => {
123
+ clearTimeout(timeout);
124
+ this.logger.warn(`[hindsight] error stopping daemon: ${err.message}`);
125
+ resolve();
126
+ });
127
+ });
128
+ }
129
+ /** Probe `/health` once with a short timeout. */
130
+ async checkHealth() {
131
+ try {
132
+ const res = await fetch(`${this.baseUrl}/health`, {
133
+ signal: AbortSignal.timeout(2e3)
134
+ });
135
+ return res.ok;
136
+ } catch {
137
+ return false;
138
+ }
139
+ }
140
+ // -------------------------------------------------------------------------
141
+ // Internal
142
+ // -------------------------------------------------------------------------
143
+ /**
144
+ * Merge the process env, the caller-supplied `env`, and (on macOS) the
145
+ * embeddings CPU workaround. Caller-supplied values always win over the
146
+ * workaround; undefined values are dropped.
147
+ */
148
+ buildEnv() {
149
+ const merged = { ...process.env };
150
+ if (this.platformCpuWorkaround && process.platform === "darwin") {
151
+ merged["HINDSIGHT_API_EMBEDDINGS_LOCAL_FORCE_CPU"] = "1";
152
+ merged["HINDSIGHT_API_RERANKER_LOCAL_FORCE_CPU"] = "1";
153
+ }
154
+ for (const [key, value] of Object.entries(this.userEnv)) {
155
+ if (value !== void 0) {
156
+ merged[key] = value;
157
+ }
158
+ }
159
+ return merged;
160
+ }
161
+ /**
162
+ * Run `profile create <name> --merge --port <port> [--env K=V ...]`.
163
+ * Every entry in the merged env that was passed via {@link userEnv} (or
164
+ * auto-applied by the CPU workaround) is forwarded as `--env`.
165
+ */
166
+ async configureProfile(env) {
167
+ this.logger.info(`[hindsight] configuring profile "${this.profile}"`);
168
+ const [cmd, ...baseArgs] = getEmbedCommand({
169
+ embedVersion: this.embedVersion,
170
+ embedPackagePath: this.embedPackagePath
171
+ });
172
+ const createArgs = [
173
+ ...baseArgs,
174
+ "profile",
175
+ "create",
176
+ this.profile,
177
+ "--merge",
178
+ "--port",
179
+ String(this.port)
180
+ ];
181
+ const envForProfile = this.collectProfileEnv(env);
182
+ for (const [key, value] of Object.entries(envForProfile)) {
183
+ createArgs.push("--env", `${key}=${value}`);
184
+ }
185
+ createArgs.push(...this.extraProfileCreateArgs);
186
+ await this.runCommand(cmd, createArgs, env, "profile.create");
187
+ }
188
+ /** Collect only the env vars that should be written into the profile file. */
189
+ collectProfileEnv(env) {
190
+ const out = {};
191
+ for (const [key, value] of Object.entries(this.userEnv)) {
192
+ if (value !== void 0) {
193
+ out[key] = value;
194
+ }
195
+ }
196
+ if (this.platformCpuWorkaround && process.platform === "darwin") {
197
+ const cpuKeys = [
198
+ "HINDSIGHT_API_EMBEDDINGS_LOCAL_FORCE_CPU",
199
+ "HINDSIGHT_API_RERANKER_LOCAL_FORCE_CPU"
200
+ ];
201
+ for (const key of cpuKeys) {
202
+ if (!(key in out) && env[key] !== void 0) {
203
+ out[key] = env[key];
204
+ }
205
+ }
206
+ }
207
+ return out;
208
+ }
209
+ async startDaemon(env) {
210
+ const [cmd, ...baseArgs] = getEmbedCommand({
211
+ embedVersion: this.embedVersion,
212
+ embedPackagePath: this.embedPackagePath
213
+ });
214
+ const args = [
215
+ ...baseArgs,
216
+ "daemon",
217
+ "--profile",
218
+ this.profile,
219
+ "start",
220
+ ...this.extraDaemonStartArgs
221
+ ];
222
+ await this.runCommand(cmd, args, env, "daemon.start");
223
+ }
224
+ /**
225
+ * Spawn `cmd` with `args`, pipe its output through the logger, and resolve
226
+ * once it exits with code 0. Rejects on non-zero exit or spawn error.
227
+ */
228
+ async runCommand(cmd, args, env, label) {
229
+ const child = spawn(cmd, args, { stdio: "pipe", env });
230
+ let output = "";
231
+ child.stdout?.on("data", (data) => {
232
+ const text = data.toString();
233
+ output += text;
234
+ for (const line of text.trimEnd().split("\n")) {
235
+ if (line) this.logger.info(`[hindsight:${label}] ${line}`);
236
+ }
237
+ });
238
+ child.stderr?.on("data", (data) => {
239
+ const text = data.toString();
240
+ output += text;
241
+ for (const line of text.trimEnd().split("\n")) {
242
+ if (line) this.logger.warn(`[hindsight:${label}] ${line}`);
243
+ }
244
+ });
245
+ await new Promise((resolve, reject) => {
246
+ child.on("exit", (code) => {
247
+ if (code === 0) {
248
+ resolve();
249
+ } else {
250
+ reject(new Error(`${label} failed with code ${code}: ${output.trim()}`));
251
+ }
252
+ });
253
+ child.on("error", (err) => {
254
+ reject(new Error(`${label} failed to spawn: ${err.message}`, { cause: err }));
255
+ });
256
+ });
257
+ }
258
+ /** Stream a spawned child's stdout/stderr through the logger without blocking. */
259
+ pipeOutput(child, label) {
260
+ child.stdout?.on("data", (data) => {
261
+ for (const line of data.toString().trimEnd().split("\n")) {
262
+ if (line) this.logger.info(`[hindsight:${label}] ${line}`);
263
+ }
264
+ });
265
+ child.stderr?.on("data", (data) => {
266
+ for (const line of data.toString().trimEnd().split("\n")) {
267
+ if (line) this.logger.warn(`[hindsight:${label}] ${line}`);
268
+ }
269
+ });
270
+ }
271
+ /** Poll `/health` until it succeeds or `readyTimeoutMs` elapses. */
272
+ async waitForReady() {
273
+ const deadline = Date.now() + this.readyTimeoutMs;
274
+ let attempt = 0;
275
+ while (Date.now() < deadline) {
276
+ attempt++;
277
+ try {
278
+ const res = await fetch(`${this.baseUrl}/health`, {
279
+ signal: AbortSignal.timeout(this.readyPollIntervalMs)
280
+ });
281
+ if (res.ok) {
282
+ this.logger.debug(`[hindsight] health check passed (attempt ${attempt})`);
283
+ return;
284
+ }
285
+ } catch {
286
+ }
287
+ await new Promise((resolve) => setTimeout(resolve, this.readyPollIntervalMs));
288
+ }
289
+ throw new Error(
290
+ `Hindsight daemon did not become ready within ${this.readyTimeoutMs}ms at ${this.baseUrl}`
291
+ );
292
+ }
293
+ };
294
+ }
295
+ });
296
+
297
+ // src/core/config.ts
298
+ import { readFileSync } from "fs";
299
+ import { homedir } from "os";
300
+ import { join as join2 } from "path";
301
+
302
+ // src/core/seed.ts
303
+ import { spawn as realSpawn } from "child_process";
304
+ import { dirname, join } from "path";
305
+ import { fileURLToPath } from "url";
306
+ var DEFAULT_SEED_LIMIT = 300;
307
+
308
+ // src/core/config.ts
309
+ var CONFIG_PATH = process.env.HINDSIGHT_CONFIG || join2(homedir(), ".hindsight", "coding-agent.json");
310
+ var DEFAULT_DAEMON_PORT = 9077;
311
+ var DEFAULT_DAEMON_IDLE_TIMEOUT = 300;
312
+ var DEFAULT_DAEMON_PROFILE = "coding-agent";
313
+ function resolveConfig(raw = {}) {
314
+ const serverMode = ["cloud", "self-hosted", "daemon"].includes(raw.serverMode) ? raw.serverMode : "cloud";
315
+ const apiPort = raw.apiPort || DEFAULT_DAEMON_PORT;
316
+ return {
317
+ serverMode,
318
+ // Daemon mode resolves the URL HERE rather than at each call site: every entry point already
319
+ // builds its client from cfg.apiUrl, so collapsing the mode into that one field means the
320
+ // daemon needs no plumbing through eight separate constructors.
321
+ apiUrl: serverMode === "daemon" ? `http://127.0.0.1:${apiPort}` : raw.apiUrl ?? "https://api.hindsight.vectorize.io",
322
+ apiToken: raw.apiToken || void 0,
323
+ apiPort,
324
+ daemonIdleTimeout: raw.daemonIdleTimeout ?? DEFAULT_DAEMON_IDLE_TIMEOUT,
325
+ daemonProfile: raw.daemonProfile || DEFAULT_DAEMON_PROFILE,
326
+ embedVersion: raw.embedVersion || void 0,
327
+ embedPackagePath: raw.embedPackagePath || void 0,
328
+ bankId: raw.bankId,
329
+ dynamicBankId: raw.dynamicBankId,
330
+ bankIdTemplate: raw.bankIdTemplate,
331
+ mapPathToBank: raw.mapPathToBank,
332
+ resolveWorktrees: raw.resolveWorktrees,
333
+ harness: raw.harness ?? "opencode",
334
+ disabled: raw.disabled ?? false,
335
+ retainSessions: raw.retainSessions ?? true,
336
+ // opencode: write back by default (parity with hook-harness Stop)
337
+ retainEveryTurns: raw.retainEveryTurns || 1,
338
+ reflectTimeoutMs: raw.reflectTimeoutMs || 12e4,
339
+ autoReflect: raw.autoReflect ?? true,
340
+ pageRefreshEveryTurns: raw.pageRefreshEveryTurns || 10,
341
+ autoSeed: raw.autoSeed ?? true,
342
+ seedLimit: raw.seedLimit || DEFAULT_SEED_LIMIT,
343
+ codebaseSurvey: raw.codebaseSurvey ?? true,
344
+ surveyModel: raw.surveyModel || "haiku",
345
+ surveyBudgetUsd: raw.surveyBudgetUsd || 2,
346
+ surveyRefreshCommits: raw.surveyRefreshCommits ?? 20,
347
+ gitIngest: ["message", "full", "none"].includes(raw.gitIngest) ? raw.gitIngest : "message",
348
+ banks: raw.banks && typeof raw.banks === "object" ? raw.banks : {},
349
+ logLevel: ["debug", "info", "warn", "error"].includes(raw.logLevel) ? raw.logLevel : "info"
350
+ };
351
+ }
352
+ function readRaw(path) {
353
+ try {
354
+ return JSON.parse(readFileSync(path, "utf8"));
355
+ } catch (e) {
356
+ if (e?.code !== "ENOENT") {
357
+ console.error(`hindsight: ignoring invalid config at ${path}: ${e?.message || e}`);
358
+ }
359
+ return {};
360
+ }
361
+ }
362
+ function mergeRaw(a, b) {
363
+ const { harnesses: _drop, ...flat } = b;
364
+ return { ...a, ...flat, banks: { ...a.banks ?? {}, ...b.banks ?? {} } };
365
+ }
366
+ function applyLayer(raw, layer, harness) {
367
+ let out = mergeRaw(raw, layer);
368
+ const perHarness = harness ? layer.harnesses?.[harness] : void 0;
369
+ if (perHarness) out = mergeRaw(out, perHarness);
370
+ return out;
371
+ }
372
+ var ENV_KEYS = {
373
+ serverMode: "HINDSIGHT_SERVER_MODE",
374
+ apiUrl: "HINDSIGHT_API_URL",
375
+ apiToken: "HINDSIGHT_API_TOKEN",
376
+ // These four keep the names the old per-agent Claude Code plugin used, so a user migrating from
377
+ // it can carry their existing environment over unchanged.
378
+ apiPort: "HINDSIGHT_API_PORT",
379
+ daemonIdleTimeout: "HINDSIGHT_DAEMON_IDLE_TIMEOUT",
380
+ embedVersion: "HINDSIGHT_EMBED_VERSION",
381
+ embedPackagePath: "HINDSIGHT_EMBED_PACKAGE_PATH",
382
+ daemonProfile: "HINDSIGHT_DAEMON_PROFILE",
383
+ bankId: "HINDSIGHT_BANK_ID",
384
+ dynamicBankId: "HINDSIGHT_DYNAMIC_BANK_ID",
385
+ bankIdTemplate: "HINDSIGHT_BANK_ID_TEMPLATE",
386
+ resolveWorktrees: "HINDSIGHT_RESOLVE_WORKTREES",
387
+ harness: "HINDSIGHT_HARNESS",
388
+ disabled: "HINDSIGHT_DISABLED",
389
+ retainSessions: "HINDSIGHT_RETAIN_SESSIONS",
390
+ retainEveryTurns: "HINDSIGHT_RETAIN_EVERY_TURNS",
391
+ reflectTimeoutMs: "HINDSIGHT_REFLECT_TIMEOUT_MS",
392
+ autoReflect: "HINDSIGHT_AUTO_REFLECT",
393
+ pageRefreshEveryTurns: "HINDSIGHT_PAGE_REFRESH_EVERY_TURNS",
394
+ autoSeed: "HINDSIGHT_AUTO_SEED",
395
+ seedLimit: "HINDSIGHT_SEED_LIMIT",
396
+ codebaseSurvey: "HINDSIGHT_CODEBASE_SURVEY",
397
+ surveyModel: "HINDSIGHT_SURVEY_MODEL",
398
+ surveyBudgetUsd: "HINDSIGHT_SURVEY_BUDGET_USD",
399
+ surveyRefreshCommits: "HINDSIGHT_SURVEY_REFRESH_COMMITS",
400
+ logLevel: "HINDSIGHT_LOG_LEVEL",
401
+ gitIngest: "HINDSIGHT_GIT_INGEST"
402
+ };
403
+ var ENV_BOOLEANS = /* @__PURE__ */ new Set([
404
+ "dynamicBankId",
405
+ "resolveWorktrees",
406
+ "disabled",
407
+ "retainSessions",
408
+ "autoReflect",
409
+ "autoSeed",
410
+ "codebaseSurvey"
411
+ ]);
412
+ var ENV_NUMBERS = /* @__PURE__ */ new Set([
413
+ "apiPort",
414
+ "daemonIdleTimeout",
415
+ "retainEveryTurns",
416
+ "reflectTimeoutMs",
417
+ "pageRefreshEveryTurns",
418
+ "seedLimit",
419
+ "surveyBudgetUsd",
420
+ "surveyRefreshCommits"
421
+ ]);
422
+ function readEnvConfig(env = process.env) {
423
+ const out = {};
424
+ for (const [key, name] of Object.entries(ENV_KEYS)) {
425
+ const value = env[name];
426
+ if (value === void 0 || value.trim() === "") continue;
427
+ if (ENV_BOOLEANS.has(key)) {
428
+ out[key] = ["1", "true", "yes", "on"].includes(value.trim().toLowerCase());
429
+ } else if (ENV_NUMBERS.has(key)) {
430
+ const n = Number(value);
431
+ if (Number.isFinite(n)) out[key] = n;
432
+ else console.error(`hindsight: ignoring ${name}=${value} \u2014 not a number`);
433
+ } else {
434
+ out[key] = value;
435
+ }
436
+ }
437
+ return out;
438
+ }
439
+ function loadConfig(opts = {}) {
440
+ const o = typeof opts === "string" ? { path: opts } : opts;
441
+ const withEnv = applyLayer({}, readEnvConfig(), o.harness);
442
+ return resolveConfig(applyLayer(withEnv, readRaw(o.path ?? CONFIG_PATH), o.harness));
443
+ }
444
+
445
+ // src/core/daemon.ts
446
+ import { execFileSync, spawn as realSpawn2 } from "child_process";
447
+ import { dirname as dirname3, join as join4 } from "path";
448
+ import { fileURLToPath as fileURLToPath2 } from "url";
449
+
450
+ // src/core/diag.ts
451
+ import { appendFileSync as appendFileSync2 } from "fs";
452
+
453
+ // src/core/log.ts
454
+ import { appendFileSync, mkdirSync } from "fs";
455
+ import { tmpdir } from "os";
456
+ import { dirname as dirname2, join as join3 } from "path";
457
+ var WEIGHT = { debug: 10, info: 20, warn: 30, error: 40 };
458
+ var current = ["debug", "info", "warn", "error"].find(
459
+ (l) => l === process.env.HINDSIGHT_LOG_LEVEL
460
+ ) ?? "info";
461
+ function setLogLevel(level) {
462
+ if (!process.env.HINDSIGHT_LOG_LEVEL) current = level;
463
+ }
464
+ function logFilePath() {
465
+ return process.env.HINDSIGHT_LOG_FILE || join3(tmpdir(), "hindsight-coding-agent", "plugin.log");
466
+ }
467
+ function write(level, scope, msg, extra) {
468
+ if (WEIGHT[level] < WEIGHT[current]) return;
469
+ try {
470
+ const file = logFilePath();
471
+ mkdirSync(dirname2(file), { recursive: true });
472
+ appendFileSync(
473
+ file,
474
+ `${(/* @__PURE__ */ new Date()).toISOString()} ${level.toUpperCase().padEnd(5)} [${scope}] ${msg}` + (extra && Object.keys(extra).length ? ` ${JSON.stringify(extra)}` : "") + "\n"
475
+ );
476
+ } catch {
477
+ }
478
+ }
479
+ var log = {
480
+ debug: (scope, msg, extra) => write("debug", scope, msg, extra),
481
+ info: (scope, msg, extra) => write("info", scope, msg, extra),
482
+ warn: (scope, msg, extra) => write("warn", scope, msg, extra),
483
+ error: (scope, msg, extra) => write("error", scope, msg, extra)
484
+ };
485
+
486
+ // src/core/diag.ts
487
+ function diag(harness, event, extra = {}) {
488
+ log.debug(harness, `diag:${event}`, extra);
489
+ try {
490
+ appendFileSync2(
491
+ process.env.HINDSIGHT_DIAG_FILE || "/tmp/hindsight-plugin.log",
492
+ JSON.stringify({ ts: (/* @__PURE__ */ new Date()).toISOString(), harness, event, ...extra }) + "\n"
493
+ );
494
+ } catch {
495
+ }
496
+ }
497
+
498
+ // src/core/daemon.ts
499
+ async function isServerHealthy(baseUrl, timeoutMs = 2e3) {
500
+ try {
501
+ const res = await fetch(`${baseUrl}/health`, { signal: AbortSignal.timeout(timeoutMs) });
502
+ return res.ok;
503
+ } catch {
504
+ return false;
505
+ }
506
+ }
507
+ function hasRustToolchain() {
508
+ if (process.platform !== "darwin") return true;
509
+ try {
510
+ execFileSync("cargo", ["--version"], { stdio: "pipe", timeout: 1e4 });
511
+ return true;
512
+ } catch {
513
+ return false;
514
+ }
515
+ }
516
+ function hasUvx() {
517
+ try {
518
+ execFileSync("uvx", ["--version"], { stdio: "pipe", timeout: 1e4 });
519
+ return true;
520
+ } catch {
521
+ return false;
522
+ }
523
+ }
524
+ var PROVIDER_PROBES = [
525
+ { provider: "openai", keyEnv: "OPENAI_API_KEY" },
526
+ { provider: "anthropic", keyEnv: "ANTHROPIC_API_KEY" },
527
+ { provider: "gemini", keyEnv: "GEMINI_API_KEY" },
528
+ { provider: "groq", keyEnv: "GROQ_API_KEY" }
529
+ ];
530
+ function detectLlm(env = process.env) {
531
+ const explicit = env.HINDSIGHT_API_LLM_PROVIDER?.trim();
532
+ if (explicit) {
533
+ return {
534
+ provider: explicit,
535
+ apiKey: env.HINDSIGHT_API_LLM_API_KEY?.trim() || void 0,
536
+ source: "HINDSIGHT_API_LLM_PROVIDER"
537
+ };
538
+ }
539
+ for (const probe of PROVIDER_PROBES) {
540
+ const key = env[probe.keyEnv]?.trim();
541
+ if (key) return { provider: probe.provider, apiKey: key, source: probe.keyEnv };
542
+ }
543
+ if (onPath("claude")) {
544
+ return { provider: "claude-code", source: "the Claude Code CLI on PATH (no API key needed)" };
545
+ }
546
+ return void 0;
547
+ }
548
+ function onPath(bin) {
549
+ try {
550
+ execFileSync("which", [bin], { stdio: "pipe", timeout: 5e3 });
551
+ return true;
552
+ } catch {
553
+ return false;
554
+ }
555
+ }
556
+ function daemonEnv(cfg, env = process.env) {
557
+ const out = {
558
+ HINDSIGHT_EMBED_DAEMON_IDLE_TIMEOUT: String(cfg.daemonIdleTimeout)
559
+ };
560
+ for (const [key, value] of Object.entries(env)) {
561
+ if (key.startsWith("HINDSIGHT_API_") && value) out[key] = value;
562
+ }
563
+ const llm = detectLlm(env);
564
+ if (llm) {
565
+ out.HINDSIGHT_API_LLM_PROVIDER = llm.provider;
566
+ if (llm.apiKey) out.HINDSIGHT_API_LLM_API_KEY = llm.apiKey;
567
+ }
568
+ return out;
569
+ }
570
+ function preflightDaemon(cfg, harness) {
571
+ if (!hasUvx()) {
572
+ diag(harness, "daemon_uvx_missing", { apiUrl: cfg.apiUrl });
573
+ log.warn(harness, "daemon mode needs `uv` on PATH \u2014 see https://docs.astral.sh/uv/");
574
+ return false;
575
+ }
576
+ if (!hasRustToolchain()) {
577
+ diag(harness, "daemon_rust_missing", { platform: process.platform });
578
+ log.warn(
579
+ harness,
580
+ "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`"
581
+ );
582
+ return false;
583
+ }
584
+ if (!detectLlm()) {
585
+ diag(harness, "daemon_no_llm", {});
586
+ log.warn(
587
+ harness,
588
+ "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"
589
+ );
590
+ return false;
591
+ }
592
+ return true;
593
+ }
594
+
595
+ // src/daemon-start.ts
596
+ function arg(name) {
597
+ const i = process.argv.indexOf(`--${name}`);
598
+ return i >= 0 ? process.argv[i + 1] : void 0;
599
+ }
600
+ async function main() {
601
+ const harness = arg("harness") ?? "coding-agent";
602
+ const cfg = loadConfig({ harness });
603
+ setLogLevel(cfg.logLevel);
604
+ if (cfg.serverMode !== "daemon") return;
605
+ if (await isServerHealthy(cfg.apiUrl)) return;
606
+ if (!preflightDaemon(cfg, harness)) return;
607
+ const { HindsightServer: HindsightServer2 } = await Promise.resolve().then(() => (init_dist(), dist_exports));
608
+ const server = new HindsightServer2({
609
+ profile: cfg.daemonProfile,
610
+ port: cfg.apiPort,
611
+ env: daemonEnv(cfg),
612
+ embedVersion: cfg.embedVersion,
613
+ embedPackagePath: cfg.embedPackagePath,
614
+ logger: {
615
+ debug: (m) => log.debug(harness, m),
616
+ info: (m) => log.info(harness, m),
617
+ warn: (m) => log.warn(harness, m),
618
+ error: (m) => log.error(harness, m)
619
+ }
620
+ });
621
+ await server.start();
622
+ diag(harness, "daemon_started", { apiUrl: cfg.apiUrl, profile: cfg.daemonProfile });
623
+ }
624
+ main().catch((error) => {
625
+ diag(arg("harness") ?? "coding-agent", "daemon_start_failed", { error: String(error) });
626
+ });
package/dist/deepen.js CHANGED
@@ -155,10 +155,24 @@ var DEFAULT_SEED_LIMIT = 300;
155
155
 
156
156
  // src/core/config.ts
157
157
  var CONFIG_PATH = process.env.HINDSIGHT_CONFIG || join3(homedir2(), ".hindsight", "coding-agent.json");
158
+ var DEFAULT_DAEMON_PORT = 9077;
159
+ var DEFAULT_DAEMON_IDLE_TIMEOUT = 300;
160
+ var DEFAULT_DAEMON_PROFILE = "coding-agent";
158
161
  function resolveConfig(raw = {}) {
162
+ const serverMode = ["cloud", "self-hosted", "daemon"].includes(raw.serverMode) ? raw.serverMode : "cloud";
163
+ const apiPort = raw.apiPort || DEFAULT_DAEMON_PORT;
159
164
  return {
160
- apiUrl: raw.apiUrl ?? "https://api.hindsight.vectorize.io",
165
+ serverMode,
166
+ // Daemon mode resolves the URL HERE rather than at each call site: every entry point already
167
+ // builds its client from cfg.apiUrl, so collapsing the mode into that one field means the
168
+ // daemon needs no plumbing through eight separate constructors.
169
+ apiUrl: serverMode === "daemon" ? `http://127.0.0.1:${apiPort}` : raw.apiUrl ?? "https://api.hindsight.vectorize.io",
161
170
  apiToken: raw.apiToken || void 0,
171
+ apiPort,
172
+ daemonIdleTimeout: raw.daemonIdleTimeout ?? DEFAULT_DAEMON_IDLE_TIMEOUT,
173
+ daemonProfile: raw.daemonProfile || DEFAULT_DAEMON_PROFILE,
174
+ embedVersion: raw.embedVersion || void 0,
175
+ embedPackagePath: raw.embedPackagePath || void 0,
162
176
  bankId: raw.bankId,
163
177
  dynamicBankId: raw.dynamicBankId,
164
178
  bankIdTemplate: raw.bankIdTemplate,
@@ -204,8 +218,16 @@ function applyLayer(raw, layer, harness) {
204
218
  return out;
205
219
  }
206
220
  var ENV_KEYS = {
221
+ serverMode: "HINDSIGHT_SERVER_MODE",
207
222
  apiUrl: "HINDSIGHT_API_URL",
208
223
  apiToken: "HINDSIGHT_API_TOKEN",
224
+ // These four keep the names the old per-agent Claude Code plugin used, so a user migrating from
225
+ // it can carry their existing environment over unchanged.
226
+ apiPort: "HINDSIGHT_API_PORT",
227
+ daemonIdleTimeout: "HINDSIGHT_DAEMON_IDLE_TIMEOUT",
228
+ embedVersion: "HINDSIGHT_EMBED_VERSION",
229
+ embedPackagePath: "HINDSIGHT_EMBED_PACKAGE_PATH",
230
+ daemonProfile: "HINDSIGHT_DAEMON_PROFILE",
209
231
  bankId: "HINDSIGHT_BANK_ID",
210
232
  dynamicBankId: "HINDSIGHT_DYNAMIC_BANK_ID",
211
233
  bankIdTemplate: "HINDSIGHT_BANK_ID_TEMPLATE",
@@ -236,6 +258,8 @@ var ENV_BOOLEANS = /* @__PURE__ */ new Set([
236
258
  "codebaseSurvey"
237
259
  ]);
238
260
  var ENV_NUMBERS = /* @__PURE__ */ new Set([
261
+ "apiPort",
262
+ "daemonIdleTimeout",
239
263
  "retainEveryTurns",
240
264
  "reflectTimeoutMs",
241
265
  "pageRefreshEveryTurns",