@llmnesia/local-agent-host 0.3.1 → 0.3.2

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
@@ -81,6 +81,13 @@ delete the retained data too.
81
81
 
82
82
  Native messaging over stdio (little-endian uint32 length prefix + UTF-8 JSON):
83
83
 
84
+ Helper 0.3.2 reports protocol version 5 and supplies per-source scan health for
85
+ Claude Code, Codex and ZCode. MCP 0.2.12 includes this same helper, so its normal
86
+ `install` command updates both components. For a standalone helper update, run
87
+ `npx -y @llmnesia/local-agent-host@0.3.2`, then fully quit and reopen the browser.
88
+ Existing protocol-v4 helpers can still sync conversations; they cannot supply
89
+ the new scan-health fields.
90
+
84
91
  - `{ cmd: "ping" }` → `{ type: "pong", version }`
85
92
  - `{ cmd: "list" }` → `{ type: "list", sessions: [{ sessionId, mtime, project }] }`
86
93
  - `{ cmd: "get", sessionId }` → `{ type: "chunk", sessionId, seq, total, data }` × N, then `{ type: "sessionDone", sessionId }`
@@ -19,11 +19,13 @@
19
19
  // without ~/.llmnesia/config.json this host is exactly as read-only as it
20
20
  // has always been for plain session indexing.
21
21
  //
22
- // Protocol v4 (extension → host). v1 was Claude-Code-only: `list` carried no
22
+ // Protocol v5 (extension → host). v1 was Claude-Code-only: `list` carried no
23
23
  // `source` and `get` took a bare sessionId. Both remain accepted, so an
24
24
  // extension older than this host keeps working; an extension NEWER than the
25
25
  // host detects v1 from the pong and syncs Claude Code only.
26
26
  //
27
+ // v5 adds per-source listing health and putSourceHealth metadata updates,
28
+ // keeping diagnostics separate from the conversation inbox.
27
29
  // v4 adds ZCode to `list`/`get` (the first source backed by a SQLite database
28
30
  // rather than per-session files; `get` materializes the transcript as JSONL).
29
31
  // The version is informational in both directions, as below: a v3 host never
@@ -34,7 +36,7 @@
34
36
  // treats that as "nothing to fetch", so the version is informational: hosts are
35
37
  // installed out of band and an extension upgraded ahead of its host is the
36
38
  // ordinary case, not a fault.
37
- // { cmd: "ping" } → { type: "pong", version: 4 }
39
+ // { cmd: "ping" } → { type: "pong", version: 5 }
38
40
  // { cmd: "list" } → { type: "list", sessions:
39
41
  // [{source, sessionId, mtime, project?, title?}] }
40
42
  // { cmd: "get", source, sessionId } → one or more { type: "chunk", sessionId, seq, total, data }
@@ -59,10 +61,10 @@ import { chmod, mkdir, readdir, readFile, rename, stat, writeFile } from "node:f
59
61
  import { homedir } from "node:os";
60
62
  import { join } from "node:path";
61
63
 
62
- // 4 adds ZCode (see the protocol comment above). Do not make it a gate: hosts
64
+ // 5 adds per-source listing health (see the protocol comment above). Do not make it a gate: hosts
63
65
  // are installed out of band and a version check would strand every user who
64
66
  // upgraded the extension first.
65
- const PROTOCOL_VERSION = 4;
67
+ const PROTOCOL_VERSION = 5;
66
68
  const PROJECTS_DIR = join(homedir(), ".claude", "projects");
67
69
  // ZCode keeps every session in one SQLite database (WAL mode) — the first
68
70
  // source with no per-session file. The host opens it READ-ONLY and materializes
@@ -78,9 +80,29 @@ const DEFAULT_CODEX_HOME = process.env.CODEX_HOME || join(homedir(), ".codex");
78
80
  // Codex nests rollouts as sessions/<year>/<month>/<day>/*.jsonl. Bounded so a
79
81
  // misconfigured codexHome can't turn into an unbounded filesystem walk.
80
82
  const CODEX_MAX_DEPTH = 3;
