@llmnesia/local-agent-host 0.2.0 → 0.3.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 +7 -7
- package/doctor.mjs +2 -0
- package/install.mjs +17 -4
- package/llmnesia-claude-host.mjs +319 -23
- package/package.json +3 -2
package/README.md
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
# LLMnesia local agent host
|
|
2
2
|
|
|
3
|
-
A tiny local helper that lets the LLMnesia browser extension (1) index your local coding-agent sessions automatically
|
|
3
|
+
A tiny local helper that lets the LLMnesia browser extension (1) index your local coding-agent sessions automatically: **Claude Code**, **Codex**, and **ZCode**, with no folder picking and no hidden-folder navigation, and (2) sync your LLMnesia conversation corpus for the [MCP companion](https://www.npmjs.com/package/@llmnesia/mcp) without the File System Access picker.
|
|
4
4
|
|
|
5
|
-
It reads `.jsonl` session files under `~/.claude/projects` and `~/.codex/sessions
|
|
5
|
+
It reads `.jsonl` session files under `~/.claude/projects` and `~/.codex/sessions`, and ZCode's session database at `~/.zcode/cli/db/db.sqlite` (opened read-only). It writes only inside the corpus root named in its own config (`~/.llmnesia/config.json`): there is no protocol field that lets a caller choose a different write location. It makes no network calls.
|
|
6
6
|
|
|
7
7
|
> Previously published as `@llmnesia/claude-code-host`. That name still works and installs this same helper; see [the compatibility package](https://www.npmjs.com/package/@llmnesia/claude-code-host).
|
|
8
8
|
|
|
@@ -14,9 +14,9 @@ Requires Node 18+.
|
|
|
14
14
|
npx -y @llmnesia/local-agent-host@latest [--corpus <dir>] [--codex-home <dir>]
|
|
15
15
|
```
|
|
16
16
|
|
|
17
|
-
For the **Chrome Web Store build, no arguments are needed
|
|
17
|
+
For the **Chrome Web Store build, no arguments are needed**; the installer already knows its permanent extension id.
|
|
18
18
|
|
|
19
|
-
Only pass an id if you're running a **dev / unpacked** build (its id is random per machine
|
|
19
|
+
Only pass an id if you're running a **dev / unpacked** build (its id is random per machine, so find it at `brave://extensions` or `chrome://extensions` with Developer mode on):
|
|
20
20
|
|
|
21
21
|
```sh
|
|
22
22
|
npx -y @llmnesia/local-agent-host@latest <your-dev-extension-id> [--corpus <dir>]
|
|
@@ -31,7 +31,7 @@ Then **fully quit and reopen** your browser and open LLMnesia → Settings. The
|
|
|
31
31
|
Resolved once at install time, in this order: `--codex-home <dir>`, then the
|
|
32
32
|
`CODEX_HOME` environment variable Codex itself honours, then `~/.codex`. The
|
|
33
33
|
result is written into `~/.llmnesia/config.json`, because native messaging
|
|
34
|
-
launches the host with almost no environment
|
|
34
|
+
launches the host with almost no environment, so it can't re-derive `CODEX_HOME`
|
|
35
35
|
at runtime.
|
|
36
36
|
|
|
37
37
|
Works on macOS, Linux, and Windows, with Brave, Chrome, Edge, and Chromium. `allowed_origins` is locked to the extension id(s) you pass, so only LLMnesia can talk to the host.
|
|
@@ -63,7 +63,7 @@ If the extension's Settings page says the helper isn't answering, run:
|
|
|
63
63
|
npx -y @llmnesia/local-agent-host@latest doctor
|
|
64
64
|
```
|
|
65
65
|
|
|
66
|
-
It
|
|
66
|
+
It is read-only: checks the host script, each browser's manifest, `config.json`, whether Claude Code, Codex, and ZCode sessions were found, and pings the helper directly, and prints exactly which step is missing instead of a generic failure.
|
|
67
67
|
|
|
68
68
|
## Uninstall
|
|
69
69
|
|
|
@@ -85,7 +85,7 @@ Native messaging over stdio (little-endian uint32 length prefix + UTF-8 JSON):
|
|
|
85
85
|
- `{ cmd: "list" }` → `{ type: "list", sessions: [{ sessionId, mtime, project }] }`
|
|
86
86
|
- `{ cmd: "get", sessionId }` → `{ type: "chunk", sessionId, seq, total, data }` × N, then `{ type: "sessionDone", sessionId }`
|
|
87
87
|
- `{ cmd: "corpusInfo" }` → `{ type: "corpusInfo", present: false }`, or `{ type: "corpusInfo", present: true, root }` if `~/.llmnesia/config.json` names a corpus
|
|
88
|
-
- `{ cmd: "putChunk", filename, seq, total, data }` → `{ type: "chunkAck", seq }`, one call per chunk. Once every chunk `0..total-1` for a `filename` has arrived, the host writes `<corpusRoot>/inbox/<filename>` (via a `.part-<pid>` temp file, `rename()`d into place so a concurrent drain never sees a partial file). `filename` must be a bare basename
|
|
88
|
+
- `{ cmd: "putChunk", filename, seq, total, data }` → `{ type: "chunkAck", seq }`, one call per chunk. Once every chunk `0..total-1` for a `filename` has arrived, the host writes `<corpusRoot>/inbox/<filename>` (via a `.part-<pid>` temp file, `rename()`d into place so a concurrent drain never sees a partial file). `filename` must be a bare basename; anything containing `/`, `\`, or `..` is rejected with `{ type: "error" }` and nothing is written. Transfers are bounded to 256 chunks, 512 KiB characters per chunk, 64 MiB characters across pending data, eight simultaneous filenames, and a five-minute idle lifetime. The corpus root always comes from the host's own config; it cannot be set over the protocol.
|
|
89
89
|
|
|
90
90
|
`putChunk` is how the extension's service worker pushes corpus sync deltas without ever holding a File System Access handle. Deltas are sent as plain uncompressed NDJSON text (each `data` string is written verbatim into a `.jsonl` file the companion drains directly), so there is no base64 or gzip round-trip. The corpus root is written by the installer into `~/.llmnesia/config.json`.
|
|
91
91
|
|
package/doctor.mjs
CHANGED
|
@@ -13,6 +13,7 @@ import {
|
|
|
13
13
|
CLAUDE_PROJECTS_DIR,
|
|
14
14
|
HOST_NAME,
|
|
15
15
|
STORE_EXTENSION_ID,
|
|
16
|
+
ZCODE_DB,
|
|
16
17
|
exists,
|
|
17
18
|
posixBrowsers,
|
|
18
19
|
resolveCodexHome,
|
|
@@ -212,6 +213,7 @@ export async function runDoctor({ log = console.log } = {}) {
|
|
|
212
213
|
log("Session sources:");
|
|
213
214
|
log((await exists(CLAUDE_PROJECTS_DIR)) ? ` ✓ Claude Code sessions at ${CLAUDE_PROJECTS_DIR}` : ` - No Claude Code sessions at ${CLAUDE_PROJECTS_DIR} (fine if you don't use it).`);
|
|
214
215
|
log((await exists(join(codexHome, "sessions"))) ? ` ✓ Codex sessions at ${codexHome}` : ` - No Codex sessions at ${codexHome} (fine if you don't use it).`);
|
|
216
|
+
log((await exists(ZCODE_DB)) ? ` ✓ ZCode sessions at ${ZCODE_DB}` : ` - No ZCode sessions at ${ZCODE_DB} (fine if you don't use it).`);
|
|
215
217
|
|
|
216
218
|
log("");
|
|
217
219
|
log("Pinging the helper…");
|
package/install.mjs
CHANGED
|
@@ -49,6 +49,9 @@ const home = homedir();
|
|
|
49
49
|
// any dependency on the host script it installs. Exported so doctor.mjs can
|
|
50
50
|
// report against the same path without a third copy.
|
|
51
51
|
export const CLAUDE_PROJECTS_DIR = join(home, ".claude", "projects");
|
|
52
|
+
// ZCode's single SQLite database — the third session source, with no
|
|
53
|
+
// per-session files to look for. Exported for doctor.mjs, same as above.
|
|
54
|
+
export const ZCODE_DB = join(home, ".zcode", "cli", "db", "db.sqlite");
|
|
52
55
|
// Test seam: LLMNESIA_FAKE_PLATFORM lets the suite exercise the Windows install
|
|
53
56
|
// path (registry + .bat) from a non-Windows host. Unset in normal use.
|
|
54
57
|
const osPlatform = process.env.LLMNESIA_FAKE_PLATFORM || platform();
|
|
@@ -253,6 +256,10 @@ export async function installNativeHost({ ids = [], corpus, codexHome, force = f
|
|
|
253
256
|
}
|
|
254
257
|
const allIds = [...new Set([STORE_EXTENSION_ID, ...ids])];
|
|
255
258
|
const allowedOrigins = allIds.map((id) => `chrome-extension://${id}/`);
|
|
259
|
+
// An unpacked extension cannot use the Web Store's fixed ID. Record the
|
|
260
|
+
// explicit ID so the companion can generate source links back into the
|
|
261
|
+
// correct local Viewer. The public store ID remains the default.
|
|
262
|
+
const viewerExtensionId = ids[0] ?? STORE_EXTENSION_ID;
|
|
256
263
|
|
|
257
264
|
// Validate every prerequisite before changing the machine. In particular,
|
|
258
265
|
// the old order left a stray host script behind when no browser existed and
|
|
@@ -307,7 +314,7 @@ export async function installNativeHost({ ids = [], corpus, codexHome, force = f
|
|
|
307
314
|
corpusRootChanged = false;
|
|
308
315
|
await writeFile(
|
|
309
316
|
configPath,
|
|
310
|
-
`${JSON.stringify({ ...existing, corpusRoot: existingRoot, codexHome: resolvedCodexHome }, null, 2)}\n`,
|
|
317
|
+
`${JSON.stringify({ ...existing, corpusRoot: existingRoot, codexHome: resolvedCodexHome, viewerExtensionId }, null, 2)}\n`,
|
|
311
318
|
{ encoding: "utf8", mode: 0o600 }
|
|
312
319
|
);
|
|
313
320
|
await chmod(configPath, 0o600);
|
|
@@ -318,7 +325,7 @@ export async function installNativeHost({ ids = [], corpus, codexHome, force = f
|
|
|
318
325
|
} else {
|
|
319
326
|
await writeFile(
|
|
320
327
|
configPath,
|
|
321
|
-
`${JSON.stringify({ ...(existing ?? {}), corpusRoot, codexHome: resolvedCodexHome }, null, 2)}\n`,
|
|
328
|
+
`${JSON.stringify({ ...(existing ?? {}), corpusRoot, codexHome: resolvedCodexHome, viewerExtensionId }, null, 2)}\n`,
|
|
322
329
|
{ encoding: "utf8", mode: 0o600 }
|
|
323
330
|
);
|
|
324
331
|
await chmod(configPath, 0o600);
|
|
@@ -330,9 +337,10 @@ export async function installNativeHost({ ids = [], corpus, codexHome, force = f
|
|
|
330
337
|
// Tell the user what the helper actually found, rather than a bare "Done" —
|
|
331
338
|
// a confident success message with a silently-empty Codex row (or vice versa)
|
|
332
339
|
// reads as broken to someone who doesn't know their absence is expected.
|
|
333
|
-
const [hasClaudeCode, hasCodex] = await Promise.all([
|
|
340
|
+
const [hasClaudeCode, hasCodex, hasZcode] = await Promise.all([
|
|
334
341
|
exists(CLAUDE_PROJECTS_DIR),
|
|
335
|
-
exists(join(resolvedCodexHome, "sessions"))
|
|
342
|
+
exists(join(resolvedCodexHome, "sessions")),
|
|
343
|
+
exists(ZCODE_DB)
|
|
336
344
|
]);
|
|
337
345
|
log("");
|
|
338
346
|
log(
|
|
@@ -345,6 +353,11 @@ export async function installNativeHost({ ids = [], corpus, codexHome, force = f
|
|
|
345
353
|
? `✓ Found Codex sessions at ${resolvedCodexHome}`
|
|
346
354
|
: `– No Codex sessions found yet (fine if you don't use Codex).`
|
|
347
355
|
);
|
|
356
|
+
log(
|
|
357
|
+
hasZcode
|
|
358
|
+
? `✓ Found ZCode sessions at ${ZCODE_DB}`
|
|
359
|
+
: `– No ZCode sessions found yet (fine if you don't use ZCode).`
|
|
360
|
+
);
|
|
348
361
|
|
|
349
362
|
const extraIdCount = allIds.length - 1;
|
|
350
363
|
if (extraIdCount > 0) {
|
package/llmnesia-claude-host.mjs
CHANGED
|
@@ -1,28 +1,40 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
// LLMnesia native messaging host — reads local coding-agent sessions (Claude
|
|
3
|
-
// Code from ~/.claude/projects, Codex from the configured Codex home
|
|
4
|
-
// streams them to the LLMnesia browser
|
|
5
|
-
// the extension sends back into the
|
|
6
|
-
// packages/../companion/src/paths.ts).
|
|
3
|
+
// Code from ~/.claude/projects, Codex from the configured Codex home, ZCode
|
|
4
|
+
// from ~/.zcode/cli/db/db.sqlite) and streams them to the LLMnesia browser
|
|
5
|
+
// extension, and writes corpus sync deltas the extension sends back into the
|
|
6
|
+
// LLMnesia corpus's inbox/ directory (see packages/../companion/src/paths.ts).
|
|
7
7
|
//
|
|
8
|
-
// It reads .jsonl session files under
|
|
9
|
-
//
|
|
10
|
-
//
|
|
11
|
-
//
|
|
12
|
-
//
|
|
13
|
-
//
|
|
14
|
-
// JSON, in both
|
|
8
|
+
// It reads .jsonl session files under the first two roots, materializes ZCode
|
|
9
|
+
// sessions out of its SQLite database, and writes only inside the corpus root
|
|
10
|
+
// named in its own config (~/.llmnesia/config.json) — never a path the caller
|
|
11
|
+
// supplies. It makes no network calls. The browser launches it on demand (see
|
|
12
|
+
// the installed com.llmnesia.claude_code.json manifest) and talks to it over
|
|
13
|
+
// stdio using Chrome's native-messaging framing: a little-endian uint32
|
|
14
|
+
// byte-length prefix followed by that many bytes of UTF-8 JSON, in both
|
|
15
|
+
// directions.
|
|
15
16
|
//
|
|
16
17
|
// The write path only ever activates for a user who has explicitly run the
|
|
17
18
|
// installer with --corpus (see install.mjs) to opt into the MCP companion;
|
|
18
19
|
// without ~/.llmnesia/config.json this host is exactly as read-only as it
|
|
19
20
|
// has always been for plain session indexing.
|
|
20
21
|
//
|
|
21
|
-
// Protocol
|
|
22
|
+
// Protocol v4 (extension → host). v1 was Claude-Code-only: `list` carried no
|
|
22
23
|
// `source` and `get` took a bare sessionId. Both remain accepted, so an
|
|
23
24
|
// extension older than this host keeps working; an extension NEWER than the
|
|
24
25
|
// host detects v1 from the pong and syncs Claude Code only.
|
|
25
|
-
//
|
|
26
|
+
//
|
|
27
|
+
// v4 adds ZCode to `list`/`get` (the first source backed by a SQLite database
|
|
28
|
+
// rather than per-session files; `get` materializes the transcript as JSONL).
|
|
29
|
+
// The version is informational in both directions, as below: a v3 host never
|
|
30
|
+
// lists zcode, and an extension gates the ZCode row on the reported version.
|
|
31
|
+
//
|
|
32
|
+
// v3 adds `listMemories`, the RC-03 reverse channel. A v2 host answers it with
|
|
33
|
+
// `{ type: "error", error: "unknown command: listMemories" }` and the extension
|
|
34
|
+
// treats that as "nothing to fetch", so the version is informational: hosts are
|
|
35
|
+
// installed out of band and an extension upgraded ahead of its host is the
|
|
36
|
+
// ordinary case, not a fault.
|
|
37
|
+
// { cmd: "ping" } → { type: "pong", version: 4 }
|
|
26
38
|
// { cmd: "list" } → { type: "list", sessions:
|
|
27
39
|
// [{source, sessionId, mtime, project?, title?}] }
|
|
28
40
|
// { cmd: "get", source, sessionId } → one or more { type: "chunk", sessionId, seq, total, data }
|
|
@@ -33,6 +45,11 @@
|
|
|
33
45
|
// seq, total, data } → { type: "chunkAck", seq }
|
|
34
46
|
// (writes <root>/inbox/<filename> once
|
|
35
47
|
// every chunk 0..total-1 has arrived)
|
|
48
|
+
// { cmd: "listMemories" } → { type: "memories", present,
|
|
49
|
+
// memories: [MemoryDoc], skipped }
|
|
50
|
+
// (reads <root>/memories/*.json; the
|
|
51
|
+
// only read path that touches the
|
|
52
|
+
// corpus rather than a session root)
|
|
36
53
|
//
|
|
37
54
|
// The extension never names a path in either direction: it asks for a
|
|
38
55
|
// (source, sessionId) pair and the host resolves it against its own roots. That
|
|
@@ -42,8 +59,17 @@ import { chmod, mkdir, readdir, readFile, rename, stat, writeFile } from "node:f
|
|
|
42
59
|
import { homedir } from "node:os";
|
|
43
60
|
import { join } from "node:path";
|
|
44
61
|
|
|
45
|
-
|
|
62
|
+
// 4 adds ZCode (see the protocol comment above). Do not make it a gate: hosts
|
|
63
|
+
// are installed out of band and a version check would strand every user who
|
|
64
|
+
// upgraded the extension first.
|
|
65
|
+
const PROTOCOL_VERSION = 4;
|
|
46
66
|
const PROJECTS_DIR = join(homedir(), ".claude", "projects");
|
|
67
|
+
// ZCode keeps every session in one SQLite database (WAL mode) — the first
|
|
68
|
+
// source with no per-session file. The host opens it READ-ONLY and materializes
|
|
69
|
+
// a session into the JSONL shape extension/src/background/zcode_import.ts
|
|
70
|
+
// parses. node:sqlite is imported lazily so a Node without it (older than
|
|
71
|
+
// 22.13) keeps serving every other source: ZCode just lists zero sessions.
|
|
72
|
+
const ZCODE_DB = join(homedir(), ".zcode", "cli", "db", "db.sqlite");
|
|
47
73
|
const CONFIG_FILE = join(homedir(), ".llmnesia", "config.json");
|
|
48
74
|
// Codex's home, resolved at install time (--codex-home > CODEX_HOME > ~/.codex)
|
|
49
75
|
// and persisted into config.json. The env var is read here too so a host
|
|
@@ -69,6 +95,12 @@ const MAX_PUT_TRANSFER_CHARS = 64 * 1024 * 1024;
|
|
|
69
95
|
const MAX_PENDING_WRITE_CHARS = 64 * 1024 * 1024;
|
|
70
96
|
const MAX_PENDING_WRITES = 8;
|
|
71
97
|
const PENDING_WRITE_TTL_MS = 5 * 60 * 1000;
|
|
98
|
+
// RC-03 reverse channel. Memories are one small JSON object each and exist to
|
|
99
|
+
// be reviewed by a person, so a corpus holding thousands of them is a bug
|
|
100
|
+
// upstream, not a case to stream. Capping the reply keeps it inside native
|
|
101
|
+
// messaging's ~1 MB per-message ceiling without a chunking protocol.
|
|
102
|
+
const MAX_MEMORY_FILE_CHARS = 128 * 1024;
|
|
103
|
+
const MAX_MEMORIES_PER_REPLY = 200;
|
|
72
104
|
|
|
73
105
|
function send(message) {
|
|
74
106
|
const body = Buffer.from(JSON.stringify(message), "utf8");
|
|
@@ -212,6 +244,192 @@ async function listCodexSessions(codexHome) {
|
|
|
212
244
|
return sessions;
|
|
213
245
|
}
|
|
214
246
|
|
|
247
|
+
// --- ZCode (SQLite source) -------------------------------------------------
|
|
248
|
+
|
|
249
|
+
let sqliteModule; // undefined = not yet imported, null = unavailable on this Node
|
|
250
|
+
async function getSqlite() {
|
|
251
|
+
if (sqliteModule === undefined) {
|
|
252
|
+
try {
|
|
253
|
+
sqliteModule = await import("node:sqlite");
|
|
254
|
+
} catch {
|
|
255
|
+
sqliteModule = null; // Node without node:sqlite (< 22.13): degrade quietly
|
|
256
|
+
}
|
|
257
|
+
}
|
|
258
|
+
return sqliteModule;
|
|
259
|
+
}
|
|
260
|
+
|
|
261
|
+
async function openZcodeDb() {
|
|
262
|
+
const sqlite = await getSqlite();
|
|
263
|
+
if (!sqlite) {
|
|
264
|
+
return null;
|
|
265
|
+
}
|
|
266
|
+
try {
|
|
267
|
+
// readOnly: the database is ZCode's live WAL database, often being written
|
|
268
|
+
// as we read it. Opening read-only fails cleanly when the file is absent.
|
|
269
|
+
return new sqlite.DatabaseSync(ZCODE_DB, { readOnly: true });
|
|
270
|
+
} catch {
|
|
271
|
+
return null; // no ZCode install, or the db is momentarily unreadable
|
|
272
|
+
}
|
|
273
|
+
}
|
|
274
|
+
|
|
275
|
+
/**
|
|
276
|
+
* Interactive ZCode sessions. Subagent runs (`task_type = 'subagent_child'`)
|
|
277
|
+
* are the harness's internal workers, not chats the user searched for, so they
|
|
278
|
+
* stay out of the listing. `title_source = 'default'` marks a placeholder
|
|
279
|
+
* title ("New Session"); only real titles are attached, so the extension's
|
|
280
|
+
* derived "<project> · <first prompt>" still wins when ZCode has no name.
|
|
281
|
+
*/
|
|
282
|
+
async function listZcodeSessions() {
|
|
283
|
+
const db = await openZcodeDb();
|
|
284
|
+
if (!db) {
|
|
285
|
+
return [];
|
|
286
|
+
}
|
|
287
|
+
try {
|
|
288
|
+
const rows = db
|
|
289
|
+
.prepare(
|
|
290
|
+
`SELECT id, title, title_source, time_updated, task_type
|
|
291
|
+
FROM session
|
|
292
|
+
WHERE task_type = 'interactive' OR task_type IS NULL`
|
|
293
|
+
)
|
|
294
|
+
.all();
|
|
295
|
+
const sessions = [];
|
|
296
|
+
for (const row of rows) {
|
|
297
|
+
const updated = Math.floor(Number(row.time_updated));
|
|
298
|
+
if (!Number.isFinite(updated) || updated <= 0) {
|
|
299
|
+
continue;
|
|
300
|
+
}
|
|
301
|
+
const session = {
|
|
302
|
+
source: "zcode",
|
|
303
|
+
sessionId: String(row.id),
|
|
304
|
+
mtime: updated,
|
|
305
|
+
path: ZCODE_DB
|
|
306
|
+
};
|
|
307
|
+
if (typeof row.title === "string" && row.title && row.title_source !== "default") {
|
|
308
|
+
session.title = row.title;
|
|
309
|
+
}
|
|
310
|
+
sessions.push(session);
|
|
311
|
+
}
|
|
312
|
+
return sessions;
|
|
313
|
+
} catch {
|
|
314
|
+
return []; // unreadable or mid-migration database — ZCode contributes nothing
|
|
315
|
+
} finally {
|
|
316
|
+
db.close();
|
|
317
|
+
}
|
|
318
|
+
}
|
|
319
|
+
|
|
320
|
+
/**
|
|
321
|
+
* Build one ZCode session's transcript as JSONL for the extension parser: a
|
|
322
|
+
* `session` header line naming the project directory, then one `message` line
|
|
323
|
+
* per user/assistant prose turn. Only text parts survive; parts flagged
|
|
324
|
+
* `synthetic` (ZCode-injected bookkeeping such as `<task-notification>`) are
|
|
325
|
+
* dropped here and defensively re-checked in the parser. Multi-part messages
|
|
326
|
+
* are joined with a blank line, mirroring how the file-based parsers treat
|
|
327
|
+
* text blocks.
|
|
328
|
+
*
|
|
329
|
+
* Returns null when the session id is unknown (or node:sqlite is unavailable —
|
|
330
|
+
* a session that could not be listed cannot be fetched either).
|
|
331
|
+
*/
|
|
332
|
+
async function materializeZcodeSession(sessionId) {
|
|
333
|
+
const db = await openZcodeDb();
|
|
334
|
+
if (!db) {
|
|
335
|
+
return null;
|
|
336
|
+
}
|
|
337
|
+
try {
|
|
338
|
+
const sessionRow = db.prepare("SELECT directory FROM session WHERE id = ?").get(sessionId);
|
|
339
|
+
if (!sessionRow) {
|
|
340
|
+
return null;
|
|
341
|
+
}
|
|
342
|
+
const lines = [];
|
|
343
|
+
const header = { type: "session" };
|
|
344
|
+
if (typeof sessionRow.directory === "string" && sessionRow.directory) {
|
|
345
|
+
header.directory = sessionRow.directory;
|
|
346
|
+
}
|
|
347
|
+
lines.push(JSON.stringify(header));
|
|
348
|
+
|
|
349
|
+
const rows = db
|
|
350
|
+
.prepare(
|
|
351
|
+
`SELECT m.id, m.time_created, m.data AS message_data, p.data AS part_data
|
|
352
|
+
FROM part p JOIN message m ON m.id = p.message_id
|
|
353
|
+
WHERE m.session_id = ?
|
|
354
|
+
ORDER BY m.sequence, p.sequence`
|
|
355
|
+
)
|
|
356
|
+
.all(sessionId);
|
|
357
|
+
|
|
358
|
+
// Rows arrive grouped by message (ORDER BY m.sequence, p.sequence), so a
|
|
359
|
+
// message's parts are contiguous: accumulate one outgoing line per group.
|
|
360
|
+
let currentId = null;
|
|
361
|
+
let current = null;
|
|
362
|
+
const flush = () => {
|
|
363
|
+
if (!current) {
|
|
364
|
+
return;
|
|
365
|
+
}
|
|
366
|
+
const text = current.texts.join("\n\n").trim();
|
|
367
|
+
if (text) {
|
|
368
|
+
const line = { type: "message", role: current.role, text };
|
|
369
|
+
if (current.timestamp !== undefined) {
|
|
370
|
+
line.timestamp = current.timestamp;
|
|
371
|
+
}
|
|
372
|
+
if (current.role === "assistant" && current.model) {
|
|
373
|
+
line.model = current.model;
|
|
374
|
+
}
|
|
375
|
+
lines.push(JSON.stringify(line));
|
|
376
|
+
}
|
|
377
|
+
current = null;
|
|
378
|
+
};
|
|
379
|
+
for (const row of rows) {
|
|
380
|
+
if (row.id !== currentId) {
|
|
381
|
+
flush();
|
|
382
|
+
currentId = row.id;
|
|
383
|
+
let meta = null;
|
|
384
|
+
try {
|
|
385
|
+
meta = JSON.parse(row.message_data);
|
|
386
|
+
} catch {
|
|
387
|
+
meta = null;
|
|
388
|
+
}
|
|
389
|
+
const role = meta && meta.role === "assistant" ? "assistant" : meta && meta.role === "user" ? "user" : null;
|
|
390
|
+
if (!role) {
|
|
391
|
+
current = null; // unknown shape — drop the whole message, keep the rest
|
|
392
|
+
continue;
|
|
393
|
+
}
|
|
394
|
+
const dataTs = meta && meta.time && typeof meta.time.created === "number" ? meta.time.created : undefined;
|
|
395
|
+
current = {
|
|
396
|
+
role,
|
|
397
|
+
texts: [],
|
|
398
|
+
timestamp:
|
|
399
|
+
dataTs !== undefined
|
|
400
|
+
? dataTs
|
|
401
|
+
: typeof row.time_created === "number"
|
|
402
|
+
? row.time_created
|
|
403
|
+
: undefined,
|
|
404
|
+
model: role === "assistant" && typeof meta.modelID === "string" && meta.modelID ? meta.modelID : null
|
|
405
|
+
};
|
|
406
|
+
}
|
|
407
|
+
if (!current) {
|
|
408
|
+
continue;
|
|
409
|
+
}
|
|
410
|
+
let part = null;
|
|
411
|
+
try {
|
|
412
|
+
part = JSON.parse(row.part_data);
|
|
413
|
+
} catch {
|
|
414
|
+
part = null;
|
|
415
|
+
}
|
|
416
|
+
if (!part || part.type !== "text" || part.synthetic === true || typeof part.text !== "string") {
|
|
417
|
+
continue;
|
|
418
|
+
}
|
|
419
|
+
const text = part.text.trim();
|
|
420
|
+
if (text) {
|
|
421
|
+
current.texts.push(text);
|
|
422
|
+
}
|
|
423
|
+
}
|
|
424
|
+
flush();
|
|
425
|
+
return lines.join("\n");
|
|
426
|
+
} catch {
|
|
427
|
+
return null;
|
|
428
|
+
} finally {
|
|
429
|
+
db.close();
|
|
430
|
+
}
|
|
431
|
+
}
|
|
432
|
+
|
|
215
433
|
/**
|
|
216
434
|
* Every session across every source. Sources are listed independently and
|
|
217
435
|
* failures are contained per source (each helper swallows its own errors), so
|
|
@@ -221,11 +439,12 @@ async function listCodexSessions(codexHome) {
|
|
|
221
439
|
async function listSessions() {
|
|
222
440
|
const config = await loadConfig();
|
|
223
441
|
const codexHome = config?.codexHome || DEFAULT_CODEX_HOME;
|
|
224
|
-
const [claude, codex] = await Promise.all([
|
|
442
|
+
const [claude, codex, zcode] = await Promise.all([
|
|
225
443
|
listClaudeCodeSessions().catch(() => []),
|
|
226
|
-
listCodexSessions(codexHome).catch(() => [])
|
|
444
|
+
listCodexSessions(codexHome).catch(() => []),
|
|
445
|
+
listZcodeSessions().catch(() => [])
|
|
227
446
|
]);
|
|
228
|
-
return [...claude, ...codex];
|
|
447
|
+
return [...claude, ...codex, ...zcode];
|
|
229
448
|
}
|
|
230
449
|
|
|
231
450
|
async function loadConfig() {
|
|
@@ -355,6 +574,60 @@ async function handlePutChunk(message) {
|
|
|
355
574
|
send({ type: "chunkAck", seq });
|
|
356
575
|
}
|
|
357
576
|
|
|
577
|
+
/**
|
|
578
|
+
* RC-03: read agent-written memories out of `<corpusRoot>/memories/*.json`.
|
|
579
|
+
*
|
|
580
|
+
* This is a different read source from `list`/`get`, which serve session
|
|
581
|
+
* transcripts from ~/.claude/projects and ~/.codex and never touch the corpus.
|
|
582
|
+
* The layout mirrors companion/src/corpus.ts `iterateMemories`: one JSON object
|
|
583
|
+
* per file, named by a slug of its memoryId.
|
|
584
|
+
*
|
|
585
|
+
* Tolerant by design, matching the companion's own reader: a single unreadable
|
|
586
|
+
* or malformed file must not deny the user every other memory waiting for
|
|
587
|
+
* review. Skipped files are counted so the extension can say something honest
|
|
588
|
+
* rather than silently under-reporting.
|
|
589
|
+
*/
|
|
590
|
+
async function readCorpusMemories(corpusRoot) {
|
|
591
|
+
const dir = join(corpusRoot, "memories");
|
|
592
|
+
let names;
|
|
593
|
+
try {
|
|
594
|
+
names = await readdir(dir);
|
|
595
|
+
} catch {
|
|
596
|
+
// No memories directory yet. Not an error: nothing has written one.
|
|
597
|
+
return { memories: [], skipped: 0 };
|
|
598
|
+
}
|
|
599
|
+
|
|
600
|
+
const memories = [];
|
|
601
|
+
let skipped = 0;
|
|
602
|
+
for (const name of names.sort()) {
|
|
603
|
+
if (!name.endsWith(".json")) {
|
|
604
|
+
continue;
|
|
605
|
+
}
|
|
606
|
+
if (memories.length >= MAX_MEMORIES_PER_REPLY) {
|
|
607
|
+
skipped += 1;
|
|
608
|
+
continue;
|
|
609
|
+
}
|
|
610
|
+
try {
|
|
611
|
+
const raw = await readFile(join(dir, name), "utf8");
|
|
612
|
+
if (raw.length > MAX_MEMORY_FILE_CHARS) {
|
|
613
|
+
skipped += 1;
|
|
614
|
+
continue;
|
|
615
|
+
}
|
|
616
|
+
const record = JSON.parse(raw);
|
|
617
|
+
// memoryId is the identity the extension dedupes on. Without it the
|
|
618
|
+
// record cannot be ingested safely, so drop it rather than invent one.
|
|
619
|
+
if (record && typeof record === "object" && typeof record.memoryId === "string" && record.memoryId) {
|
|
620
|
+
memories.push(record);
|
|
621
|
+
} else {
|
|
622
|
+
skipped += 1;
|
|
623
|
+
}
|
|
624
|
+
} catch {
|
|
625
|
+
skipped += 1;
|
|
626
|
+
}
|
|
627
|
+
}
|
|
628
|
+
return { memories, skipped };
|
|
629
|
+
}
|
|
630
|
+
|
|
358
631
|
async function handle(message) {
|
|
359
632
|
if (!message || typeof message !== "object") {
|
|
360
633
|
return;
|
|
@@ -376,24 +649,47 @@ async function handle(message) {
|
|
|
376
649
|
await handlePutChunk(message);
|
|
377
650
|
return;
|
|
378
651
|
}
|
|
652
|
+
if (message.cmd === "listMemories") {
|
|
653
|
+
const config = await loadConfig();
|
|
654
|
+
if (!config?.corpusRoot) {
|
|
655
|
+
send({ type: "memories", present: false, memories: [], skipped: 0 });
|
|
656
|
+
return;
|
|
657
|
+
}
|
|
658
|
+
const { memories, skipped } = await readCorpusMemories(config.corpusRoot);
|
|
659
|
+
send({ type: "memories", present: true, memories, skipped });
|
|
660
|
+
return;
|
|
661
|
+
}
|
|
379
662
|
if (message.cmd === "list") {
|
|
380
663
|
const sessions = await listSessions();
|
|
381
664
|
send({ type: "list", sessions: sessions.map(({ path, ...rest }) => rest) });
|
|
382
665
|
return;
|
|
383
666
|
}
|
|
384
667
|
if (message.cmd === "get") {
|
|
385
|
-
const sessions = await listSessions();
|
|
386
668
|
// Session ids are only unique WITHIN a source, so a v2 caller names both.
|
|
387
669
|
// A v1 caller sends no source; everything it knows about is Claude Code, so
|
|
388
670
|
// that's what an absent source resolves to — never a bare id match that
|
|
389
671
|
// could hand back the wrong source's file.
|
|
390
672
|
const wantSource = typeof message.source === "string" ? message.source : "claude_code";
|
|
391
|
-
|
|
392
|
-
if (
|
|
393
|
-
|
|
394
|
-
|
|
673
|
+
let text;
|
|
674
|
+
if (wantSource === "zcode") {
|
|
675
|
+
// No file to read: the transcript is materialized out of the database.
|
|
676
|
+
// The session id is only ever a bound query parameter, never a path
|
|
677
|
+
// component, so the trust boundary holds unchanged.
|
|
678
|
+
const materialized = await materializeZcodeSession(String(message.sessionId ?? ""));
|
|
679
|
+
if (materialized === null) {
|
|
680
|
+
send({ type: "session", sessionId: message.sessionId, notFound: true });
|
|
681
|
+
return;
|
|
682
|
+
}
|
|
683
|
+
text = materialized;
|
|
684
|
+
} else {
|
|
685
|
+
const sessions = await listSessions();
|
|
686
|
+
const match = sessions.find((s) => s.source === wantSource && s.sessionId === message.sessionId);
|
|
687
|
+
if (!match) {
|
|
688
|
+
send({ type: "session", sessionId: message.sessionId, notFound: true });
|
|
689
|
+
return;
|
|
690
|
+
}
|
|
691
|
+
text = await readFile(match.path, "utf8");
|
|
395
692
|
}
|
|
396
|
-
const text = await readFile(match.path, "utf8");
|
|
397
693
|
const total = Math.max(1, Math.ceil(text.length / CHUNK_CHARS));
|
|
398
694
|
for (let i = 0, seq = 0; seq < total; i += CHUNK_CHARS, seq++) {
|
|
399
695
|
send({
|
package/package.json
CHANGED
|
@@ -1,11 +1,12 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@llmnesia/local-agent-host",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"description": "LLMnesia native messaging host — lets the browser extension read local coding-agent sessions (Claude Code, Codex) automatically.",
|
|
3
|
+
"version": "0.3.0",
|
|
4
|
+
"description": "LLMnesia native messaging host — lets the browser extension read local coding-agent sessions (Claude Code, Codex, ZCode) automatically.",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"llmnesia",
|
|
7
7
|
"claude-code",
|
|
8
8
|
"codex",
|
|
9
|
+
"zcode",
|
|
9
10
|
"native-messaging",
|
|
10
11
|
"browser-extension",
|
|
11
12
|
"chat-history",
|