@chatpanel/bridge 0.11.7 → 0.11.8

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