@llmnesia/local-agent-host 0.3.3 → 0.3.5

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
@@ -4,6 +4,8 @@ A tiny local helper that lets the LLMnesia browser extension (1) index your loca
4
4
 
5
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
+ Claude Code project folders inside `~/.claude/projects` can be symbolic links to relocated folders. The helper reads session files directly inside each project folder without scanning nested folders. Broken or inaccessible project links are skipped and reported as a partial scan, so other projects can still sync.
8
+
7
9
  > 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
10
 
9
11
  ## Install
@@ -81,10 +83,12 @@ delete the retained data too.
81
83
 
82
84
  Native messaging over stdio (little-endian uint32 length prefix + UTF-8 JSON):
83
85
 
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.
86
+ Helper 0.3.5 reports protocol version 5 and supplies per-source scan health for
87
+ 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. It also discovers Claude Code projects relocated through symbolic links. To update the helper, run
88
+ `npx -y @llmnesia/local-agent-host@0.3.5`, then fully quit and reopen the browser.
89
+ MCP installers bundle their own helper copy. If an older MCP installer replaces
90
+ this helper, run the standalone helper update again afterward.
91
+ Session files stream in bounded blocks with output backpressure, so a large session does not require a second full in-memory chunk collection.
88
92
  Existing protocol-v4 helpers can still sync conversations; they cannot supply
89
93
  the new scan-health fields.
90
94
 
@@ -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
@@ -150,10 +185,18 @@ async function listClaudeCodeSessions(issues) {
150
185
  return sessions; // no ~/.claude/projects yet
151
186
  }
152
187
  for (const entry of projectDirs) {
188
+ const dir = join(PROJECTS_DIR, entry.name);
153
189
  if (!entry.isDirectory()) {
154
- continue;
190
+ if (!entry.isSymbolicLink()) continue;
191
+ try {
192
+ // Dirent describes the link itself. Follow relocated project folders,
193
+ // keeping the same one-level scan and project name used for real dirs.
194
+ if (!(await stat(dir)).isDirectory()) continue;
195
+ } catch {
196
+ if (issues) issues.failed += 1;
197
+ continue; // A broken, cyclic or inaccessible link cannot stop the scan.
198
+ }
155
199
  }
156
- const dir = join(PROJECTS_DIR, entry.name);
157
200
  let files;
158
201
  try {
159
202
  files = await readdir(dir);
@@ -776,7 +819,6 @@ async function handle(message) {
776
819
  // that's what an absent source resolves to — never a bare id match that
777
820
  // could hand back the wrong source's file.
778
821
  const wantSource = typeof message.source === "string" ? message.source : "claude_code";
779
- let text;
780
822
  if (wantSource === "zcode") {
781
823
  // No file to read: the transcript is materialized out of the database.
782
824
  // The session id is only ever a bound query parameter, never a path
@@ -786,7 +828,7 @@ async function handle(message) {
786
828
  send({ type: "session", sessionId: message.sessionId, notFound: true });
787
829
  return;
788
830
  }
789
- text = materialized;
831
+ await streamSessionText(materialized, message.sessionId);
790
832
  } else {
791
833
  const sessions = await listSessions();
792
834
  const match = sessions.find((s) => s.source === wantSource && s.sessionId === message.sessionId);
@@ -794,36 +836,9 @@ async function handle(message) {
794
836
  send({ type: "session", sessionId: message.sessionId, notFound: true });
795
837
  return;
796
838
  }
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
- });
839
+ await streamSessionFile(match.path, message.sessionId);
825
840
  }
826
- send({ type: "sessionDone", sessionId: message.sessionId });
841
+ await sendSessionFrame({ type: "sessionDone", sessionId: message.sessionId });
827
842
  return;
828
843
  }
829
844
  send({ type: "error", error: `unknown command: ${String(message.cmd)}` });
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@llmnesia/local-agent-host",
3
- "version": "0.3.3",
4
- "description": "LLMnesia native messaging host — lets the browser extension read local coding-agent sessions (Claude Code, Codex, ZCode) automatically.",
3
+ "version": "0.3.5",
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",