@llmnesia/local-agent-host 0.3.3 → 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.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
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.3`, 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
 
@@ -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,6 +116,57 @@ 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
171
  // One entry per session: { source, sessionId, mtime, size?, project?, title?, path }.
137
172
  // `path` is stripped before anything goes on the wire. `size` is the file's
@@ -776,7 +811,6 @@ async function handle(message) {
776
811
  // that's what an absent source resolves to — never a bare id match that
777
812
  // could hand back the wrong source's file.
778
813
  const wantSource = typeof message.source === "string" ? message.source : "claude_code";
779
- let text;
780
814
  if (wantSource === "zcode") {
781
815
  // No file to read: the transcript is materialized out of the database.
782
816
  // The session id is only ever a bound query parameter, never a path
@@ -786,7 +820,7 @@ async function handle(message) {
786
820
  send({ type: "session", sessionId: message.sessionId, notFound: true });
787
821
  return;
788
822
  }
789
- text = materialized;
823
+ await streamSessionText(materialized, message.sessionId);
790
824
  } else {
791
825
  const sessions = await listSessions();
792
826
  const match = sessions.find((s) => s.source === wantSource && s.sessionId === message.sessionId);
@@ -794,36 +828,9 @@ async function handle(message) {
794
828
  send({ type: "session", sessionId: message.sessionId, notFound: true });
795
829
  return;
796
830
  }
797
- text = await readFile(match.path, "utf8");
798
- }
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++) {
818
- send({
819
- type: "chunk",
820
- sessionId: message.sessionId,
821
- seq,
822
- total,
823
- data: chunks[seq] ?? ""
824
- });
831
+ await streamSessionFile(match.path, message.sessionId);
825
832
  }
826
- send({ type: "sessionDone", sessionId: message.sessionId });
833
+ await sendSessionFrame({ type: "sessionDone", sessionId: message.sessionId });
827
834
  return;
828
835
  }
829
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.3",
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",