@llmnesia/local-agent-host 0.3.2 → 0.3.4

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,10 +81,11 @@ 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
84
+ Helper 0.3.4 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.15 includes this same helper, so its normal
86
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.
87
+ `npx -y @llmnesia/local-agent-host@0.3.4`, then fully quit and reopen the browser.
88
+ Session files stream in bounded blocks with output backpressure, so a large session does not require a second full in-memory chunk collection.
88
89
  Existing protocol-v4 helpers can still sync conversations; they cannot supply
89
90
  the new scan-health fields.
90
91
 
@@ -38,7 +38,7 @@
38
38
  // ordinary case, not a fault.
39
39
  // { cmd: "ping" } → { type: "pong", version: 5 }
40
40
  // { cmd: "list" } → { type: "list", sessions:
41
- // [{source, sessionId, mtime, project?, title?}] }
41
+ // [{source, sessionId, mtime, size?, project?, title?}] }
42
42
  // { cmd: "get", source, sessionId } → one or more { type: "chunk", sessionId, seq, total, data }
43
43
  // then { type: "sessionDone", sessionId }
44
44
  // (or { type: "session", sessionId, notFound: true })
@@ -57,9 +57,10 @@
57
57
  // (source, sessionId) pair and the host resolves it against its own roots. That
58
58
  // is what keeps a compromised or buggy caller from reading arbitrary files.
59
59
 
60
- import { chmod, mkdir, readdir, readFile, rename, stat, writeFile } from "node:fs/promises";
60
+ import { chmod, mkdir, open, readdir, readFile, rename, stat, writeFile } from "node:fs/promises";
61
61
  import { homedir } from "node:os";
62
62
  import { join } from "node:path";
63
+ import { StringDecoder } from "node:string_decoder";
63
64
 
64
65
  // 5 adds per-source listing health (see the protocol comment above). Do not make it a gate: hosts
65
66
  // are installed out of band and a version check would strand every user who
@@ -80,29 +81,12 @@ const DEFAULT_CODEX_HOME = process.env.CODEX_HOME || join(homedir(), ".codex");
80
81
  // Codex nests rollouts as sessions/<year>/<month>/<day>/*.jsonl. Bounded so a
81
82
  // misconfigured codexHome can't turn into an unbounded filesystem walk.
82
83
  const CODEX_MAX_DEPTH = 3;
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
+ // At most six JSON-escaped bytes per input byte, plus a small envelope. Read
85
+ // one bounded block at a time and wait for stdout before reading the next.
86
+ // Building a whole session and a per-character rope for every chunk can exhaust
87
+ // V8's heap on a long session and disconnect every subsequent import.
88
+ const SESSION_READ_BYTES = 32 * 1024;
89
+ const SESSION_TEXT_CHARS = 32 * 1024;
106
90
  // Matches companion/src/corpus.ts DIR_MODE/FILE_MODE — the corpus holds
107
91
  // plaintext conversation history, so writes here should be no more readable
108
92
  // than the browser profile it was copied out of.
@@ -132,9 +116,64 @@ function send(message) {
132
116
  process.stdout.write(body);
133
117
  }
134
118
 
119
+ // The write callback applies backpressure, so a slow browser cannot make a
120
+ // large session accumulate queued JSON frames in the helper's heap.
121
+ async function sendSessionFrame(message) {
122
+ const body = Buffer.from(JSON.stringify(message), "utf8");
123
+ const frame = Buffer.allocUnsafe(4 + body.length);
124
+ frame.writeUInt32LE(body.length, 0);
125
+ body.copy(frame, 4);
126
+ await new Promise((resolve, reject) => {
127
+ process.stdout.write(frame, error => error ? reject(error) : resolve());
128
+ });
129
+ }
130
+
131
+ async function streamSessionFile(path, sessionId) {
132
+ const file = await open(path, "r");
133
+ try {
134
+ // Freeze the byte boundary, so a live append is picked up on the next sync
135
+ // rather than making this transfer grow indefinitely.
136
+ const { size } = await file.stat();
137
+ const total = Math.max(1, Math.ceil(size / SESSION_READ_BYTES));
138
+ const buffer = Buffer.allocUnsafe(SESSION_READ_BYTES);
139
+ const decoder = new StringDecoder("utf8");
140
+ let position = 0;
141
+ for (let seq = 0; seq < total; seq++) {
142
+ const wanted = Math.min(buffer.length, size - position);
143
+ let filled = 0;
144
+ while (filled < wanted) {
145
+ const { bytesRead } = await file.read(buffer, filled, wanted - filled, position + filled);
146
+ if (!bytesRead) break;
147
+ filled += bytesRead;
148
+ }
149
+ position += filled;
150
+ let data = decoder.write(buffer.subarray(0, filled));
151
+ if (seq === total - 1 || filled < wanted) data += decoder.end();
152
+ await sendSessionFrame({ type: "chunk", sessionId, seq, total, data });
153
+ if (filled < wanted) break; // A truncated file still ends the transfer.
154
+ }
155
+ } finally {
156
+ await file.close();
157
+ }
158
+ }
159
+
160
+ async function streamSessionText(text, sessionId) {
161
+ const total = Math.max(1, Math.ceil(text.length / SESSION_TEXT_CHARS));
162
+ for (let seq = 0; seq < total; seq++) {
163
+ await sendSessionFrame({
164
+ type: "chunk", sessionId, seq, total,
165
+ data: text.slice(seq * SESSION_TEXT_CHARS, (seq + 1) * SESSION_TEXT_CHARS)
166
+ });
167
+ }
168
+ }
169
+
135
170
  // --- session discovery ----------------------------------------------------
