@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.
package/README.md CHANGED
@@ -12,103 +12,7 @@ tie-break policy. Those decisions live in git history and past conversations. Th
12
12
  in front of the agent at the moment it starts working, and keeps a curated set of **knowledge pages**
13
13
  (architecture, conventions, in-flight initiatives) that future sessions start from.
14
14
 
15
- ## How it works
16
-
17
- 1. **Seed a cold repo (automatic, once).** The first time an agent opens a repo whose bank is empty,
18
- the entry point deterministically kicks off a background **seed**: it aggregates the last N commit
19
- **messages** into a single cheap document (`gitlog` strategy) and spawns a short headless
20
- **codebase survey** — run under the current agent's own CLI (claude/codex/antigravity/opencode),
21
- read-only sandboxed — to map the structure. Both feed the knowledge pages.
22
- 1. **Deepen progressively (automatic, every session).** Every session start also fires the
23
- idempotent background **deepen engine**: it ingests any conversations not yet in the bank and the
24
- next batch of recent commits **individually with their full diffs, newest first** — so full
25
- decision-level precision arrives across sessions without a big-bang ingest. A per-bank lock and
26
- document-id dedup make concurrent or repeated runs a no-op. Ask the agent
27
- `hindsight_sync_status` to see where ingestion stands (`synced: true` = seeded memory fully
28
- queryable).
29
- 1. **Reflect once per session.** On the session's first prompt, the entry point runs Hindsight
30
- `reflect` — an agentic synthesis over the bank that returns the past decision explaining the task
31
- at hand, with its exact rule and literal values. The answer is cached for the session and
32
- re-injected on every turn, wrapped in a visible-attribution directive so the agent surfaces a
33
- `🧠 Using Hindsight Memories` header when memory informs its answer.
34
- 1. **Knowledge-page sections every turn.** The repo's knowledge pages are fetched on a cadence and
35
- matched **locally** against each prompt (a lexical section index — no server round-trip, no LLM
36
- call, ~ms): the top-scoring page sections are injected with provenance and a pointer to the full
37
- page. Fast like recall, organized like reflect; below a relevance floor nothing is injected.
38
- 1. **Knowledge pages + tools.** At session start the agent is given the repo's page roster plus a
39
- guide to the `hindsight_*` tools; it lists/reads pages to ground itself, searches raw memory for
40
- specifics (`hindsight_search_memory` is where recall lives now), and calls
41
- `hindsight_capture_initiative` right after a plan is approved to record a new feature as a tracked
42
- page. On opencode these tools are registered natively; the hook harnesses get them through the
43
- bundled **MCP server**.
44
- 1. **Write back.** The live session is upserted into the bank as a JSON transcript — user/assistant
45
- turns plus a compact `action` turn per tool call (tool name + primary target, e.g.
46
- `Edit boltons/strutils.py`; no arguments or outputs) — so sessions compound into memory without
47
- burying decisions in mechanical noise. On Stop for the hook harnesses; for the plugin harnesses
48
- (opencode, Kilo) on the turn cadence **and** again when the session goes idle. The idle pass is
49
- what captures the agent's reply: the per-turn hook fires while the host is building a request, so
50
- the transcript it sees always stops short of the answer that request produces — without the idle
51
- pass, write-back lagged a turn and a session's final exchange was never stored at all.
52
- 1. **Never break the agent — never fail silently.** A failed reflect or page fetch degrades to
53
- no-memory, but every outcome (`reflect_ok` / `reflect_empty` / `reflect_failed`, `pages_ok` /
54
- `pages_failed`, with duration and error) is appended to a diagnostics file, so a memory-less
55
- session can't masquerade as a memory session.
56
-
57
- If the configured Hindsight server predates knowledge pages, the client detects that capability at
58
- session start, skips page seeding and page lookups, and records `knowledge_pages_unavailable`.
59
- Legacy bank configuration, git/session ingestion, reflection, and retention continue normally.
60
-
61
- When memories **conflict** on the same rule, reflect prefers the latest/superseding decision — a rule
62
- amended in a later conversation wins over the original.
63
-
64
- ## Harnesses
65
-
66
- Every harness runs the same surface (seed → session reflect → per-turn page sections → knowledge
67
- tools → write-back); they differ only in how that surface is delivered.
68
-
69
- | harness | kind | lifecycle wiring | install |
70
- | ------------------------- | ----------------- | ---------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------- |
71
- | `opencode` | persistent plugin | one process: load-time seed, session reflect + page sections, native tools, write-back | add the package dir to `opencode.json` → `"plugin": [...]` |
72
- | `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"` |
73
- | `claude-code` | per-prompt hooks | `SessionStart` (seed) + `UserPromptSubmit` (reflect + pages) + `Stop` (write-back) + MCP | `hindsight-coding-agents install claude-code` |
74
- | `codex` | per-prompt hooks | same three hooks in `~/.codex/hooks.json` (+ `codex_hooks = true`, CLI ≥ 0.116) | `hindsight-coding-agents install codex` |
75
- | `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` |
76
- | `cursor-cli` | lifecycle hooks | `sessionStart` (seed + pages) + `beforeSubmitPrompt` (reflect) + `stop` (write-back) | hooks in Cursor `hooks.json` |
77
- | `copilot-cli` | lifecycle hooks | `sessionStart` (seed + pages) + `userPromptTransformed` (reflect) + `agentStop` (write-back) + MCP | `~/.copilot/hooks/hindsight-coding-agents.json` + `mcp-config.json` |
78
- | `grok-build` | lifecycle hooks | `SessionStart` (seed) + `Stop` (write-back) + MCP | native `~/.grok/config.toml` — no Claude Code dependency |
79
- | `cline-cli` | persistent plugin | native `beforeModel` (seed/reflect/pages) + `afterRun` (write-back) + MCP | `cline plugin install` (run by the installer) |
80
-
81
- The hook-based harnesses share one runtime (`src/core/hook.ts`) plus their SessionStart/Stop
82
- entrypoints. Persistent-plugin hosts (opencode/Kilo/Cline) delegate to the same `RuntimeCore`,
83
- which in turn calls those shared session-start, prompt, and retain operations; only their host API
84
- adapters differ. Opencode and Kilo can register the knowledge tools natively; Cline uses the shared
85
- MCP server. All support opt-in **incremental git-sync** (retain commits new since the seed on load).
86
-
87
- Antigravity renders the Hindsight indicator with its documented custom status-line command. It is
88
- local and never calls the Hindsight API while the TUI redraws. If you already configured an
89
- Antigravity custom status line, the installer leaves it untouched rather than replacing it.
90
-
91
- ### Grok Build limitation
92
-
93
- Grok Build executes `UserPromptSubmit` hooks but ignores their stdout. Hindsight can therefore not
94
- inject a reflect result, memory block, or banner into Grok's model-visible conversation. Grok still
95
- gets native bank setup and transcript retention plus Hindsight MCP tools and the companion skill;
96
- ask it to call `hindsight_reflect` or `hindsight_search_knowledge_pages` when needed. Automatic
97
- injection requires a future Grok prompt-transform API.
98
-
99
- ### Cline CLI scope
100
-
101
- Cline's external file hooks cannot alter a model request, so Hindsight uses Cline's native plugin
102
- API instead. Its `beforeModel` hook injects the shared reflect/page context and
103
- its `afterRun` hook upserts Cline's runtime transcript. `hindsight-coding-agents install cline-cli`
104
- runs `cline plugin install --force <package-path>` and configures MCP plus the companion skill.
105
- Cline CLI sandboxes plugin hooks with a three-second limit, so a slow first reflect finishes in the
106
- background and is injected on a subsequent model call or turn rather than aborting the session.
107
- Its write-back retains only user-visible user/assistant text; tool arguments, tool results and
108
- command output, tool-role messages, reasoning parts, and Hindsight's injected context are excluded.
109
- Cline IDE extensions are not currently supported by this CLI integration.
110
-
111
- ### Install — one command, every agent
15
+ ## Install
112
16
 
