@chatpanel/bridge 0.11.8 → 0.11.10

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/package.json CHANGED
@@ -1,8 +1,8 @@
1
1
  {
2
2
  "name": "@chatpanel/bridge",
3
- "version": "0.11.8",
3
+ "version": "0.11.10",
4
4
  "type": "module",
5
- "description": "Local bridge that exposes the AI coding agents installed on your machine \u2014 Claude Code (CLI), Codex (CLI), and Antigravity CLI (formerly Gemini CLI, which remains available for business/enterprise) \u2014 to the ChatPanel Chrome extension over a localhost SSE endpoint. Bring your own agent.",
5
+ "description": "Local bridge that exposes the AI coding agents installed on your machine — Claude Code (CLI), Codex (CLI), and Antigravity CLI (formerly Gemini CLI, which remains available for business/enterprise) — to the ChatPanel Chrome extension over a localhost SSE endpoint. Bring your own agent.",
6
6
  "keywords": [
7
7
  "chatpanel",
8
8
  "claude-code",
package/src/env.js CHANGED
@@ -273,6 +273,52 @@ function stripBom(s) {
273
273
 
274
274
  // Version managers install CLIs under versioned bin dirs that a lazy-loaded
275
275
  // shell (nvm/fnm) doesn't export into a non-interactive service PATH. Add them.
276
+ /**
277
+ * The node version nvm would actually give you, and only that one.
278
+ *
279
+ * WHY THIS EXISTS. PATH discovery asks a LOGIN shell, which never reads .zshrc — and .zshrc
280
+ * is where nvm lives. So the learned PATH has no nvm in it, and the hardcoded fallbacks
281
+ * below take over. Those start with /opt/homebrew/bin, so a Homebrew copy of an agent CLI
282
+ * beat the one the user's terminal uses.
283
+ *
284
+ * One machine had Claude Code 2.1.268 under nvm and 2.1.175 under Homebrew. Every turn
285
+ * through the bridge answered "Claude Code 2.1.175 does not support this model" to a user
286
+ * who had just updated Claude Code — twice.
287
+ *
288
+ * `versionManagerBins` cannot fix that on its own: it lists EVERY installed version, in
289
+ * directory order, so preferring it wholesale would pick an arbitrary old node. This picks
290
+ * the one nvm itself would: the `default` alias if it names a version, else the highest
291
+ * installed. Pure filesystem reads — no shell, so nothing can block startup.
292
+ */
293
+ export function nvmCurrentBin(home = os.homedir(), env = process.env) {
294
+ const root = path.join(env.NVM_DIR || path.join(home, '.nvm'), 'versions', 'node');
295
+ let versions;
296
+ try {
297
+ versions = readdirSync(root).filter((v) => /^v\d+\./.test(v));
298
+ } catch {
299
+ return null; // no nvm on this machine
300
+ }
301
+ if (!versions.length) return null;
302
+
303
+ const byVersion = (a, b) => {
304
+ const pa = a.slice(1).split('.').map(Number);
305
+ const pb = b.slice(1).split('.').map(Number);
306
+ for (let i = 0; i < 3; i += 1) if ((pa[i] || 0) !== (pb[i] || 0)) return (pb[i] || 0) - (pa[i] || 0);
307
+ return 0;
308
+ };
309
+
310
+ // The `default` alias is what a new shell resolves to. It may name a version directly
311
+ // ("24.14.0"), or point at another alias ("lts/*"), which we do not chase — the highest
312
+ // installed is a better guess than a wrong one.
313
+ try {
314
+ const alias = readFileSync(path.join(env.NVM_DIR || path.join(home, '.nvm'), 'alias', 'default'), 'utf8').trim();
315
+ const want = alias.startsWith('v') ? alias : `v${alias}`;
316
+ if (versions.includes(want)) return path.join(root, want, 'bin');
317
+ } catch { /* no alias file — fall through */ }
318
+
319
+ return path.join(root, versions.sort(byVersion)[0], 'bin');
320
+ }
321
+
276
322
  function versionManagerBins(home) {
277
323
  const bins = [];
278
324
  const tryDir = (dir, sub) => {
@@ -501,7 +547,12 @@ export function enrichPath() {
501
547
  return;
502
548
  }
503
549
 
550
+ const nvmBin = nvmCurrentBin(home);
504
551
  const common = [
552
+ // BEFORE the package-manager dirs. A version manager PREPENDS itself to PATH in the
553
+ // user's shell, so its copy is the one their terminal runs — and the whole purpose of
554
+ // this list is to reproduce what the terminal would do.
555
+ ...(nvmBin ? [nvmBin] : []),
505
556
  '/opt/homebrew/bin',
506
557
  '/opt/homebrew/sbin',
507
558
  '/usr/local/bin',
@@ -523,6 +574,12 @@ export function enrichPath() {
523
574
  let shellPath = '';
524
575
  try {
525
576
  const shell = process.env.SHELL || '/bin/zsh';
577
+ // `-lc`, NOT `-ilc`, and deliberately: an INTERACTIVE shell can block on a prompt and
578
+ // hang the daemon's own startup. tests/env-startup.test.mjs holds that line.
579
+ //
580
+ // The cost is that a login shell does not read .zshrc/.bashrc, which is where nvm and
581
+ // friends install themselves — so this answer arrives WITHOUT the version manager, and
582
+ // the merge below has to supply it. See nvmCurrentBin().
526
583
  const r = spawnSync(shell, ['-lc', 'command -p echo "$PATH"'], {
527
584
  encoding: 'utf8',
528
585
  timeout: 4000,
@@ -534,6 +591,17 @@ export function enrichPath() {
534
591
 
535
592
  const seen = new Set();
536
593
  const merged = [
594
+ // THE VERSION MANAGER GOES FIRST, ahead even of the login shell's own answer.
595
+ //
596
+ // That looks aggressive until you see why the shell's answer is incomplete: `-lc` never
597
+ // reads .zshrc, which is where nvm installs itself, so the PATH we learn is the user's
598
+ // MINUS their version manager — while still containing /opt/homebrew/bin from .zprofile.
599
+ // Merging it first therefore hands Homebrew the win over a tool the user manages with
600
+ // nvm, which is the opposite of what their terminal does: nvm PREPENDS.
601
+ //
602
+ // So we put it back where nvm would have. `nvmCurrentBin` resolves the one version nvm
603
+ // itself would pick, from the filesystem, with no shell to block on.
604
+ ...(nvmBin ? [nvmBin] : []),
537
605
  ...(shellPath ? shellPath.split(':') : []),
538
606
  ...(process.env.PATH ? process.env.PATH.split(path.delimiter) : []),
539
607
  ...common,
package/src/events/ref.js CHANGED
@@ -17,7 +17,10 @@
17
17
  // version of the note, because that would make replay quietly wrong instead of loudly
18
18
  // incomplete.
19
19
 
20
- export const REF_KINDS = Object.freeze(['note', 'meeting', 'chat', 'page', 'result', 'blob']);
20
+ // `memory` and `brief` joined when the derived layer landed: a brief's claim cites the
21
+ // record it came from, and a claim the USER stated cites the memory they stated it in.
22
+ // Additive — no existing ref changes meaning.
23
+ export const REF_KINDS = Object.freeze(['note', 'meeting', 'chat', 'page', 'result', 'blob', 'memory', 'brief']);
21
24
 
22
25
  export const RESOLUTION = Object.freeze({
23
26
  EXACT: 'exact', // blob present, hash matches
@@ -47,15 +47,57 @@ export function withTimeout(promise, ms, signal) {
47
47
  });
48
48
  }
49
49
 
50
- // Map common NER labels (spaCy, HF, Presidio) onto our placeholder types.
50
+ // Map common NER labels onto our placeholder types.
51
+ //
52
+ // FOUR VOCABULARIES, not one, and an unmapped label is SILENTLY DROPPED — `keepEntity` sends
53
+ // anything it does not recognise to the digit-count fallback, where a name has no digits and
54
+ // fails. So a missing row here does not degrade redaction, it turns it off for that type,
55
+ // with nothing on screen to say so.
56
+ //
57
+ // That is not hypothetical. The `multilang-pii-ner` model emits the ai4privacy vocabulary —
58
+ // GIVENNAME, SURNAME, TELEPHONENUM, CITY — and none of those were mapped, so selecting it
59
+ // (it is the default in some builds) meant person names sailed through to the model in
60
+ // plaintext while the shield in the composer still read as on. The deterministic detectors
61
+ // kept catching emails and card numbers, which is exactly what made it hard to notice.
62
+ //
63
+ // • spaCy / OntoNotes PER, ORG, GPE, LOC, NORP
64
+ // • HF bert-base-NER PER, ORG, LOC, MISC
65
+ // • Presidio PERSON, PHONE_NUMBER, EMAIL_ADDRESS, US_SSN…
66
+ // • ai4privacy / multilang GIVENNAME, SURNAME, STREET, ZIPCODE, TELEPHONENUM…
67
+ //
68
+ // When adding a model, run one sentence through it and map every label it returns. An
69
+ // unrecognised label is a hole, and it is an invisible one.
51
70
  function normType(t) {
52
71
  const s = String(t || 'ENTITY').toUpperCase().replace(/[^A-Z0-9]/g, '') || 'ENTITY';
53
72
  const map = {
73
+ // People
54
74
  PER: 'PERSON', PERSON: 'PERSON', PERSONNAME: 'PERSON',
55
- ORG: 'ORG', ORGANIZATION: 'ORG',
75
+ GIVENNAME: 'PERSON', FIRSTNAME: 'PERSON', MIDDLENAME: 'PERSON',
76
+ SURNAME: 'PERSON', LASTNAME: 'PERSON', FULLNAME: 'PERSON',
77
+ // Organisations
78
+ ORG: 'ORG', ORGANIZATION: 'ORG', COMPANYNAME: 'ORG', COMPANY: 'ORG',
79
+ // Places. An address PART is still an address — a building number and a postcode
80
+ // identify a household as surely as the street does.
56
81
  GPE: 'LOCATION', LOC: 'LOCATION', LOCATION: 'LOCATION',
57
- NORP: 'GROUP', EMAIL: 'EMAIL', EMAILADDRESS: 'EMAIL',
58
- PHONE: 'PHONE', PHONENUMBER: 'PHONE',
82
+ CITY: 'LOCATION', STATE: 'LOCATION', COUNTY: 'LOCATION', COUNTRY: 'LOCATION',
83
+ STREET: 'ADDRESS', BUILDINGNUM: 'ADDRESS', BUILDINGNUMBER: 'ADDRESS',
84
+ ZIPCODE: 'ADDRESS', POSTCODE: 'ADDRESS', SECADDRESS: 'ADDRESS', ADDRESS: 'ADDRESS',
85
+ NORP: 'GROUP',
86
+ // Contact
87
+ EMAIL: 'EMAIL', EMAILADDRESS: 'EMAIL',
88
+ PHONE: 'PHONE', PHONENUMBER: 'PHONE', TELEPHONENUM: 'PHONE', PHONEIMEI: 'ID',
89
+ // Numbers that identify a person. These are ALWAYS redacted (see ALWAYS_KEEP), which is
90
+ // the point of naming them rather than leaving them to the digit-count fallback.
91
+ SOCIALNUM: 'SSN', USSSN: 'SSN', SSN: 'SSN',
92
+ CREDITCARDNUMBER: 'CREDITCARD', CREDITCARD: 'CREDITCARD',
93
+ IBAN: 'IBAN', IBANCODE: 'IBAN',
94
+ ACCOUNTNUM: 'ID', ACCOUNTNUMBER: 'ID', TAXNUM: 'ID', IDCARDNUM: 'ID',
95
+ DRIVERLICENSENUM: 'ID', PASSPORTNUM: 'ID', VEHICLEVRM: 'ID',
96
+ // A date of birth identifies; a plain date does not, and small models tag "today".
97
+ DATEOFBIRTH: 'ID', DOB: 'ID',
98
+ // Handles and secrets
99
+ USERNAME: 'ID', USERID: 'ID', IP: 'ID', IPADDRESS: 'ID', MAC: 'ID',
100
+ PASSWORD: 'SECRET', APIKEY: 'SECRET', SECRET: 'SECRET',
59
101
  };
60
102
  return map[s] || s;
61
103
  }
@@ -65,7 +107,9 @@ function normType(t) {
65
107
  // questions still work if "location" is turned off, etc. Numeric/temporal labels
66
108
  // (DATE, CARDINAL, ORDINAL…) are noisy — small NER models tag "today" / "4" — so
67
109
  // they only count when the value is a long digit run (phone/account/ID).
68
- const ALWAYS_KEEP = new Set(['EMAIL', 'PHONE', 'SSN', 'CREDITCARD', 'IBAN', 'ID']);
110
+ // SECRET joined these: a password or a key must never reach a model, and leaving it to the
111
+ // per-category toggles would let "turn off numbers" switch it off.
112
+ const ALWAYS_KEEP = new Set(['EMAIL', 'PHONE', 'SSN', 'CREDITCARD', 'IBAN', 'ID', 'SECRET']);
69
113
  const LOCATION_TYPES = new Set(['LOCATION', 'FAC', 'ADDRESS', 'GROUP', 'NRP']);
70
114
 
71
115
  function keepEntity(value, type, types) {
@@ -208,6 +252,24 @@ const hostOf = (u) => { try { return new URL(String(u)).host; } catch { return '
208
252
  export async function detectEntities(text, cfg, { signal, fetchImpl = globalThis.fetch, strict = false, structured = NO_STRUCTURE, onEgress = null } = {}) {
209
253
  const det = cfg?.detection;
210
254
  if (!det || !det.backend || det.backend === 'off' || !det.url || typeof fetchImpl !== 'function') return [];
255
+ // AN IN-PROCESS DETECTOR SENDS NOTHING ANYWHERE, so the network guard below must not
256
+ // judge it by a URL it never dials.
257
+ //
258
+ // This is not a hypothetical. A host that runs the model in its own process passes a
259
+ // sentinel URL and a fetchImpl that ignores it entirely — and the sentinel failed the
260
+ // http(s) scheme check, threw, and was swallowed by the fail-open path. The result was a
261
+ // detector that reported itself ready, answered its own health route correctly, and
262
+ // contributed NOTHING to a single redaction: names, organisations and places went to the
263
+ // model in full while the UI said full tier.
264
+ //
265
+ // The opt-out is deliberately narrow. It requires the caller to have supplied its OWN
266
+ // fetch, so a `transport: 'in-process'` line in a config file cannot turn the SSRF guard
267
+ // off for a real network address — without an injected transport there is no in-process
268
+ // anything, and the flag is refused rather than honoured.
269
+ const inProcess = det.transport === 'in-process';
270
+ if (inProcess && fetchImpl === globalThis.fetch) {
271
+ throw new Error("detection.transport 'in-process' needs an injected fetch; refusing to treat a network call as in-process");
272
+ }
211
273
  const capped = String(text || '').slice(0, det.maxChars || 8000);
212
274
  if (capped.trim().length < 8) return [];
213
275
  const key = cacheKey(capped, det);
@@ -219,12 +281,12 @@ export async function detectEntities(text, cfg, { signal, fetchImpl = globalThis
219
281
  // only, never cloud metadata. Loopback/LAN allowed — a local NER server / Ollama
220
282
  // is the normal case. A blocked URL fails open (deterministic-only), or surfaces
221
283
  // to the Test button in strict mode.
222
- assertEndpointUrl(det.url);
284
+ if (!inProcess) assertEndpointUrl(det.url);
223
285
  const t0 = Date.now();
224
286
  try {
225
287
  ents = await withTimeout(run(capped, det, signal, fetchImpl, structured), det.timeoutMs || 1500, signal);
226
- report(onEgress, det, capped, t0, ents.length, null);
227
- } catch (e) { report(onEgress, det, capped, t0, 0, e); throw e; }
288
+ if (!inProcess) report(onEgress, det, capped, t0, ents.length, null);
289
+ } catch (e) { if (!inProcess) report(onEgress, det, capped, t0, 0, e); throw e; }
228
290
  } catch (e) {
229
291
  if (strict) throw e; // surface errors to the Test button
230
292
  ents = []; // otherwise fail open — deterministic redaction still applies
@@ -30,6 +30,46 @@ import { stripHidden, confusablesSkeleton } from './sanitize.js';
30
30
 
31
31
  const TOKEN_RE = /\[\[([A-Z][A-Z0-9]*)_(\d+)\]\]/g;
32
32
 
33
+ /**
34
+ * THE TOKEN FORMAT, PUBLISHED — because `[[TYPE_n]]` collides with `[[wikilink]]`.
35
+ *
36
+ * The placeholder grammar was chosen to be visually obvious in a prompt, and it is
37
+ * character-for-character the wikilink syntax notes and briefs use. So `[[PERSON_1]]` in a
38
+ * stored message reads as a link to a page called "PERSON_1", and downstream that became a
39
+ * backlink, a graph node, and a subject with its own page. The name of a person we
40
+ * deliberately did not learn was being filed as a thing we know about.
41
+ *
42
+ * A placeholder is the ABSENCE of an identity. It must never become a link, a subject, a tag
43
+ * or a topic — and it must never be restored into anything derived and persisted, because
44
+ * that would put the PII back on disk in a second place.
45
+ *
46
+ * Exported rather than left private so consumers ASK instead of re-deriving the pattern:
47
+ * this package owns the format, and `CLAUDE.md` lists it as a wire contract that only
48
+ * changes additively.
49
+ */
50
+ export const REDACTION_TOKEN_TYPES = Object.freeze([
51
+ 'PERSON', 'ORG', 'LOCATION', 'ADDRESS', 'EMAIL', 'PHONE', 'ID', 'SSN', 'IBAN',
52
+ 'CREDITCARD', 'CARD', 'POST', 'FAC', 'GROUP', 'NRP', 'ENTITY', 'KEY', 'SECRET',
53
+ 'TERM', 'PII', 'OTHER',
54
+ ]);
55
+
56
+ /**
57
+ * Is this bare string one of OUR placeholders?
58
+ *
59
+ * Matched against the known type vocabulary rather than the bare `[A-Z]+_\d+` shape, and
60
+ * that holds even inside brackets: `[[Q3_2026]]` and `[[PHASE_2]]` are links people
61
+ * genuinely write, so a shape test would trade one invisible bug for another. A custom
62
+ * dictionary type is the accepted gap — it is user-chosen, so a downstream consumer filing
63
+ * it is a name the user picked, not a stranger's identity.
64
+ *
65
+ * Bracket-tolerant: callers ask both before and after a wikilink parser has stripped them.
66
+ */
67
+ export function isRedactionToken(value) {
68
+ const bare = String(value ?? '').trim().replace(/^\[{1,2}|\]{1,2}$/g, '');
69
+ const m = /^([A-Z][A-Z0-9]*)_\d+$/.exec(bare);
70
+ return !!m && REDACTION_TOKEN_TYPES.includes(m[1]);
71
+ }
72
+
33
73
  // Bracket-TOLERANT match of the same token. Smaller models routinely drop or mangle
34
74
  // the [[ ]] when echoing a placeholder into tool-call JSON — e.g. they emit "ORG_1"
35
75
  // or "[ORG_1]" instead of "[[ORG_1]]" — which the strict TOKEN_RE misses, leaving
@@ -347,6 +387,37 @@ export function restoreWithAliases(text, vault) {
347
387
  return out;
348
388
  }
349
389
 
390
+ /**
391
+ * THE LAST LINE BEFORE A HUMAN READS IT.
392
+ *
393
+ * `restoreText` undoes what a given vault minted. This asks the harder question a UI has to
394
+ * answer: is there ANY placeholder left in what I am about to show? A reply is redacted for
395
+ * the model's benefit, never the reader's — so a token reaching the screen is always a bug,
396
+ * and one that is invisible to the code that caused it, because by then the turn is over.
397
+ *
398
+ * It exists because a turn can mint tokens in one vault and be restored against another (or
399
+ * against none): a local agent under "redact for remote only" gets no vault at all, while
400
+ * tool results reaching it may already carry placeholders from somewhere else. Every one of
401
+ * those paths ends at the same render call, so the check belongs there.
402
+ *
403
+ * Returns `{ text, unresolved }` — restored where the vault knows the token, and the list of
404
+ * the ones it could not, so the caller can decide (mask, warn, log) rather than silently
405
+ * shipping `[[PERSON_5]]` to a person reading about their own colleagues.
406
+ */
407
+ export function scrubPlaceholders(text, vault) {
408
+ const src = String(text ?? '');
409
+ if (!src) return { text: src, unresolved: [] };
410
+ const unresolved = [];
411
+ const out = src.replace(TOKEN_RE, (match) => {
412
+ const value = vault?.byToken?.get(match);
413
+ if (value != null) return value;
414
+ unresolved.push(match);
415
+ return match;
416
+ });
417
+ TOKEN_RE.lastIndex = 0;
418
+ return { text: out, unresolved };
419
+ }
420
+
350
421
  // True if the text still contains any redaction placeholder (useful for streaming
351
422
  // restore — buffer a tail when a token may be split across chunks).
352
423
  export function hasToken(text) {
package/src/server.js CHANGED
@@ -67,7 +67,7 @@ import {
67
67
  // Hardcoded (not read from package.json) so it survives Bun's single-file
68
68
  // --compile, where package.json isn't on a readable FS. CI fails the publish if
69
69
  // this drifts from package.json, so the two can't silently diverge.
70
- const VERSION = '0.11.8';
70
+ const VERSION = '0.11.10';
71
71
  const HOST = process.env.CHATPANEL_BRIDGE_HOST || '127.0.0.1';
72
72
  const PORT = Number(process.env.CHATPANEL_BRIDGE_PORT) || 4319;
73
73