@llmnesia/local-agent-host 0.3.1 → 0.3.3

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.3 reports protocol version 5 and supplies per-source scan health for
85
+ Claude Code, Codex and ZCode, plus each Claude Code and Codex session's size in bytes so the extension can skip sessions that were touched but not changed. 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.3`, 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,9 +36,9 @@
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
- // [{source, sessionId, mtime, project?, title?}] }
41
+ // [{source, sessionId, mtime, size?, project?, title?}] }
40
42
  // { cmd: "get", source, sessionId } → one or more { type: "chunk", sessionId, seq, total, data }
41
43
  // then { type: "sessionDone", sessionId }
42
44
  // (or { type: "session", sessionId, notFound: true })
@@ -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.
@@ -111,15 +133,20 @@ function send(message) {
111
133
  }
112
134
 
113
135
  // --- session discovery ----------------------------------------------------
114
- // One entry per session: { source, sessionId, mtime, project?, title?, path }.
115
- // `path` is stripped before anything goes on the wire.
116
-
117
- async function listClaudeCodeSessions() {
136
+ // One entry per session: { source, sessionId, mtime, size?, project?, title?, path }.
137
+ // `path` is stripped before anything goes on the wire. `size` is the file's
138
+ // byte length for the JSONL sources and is omitted for ZCode (a database row,
139
+ // not a file). The extension uses it to tell a session another app merely
140
+ // touched from one that changed; an extension that does not know the field
141
+ // ignores it, and one that sees no size falls back to comparing mtime alone.
142
+
143
+ async function listClaudeCodeSessions(issues) {
118
144
  const sessions = [];
119
145
  let projectDirs;
120
146
  try {
121
147
  projectDirs = await readdir(PROJECTS_DIR, { withFileTypes: true });
122
148
  } catch {
149
+ if (issues) issues.failed += 1;
123
150
  return sessions; // no ~/.claude/projects yet
124
151
  }
125
152
  for (const entry of projectDirs) {
@@ -131,6 +158,7 @@ async function listClaudeCodeSessions() {
131
158
  try {
132
159
  files = await readdir(dir);
133
160
  } catch {
161
+ if (issues) issues.failed += 1;
134
162
  continue;
135
163
  }
136
164
  for (const file of files) {
@@ -144,10 +172,12 @@ async function listClaudeCodeSessions() {
144
172
  source: "claude_code",
145
173
  sessionId: file.replace(/\.jsonl$/, ""),
146
174
  mtime: Math.floor(info.mtimeMs),
175
+ size: info.size,
147
176
  project: entry.name,
148
177
  path
149
178
  });
150
179
  } catch {
180
+ if (issues) issues.failed += 1;
151
181
  // Skip unreadable files.
152
182
  }
153
183
  }
@@ -166,18 +196,19 @@ function codexSessionId(filename) {
166
196
  return match ? match[1].toLowerCase() : base;
167
197
  }
168
198
 
169
- async function walkCodexDir(dir, depth, out) {
199
+ async function walkCodexDir(dir, depth, out, issues) {
170
200
  let entries;
171
201
  try {
172
202
  entries = await readdir(dir, { withFileTypes: true });
173
203
  } catch {
204
+ if (issues) issues.failed += 1;
174
205
  return out; // missing or unreadable — nothing to add
175
206
  }
176
207
  for (const entry of entries) {
177
208
  const path = join(dir, entry.name);
178
209
  if (entry.isDirectory()) {
179
210
  if (depth > 0) {
180
- await walkCodexDir(path, depth - 1, out);
211
+ await walkCodexDir(path, depth - 1, out, issues);
181
212
  }
182
213
  continue;
183
214
  }
@@ -190,9 +221,11 @@ async function walkCodexDir(dir, depth, out) {
190
221
  source: "codex",
191
222
  sessionId: codexSessionId(entry.name),
192
223
  mtime: Math.floor(info.mtimeMs),
224
+ size: info.size,
193
225
  path
194
226
  });
195
227
  } catch {
228
+ if (issues) issues.failed += 1;
196
229
  // Skip unreadable files.
197
230
  }
198
231
  }
@@ -229,8 +262,8 @@ async function readCodexThreadNames(codexHome) {
229
262
  return titles;
230
263
  }
231
264
 
232
- async function listCodexSessions(codexHome) {
233
- const sessions = await walkCodexDir(join(codexHome, "sessions"), CODEX_MAX_DEPTH, []);
265
+ async function listCodexSessions(codexHome, issues) {
266
+ const sessions = await walkCodexDir(join(codexHome, "sessions"), CODEX_MAX_DEPTH, [], issues);
234
267
  if (sessions.length === 0) {
235
268
  return sessions;
236
269
  }
@@ -279,9 +312,10 @@ async function openZcodeDb() {
279
312
  * title ("New Session"); only real titles are attached, so the extension's
280
313
  * derived "<project> · <first prompt>" still wins when ZCode has no name.
281
314
  */
282
- async function listZcodeSessions() {
315
+ async function listZcodeSessions(issues) {
283
316
  const db = await openZcodeDb();
284
317
  if (!db) {
318
+ if (issues) issues.failed += 1;
285
319
  return [];
286
320
  }
287
321
  try {
@@ -311,6 +345,7 @@ async function listZcodeSessions() {
311
345
  }
312
346
  return sessions;
313
347
  } catch {
348
+ if (issues) issues.failed += 1;
314
349
  return []; // unreadable or mid-migration database — ZCode contributes nothing
315
350
  } finally {
316
351
  db.close();
@@ -447,6 +482,36 @@ async function listSessions() {
447
482
  return [...claude, ...codex, ...zcode];
448
483
  }
449
484
 
485
+ // A missing root and an unreadable source must not both appear as a healthy,
486
+ // empty scan. Paths and transcript data never enter these diagnostics.
487
+ async function listSessionsWithHealth() {
488
+ const config = await loadConfig();
489
+ const codexHome = config?.codexHome || DEFAULT_CODEX_HOME;
490
+ const sources = [
491
+ ["claude_code", PROJECTS_DIR, (issues) => listClaudeCodeSessions(issues)],
492
+ ["codex", join(codexHome, "sessions"), (issues) => listCodexSessions(codexHome, issues)],
493
+ ["zcode", ZCODE_DB, (issues) => listZcodeSessions(issues)]
494
+ ];
495
+ const sessions = [];
496
+ const sourceStatus = {};
497
+ for (const [source, path, list] of sources) {
498
+ try {
499
+ await stat(path);
500
+ } catch (error) {
501
+ sourceStatus[source] = { state: error?.code === "ENOENT" ? "missing" : "error" };
502
+ continue;
503
+ }
504
+ const issues = { failed: 0 };
505
+ try {
506
+ sessions.push(...await list(issues));
507
+ sourceStatus[source] = { state: issues.failed > 0 ? "partial" : "ok" };
508
+ } catch {
509
+ sourceStatus[source] = { state: "error" };
510
+ }
511
+ }
512
+ return { sessions, sourceStatus };
513
+ }
514
+
450
515
  async function loadConfig() {
451
516
  try {
452
517
  const raw = await readFile(CONFIG_FILE, "utf8");
@@ -628,6 +693,43 @@ async function readCorpusMemories(corpusRoot) {
628
693
  return { memories, skipped };
629
694
  }
630
695
 
696
+ // A separate metadata channel keeps health heartbeats out of the conversation
697
+ // inbox. Older MCP readers ignore this file and keep their true data age.
698
+ function sourceHealthRow(value) {
699
+ if (!value || typeof value !== "object") return null;
700
+ const { source, observedAt, connection, state, lastAttemptAt, lastSuccessfulSyncAt, lastCaptureAt, failedSessions } = value;
701
+ const time = (v) => Number.isSafeInteger(v) && v >= 0;
702
+ if (!["claude_code", "codex", "zcode"].includes(source) || !["connected", "disconnected"].includes(connection) ||
703
+ !["ok", "partial", "missing", "error", "unknown"].includes(state) || !time(observedAt) ||
704
+ observedAt > Date.now() + 300000 || !time(lastAttemptAt) || lastAttemptAt > observedAt ||
705
+ (lastSuccessfulSyncAt !== null && (!time(lastSuccessfulSyncAt) || lastSuccessfulSyncAt > observedAt)) ||
706
+ (lastCaptureAt !== null && (!time(lastCaptureAt) || lastCaptureAt > observedAt)) || !time(failedSessions)) return null;
707
+ return { source, observedAt, connection, state, lastAttemptAt, lastSuccessfulSyncAt, lastCaptureAt, failedSessions };
708
+ }
709
+
710
+ async function handleSourceHealth(message) {
711
+ const config = await loadConfig();
712
+ if (!config?.corpusRoot || !Array.isArray(message.rows) || message.rows.length > 3) {
713
+ send({ type: "error", error: "source health: invalid rows or no corpus configured" }); return;
714
+ }
715
+ const rows = message.rows.map(sourceHealthRow);
716
+ if (rows.some((row) => !row)) {
717
+ send({ type: "error", error: "source health: invalid report" }); return;
718
+ }
719
+ const path = join(config.corpusRoot, "source-health-v1.json");
720
+ let previous = [];
721
+ try { previous = JSON.parse(await readFile(path, "utf8")); } catch { /* First report. */ }
722
+ const current = new Map((Array.isArray(previous) ? previous : []).map(sourceHealthRow).filter(Boolean).map((row) => [row.source, row]));
723
+ for (const row of rows) {
724
+ if ((current.get(row.source)?.observedAt ?? -1) < row.observedAt) current.set(row.source, row);
725
+ }
726
+ await mkdir(config.corpusRoot, { recursive: true, mode: 0o700 });
727
+ const temp = `${path}.${process.pid}.tmp`;
728
+ await writeFile(temp, JSON.stringify([...current.values()]) + "\n", { mode: FILE_MODE });
729
+ await rename(temp, path);
730
+ send({ type: "sourceHealthAck" });
731
+ }
732
+
631
733
  async function handle(message) {
632
734
  if (!message || typeof message !== "object") {
633
735
  return;
@@ -642,7 +744,11 @@ async function handle(message) {
642
744
  send({ type: "corpusInfo", present: false });
643
745
  return;
644
746
  }
645
- send({ type: "corpusInfo", present: true, root: config.corpusRoot });
747
+ send({ type: "corpusInfo", present: true, root: config.corpusRoot, sourceHealthSupported: true });
748
+ return;
749
+ }
750
+ if (message.cmd === "putSourceHealth") {
751
+ await handleSourceHealth(message);
646
752
  return;
647
753
  }
648
754
  if (message.cmd === "putChunk") {
@@ -660,8 +766,8 @@ async function handle(message) {
660
766
  return;
661
767
  }
662
768
  if (message.cmd === "list") {
663
- const sessions = await listSessions();
664
- send({ type: "list", sessions: sessions.map(({ path, ...rest }) => rest) });
769
+ const { sessions, sourceStatus } = await listSessionsWithHealth();
770
+ send({ type: "list", sessions: sessions.map(({ path, ...rest }) => rest), sourceStatus });
665
771
  return;
666
772
  }
667
773
  if (message.cmd === "get") {
@@ -690,14 +796,31 @@ async function handle(message) {
690
796
  }
691
797
  text = await readFile(match.path, "utf8");
692
798
  }
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++) {
799
+ const chunks = [];
800
+ let chunk = "";
801
+ let chunkBytes = 0;
802
+ for (let i = 0; i < text.length; i++) {
803
+ const unit = text.charCodeAt(i);
804
+ const size = escapedUnitBytes(unit, i + 1 < text.length ? text.charCodeAt(i + 1) : NaN);
805
+ if (chunk && chunkBytes + size > MAX_CHUNK_ESCAPED_BYTES) {
806
+ chunks.push(chunk);
807
+ chunk = "";
808
+ chunkBytes = 0;
809
+ }
810
+ chunk += text[i];
811
+ chunkBytes += size;
812
+ }
813
+ if (chunk) {
814
+ chunks.push(chunk);
815
+ }
816
+ const total = Math.max(1, chunks.length);
817
+ for (let seq = 0; seq < total; seq++) {
695
818
  send({
696
819
  type: "chunk",
697
820
  sessionId: message.sessionId,
698
821
  seq,
699
822
  total,
700
- data: text.slice(i, i + CHUNK_CHARS)
823
+ data: chunks[seq] ?? ""
701
824
  });
702
825
  }
703
826
  send({ type: "sessionDone", sessionId: message.sessionId });
@@ -728,7 +851,16 @@ process.stdin.on("data", (data) => {
728
851
  // Serialize handling so chunk ordering per session is preserved.
729
852
  processing = processing
730
853
  .then(() => handle(message))
731
- .catch((error) => send({ type: "error", error: String((error && error.message) || error) }));
854
+ .catch((error) =>
855
+ // Attribute the failure to the command's session when it names one, so
856
+ // the extension's fetch loop can drop a STALE error that arrives after
857
+ // it gave up on that session instead of failing the next one.
858
+ send({
859
+ type: "error",
860
+ ...(typeof message.sessionId === "string" ? { sessionId: message.sessionId } : {}),
861
+ error: String((error && error.message) || error)
862
+ })
863
+ );
732
864
  }
733
865
  });
734
866
 
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.3",
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",