81
- // Conservative chunk size (chars). After JSON-escaping + any multibyte chars the
82
- // on-wire message stays well under native messaging's 1 MB per-message ceiling.
83
- const CHUNK_CHARS = 256 * 1024;
83
+ // Conservative chunk size. Native messaging caps a single message at 1 MB,
84
+ // and the wire size of a chunk is the JSON-ESCAPED UTF-8 length of `data`
85
+ // (an astral character is 4 raw bytes; a literal backslash doubles), so
86
+ // chunks are budgeted by measuring exactly that as they are built: a chunk
87
+ // can never push the framed message over the ceiling no matter what the
88
+ // transcript contains.
89
+ const MAX_CHUNK_ESCAPED_BYTES = 256 * 1024;
90
+ // JSON-escaped UTF-8 byte length of one UTF-16 code unit of `text` as
91
+ // JSON.stringify would emit it: quotes/backslashes and the short escapes
92
+ // double, other control characters become \u00XX (6 bytes), a lone surrogate
93
+ // becomes \udXXX, BMP non-ASCII passes through at its UTF-8 width, and a
94
+ // surrogate PAIR is one 4-byte astral character.
95
+ function escapedUnitBytes(unit, nextUnit) {
96
+ if (unit >= 0xd800 && unit <= 0xdbff) {
97
+ return nextUnit >= 0xdc00 && nextUnit <= 0xdfff ? 4 : 6; // astral char or lone high surrogate
98
+ }
99
+ if (unit >= 0xdc00 && unit <= 0xdfff) return 6; // lone low surrogate
100
+ if (unit === 0x22 || unit === 0x5c) return 2; // " and \
101
+ if (unit < 0x20) return [0x08, 0x09, 0x0a, 0x0c, 0x0d].includes(unit) ? 2 : 6;
102
+ if (unit < 0x80) return 1;
103
+ if (unit < 0x800) return 2;
104
+ return 3;
105
+ }
84
106
  // Matches companion/src/corpus.ts DIR_MODE/FILE_MODE — the corpus holds
85
107
  // plaintext conversation history, so writes here should be no more readable
86
108
  // than the browser profile it was copied out of.
