@chatpanel/bridge 0.11.23 → 0.11.25

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.
Files changed (62) hide show
  1. package/README.md +7 -7
  2. package/package.json +1 -13
  3. package/scripts/sync-channels.mjs +8 -90
  4. package/scripts/sync-events.mjs +7 -78
  5. package/scripts/sync-pii.mjs +7 -68
  6. package/src/api-compat.js +5 -294
  7. package/src/channels/adapters/telegram.js +3 -298
  8. package/src/channels/bridge.js +1 -59
  9. package/src/channels/eventlog.js +3 -57
  10. package/src/channels/gateway.js +1 -114
  11. package/src/channels/invoke.js +1 -172
  12. package/src/channels/normalize.js +1 -58
  13. package/src/channels/pairing.js +1 -95
  14. package/src/channels/service.js +1 -329
  15. package/src/channels/stream.js +5 -104
  16. package/src/cli-errors.js +3 -136
  17. package/src/connections.js +1 -160
  18. package/src/connectors.js +1 -100
  19. package/src/engines/antigravity.js +5 -235
  20. package/src/engines/args.js +1 -47
  21. package/src/engines/claude.js +6 -586
  22. package/src/engines/cli-agents.js +7 -312
  23. package/src/engines/codex.js +6 -463
  24. package/src/engines/custom.js +17 -577
  25. package/src/engines/prompt.js +6 -32
  26. package/src/engines/stream-formats.js +2 -222
  27. package/src/entitlement.js +1 -77
  28. package/src/env.js +3 -628
  29. package/src/events/capability.js +1 -134
  30. package/src/events/event.js +1 -183
  31. package/src/events/reach.js +1 -31
  32. package/src/events/ref.js +1 -63
  33. package/src/events/scm-connection.js +1 -188
  34. package/src/events/scopes.js +1 -20
  35. package/src/events/skill-manifest.js +1 -338
  36. package/src/events/skill-scan.js +3 -217
  37. package/src/events/view.js +1 -96
  38. package/src/mcp-capabilities.js +2 -139
  39. package/src/mcp-local.js +0 -0
  40. package/src/mcp-quarantine.js +1 -110
  41. package/src/net.js +1 -107
  42. package/src/pii/index.js +1 -29
  43. package/src/pii/net.js +1 -111
  44. package/src/pii/pii-detect.js +2 -296
  45. package/src/pii/pii-redact.js +1 -470
  46. package/src/pii/pipeline.js +1 -137
  47. package/src/pii/sanitize.js +2 -179
  48. package/src/pii/tool-harness.js +1 -184
  49. package/src/pii/tool-rank.js +1 -110
  50. package/src/proc.js +2 -91
  51. package/src/relay-timeout.js +1 -21
  52. package/src/runs.js +1 -49
  53. package/src/sanitize.js +1 -7
  54. package/src/scm.js +1 -76
  55. package/src/server.js +10 -1492
  56. package/src/service.js +11 -176
  57. package/src/sign-in.js +1 -91
  58. package/src/skills.js +1 -399
  59. package/src/ssrf.js +1 -70
  60. package/src/update.js +1 -216
  61. package/src/workdir.js +1 -108
  62. package/src/worktree.js +3 -125
