@chatpanel/bridge 0.11.7 → 0.11.9

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.7",
3
+ "version": "0.11.9",
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/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) {
@@ -109,10 +153,19 @@ export function parseJsonLoose(s) {
109
153
  try { return JSON.parse(String(s).slice(a, b + 1)); } catch { return null; }
110
154
  }
111
155
 
156
+ // The instruction WITHOUT the shape. The shape now comes from ENTITIES_SCHEMA in
157
+ // `@chatpanel/events` — the one object that renders the prompt block, builds the
158
+ // `response_format` a server enforces, and reads the reply. INJECTED, not imported: this
159
+ // package ships zero dependencies so the bridge can vendor it. A host without it still works.
112
160
  export const EXTRACT_SYS = 'You extract sensitive entities from text for redaction. '
113
- + 'Return ONLY JSON: {"entities":[{"value":"<verbatim text>","type":"PERSON|ORG|LOCATION|ID|EMAIL|PHONE|OTHER"}]}. '
114
161
  + 'Copy each value exactly as it appears. Include people, organizations, locations, and account/ID numbers. No commentary, no code fences.';
115
162
 
163
+ const FALLBACK_SHAPE = 'Return ONLY JSON: {"entities":[{"value":"<verbatim text>",'
164
+ + '"type":"PERSON|ORG|LOCATION|ID|EMAIL|PHONE|OTHER"}]}. No commentary, no code fences.';
165
+
166
+ // The seam: { block, format(mode), parse(text) }. Absent, everything below behaves as before.
167
+ const NO_STRUCTURE = Object.freeze({ block: '', format: null, parse: null });
168
+
116
169
  async function detectViaEndpoint(text, det, signal, fetchImpl) {
117
170
  const res = await fetchImpl(det.url, {
118
171
  method: 'POST',
@@ -124,7 +177,7 @@ async function detectViaEndpoint(text, det, signal, fetchImpl) {
124
177
  return normalizeEntities(await res.json(), det.types);
125
178
  }
126
179
 
127
- async function detectViaOpenAI(text, det, signal, fetchImpl) {
180
+ async function detectViaOpenAI(text, det, signal, fetchImpl, structured = NO_STRUCTURE) {
128
181
  const base = String(det.url || '').replace(/\/$/, '');
129
182
  // Build the chat URL the SAME way the chat path does. An OpenAI-compatible baseUrl
130
183
  // already ends in /v1 (Ollama, OpenRouter, NVIDIA, OpenAI…) → only add
@@ -133,27 +186,90 @@ async function detectViaOpenAI(text, det, signal, fetchImpl) {
133
186
  const url = /\/chat\/completions$/.test(base) ? base
134
187
  : /\/v\d+$/.test(base) ? `${base}/chat/completions`
135
188
  : `${base}/v1/chat/completions`;
136
- const res = await fetchImpl(url, {
137
- method: 'POST',
138
- headers: { 'Content-Type': 'application/json', ...(det.apiKey ? { Authorization: `Bearer ${det.apiKey}` } : {}) },
139
- body: JSON.stringify({
140
- model: det.model || 'local',
141
- temperature: 0,
142
- max_tokens: det.maxTokens || 256,
143
- messages: [{ role: 'system', content: EXTRACT_SYS }, { role: 'user', content: text }],
144
- }),
145
- signal,
146
- });
147
- if (!res.ok) throw new Error(`detect HTTP ${res.status}`);
148
- const json = await res.json();
189
+ const sys = `${EXTRACT_SYS}\n\n${structured.block || FALLBACK_SHAPE}`;
190
+ const ask = async (mode) => {
191
+ const fmt = structured.format ? structured.format(mode) : null;
192
+ const res = await fetchImpl(url, {
193
+ method: 'POST',
194
+ headers: { 'Content-Type': 'application/json', ...(det.apiKey ? { Authorization: `Bearer ${det.apiKey}` } : {}) },
195
+ body: JSON.stringify({
196
+ model: det.model || 'local',
197
+ temperature: 0,
198
+ max_tokens: det.maxTokens || 256,
199
+ messages: [{ role: 'system', content: sys }, { role: 'user', content: text }],
200
+ ...(fmt || {}),
201
+ }),
202
+ signal,
203
+ });
204
+ // 400/422 is the server saying it does not understand the body — a different thing from
205
+ // being down, and the only one worth retrying with a weaker one.
206
+ if (!res.ok) { const e = new Error(`detect HTTP ${res.status}`); e.status = res.status; throw e; }
207
+ return res.json();
208
+ };
209
+
210
+ // Grammar first, then plain JSON mode, then nothing. `json_schema` constrains the decoder to
211
+ // this exact shape — the difference between a 3B local model that answers and one that
212
+ // writes a paragraph — but many servers reject the field, so each rung is tried once.
213
+ let json = null;
214
+ if (structured.format) {
215
+ for (const mode of ['schema', 'object', 'none']) {
216
+ try { json = await ask(mode); break; }
217
+ catch (e) { if (mode === 'none' || (e.status !== 400 && e.status !== 422)) throw e; }
218
+ }
219
+ } else {
220
+ json = await ask('none');
221
+ }
149
222
  const content = json?.choices?.[0]?.message?.content ?? json?.content ?? '';
150
- return normalizeEntities(parseJsonLoose(content), det.types);
223
+ // The schema-aligned reader when the host has one; the loose slice otherwise.
224
+ const parsed = structured.parse ? structured.parse(content) : parseJsonLoose(content);
225
+ return normalizeEntities(parsed, det.types);
226
+ }
227
+
228
+ // Never throws: an egress record that could break redaction is worse than no record.
229
+ function report(onEgress, det, sent, t0, count, err) {
230
+ if (typeof onEgress !== 'function') return;
231
+ try {
232
+ onEgress({
233
+ backend: det.backend || '',
234
+ host: hostOf(det.url),
235
+ chars: sent.length,
236
+ entities: count,
237
+ ms: Date.now() - t0,
238
+ ok: !err,
239
+ error: err ? String(err.message || err).slice(0, 200) : '',
240
+ });
241
+ } catch { /* observability must never be the reason detection fails */ }
151
242
  }
152
243
 
153
244
  // Returns [{value, type}] spans for `text`, or [] (fail-open) on any error/timeout.
154
- export async function detectEntities(text, cfg, { signal, fetchImpl = globalThis.fetch, strict = false } = {}) {
245
+ // `onEgress` reports that RAW text left for a detector — the FACT, never the text. This is
246
+ // the one call that sends un-redacted content off the device (you cannot redact before you
247
+ // have detected); it is SSRF-guarded but was logged nowhere, and det.url accepts any public
248
+ // host. Injected, like `structured`: this package has no logger. The record carries the HOST
249
+ // (never the full URL, which can hold a token) and counts — never values.
250
+ const hostOf = (u) => { try { return new URL(String(u)).host; } catch { return ''; } };
251
+
252
+ export async function detectEntities(text, cfg, { signal, fetchImpl = globalThis.fetch, strict = false, structured = NO_STRUCTURE, onEgress = null } = {}) {
155
253
  const det = cfg?.detection;
156
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
+ }
157
273
  const capped = String(text || '').slice(0, det.maxChars || 8000);
158
274
  if (capped.trim().length < 8) return [];
159
275
  const key = cacheKey(capped, det);
@@ -165,8 +281,12 @@ export async function detectEntities(text, cfg, { signal, fetchImpl = globalThis
165
281
  // only, never cloud metadata. Loopback/LAN allowed — a local NER server / Ollama
166
282
  // is the normal case. A blocked URL fails open (deterministic-only), or surfaces
167
283
  // to the Test button in strict mode.
168
- assertEndpointUrl(det.url);
169
- ents = await withTimeout(run(capped, det, signal, fetchImpl), det.timeoutMs || 1500, signal);
284
+ if (!inProcess) assertEndpointUrl(det.url);
285
+ const t0 = Date.now();
286
+ try {
287
+ ents = await withTimeout(run(capped, det, signal, fetchImpl, structured), det.timeoutMs || 1500, signal);
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; }
170
290
  } catch (e) {
171
291
  if (strict) throw e; // surface errors to the Test button
172
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.7';
70
+ const VERSION = '0.11.9';
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