@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.
package/README.md CHANGED
@@ -25,6 +25,10 @@ hindsight-coding-agents uninstall all # removes exactly what install adde
25
25
  `hindsight-coding-agents install` changes nothing and prints the choice, so wiring every agent on
26
26
  the machine is never something that happens by accident.
27
27
 
28
+ On a terminal it also asks **where memory should live** — Hindsight Cloud, a server you run, or a
29
+ local daemon on this machine (see [Where memory lives](#where-memory-lives)). Scripted installs pass
30
+ `--server cloud|self-hosted|daemon` instead; it is asked only once, and never again on re-install.
31
+
28
32
  ### Per agent
29
33
 
30
34
  Same command, only the harness name changes. Run after installing the package globally.
@@ -80,18 +84,33 @@ a `hookAdapter` in `src/harness/registry.ts`; persistent-plugin → implement `H
80
84
 
81
85
  ## Migrating from the per-agent plugins
82
86
 
83
- The older per-agent integrations (`hindsight-claude-code`, `hindsight-cursor-cli`, `hindsight-codex`, …) are superseded by this package. Their memory does **not** carry over automatically, and it cannot be merged:
87
+ The older per-agent integrations (`hindsight-claude-code`, `hindsight-cursor-cli`, `hindsight-codex`, …) are superseded by this package. Two things move; nothing else does.
84
88
 
85
- - They scope a bank **per agent per project** (`claude-code::myrepo`); this package uses one **per repo** (`coding-agent::myrepo`) so every agent shares it. Two old banks map onto one new one.
86
- - The server restores a whole bank rather than merging into an existing one, so the old bank can't be folded in.
89
+ **Your server moves automatically.** If `~/.hindsight/claude-code.json` or `~/.hindsight/codex.json`
90
+ exists, `install` adopts its endpoint — `hindsightApiUrl` → `apiUrl`, `hindsightApiToken` →
91
+ `apiToken`, and an empty URL means the local daemon, as it did there. The agent you are installing
92
+ is checked first, so wiring Codex takes Codex's server even if an old `claude-code.json` is still
93
+ lying around. You already chose where your memory lives; defaulting to Cloud instead would quietly
94
+ send your prompts somewhere else. Pass `--server` to override. (Those two are the only old plugins
95
+ that shipped a user config — Cursor CLI, Copilot CLI, opencode and Cline have no endpoint to carry.)
87
96
 
88
- Instead, re-import the conversations the agent already wrote to disk — they get re-extracted into the current bank:
97
+ **Your conversations are re-imported from local disk**, as new documents:
89
98
 
90
99
  ```bash
91
100
  cd /path/to/your/repo
92
- hindsight-coding-agents install claude-code --import-conversations
101
+ hindsight-coding-agents install claude-code --import-conversations # or: install codex --import-conversations
93
102
  ```
94
103
 
104
+ This re-extracts the transcripts the agent already wrote, so it costs tokens roughly in proportion
105
+ to the history imported, and it is safe to re-run (ingestion dedups by document id).
106
+
107
+ Local transcripts are the source rather than the old bank, because the old bank cannot be split by
108
+ repo. Its default was a **single static bank** — `dynamicBankId` defaults to false, so everything
109
+ landed in one bank named `claude_code` — and its documents record only `retained_at`,
110
+ `message_count` and `session_id`, nothing identifying the project. Working out which documents
111
+ belong to which repo means joining `session_id` back to the `cwd` in the local transcript, so the
112
+ transcripts are needed either way; going through them directly is simply the shorter path.
113
+
95
114
  **How sessions are matched.** A conversation is imported only when the session itself records the
96
115
  directory it ran in — never inferred from a file or folder name. Claude Code writes that directory
97
116
  on its entries and Codex in its `session_meta` header, so both can be attributed exactly, including
@@ -102,89 +121,71 @@ conversation into your bank. Sessions that record nothing are skipped and the co
102
121
  The other harnesses (opencode, Kilo, Cursor, Cline, Copilot, Devin) keep history in internal SQLite
103
122
  databases with unversioned schemas and are skipped with a reason.
104
123
 
105
- The import is scoped to the **current repo**, safe to re-run (ingestion dedups by document id), and
106
- runs extraction — so it costs tokens roughly in proportion to the history imported.
107
-
108
- Prefer to keep the old bank instead? Point this package at it — no data moves:
124
+ **Nothing else is translated.** The old plugin's behavioural settings — 12 `recall*`, 7 `retain*`,
125
+ `bankMission`/`retainMission`, `dynamicBankGranularity` — describe a pipeline this package replaced,
126
+ and reinterpreting them would be guesswork. Bank naming changes too: this package uses one bank per
127
+ **repo** (`coding-agent::{gitProject}`) shared by every agent. To keep the old naming instead:
109
128
 
110
129
  ```jsonc
111
130
  { "bankIdTemplate": "{harness}::{gitProject}" } // reproduces the old per-agent naming
112
131
  ```
113
132
 
114
- ## How it works
115
-
116
- **Ingestion — automatic, no command to run**
117
-
118
- - On a **cold repo**, the first session kicks off a background seed: recent commit **messages** as one cheap document, plus a short headless **codebase survey** to map the structure.
119
- - On **every** session, a background "deepen" pass ingests conversations not yet stored and the next batch of recent commits **with full diffs, newest first** — precision arrives across sessions instead of one big ingest.
120
- - Repeated or concurrent runs are a no-op (per-bank lock + document-id dedup).
121
- - Ask the agent `hindsight_sync_status` to see where ingestion stands — `synced: true` means everything is queryable.
122
-
123
- **In the session — what the agent actually receives**
124
-
125
- - On the first prompt, a **reflect** call returns the past decision behind the task, with its exact rule and values. It's cached and re-injected each turn.
126
- - Every turn, the repo's **knowledge pages** are matched locally against the prompt (lexical index — no server call, no LLM, ~ms) and the best sections are injected with provenance. Below a relevance floor, nothing is injected.
127
- - The agent also gets the page roster and the `hindsight_*` tools, so it can read a page, search raw memory, or record a new initiative itself.
128
- - Injected memory carries a visible-attribution directive, so the agent shows a `🧠 Using Hindsight Memories` header when memory shaped its answer.
129
-
130
- **Write-back — sessions become memory**
131
-
132
- - The live session is stored as a transcript: user/assistant turns plus a compact `action` line per tool call (name + target, no arguments or output) — decisions without the mechanical noise.
133
- - Hook harnesses write on `Stop`. Plugin harnesses (opencode, Kilo) write on a turn cadence **and** when the session goes idle — the idle pass is what captures the agent's own reply, which the per-turn pass runs too early to see.
133
+ ## Where memory lives
134
134
 
135
- **Guarantees**
135
+ Three modes, chosen once when you install (`install` asks on a terminal; pass `--server` to script it):
136
136
 
137
- - A failed reflect or page fetch degrades to a no-memory turn; it never breaks the agent.
138
- - It never fails _silently_ either: every outcome is written to a diagnostics file, so a memory-less session can't pass for a memory session.
139
- - When two memories conflict on the same rule, the later decision wins and the superseded one is reported as no longer in effect.
140
- - Against a Hindsight server that predates knowledge pages, page features are skipped (recorded as `knowledge_pages_unavailable`) and everything else continues.
137
+ | mode | what runs | needs |
138
+ | ------------- | ----------------------------------------- | ---------------------------------------- |
139
+ | `cloud` | Hindsight Cloud (default) | an API token |
140
+ | `self-hosted` | a Hindsight server you already run | its URL |
141
+ | `daemon` | a local `hindsight-embed` on this machine | `uv` on PATH + an LLM key for extraction |
141
142
 
142
- ## Harnesses
143
-
144
- Every harness runs the same surface (seed → session reflect → per-turn page sections → knowledge
145
- tools → write-back); they differ only in how that surface is delivered.
146
-
147
- | harness | kind | lifecycle wiring | install |
148
- | ------------------------- | ----------------- | ---------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------- |
149
- | `opencode` | persistent plugin | one process: load-time seed, session reflect + page sections, native tools, write-back | add the package dir to `opencode.json` → `"plugin": [...]` |
150
- | `kilo` | persistent plugin | identical to `opencode` — Kilo CLI is an opencode fork, so it loads the same runtime (no hooks system) | `hindsight-coding-agents install kilo` → `kilo.json[c]` `"plugin"` |
151
- | `claude-code` | per-prompt hooks | `SessionStart` (seed) + `UserPromptSubmit` (reflect + pages) + `Stop` (write-back) + MCP | `hindsight-coding-agents install claude-code` |
152
- | `codex` | per-prompt hooks | same three hooks in `~/.codex/hooks.json` (+ `codex_hooks = true`, CLI ≥ 0.116) | `hindsight-coding-agents install codex` |
153
- | `antigravity-cli` (`agy`) | lifecycle hooks | Antigravity CLI lifecycle hooks (`PreInvocation` + `Stop`) + MCP, plus a native colored `Hindsight · <bank>` status-line indicator | `hindsight-coding-agents install agy` |
154
- | `cursor-cli` | lifecycle hooks | `sessionStart` (seed + pages) + `beforeSubmitPrompt` (reflect) + `stop` (write-back) | hooks in Cursor `hooks.json` |
155
- | `copilot-cli` | lifecycle hooks | `sessionStart` (seed + pages) + `userPromptTransformed` (reflect) + `agentStop` (write-back) + MCP | `~/.copilot/hooks/hindsight-coding-agents.json` + `mcp-config.json` |
156
- | `grok-build` | lifecycle hooks | `SessionStart` (seed) + `Stop` (write-back) + MCP | native `~/.grok/config.toml` — no Claude Code dependency |
157
- | `cline-cli` | persistent plugin | native `beforeModel` (seed/reflect/pages) + `afterRun` (write-back) + MCP | `cline plugin install` (run by the installer) |
158
-
159
- The hook-based harnesses share one runtime (`src/core/hook.ts`) plus their SessionStart/Stop
160
- entrypoints. Persistent-plugin hosts (opencode/Kilo/Cline) delegate to the same `RuntimeCore`,
161
- which in turn calls those shared session-start, prompt, and retain operations; only their host API
162
- adapters differ. Opencode and Kilo can register the knowledge tools natively; Cline uses the shared
163
- MCP server. All support opt-in **incremental git-sync** (retain commits new since the seed on load).
164
-
165
- Antigravity renders the Hindsight indicator with its documented custom status-line command. It is
166
- local and never calls the Hindsight API while the TUI redraws. If you already configured an
167
- Antigravity custom status line, the installer leaves it untouched rather than replacing it.
168
-
169
- ### Grok Build limitation
170
-
171
- Grok Build executes `UserPromptSubmit` hooks but ignores their stdout. Hindsight can therefore not
172
- inject a reflect result, memory block, or banner into Grok's model-visible conversation. Grok still
173
- gets native bank setup and transcript retention plus Hindsight MCP tools and the companion skill;
174
- ask it to call `hindsight_reflect` or `hindsight_search_knowledge_pages` when needed. Automatic
175
- injection requires a future Grok prompt-transform API.
176
-
177
- ### Cline CLI scope
143
+ ```bash
144
+ hindsight-coding-agents install claude-code --server daemon
145
+ hindsight-coding-agents install claude-code --server self-hosted --api-url http://localhost:8888
146
+ hindsight-coding-agents install claude-code --server cloud --api-token <token>
147
+ ```
178
148
 
179
- Cline's external file hooks cannot alter a model request, so Hindsight uses Cline's native plugin
180
- API instead. Its `beforeModel` hook injects the shared reflect/page context and
181
- its `afterRun` hook upserts Cline's runtime transcript. `hindsight-coding-agents install cline-cli`
182
- runs `cline plugin install --force <package-path>` and configures MCP plus the companion skill.
183
- Cline CLI sandboxes plugin hooks with a three-second limit, so a slow first reflect finishes in the
184
- background and is injected on a subsequent model call or turn rather than aborting the session.
185
- Its write-back retains only user-visible user/assistant text; tool arguments, tool results and
186
- command output, tool-role messages, reasoning parts, and Hindsight's injected context are excluded.
187
- Cline IDE extensions are not currently supported by this CLI integration.
149
+ Re-running `install` never re-asks: a config that already names a server is left alone.
150
+
151
+ ### Local daemon mode
152
+
153
+ Nothing to sign up for and nothing to host — memory runs on your machine. The plugin starts
154
+ `hindsight-embed` on demand at `127.0.0.1:9077` and points every agent at it.
155
+
156
+ - **A server already on the port is adopted, never restarted** — so one daemon serves every agent
157
+ and every repo, and your own `hindsight-embed` is reused if you already run one.
158
+ - **Cold starts happen in the background.** The first start downloads the daemon and loads models,
159
+ which takes longer than any hook is allowed to run, so it is launched detached at session start.
160
+ A session that begins before it is ready simply has no memory for a turn or two — a daemon that
161
+ isn't up is treated as an unreachable server, exactly like a Cloud or self-hosted outage, with the
162
+ same error handling and the same diagnostics. Nothing downstream of the URL knows which mode it is.
163
+ - **It shuts down on idle**, after `daemonIdleTimeout` seconds. There is deliberately no
164
+ stop-on-exit: one daemon is shared, so ending one session must not cut memory out from under
165
+ another agent still working.
166
+ - **macOS additionally needs a current Rust toolchain.** `litellm` (a transitive dependency of the
167
+ API) publishes wheels only for Linux and Windows, so a Mac compiles it from source through
168
+ maturin and its crates pin a recent `rustc`. Install from [rustup.rs](https://rustup.rs) and keep
169
+ it updated — an out-of-date toolchain fails as surely as a missing one. Linux and Windows install
170
+ from wheels and need none of this.
171
+ - **Fact extraction runs locally**, so it needs an LLM. `HINDSIGHT_API_LLM_PROVIDER` wins if set;
172
+ otherwise the first of `OPENAI_API_KEY`, `ANTHROPIC_API_KEY`, `GEMINI_API_KEY`, `GROQ_API_KEY`;
173
+ otherwise the Claude Code CLI, which needs no key. `install` tells you which it found.
174
+
175
+ Daemon settings keep the names the old per-agent Claude Code plugin used, so an existing
176
+ environment carries over unchanged:
177
+
178
+ | field | env | default | meaning |
179
+ | ------------------- | ------------------------------- | -------------- | ------------------------------------------ |
180
+ | `serverMode` | `HINDSIGHT_SERVER_MODE` | `cloud` | `cloud` \| `self-hosted` \| `daemon` |
181
+ | `apiPort` | `HINDSIGHT_API_PORT` | `9077` | port the local daemon listens on |
182
+ | `daemonIdleTimeout` | `HINDSIGHT_DAEMON_IDLE_TIMEOUT` | `300` | seconds of inactivity before it exits |
183
+ | `daemonProfile` | `HINDSIGHT_DAEMON_PROFILE` | `coding-agent` | which local database it uses |
184
+ | `embedVersion` | `HINDSIGHT_EMBED_VERSION` | `latest` | which `hindsight-embed` release to run |
185
+ | `embedPackagePath` | `HINDSIGHT_EMBED_PACKAGE_PATH` | — | run a local checkout instead (development) |
186
+
187
+ Any `HINDSIGHT_API_*` variable you export is forwarded to the daemon, so server-side settings need
188
+ no equivalent here.
188
189
 
189
190
  ## Configuration
190
191
 
@@ -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",
@@ -1011,6 +1035,11 @@ async function runHook(spec, makeClient = (o) => new HindsightClient(o)) {
1011
1035
  // src/core/retain-hook.ts
1012
1036
  import { readFileSync as readFileSync5 } from "fs";
1013
1037
 
1038
+ // src/core/daemon.ts
1039
+ import { execFileSync as execFileSync2, spawn as realSpawn2 } from "child_process";
1040
+ import { dirname as dirname5, join as join6 } from "path";
1041
+ import { fileURLToPath as fileURLToPath2 } from "url";
1042
+
1014
1043
  // src/core/transcript.ts
1015
1044
  import { readFileSync as readFileSync4 } from "fs";
1016
1045
 
@@ -1053,24 +1082,24 @@ function actionLine(tool, input) {
1053
1082
  import { readFileSync as readFileSync7 } from "fs";
1054
1083
 
1055
1084
  // src/core/git.ts
1056
- import { execFileSync as execFileSync2 } from "child_process";
1085
+ import { execFileSync as execFileSync3 } from "child_process";
1057
1086
  import { resolve } from "path";
1058
1087
 
1059
1088
  // src/core/status.ts
1060
- import { execFileSync as execFileSync3 } from "child_process";
1089
+ import { execFileSync as execFileSync4 } from "child_process";
1061
1090
 
1062
1091
  // src/core/survey.ts
1063
- import { spawn as realSpawn2 } from "child_process";
1092
+ import { spawn as realSpawn3 } from "child_process";
1064
1093
  import { accessSync, constants, existsSync as existsSync2 } from "fs";
1065
1094
  import { homedir as homedir3 } from "os";
1066
- import { delimiter, dirname as dirname5, join as join6 } from "path";
1067
- import { fileURLToPath as fileURLToPath2 } from "url";
1095
+ import { delimiter, dirname as dirname6, join as join7 } from "path";
1096
+ import { fileURLToPath as fileURLToPath3 } from "url";
1068
1097
 
1069
1098
  // src/core/skill-sync.ts
1070
1099
  import { cpSync, existsSync as existsSync3, readFileSync as readFileSync6 } from "fs";
1071
1100
  import { homedir as homedir4 } from "os";
1072
- import { dirname as dirname6, join as join7 } from "path";
1073
- import { fileURLToPath as fileURLToPath3 } from "url";
1101
+ import { dirname as dirname7, join as join8 } from "path";
1102
+ import { fileURLToPath as fileURLToPath4 } from "url";
1074
1103
 
1075
1104
  // src/core/transcript-codex.ts
1076
1105
  import { readFileSync as readFileSync8 } from "fs";
@@ -1232,17 +1261,17 @@ function readCopilotTranscript(path) {
1232
1261
  // src/core/transcript-grok.ts
1233
1262
  import { existsSync as existsSync4, readFileSync as readFileSync12, readdirSync } from "fs";
1234
1263
  import { homedir as homedir5 } from "os";
1235
- import { join as join8 } from "path";
1264
+ import { join as join9 } from "path";
1236
1265
  var CHAT_HISTORY = "chat_history.jsonl";
1237
- function grokTranscriptPath(cwd, sessionId, grokHome = process.env.GROK_HOME || join8(homedir5(), ".grok")) {
1238
- const sessionsDir = join8(grokHome, "sessions");
1239
- const direct = join8(sessionsDir, encodeURIComponent(cwd), sessionId, CHAT_HISTORY);
1266
+ function grokTranscriptPath(cwd, sessionId, grokHome = process.env.GROK_HOME || join9(homedir5(), ".grok")) {
1267
+ const sessionsDir = join9(grokHome, "sessions");
1268
+ const direct = join9(sessionsDir, encodeURIComponent(cwd), sessionId, CHAT_HISTORY);
1240
1269
  if (existsSync4(direct)) return direct;
1241
1270
  try {
1242
1271
  for (const candidate of readdirSync(sessionsDir)) {
1243
- const directory = join8(sessionsDir, candidate);
1244
- if (readFileSync12(join8(directory, ".cwd"), "utf8").trim() === cwd) {
1245
- return join8(directory, sessionId, CHAT_HISTORY);
1272
+ const directory = join9(sessionsDir, candidate);
1273
+ if (readFileSync12(join9(directory, ".cwd"), "utf8").trim() === cwd) {
1274
+ return join9(directory, sessionId, CHAT_HISTORY);
1246
1275
  }
1247
1276
  }
1248
1277
  } catch {
@@ -1286,9 +1315,9 @@ function readGrokTranscript(path) {
1286
1315
  import { existsSync as existsSync5 } from "fs";
1287
1316
  import { createRequire } from "module";
1288
1317
  import { homedir as homedir6 } from "os";
1289
- import { join as join9 } from "path";
1318
+ import { join as join10 } from "path";
1290
1319
  function devinSessionDb(home = homedir6()) {
1291
- return join9(home, ".local", "share", "devin", "cli", "sessions.db");
1320
+ return join10(home, ".local", "share", "devin", "cli", "sessions.db");
1292
1321
  }
1293
1322
  function parseDevinMessages(nodes) {
1294
1323
  const messages = /* @__PURE__ */ new Map();
@@ -13,10 +13,24 @@ var DEFAULT_SEED_LIMIT = 300;
13
13
 
14
14
  // src/core/config.ts
15
15
  var CONFIG_PATH = process.env.HINDSIGHT_CONFIG || join2(homedir(), ".hindsight", "coding-agent.json");
16
+ var DEFAULT_DAEMON_PORT = 9077;
17
+ var DEFAULT_DAEMON_IDLE_TIMEOUT = 300;
18
+ var DEFAULT_DAEMON_PROFILE = "coding-agent";
16
19
  function resolveConfig(raw = {}) {
20
+ const serverMode = ["cloud", "self-hosted", "daemon"].includes(raw.serverMode) ? raw.serverMode : "cloud";
21
+ const apiPort = raw.apiPort || DEFAULT_DAEMON_PORT;
17
22
  return {
18
- apiUrl: raw.apiUrl ?? "https://api.hindsight.vectorize.io",
23
+ serverMode,
24
+ // Daemon mode resolves the URL HERE rather than at each call site: every entry point already
25
+ // builds its client from cfg.apiUrl, so collapsing the mode into that one field means the
26
+ // daemon needs no plumbing through eight separate constructors.
27
+ apiUrl: serverMode === "daemon" ? `http://127.0.0.1:${apiPort}` : raw.apiUrl ?? "https://api.hindsight.vectorize.io",
19
28
  apiToken: raw.apiToken || void 0,
29
+ apiPort,
30
+ daemonIdleTimeout: raw.daemonIdleTimeout ?? DEFAULT_DAEMON_IDLE_TIMEOUT,
31
+ daemonProfile: raw.daemonProfile || DEFAULT_DAEMON_PROFILE,
32
+ embedVersion: raw.embedVersion || void 0,
33
+ embedPackagePath: raw.embedPackagePath || void 0,
20
34
  bankId: raw.bankId,
21
35
  dynamicBankId: raw.dynamicBankId,
22
36
  bankIdTemplate: raw.bankIdTemplate,
@@ -62,8 +76,16 @@ function applyLayer(raw, layer, harness) {
62
76
  return out;
63
77
  }
64
78
  var ENV_KEYS = {
79
+ serverMode: "HINDSIGHT_SERVER_MODE",
65
80
  apiUrl: "HINDSIGHT_API_URL",
66
81
  apiToken: "HINDSIGHT_API_TOKEN",
82
+ // These four keep the names the old per-agent Claude Code plugin used, so a user migrating from
83
+ // it can carry their existing environment over unchanged.
84
+ apiPort: "HINDSIGHT_API_PORT",
85
+ daemonIdleTimeout: "HINDSIGHT_DAEMON_IDLE_TIMEOUT",
86
+ embedVersion: "HINDSIGHT_EMBED_VERSION",
87
+ embedPackagePath: "HINDSIGHT_EMBED_PACKAGE_PATH",
88
+ daemonProfile: "HINDSIGHT_DAEMON_PROFILE",
67
89
  bankId: "HINDSIGHT_BANK_ID",
68
90
  dynamicBankId: "HINDSIGHT_DYNAMIC_BANK_ID",
69
91
  bankIdTemplate: "HINDSIGHT_BANK_ID_TEMPLATE",
@@ -94,6 +116,8 @@ var ENV_BOOLEANS = /* @__PURE__ */ new Set([
94
116
  "codebaseSurvey"
95
117
  ]);
96
118
  var ENV_NUMBERS = /* @__PURE__ */ new Set([
119
+ "apiPort",
120
+ "daemonIdleTimeout",
97
121
  "retainEveryTurns",
98
122
  "reflectTimeoutMs",
99
123
  "pageRefreshEveryTurns",
@@ -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();