@@ -1,297 +1,3 @@
1
- // GENERATED — do not edit.
2
- // Source of truth: chatpanel-pii/pii-detect.js (npm @chatpanel/pii).
3
- // Edit there, then run: npm run sync:pii
4
- //
5
- // Vendored rather than depended on: the bridge ships zero runtime dependencies so a
6
- // curl one-liner install cannot fail on someone's registry, and so the compiled
7
- // single-file binary has nothing to resolve.
1
+ import{assertEndpointUrl as T}from"./net.js";const O=new Map,C=300;function $(){O.clear()}function p(e,t){let n=5381;const s=`${t?.backend}|${t?.url}|${t?.model}|${e}`;for(let r=0;r<s.length;r++)n=(n<<5)+n+s.charCodeAt(r)|0;return`${s.length}:${n}`}function h(e,t,n){return new Promise((s,r)=>{const o=setTimeout(()=>r(new Error("detect timeout")),Math.max(200,t||1500)),c=()=>{clearTimeout(o),r(new Error("aborted"))};n&&n.addEventListener?.("abort",c,{once:!0}),e.then(i=>{clearTimeout(o),s(i)},i=>{clearTimeout(o),r(i)})})}function m(e){const t=String(e||"ENTITY").toUpperCase().replace(/[^A-Z0-9]/g,"")||"ENTITY";return{PER:"PERSON",PERSON:"PERSON",PERSONNAME:"PERSON",GIVENNAME:"PERSON",FIRSTNAME:"PERSON",MIDDLENAME:"PERSON",SURNAME:"PERSON",LASTNAME:"PERSON",FULLNAME:"PERSON",ORG:"ORG",ORGANIZATION:"ORG",COMPANYNAME:"ORG",COMPANY:"ORG",GPE:"LOCATION",LOC:"LOCATION",LOCATION:"LOCATION",CITY:"LOCATION",STATE:"LOCATION",COUNTY:"LOCATION",COUNTRY:"LOCATION",STREET:"ADDRESS",BUILDINGNUM:"ADDRESS",BUILDINGNUMBER:"ADDRESS",ZIPCODE:"ADDRESS",POSTCODE:"ADDRESS",SECADDRESS:"ADDRESS",ADDRESS:"ADDRESS",NORP:"GROUP",EMAIL:"EMAIL",EMAILADDRESS:"EMAIL",PHONE:"PHONE",PHONENUMBER:"PHONE",TELEPHONENUM:"PHONE",PHONEIMEI:"ID",SOCIALNUM:"SSN",USSSN:"SSN",SSN:"SSN",CREDITCARDNUMBER:"CREDITCARD",CREDITCARD:"CREDITCARD",IBAN:"IBAN",IBANCODE:"IBAN",ACCOUNTNUM:"ID",ACCOUNTNUMBER:"ID",TAXNUM:"ID",IDCARDNUM:"ID",DRIVERLICENSENUM:"ID",PASSPORTNUM:"ID",VEHICLEVRM:"ID",DATEOFBIRTH:"ID",DOB:"ID",USERNAME:"ID",USERID:"ID",IP:"ID",IPADDRESS:"ID",MAC:"ID",PASSWORD:"SECRET",APIKEY:"SECRET",SECRET:"SECRET"}[t]||t}const P=new Set(["EMAIL","PHONE","SSN","CREDITCARD","IBAN","ID","SECRET"]),y=new Set(["LOCATION","FAC","ADDRESS","GROUP","NRP"]);function M(e,t,n){const s=o=>!n||n[o]!==!1;return P.has(t)?!0:t==="PERSON"?s("person"):t==="ORG"?s("org"):y.has(t)?s("location"):(String(e).match(/\d/g)||[]).length>=7?s("number"):!1}function f(e,t){let n=[];Array.isArray(e)?n=e:e&&Array.isArray(e.entities)?n=e.entities:e&&Array.isArray(e.ents)?n=e.ents:e&&Array.isArray(e.results)&&(n=e.results);const s=[],r=new Set;for(const o of n){if(!o)continue;const c=String(o.value??o.text??o.entity??o.word??"").trim(),i=m(o.type??o.label??o.entity_group??o.entity_type??o.tag);if(!c||c.length>200||!M(c,i,t))continue;const a=`${i}:${c.toLowerCase()}`;r.has(a)||(r.add(a),s.push({value:c,type:i}))}return s}function L(e){if(!e)return null;const t=String(e).indexOf("{"),n=String(e).lastIndexOf("}");if(t<0||n<=t)return null;try{return JSON.parse(String(e).slice(t,n+1))}catch{return null}}const g="You extract sensitive entities from text for redaction. Copy each value exactly as it appears. Include people, organizations, locations, and account/ID numbers. No commentary, no code fences.",U='Return ONLY JSON: {"entities":[{"value":"<verbatim text>","type":"PERSON|ORG|LOCATION|ID|EMAIL|PHONE|OTHER"}]}. No commentary, no code fences.',I=Object.freeze({block:"",format:null,parse:null});async function w(e,t,n,s){const r=await s(t.url,{method:"POST",headers:{"Content-Type":"application/json",...t.apiKey?{Authorization:`Bearer ${t.apiKey}`}:{}},body:JSON.stringify({text:e}),signal:n});if(!r.ok)throw new Error(`detect HTTP ${r.status}`);return f(await r.json(),t.types)}async function b(e,t,n,s,r=I){const o=String(t.url||"").replace(/\/$/,""),c=/\/chat\/completions$/.test(o)?o:/\/v\d+$/.test(o)?`${o}/chat/completions`:`${o}/v1/chat/completions`,i=`${g}
8
2
 
9
- // Phase 2: configurable, LOCAL entity detection.
10
- //
11
- // Produces [{value, type}] spans that feed the redaction engine, so names / orgs /
12
- // IDs get redacted WITHOUT a hand-maintained dictionary. Detection runs on-device
13
- // only — the detector is a local NER service (spaCy / Presidio / any HTTP service)
14
- // or a local LLM (OpenAI-compatible, e.g. a gemma served by llama.cpp). Raw text
15
- // reaches the detector but never the final agent; only the redacted text does.
16
- //
17
- // Performance / flexibility (the whole point):
18
- // - backends are pluggable and user-configured (URL + model + timeout).
19
- // - a content-hash cache avoids re-detecting unchanged text.
20
- // - a per-call timeout + fail-open means a slow/broken detector NEVER blocks the
21
- // chat — redaction silently falls back to the deterministic layer.
22
- // - input is length-capped so a huge transcript can't stall detection.
23
-
24
- import { assertEndpointUrl } from './net.js';
25
-
26
- const cache = new Map(); // key -> [{value,type}]
27
- const CACHE_MAX = 300;
28
-
29
- export function clearDetectCache() { cache.clear(); }
30
-
31
- function cacheKey(text, det) {
32
- let h = 5381;
33
- const s = `${det?.backend}|${det?.url}|${det?.model}|${text}`;
34
- for (let i = 0; i < s.length; i++) h = ((h << 5) + h + s.charCodeAt(i)) | 0;
35
- return `${s.length}:${h}`;
36
- }
37
-
38
- export function withTimeout(promise, ms, signal) {
39
- return new Promise((resolve, reject) => {
40
- const timer = setTimeout(() => reject(new Error('detect timeout')), Math.max(200, ms || 1500));
41
- const onAbort = () => { clearTimeout(timer); reject(new Error('aborted')); };
42
- if (signal) signal.addEventListener?.('abort', onAbort, { once: true });
43
- promise.then(
44
- (v) => { clearTimeout(timer); resolve(v); },
45
- (e) => { clearTimeout(timer); reject(e); },
46
- );
47
- });
48
- }
49
-
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.
70
- function normType(t) {
71
- const s = String(t || 'ENTITY').toUpperCase().replace(/[^A-Z0-9]/g, '') || 'ENTITY';
72
- const map = {
73
- // People
74
- PER: 'PERSON', PERSON: 'PERSON', PERSONNAME: 'PERSON',
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.
81
- GPE: 'LOCATION', LOC: 'LOCATION', LOCATION: 'LOCATION',
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',
101
- };
102
- return map[s] || s;
103
- }
104
-
105
- // Identifiers we ALWAYS redact (also caught deterministically). The user-facing
106
- // category toggles (person/org/location/number) control the rest, so geography
107
- // questions still work if "location" is turned off, etc. Numeric/temporal labels
108
- // (DATE, CARDINAL, ORDINAL…) are noisy — small NER models tag "today" / "4" — so
109
- // they only count when the value is a long digit run (phone/account/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']);
113
- const LOCATION_TYPES = new Set(['LOCATION', 'FAC', 'ADDRESS', 'GROUP', 'NRP']);
114
-
115
- function keepEntity(value, type, types) {
116
- const on = (k) => !types || types[k] !== false; // default on
117
- if (ALWAYS_KEEP.has(type)) return true;
118
- if (type === 'PERSON') return on('person');
119
- if (type === 'ORG') return on('org');
120
- if (LOCATION_TYPES.has(type)) return on('location');
121
- const digits = (String(value).match(/\d/g) || []).length;
122
- return digits >= 7 ? on('number') : false;
123
- }
124
-
125
- // Normalize the many detector response shapes to [{value, type}], de-duplicated.
126
- // `types` (optional) is the user's category toggles {person,org,location,number}.
127
- export function normalizeEntities(data, types) {
128
- let list = [];
129
- if (Array.isArray(data)) list = data;
130
- else if (data && Array.isArray(data.entities)) list = data.entities;
131
- else if (data && Array.isArray(data.ents)) list = data.ents; // spaCy displacy
132
- else if (data && Array.isArray(data.results)) list = data.results; // Presidio
133
- const out = [];
134
- const seen = new Set();
135
- for (const e of list) {
136
- if (!e) continue;
137
- const value = String(e.value ?? e.text ?? e.entity ?? e.word ?? '').trim();
138
- const type = normType(e.type ?? e.label ?? e.entity_group ?? e.entity_type ?? e.tag);
139
- if (!value || value.length > 200 || !keepEntity(value, type, types)) continue;
140
- const k = `${type}:${value.toLowerCase()}`;
141
- if (seen.has(k)) continue;
142
- seen.add(k);
143
- out.push({ value, type });
144
- }
145
- return out;
146
- }
147
-
148
- export function parseJsonLoose(s) {
149
- if (!s) return null;
150
- const a = String(s).indexOf('{');
151
- const b = String(s).lastIndexOf('}');
152
- if (a < 0 || b <= a) return null;
153
- try { return JSON.parse(String(s).slice(a, b + 1)); } catch { return null; }
154
- }
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.
160
- export const EXTRACT_SYS = 'You extract sensitive entities from text for redaction. '
161
- + 'Copy each value exactly as it appears. Include people, organizations, locations, and account/ID numbers. No commentary, no code fences.';
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
-
169
- async function detectViaEndpoint(text, det, signal, fetchImpl) {
170
- const res = await fetchImpl(det.url, {
171
- method: 'POST',
172
- headers: { 'Content-Type': 'application/json', ...(det.apiKey ? { Authorization: `Bearer ${det.apiKey}` } : {}) },
173
- body: JSON.stringify({ text }),
174
- signal,
175
- });
176
- if (!res.ok) throw new Error(`detect HTTP ${res.status}`);
177
- return normalizeEntities(await res.json(), det.types);
178
- }
179
-
180
- async function detectViaOpenAI(text, det, signal, fetchImpl, structured = NO_STRUCTURE) {
181
- const base = String(det.url || '').replace(/\/$/, '');
182
- // Build the chat URL the SAME way the chat path does. An OpenAI-compatible baseUrl
183
- // already ends in /v1 (Ollama, OpenRouter, NVIDIA, OpenAI…) → only add
184
- // /chat/completions (appending /v1/chat/completions would 404 on /v1/v1/…). A bare
185
- // host gets /v1/chat/completions; a full chat URL is used as-is.
186
- const url = /\/chat\/completions$/.test(base) ? base
187
- : /\/v\d+$/.test(base) ? `${base}/chat/completions`
188
- : `${base}/v1/chat/completions`;
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
- }
222
- const content = json?.choices?.[0]?.message?.content ?? json?.content ?? '';
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 */ }
242
- }
243
-
244
- // Returns [{value, type}] spans for `text`, or [] (fail-open) on any error/timeout.
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 } = {}) {
253
- const det = cfg?.detection;
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
- }
273
- const capped = String(text || '').slice(0, det.maxChars || 8000);
274
- if (capped.trim().length < 8) return [];
275
- const key = cacheKey(capped, det);
276
- if (!strict && cache.has(key)) return cache.get(key);
277
- const run = det.backend === 'endpoint' ? detectViaEndpoint : detectViaOpenAI;
278
- let ents = [];
279
- try {
280
- // SSRF guard before RAW (pre-redaction) text leaves for the detector: http(s)
281
- // only, never cloud metadata. Loopback/LAN allowed — a local NER server / Ollama
282
- // is the normal case. A blocked URL fails open (deterministic-only), or surfaces
283
- // to the Test button in strict mode.
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; }
290
- } catch (e) {
291
- if (strict) throw e; // surface errors to the Test button
292
- ents = []; // otherwise fail open — deterministic redaction still applies
293
- }
294
- if (cache.size >= CACHE_MAX) cache.clear();
295
- if (!strict) cache.set(key, ents);
296
- return ents;
297
- }
3
+ ${r.block||U}`,a=async S=>{const N=r.format?r.format(S):null,l=await s(c,{method:"POST",headers:{"Content-Type":"application/json",...t.apiKey?{Authorization:`Bearer ${t.apiKey}`}:{}},body:JSON.stringify({model:t.model||"local",temperature:0,max_tokens:t.maxTokens||256,messages:[{role:"system",content:i},{role:"user",content:e}],...N||{}}),signal:n});if(!l.ok){const R=new Error(`detect HTTP ${l.status}`);throw R.status=l.status,R}return l.json()};let E=null;if(r.format)for(const S of["schema","object","none"])try{E=await a(S);break}catch(N){if(S==="none"||N.status!==400&&N.status!==422)throw N}else E=await a("none");const A=E?.choices?.[0]?.message?.content??E?.content??"",u=r.parse?r.parse(A):L(A);return f(u,t.types)}function D(e,t,n,s,r,o){if(typeof e=="function")try{e({backend:t.backend||"",host:d(t.url),chars:n.length,entities:r,ms:Date.now()-s,ok:!o,error:o?String(o.message||o).slice(0,200):""})}catch{}}const d=e=>{try{return new URL(String(e)).host}catch{return""}};async function x(e,t,{signal:n,fetchImpl:s=globalThis.fetch,strict:r=!1,structured:o=I,onEgress:c=null}={}){const i=t?.detection;if(!i||!i.backend||i.backend==="off"||!i.url||typeof s!="function")return[];const a=i.transport==="in-process";if(a&&s===globalThis.fetch)throw new Error("detection.transport 'in-process' needs an injected fetch; refusing to treat a network call as in-process");const E=String(e||"").slice(0,i.maxChars||8e3);if(E.trim().length<8)return[];const A=p(E,i);if(!r&&O.has(A))return O.get(A);const u=i.backend==="endpoint"?w:b;let S=[];try{a||T(i.url);const N=Date.now();try{S=await h(u(E,i,n,s,o),i.timeoutMs||1500,n),a||D(c,i,E,N,S.length,null)}catch(l){throw a||D(c,i,E,N,0,l),l}}catch(N){if(r)throw N;S=[]}return O.size>=C&&O.clear(),r||O.set(A,S),S}export{g as EXTRACT_SYS,$ as clearDetectCache,x as detectEntities,f as normalizeEntities,L as parseJsonLoose,h as withTimeout};