113
17
  ```bash
114
18
  npm install -g @vectorize-io/hindsight-coding-agents
@@ -121,7 +25,11 @@ hindsight-coding-agents uninstall all # removes exactly what install adde
121
25
  `hindsight-coding-agents install` changes nothing and prints the choice, so wiring every agent on
122
26
  the machine is never something that happens by accident.
123
27
 
124
- #### Per agent
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
+
32
+ ### Per agent
125
33
 
126
34
  Same command, only the harness name changes. Run after installing the package globally.
127
35
 
@@ -135,11 +43,16 @@ Same command, only the harness name changes. Run after installing the package gl
135
43
  | GitHub Copilot CLI | `hindsight-coding-agents install copilot-cli` | `~/.copilot/hooks/` + `mcp-config.json` + skill |
136
44
  | Grok Build | `hindsight-coding-agents install grok-build` | native hooks + MCP in `~/.grok/config.toml` + skill |
137
45
  | Antigravity CLI | `hindsight-coding-agents install agy` | lifecycle hooks + MCP + the `Hindsight · <bank>` status line |
138
- | Devin CLI | `hindsight-coding-agents install devin-cli` | hooks in `~/.config/devin/config.json` + MCP |
46
+ | Devin CLI | `hindsight-coding-agents install devin-cli` | hooks in `~/.config/devin/config.json` + MCP (needs Node 22.5+, see below) |
139
47
  | Cline CLI | `hindsight-coding-agents install cline-cli` | native plugin via `cline plugin install` + MCP + skill |
140
48
 
141
49
  Uninstall the same way: `hindsight-coding-agents uninstall claude-code` (or `uninstall all`).
142
50
 
51
+ **Devin CLI needs Node 22.5 or newer.** Its hooks pass only a session id — the conversation itself
52
+ lives in `~/.local/share/devin/cli/sessions.db` — so reading it depends on Node's built-in
53
+ `node:sqlite`. Installing `devin-cli` checks for this first and refuses (with the reason) rather
54
+ than wiring hooks that could never retain anything. Every other agent works on any supported Node.
55
+
143
56
  Install globally (not `npx`): the wiring points at this package's files, so it must live at a
144
57
  stable path — the installer refuses to run from an npx cache. **Updating** is just
145
58
  `npm update -g @vectorize-io/hindsight-coding-agents`: the wired paths stay valid, every new session runs the
@@ -169,14 +82,124 @@ Adding an agent: hook-based → write a `HookSpec` entry point (see `src/cursor-
169
82
  a `hookAdapter` in `src/harness/registry.ts`; persistent-plugin → implement `HarnessAdapter`