@@ -114,12 +136,13 @@ function send(message) {
114
136
  // One entry per session: { source, sessionId, mtime, project?, title?, path }.
115
137
  // `path` is stripped before anything goes on the wire.
116
138
 
117
- async function listClaudeCodeSessions() {
139
+ async function listClaudeCodeSessions(issues) {
118
140
  const sessions = [];
119
141
  let projectDirs;
120
142
  try {
121
143
  projectDirs = await readdir(PROJECTS_DIR, { withFileTypes: true });
122
144
  } catch {
145
+ if (issues) issues.failed += 1;
123
146
  return sessions; // no ~/.claude/projects yet
124
147
  }
125
148
  for (const entry of projectDirs) {
@@ -131,6 +154,7 @@ async function listClaudeCodeSessions() {
131
154
  try {
132
155
  files = await readdir(dir);
133
156
  } catch {
157
+ if (issues) issues.failed += 1;
134
158
  continue;
135
159
  }
136
160
  for (const file of files) {
@@ -148,6 +172,7 @@ async function listClaudeCodeSessions() {
148
172
  path
149
173
  });
150
174
  } catch {
175
+ if (issues) issues.failed += 1;
151
176
  // Skip unreadable files.
152
177
  }
153
178
  }
@@ -166,18 +191,19 @@ function codexSessionId(filename) {
166
191
  return match ? match[1].toLowerCase() : base;
167
192
  }
168
193
 
169
- async function walkCodexDir(dir, depth, out) {
194
+ async function walkCodexDir(dir, depth, out, issues) {
170
195
  let entries;
171
196
  try {
172
197
  entries = await readdir(dir, { withFileTypes: true });
173
198
  } catch {
199
+ if (issues) issues.failed += 1;
174
200
  return out; // missing or unreadable — nothing to add
175
201
  }
176
202
  for (const entry of entries) {
177
203
  const path = join(dir, entry.name);
178
204
  if (entry.isDirectory()) {
179
205
  if (depth > 0) {
180
- await walkCodexDir(path, depth - 1, out);
206
+ await walkCodexDir(path, depth - 1, out, issues);
181
207
  }
182
208
  continue;
183
209
  }
@@ -193,6 +219,7 @@ async function walkCodexDir(dir, depth, out) {
193
219
  path
194
220
  });
195
221
  } catch {
222
+ if (issues) issues.failed += 1;
196
223
  // Skip unreadable files.
197
224
  }
198
225
  }
@@ -229,8 +256,8 @@ async function readCodexThreadNames(codexHome) {
229
256
  return titles;
230
257
  }
231
258
 
232
- async function listCodexSessions(codexHome) {
233
- const sessions = await walkCodexDir(join(codexHome, "sessions"), CODEX_MAX_DEPTH, []);
259
+ async function listCodexSessions(codexHome, issues) {
260
+ const sessions = await walkCodexDir(join(codexHome, "sessions"), CODEX_MAX_DEPTH, [], issues);
234
261
  if (sessions.length === 0) {
235
262
  return sessions;
236
263
  }
@@ -279,9 +306,10 @@ async function openZcodeDb() {
279
306
  * title ("New Session"); only real titles are attached, so the extension's
280
307
  * derived "<project> · <first prompt>" still wins when ZCode has no name.
281
308
  */
282
- async function listZcodeSessions() {
309
+ async function listZcodeSessions(issues) {
283
310
  const db = await openZcodeDb();
284
311
  if (!db) {
312
+ if (issues) issues.failed += 1;
285
313
  return [];
286
314
  }
287
315
  try {
@@ -311,6 +339,7 @@ async function listZcodeSessions() {
311
339
  }
312
340
  return sessions;
313
341
  } catch {
342
+ if (issues) issues.failed += 1;
314
343
  return []; // unreadable or mid-migration database — ZCode contributes nothing
315
344
  } finally {
316
345
  db.close();
@@ -447,6 +476,36 @@ async function listSessions() {
447
476
  return [...claude, ...codex, ...zcode];
448
477
  }
449
478
 
479
+ // A missing root and an unreadable source must not both appear as a healthy,
480
+ // empty scan. Paths and transcript data never enter these diagnostics.
481
+ async function listSessionsWithHealth() {
482
+ const config = await loadConfig();
483
+ const codexHome = config?.codexHome || DEFAULT_CODEX_HOME;
484
+ const sources = [
485
+ ["claude_code", PROJECTS_DIR, (issues) => listClaudeCodeSessions(issues)],
486
+ ["codex", join(codexHome, "sessions"), (issues) => listCodexSessions(codexHome, issues)],
487
+ ["zcode", ZCODE_DB, (issues) => listZcodeSessions(issues)]
488
+ ];
489
+ const sessions = [];
490
+ const sourceStatus = {};
491
+ for (const [source, path, list] of sources) {
492
+ try {
493
+ await stat(path);
494
+ } catch (error) {
495
+ sourceStatus[source] = { state: error?.code === "ENOENT" ? "missing" : "error" };
496
+ continue;
497
+ }
498
+ const issues = { failed: 0 };
499
+ try {
500
+ sessions.push(...await list(issues));
501
+ sourceStatus[source] = { state: issues.failed > 0 ? "partial" : "ok" };
502
+ } catch {
503
+ sourceStatus[source] = { state: "error" };
504
+ }
505
+ }
506
+ return { sessions, sourceStatus };
507
+ }
508
+
450
509
  async function loadConfig() {
451
510
  try {
452
511
  const raw = await readFile(CONFIG_FILE, "utf8");
@@ -628,6 +687,43 @@ async function readCorpusMemories(corpusRoot) {
628
687
  return { memories, skipped };
629
688
  }
630
689
 
690
+ // A separate metadata channel keeps health heartbeats out of the conversation
691
+ // inbox. Older MCP readers ignore this file and keep their true data age.
692
+ function sourceHealthRow(value) {
693
+ if (!value || typeof value !== "object") return null;
694
+ const { source, observedAt, connection, state, lastAttemptAt, lastSuccessfulSyncAt, lastCaptureAt, failedSessions } = value;
695
+ const time = (v) => Number.isSafeInteger(v) && v >= 0;
696
+ if (!["claude_code", "codex", "zcode"].includes(source) || !["connected", "disconnected"].includes(connection) ||
697
+ !["ok", "partial", "missing", "error", "unknown"].includes(state) || !time(observedAt) ||
698
+ observedAt > Date.now() + 300000 || !time(lastAttemptAt) || lastAttemptAt > observedAt ||
699
+ (lastSuccessfulSyncAt !== null && (!time(lastSuccessfulSyncAt) || lastSuccessfulSyncAt > observedAt)) ||
700
+ (lastCaptureAt !== null && (!time(lastCaptureAt) || lastCaptureAt > observedAt)) || !time(failedSessions)) return null;
701
+ return { source, observedAt, connection, state, lastAttemptAt, lastSuccessfulSyncAt, lastCaptureAt, failedSessions };
702
+ }
703
+
704
+ async function handleSourceHealth(message) {
705
+ const config = await loadConfig();
706
+ if (!config?.corpusRoot || !Array.isArray(message.rows) || message.rows.length > 3) {
707
+ send({ type: "error", error: "source health: invalid rows or no corpus configured" }); return;
708
+ }
709
+ const rows = message.rows.map(sourceHealthRow);
710
+ if (rows.some((row) => !row)) {
711
+ send({ type: "error", error: "source health: invalid report" }); return;
712
+ }
713
+ const path = join(config.corpusRoot, "source-health-v1.json");
714
+ let previous = [];
715
+ try { previous = JSON.parse(await readFile(path, "utf8")); } catch { /* First report. */ }
716
+ const current = new Map((Array.isArray(previous) ? previous : []).map(sourceHealthRow).filter(Boolean).map((row) => [row.source, row]));
717
+ for (const row of rows) {
718
+ if ((current.get(row.source)?.observedAt ?? -1) < row.observedAt) current.set(row.source, row);
719
+ }
720
+ await mkdir(config.corpusRoot, { recursive: true, mode: 0o700 });
721
+ const temp = `${path}.${process.pid}.tmp`;
722
+ await writeFile(temp, JSON.stringify([...current.values()]) + "\n", { mode: FILE_MODE });
723
+ await rename(temp, path);
724
+ send({ type: "sourceHealthAck" });
725
+ }
726
+
631
727
  async function handle(message) {
632
728
  if (!message || typeof message !== "object") {
633
729
  return;
@@ -642,7 +738,11 @@ async function handle(message) {
642
738
  send({ type: "corpusInfo", present: false });
643
739
  return;
644
740
  }
645
- send({ type: "corpusInfo", present: true, root: config.corpusRoot });
741
+ send({ type: "corpusInfo", present: true, root: config.corpusRoot, sourceHealthSupported: true });
742
+ return;
743
+ }
744
+ if (message.cmd === "putSourceHealth") {
745
+ await handleSourceHealth(message);
646
746
  return;
647
747
  }
648
748
  if (message.cmd === "putChunk") {
@@ -660,8 +760,8 @@ async function handle(message) {
660
760
  return;
661
761
  }
662
762
  if (message.cmd === "list") {
663
- const sessions = await listSessions();
664
- send({ type: "list", sessions: sessions.map(({ path, ...rest }) => rest) });
763
+ const { sessions, sourceStatus } = await listSessionsWithHealth();
764
+ send({ type: "list", sessions: sessions.map(({ path, ...rest }) => rest), sourceStatus });
665
765
  return;
666
766
  }
667
767
  if (message.cmd === "get") {
@@ -690,14 +790,31 @@ async function handle(message) {
690
790
  }
691
791
  text = await readFile(match.path, "utf8");
692
792
  }
693
- const total = Math.max(1, Math.ceil(text.length / CHUNK_CHARS));
694
- for (let i = 0, seq = 0; seq < total; i += CHUNK_CHARS, seq++) {
793
+ const chunks = [];
794
+ let chunk = "";
795
+ let chunkBytes = 0;
796
+ for (let i = 0; i < text.length; i++) {
797
+ const unit = text.charCodeAt(i);
798
+ const size = escapedUnitBytes(unit, i + 1 < text.length ? text.charCodeAt(i + 1) : NaN);
799
+ if (chunk && chunkBytes + size > MAX_CHUNK_ESCAPED_BYTES) {
800
+ chunks.push(chunk);
801
+ chunk = "";
802
+ chunkBytes = 0;
803
+ }
804
+ chunk += text[i];
805
+ chunkBytes += size;
806
+ }
807
+ if (chunk) {
808
+ chunks.push(chunk);
809
+ }
810
+ const total = Math.max(1, chunks.length);
811
+ for (let seq = 0; seq < total; seq++) {
695
812
  send({
696
813
  type: "chunk",
697
814
  sessionId: message.sessionId,
698
815
  seq,
699
816
  total,
700
- data: text.slice(i, i + CHUNK_CHARS)
817
+ data: chunks[seq] ?? ""
701
818
  });
702
819
  }
703
820
  send({ type: "sessionDone", sessionId: message.sessionId });
@@ -728,7 +845,16 @@ process.stdin.on("data", (data) => {
728
845
  // Serialize handling so chunk ordering per session is preserved.
729
846
  processing = processing
730
847
  .then(() => handle(message))
731
- .catch((error) => send({ type: "error", error: String((error && error.message) || error) }));
848
+ .catch((error) =>
849
+ // Attribute the failure to the command's session when it names one, so
850
+ // the extension's fetch loop can drop a STALE error that arrives after
851
+ // it gave up on that session instead of failing the next one.
852
+ send({
853
+ type: "error",
854
+ ...(typeof message.sessionId === "string" ? { sessionId: message.sessionId } : {}),
855
+ error: String((error && error.message) || error)
856
+ })
857
+ );
732
858
  }
733
859
  });
734
860
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@llmnesia/local-agent-host",
3
- "version": "0.3.1",
3
+ "version": "0.3.2",
4
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",