136
- // One entry per session: { source, sessionId, mtime, project?, title?, path }.
137
- // `path` is stripped before anything goes on the wire.
171
+ // One entry per session: { source, sessionId, mtime, size?, project?, title?, path }.
172
+ // `path` is stripped before anything goes on the wire. `size` is the file's
173
+ // byte length for the JSONL sources and is omitted for ZCode (a database row,
174
+ // not a file). The extension uses it to tell a session another app merely
175
+ // touched from one that changed; an extension that does not know the field
176
+ // ignores it, and one that sees no size falls back to comparing mtime alone.
138
177
 
139
178
  async function listClaudeCodeSessions(issues) {
140
179
  const sessions = [];
@@ -168,6 +207,7 @@ async function listClaudeCodeSessions(issues) {
168
207
  source: "claude_code",
169
208
  sessionId: file.replace(/\.jsonl$/, ""),
170
209
  mtime: Math.floor(info.mtimeMs),
210
+ size: info.size,
171
211
  project: entry.name,
172
212
  path
173
213
  });
@@ -216,6 +256,7 @@ async function walkCodexDir(dir, depth, out, issues) {
216
256
  source: "codex",
217
257
  sessionId: codexSessionId(entry.name),
218
258
  mtime: Math.floor(info.mtimeMs),
259
+ size: info.size,
219
260
  path
220
261
  });
221
262
  } catch {
@@ -770,7 +811,6 @@ async function handle(message) {
770
811
  // that's what an absent source resolves to — never a bare id match that
771
812
  // could hand back the wrong source's file.
772
813
  const wantSource = typeof message.source === "string" ? message.source : "claude_code";
773
- let text;
774
814
  if (wantSource === "zcode") {
775
815
  // No file to read: the transcript is materialized out of the database.
776
816
  // The session id is only ever a bound query parameter, never a path
@@ -780,7 +820,7 @@ async function handle(message) {
780
820
  send({ type: "session", sessionId: message.sessionId, notFound: true });
781
821
  return;
782
822
  }
783
- text = materialized;
823
+ await streamSessionText(materialized, message.sessionId);
784
824
  } else {
785
825
  const sessions = await listSessions();
786
826
  const match = sessions.find((s) => s.source === wantSource && s.sessionId === message.sessionId);
@@ -788,36 +828,9 @@ async function handle(message) {
788
828
  send({ type: "session", sessionId: message.sessionId, notFound: true });
789
829
  return;
790
830
  }
791
- text = await readFile(match.path, "utf8");
792
- }
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++) {
812
- send({
813
- type: "chunk",
814
- sessionId: message.sessionId,
815
- seq,
816
- total,
817
- data: chunks[seq] ?? ""
818
- });
831
+ await streamSessionFile(match.path, message.sessionId);
819
832
  }
820
- send({ type: "sessionDone", sessionId: message.sessionId });
833
+ await sendSessionFrame({ type: "sessionDone", sessionId: message.sessionId });
821
834
  return;
822
835
  }
823
836
  send({ type: "error", error: `unknown command: ${String(message.cmd)}` });
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@llmnesia/local-agent-host",
3
- "version": "0.3.2",
3
+ "version": "0.3.4",
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",