170
83
  (`src/core/types.ts`) fully (see `src/harness/opencode.ts`).
171
84
 
85
+ ## Migrating from the per-agent plugins
86
+
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.
88
+
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.)
96
+
97
+ **Your conversations are re-imported from local disk**, as new documents:
98
+
99
+ ```bash
100
+ cd /path/to/your/repo
101
+ hindsight-coding-agents install claude-code --import-conversations # or: install codex --import-conversations
102
+ ```
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
+
114
+ **How sessions are matched.** A conversation is imported only when the session itself records the
115
+ directory it ran in — never inferred from a file or folder name. Claude Code writes that directory
116
+ on its entries and Codex in its `session_meta` header, so both can be attributed exactly, including
117
+ sessions started in a subdirectory of the repo. Guessing was tempting (Claude names its history
118
+ folders after the project path) but unsafe: `/` and `.` both encode to `-`, so `repo-sub` is either
119
+ the subdirectory `repo/sub` or an unrelated sibling repo — and a wrong guess files someone else's
120
+ conversation into your bank. Sessions that record nothing are skipped and the count is reported.
121
+ The other harnesses (opencode, Kilo, Cursor, Cline, Copilot, Devin) keep history in internal SQLite
122
+ databases with unversioned schemas and are skipped with a reason.
123
+
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:
128
+
129
+ ```jsonc
130
+ { "bankIdTemplate": "{harness}::{gitProject}" } // reproduces the old per-agent naming
131
+ ```
132
+
133
+ ## Where memory lives
134
+
135
+ Three modes, chosen once when you install (`install` asks on a terminal; pass `--server` to script it):
136
+
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 |
142
+
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
+ ```
148
+
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.
189
+
172
190
  ## Configuration
173
191
 
174
- All configuration is **ONE JSON file, no environment variables** (exception: `HINDSIGHT_DIAG_FILE`
175
- for the diagnostics path): `~/.hindsight/coding-agent.json`. Layering, later wins per field:
192
+ Configuration is **one JSON file**: `~/.hindsight/coding-agent.json`. Layering, later wins per field:
176
193
 
177
194
  1. built-in defaults
178
- 2. the file's top level
179
- 3. its `harnesses.<name>` section — per-agent override
195
+ 2. environment variables — `HINDSIGHT_API_URL`, `HINDSIGHT_API_TOKEN`, and one per scalar setting
196
+ (`HINDSIGHT_<FIELD_IN_CAPS>`), for containers and CI that inject config rather than write a file
197
+ 3. the file's top level
198
+ 4. its `harnesses.<name>` section — per-agent override
199
+
200
+ Environment variables are a **fallback**: the file wins wherever it sets a value, so adding env to
201
+ an existing setup changes nothing. The map-valued settings (`mapPathToBank`, `harnesses`, `banks`)
202
+ are file-only — nested branching doesn't survive flattening into one variable.
180
203
 
181
204
  There is deliberately no repo-carried config file — per-repo bank routing is `mapPathToBank`,
182
205
  per-agent differences are `harnesses.<name>`.
@@ -336,22 +359,3 @@ as a JSON line to `/tmp/hindsight-plugin.log` (override with `HINDSIGHT_DIAG_FIL
336
359
  `reflect_failed` / `pages_failed` record the error; if you're comparing memory-on vs memory-off,
337
360
  check this file — a run whose reflects failed is a no-memory run. Seed starts are logged as
338
361
  `seed_started`.
339
-
340
- ## Layout
341
-
342
- ```
343
- src/
344
- core/ # harness-agnostic: config (layered), bank resolution, hindsight client, missions,
345
- # git + chat ingest, git-sync, seed + survey, pages-index (local section matching),
346
- # knowledge-injection, knowledge-tools, session-start, transcript readers,
347
- # hook runtime, RuntimeCore
348
- harness/ # per-agent adapters + registry (opencode persistent; claude/codex/antigravity/cursor/copilot as hooks)
349
- index.ts # opencode plugin entrypoint
350
- claude-hook.ts / claude-sessionstart-hook.ts / claude-stop-hook.ts # Claude Code entrypoints
351
- codex-hook.ts / codex-sessionstart-hook.ts / codex-stop-hook.ts # Codex CLI entrypoints
352
- antigravity-hook.ts / antigravity-stop-hook.ts # Antigravity CLI entrypoints
353
- cursor-hook.ts # Cursor CLI hook entrypoint (bin: hindsight-cursor-hook)
354
- copilot-*.ts # GitHub Copilot CLI SessionStart/prompt/agentStop entrypoints
355
- mcp-server.ts # hindsight_* knowledge/recall tools for the hook harnesses (MCP)
356
- backfill.ts # backfill CLI (bin: hindsight-coding-backfill)
357
- ```
@@ -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 {
@@ -1283,10 +1312,13 @@ function readGrokTranscript(path) {
1283
1312
  }
1284
1313
 
1285
1314
  // src/core/transcript-devin.ts
1286
- import { execFileSync as execFileSync4 } from "child_process";
1315
+ import { existsSync as existsSync5 } from "fs";
1316
+ import { createRequire } from "module";
1287
1317
  import { homedir as homedir6 } from "os";
1288
- import { join as join9 } from "path";
1289
- var sessionDb = join9(homedir6(), ".local", "share", "devin", "cli", "sessions.db");
1318
+ import { join as join10 } from "path";
1319
+ function devinSessionDb(home = homedir6()) {
1320
+ return join10(home, ".local", "share", "devin", "cli", "sessions.db");
1321
+ }
1290
1322
  function parseDevinMessages(nodes) {
1291
1323
  const messages = /* @__PURE__ */ new Map();
1292
1324
  for (const node of nodes) {
@@ -1307,23 +1339,41 @@ function parseDevinMessages(nodes) {
1307
1339
  }
1308
1340
  return [...messages.values()].sort((a, b) => a.index - b.index).map(({ role, content }) => ({ role, content }));
1309
1341
  }
1310
- function readDevinTranscript(sessionId) {
1311
- if (!sessionId) return [];
1342
+ var requireBuiltin = createRequire(import.meta.url);
1343
+ function loadSqlite() {
1312
1344
  try {
1313
- const quotedId = sessionId.replace(/'/g, "''");
1314
- const raw = execFileSync4(
1315
- "sqlite3",
1316
- [
1317
- "-json",
1318
- sessionDb,
1319
- `SELECT node_id, chat_message FROM message_nodes WHERE session_id = '${quotedId}' ORDER BY node_id`
1320
- ],
1321
- { encoding: "utf8", stdio: ["ignore", "pipe", "ignore"], timeout: 2e3 }
1322
- );
1323
- return parseDevinMessages(JSON.parse(raw));
1345
+ return requireBuiltin("node:sqlite").DatabaseSync;
1324
1346
  } catch {
1347
+ return void 0;
1348
+ }
1349
+ }
1350
+ function readDevinTranscript(sessionId, dbPath = devinSessionDb()) {
1351
+ if (!sessionId) return [];
1352
+ const Database = loadSqlite();
1353
+ if (!Database) {
1354
+ diag("devin-cli", "sqlite_unavailable", { node: process.version, dbPath });
1355
+ return [];
1356
+ }
1357
+ if (!existsSync5(dbPath)) {
1358
+ diag("devin-cli", "session_db_missing", { dbPath });
1325
1359
  return [];
1326
1360
  }
1361
+ let db;
1362
+ try {
1363
+ db = new Database(dbPath, { readOnly: true });
1364
+ const rows = db.prepare(
1365
+ "SELECT node_id, chat_message FROM message_nodes WHERE session_id = ? ORDER BY node_id"
1366
+ ).all(sessionId);
1367
+ return parseDevinMessages(rows);
1368
+ } catch (error) {
1369
+ diag("devin-cli", "session_db_read_failed", { dbPath, error: String(error) });
1370
+ return [];
1371
+ } finally {
1372
+ try {
1373
+ db?.close();
1374
+ } catch {
1375
+ }
1376
+ }
1327
1377
  }
1328
1378
 
1329
1379
  // src/harness/hook-lifecycle.ts
@@ -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",