@chatpanel/gateway 0.119.0 → 0.120.1
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 +4 -4
- package/src/ner-engine.js +1 -1
- package/src/redact.js +1 -1
- package/src/server.js +1 -1
- package/src/version.js +1 -1
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@chatpanel/gateway",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.120.1",
|
|
4
4
|
"description": "Local privacy gateway — redacts PII out of OpenAI/Anthropic API traffic before it reaches a model, then restores it in the reply. Point opencode, codex, aider, Claude Code, etc. at it.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"bin": {
|
|
@@ -23,9 +23,9 @@
|
|
|
23
23
|
},
|
|
24
24
|
"dependencies": {
|
|
25
25
|
"@anthropic-ai/sandbox-runtime": "^0.0.77",
|
|
26
|
-
"@chatpanel/bridge": "^0.
|
|
27
|
-
"@chatpanel/events": "^0.
|
|
28
|
-
"@chatpanel/pii": "^0.15.
|
|
26
|
+
"@chatpanel/bridge": "^0.48.0",
|
|
27
|
+
"@chatpanel/events": "^0.396.3",
|
|
28
|
+
"@chatpanel/pii": "^0.15.6",
|
|
29
29
|
"@huggingface/transformers": "^4.2.0",
|
|
30
30
|
"defuddle": "^0.19.4",
|
|
31
31
|
"fflate": "^0.8.3",
|
package/src/ner-engine.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import q from"node:os";import{join as S}from"node:path";import{existsSync as K,mkdirSync as ft,readdirSync as V,readFileSync as pt}from"node:fs";import{DEFAULT_MODEL as X,isMirroredModel as dt}from"./models.js";import{isLoopbackHost as ht,isPrivateHost as mt,isMetadataHost as gt}from"@chatpanel/pii";import{recaseForDetection as yt}from"@chatpanel/pii/pii-detect.js";import{recasedSpanOk as wt}from"@chatpanel/pii/recased-spans.js";import{verifyModelWeights as _t}from"./model-integrity.js";import{runtimeName as Mt}from"./model-runtime.js";import{nativeOrtFailure as xt}from"./ort.js";import{makeWarmTimer as Z}from"./warm-timer.js";import{makeModelFileCache as bt}from"./model-file-cache.js";import{modelFetch as Lt}from"./model-sources.js";import{onLane as Tt}from"./inference-lane.js";const C="https://huggingface.co/";function At(t=process.env){const e=t.CHATPANEL_MODEL_BASE_URL?"CHATPANEL_MODEL_BASE_URL":"registries.models",r=t.CHATPANEL_MODEL_BASE_URL||t.CHATPANEL_REGISTRY_MODELS;if(!r)return C;const n=l=>(console.warn(`[models] ignoring ${e} (${r}): ${l} — using ${C}`),C);let o;try{o=new URL(r)}catch{return n("not a valid URL")}if(o.protocol!=="http:"&&o.protocol!=="https:")return n(`scheme ${o.protocol} not allowed`);if(gt(o.hostname))return n("points at cloud metadata");const s=ht(o.hostname)||mt(o.hostname);return o.protocol==="http:"&&!s?n("plaintext http:// to a public host (use https or a LAN/loopback mirror)"):(console.warn(`[models] ⚠ model weights will be downloaded from ${o.origin} (${e}), not ${C}`),r.replace(/\/*$/,"/"))}const I=At();let h="off",y=null,w=null,b=null,T=null,E=null,L=null,m=null,M=null,N=0,H=null;const g=new Map;let tt=Promise.resolve();function oe({host:t=null,allowRemote:e=!1}={},r){const n=tt.then(async()=>{const o=await z(),s=o.env.remoteHost,l=o.env.allowRemoteModels;try{o.env.allowRemoteModels=e,t&&(o.env.remoteHost=t)}catch{}try{return await r(o)}finally{try{o.env.remoteHost=s,o.env.allowRemoteModels=l}catch{}}});return tt=n.catch(()=>{}),n}function P(){return process.env.CHATPANEL_MODELS_DIR||S(q.homedir(),".chatpanel","models")}function R(t=y||X){const e=S(P(),...t.split("/"));return K(S(e,"onnx","model_quantized.onnx"))||K(S(e,"onnx","model.onnx"))}function re(){const t=P(),e=[];try{for(const r of V(t,{withFileTypes:!0}))if(r.isDirectory())for(const n of V(S(t,r.name),{withFileTypes:!0})){if(!n.isDirectory())continue;const o=`${r.name}/${n.name}`;R(o)&&St(S(t,r.name,n.name))&&e.push(o)}}catch{}return e}function St(t){try{return(JSON.parse(pt(S(t,"config.json"),"utf8")).architectures||[]).some(r=>/ForTokenClassification$/.test(String(r)))}catch{return!1}}function se(){return h}function O(){return h==="ready"&&!!w}function ie(){return{configured:h!=="off",ok:O(),state:h,model:y,error:b,runtime:Mt(),dtype:w?"q8":null,stats:Ft(),companions:Et(),warmMs:M?.warmMs??null}}async function Ot(t,{signal:e,strict:r=!1}={}){if(!O())return[];if(e?.aborted)return[];const n=String(t||""),o=await et(n,e);if(!o)return[];const s=[];for(const f of o||[]){if(nt(f,r))continue;let a=String(f.word??"");const u=f.entity_group??f.entity??"ENTITY";if(a.startsWith("##")&&s.length&&s[s.length-1].type===u){s[s.length-1].value+=a.slice(2);continue}a=a.replace(/##/g,"").trim(),a&&s.push({value:a,type:u})}const l=new Set,c=[];for(const f of s){const a=Wt(n,Dt(n,f.value.trim()));if(a.length<=1)continue;const u=`${f.type}:${a.toLowerCase()}`;l.has(u)||(l.add(u),c.push({value:a,type:f.type}))}return c}async function et(t,e){N++;try{return await vt(t,e)}finally{N--,$()||M?.arm()}}async function vt(t,e){const r=performance.now(),n=[],o=[{text:t,key:"orig"}];if(F){const s=yt(t);s.changed&&o.push({text:s.text,key:"recased"})}for(const{model:s,pipe:l}of st())for(const c of o){let f=0;for(const a of Nt(c.text,l.tokenizer)){if(e?.aborted)return null;const u=c.text.indexOf(a,f),d=await Tt(()=>l(a,{aggregation_strategy:"simple"}));for(const i of d||[])n.push({...i,_win:u<0?f:u,_winText:a,_model:s,_pass:c.key,_passText:c.text});u>=0&&(f=Math.max(f,u+1))}}return Rt(performance.now()-r,t.length,n.length),n}let F=!0;function ae(t){F=t!==!1}const nt=(t,e)=>!e&&t._pass==="recased"&&!wt(String(t.word??"").replace(/##/g,""),t.entity_group??t.entity);async function le(t,{signal:e,strict:r=!1}={}){if(!O())return[];const n=String(t||""),o=await et(n,e);if(!o)return[];const s=[],l=new Set;let c=-1,f=-1,a=null,u=null;for(const i of o){if(nt(i,r))continue;const p=String(i.word??"").replace(/##/g,"").trim();if(!p)continue;(i._win!==f||i._model!==a||i._pass!==u)&&(f=i._win,a=i._model,u=i._pass,c=i._win);const v=i._passText||n;let x=v.indexOf(p,c);if(x<0&&(x=v.indexOf(p,i._win)),x<0)continue;let A=x+p.length;c=A;const Y=Q=>!!Q&&/[\p{L}\p{N}'’-]/u.test(Q);for(;x>0&&Y(n[x-1]);)x--;for(;A<n.length&&Y(n[A]);)A++;const B=String(i.entity_group??i.entity??"ENTITY"),J=`${x}:${A}:${B}`;if(l.has(J))continue;l.add(J);const G=Number(i.score);s.push({value:n.slice(x,A),type:B,start:x,end:A,score:Number.isFinite(G)?Math.max(0,Math.min(1,G)):1,model:i._model})}s.sort((i,p)=>i.start-p.start||i.end-p.end);const d=[];for(const i of s){const p=d[d.length-1];if(p&&p.type===i.type&&p.end===i.start){p.end=i.end,p.value=n.slice(p.start,p.end),p.score=Math.min(p.score,i.score);continue}d.push({...i})}return g.size||F?Ct(d):d}const ot=["secret","ssn","card","iban","account","id","email","phone","address","person","org","loc"];function kt(t){const e=String(t).toLowerCase();return/secret|password|key/.test(e)?"secret":/ssn|social/.test(e)?"ssn":/card/.test(e)?"card":/iban/.test(e)?"iban":/account/.test(e)?"account":/^id|num|username|passport|licen|url|date|imei|ip$|mac$/.test(e)?"id":/email/.test(e)?"email":/phone|tel/.test(e)?"phone":/address|street|zip|post|building/.test(e)?"address":/per|name|person/.test(e)?"person":/org|company/.test(e)?"org":"loc"}function D(t){const e=ot.indexOf(kt(t.type));return e<0?ot.length:e}let k=[];function $t(t){k=Array.isArray(t)?t.slice():[],m&&(m={...m,union:k.slice()})}function W(t){if(t.model===y)return-1;const e=k.indexOf(t.model);return e<0?k.length:e}function Ct(t){const e=[...t].sort((n,o)=>n.start-o.start||o.end-n.end),r=[];for(const n of e){const o=r[r.length-1];if(o&&n.start<o.end){const s=c=>c.end-c.start;(D(n)<D(o)||D(n)===D(o)&&(s(n)>s(o)||s(n)===s(o)&&(W(n)<W(o)||W(n)===W(o)&&n.score>o.score)))&&(r[r.length-1]=n);continue}r.push(n)}return r}function ce(){const t=w?.model?.config?.id2label;if(!t)return[];const e=new Set;for(const r of Object.values(t)){const n=String(r).replace(/^[BIES]-/,"");n&&n!=="O"&&e.add(n)}return[...e]}function ue(){const t=Number(w?.tokenizer?.model_max_length);return Number.isFinite(t)&&t>0&&t<=65536?t:null}function Et(){return[...g].map(([t,e])=>({model:t,state:e.state,error:e.error||null}))}async function rt(t,{log:e=()=>{},allowDownload:r=!0}={}){if(!t||t===y)return!1;if(g.get(t)?.pipe)return!0;g.set(t,{pipe:null,state:R(t)?"loading":"downloading",error:null});try{const{pipe:o}=await at(t,{log:e,allowDownload:r});return g.set(t,{pipe:o,state:"ready",error:null}),e(`[ner] companion ready — ${t} joins the union`),!0}catch(o){return g.set(t,{pipe:null,state:"error",error:o.message}),e(`[ner] companion ${t} failed to load (${o.message}) — the union runs without it`),!1}}async function fe(t){const e=g.get(t);if(!e)return!1;g.delete(t);try{await e.pipe?.dispose?.()}catch{}return!0}function st(){const t=w?[{model:y,pipe:w}]:[];for(const[e,r]of g)r.pipe&&t.push({model:e,pipe:r.pipe});return t}const Ht=160,it=256;function Nt(t,e){if(!t||typeof e!="function")return[t];const r=Number(e.model_max_length),o=Math.min(it,Number.isFinite(r)&&r>0?r:it)-8,s=a=>{try{return e(a).input_ids.dims[1]}catch{return 1/0}};if(s(t)<=o)return[t];const l=[];let c=0,f=Math.max(64,Math.floor(o*3));for(;c<t.length;){let a=Math.min(t.length,c+f);if(a<t.length){const p=t.lastIndexOf(" ",a);p>c+f/2&&(a=p)}let u=t.slice(c,a);for(;s(u)>o&&u.length>32;){f=Math.max(32,Math.floor(u.length/2)),a=c+f;const p=t.lastIndexOf(" ",a);p>c+f/2&&(a=p),u=t.slice(c,a)}if(l.push(u),a>=t.length)break;const d=Math.max(c+1,a-Ht),i=t.indexOf(" ",d);c=i>0&&i<a?i+1:a}return l}const Pt=200,_=[];function Rt(t,e,r){_.push({ms:t,chars:e,spans:r}),_.length>Pt&&_.shift()}function Ft(){if(!_.length)return{calls:0};const t=_.map(o=>o.ms).sort((o,s)=>o-s),e=o=>t[Math.min(t.length-1,Math.floor(o*t.length))],r=_.reduce((o,s)=>o+s.chars,0),n=_.reduce((o,s)=>o+s.ms,0);return{calls:_.length,p50Ms:Math.round(e(.5)),p95Ms:Math.round(e(.95)),maxMs:Math.round(t[t.length-1]),lastMs:Math.round(_[_.length-1].ms),charsPerSec:n>0?Math.round(r/(n/1e3)):null}}function Dt(t,e){if(!e||t.includes(e))return e;const r=t.toLowerCase().indexOf(e.toLowerCase());return r<0?e:t.slice(r,r+e.length)}function Wt(t,e){if(!e)return e;const r=t.indexOf(e);if(r<0)return e;const n=l=>!!l&&/[\p{L}\p{N}'’-]/u.test(l);let o=r,s=r+e.length;for(;o>0&&n(t[o-1]);)o--;for(;s<t.length&&n(t[s]);)s++;return t.slice(o,s)}async function pe(t,e={}){let r="",n=!1;try{const s=JSON.parse(e.body||"{}");r=s.text||"",n=s.strict===!0}catch{}const o=await Ot(r,{signal:e.signal,strict:n});return new Response(JSON.stringify({entities:o}),{status:200,headers:{"content-type":"application/json"}})}function de(){return L}async function z(){if(E)return E;const t=P();try{ft(t,{recursive:!0})}catch{}const e=globalThis.__CHATPANEL_WASM_PATHS__||null;if(e)try{Object.defineProperty(process,"release",{value:{...process.release,name:"bun"},configurable:!0})}catch{}let r;try{r=await import("@huggingface/transformers")}catch(i){throw e?i:new Error(xt(i))}const{env:n,pipeline:o,Tensor:s,AutoModel:l,AutoProcessor:c,AutoTokenizer:f,AutoModelForSequenceClassification:a,LogLevel:u}=r;if(n.cacheDir=t,e&&u)try{n.logLevel=u.ERROR}catch{}n.localModelPath=t,e||(n.useCustomCache=!0,n.customCache=bt(t,{remoteHost:()=>n.remoteHost}));try{n.remoteHost=I}catch{}if(I===C&&n.fetch&&!n.fetch.__chatpanel)try{const i=Lt(n.fetch);i.__chatpanel=!0,n.fetch=i}catch{}try{n.backends.onnx.wasm.numThreads=1}catch{}if(e)try{n.backends.onnx.wasm.proxy=!1,n.backends.onnx.wasm.wasmPaths=e}catch{}return E={env:n,pipeline:(i,p,v={})=>o(i,p,v.progress_callback&&n.allowRemoteModels===!1?{...v,progress_callback:void 0}:v),Tensor:s,AutoModel:l,AutoProcessor:c,AutoTokenizer:f,AutoModelForSequenceClassification:a,AutoModelForAudioFrameClassification:r.AutoModelForAudioFrameClassification},E}function Ut({cores:t=q.availableParallelism?.()??q.cpus().length,wasm:e=!!globalThis.__CHATPANEL_WASM_PATHS__,env:r=process.env}={}){const n=Number(r.CHATPANEL_NER_THREADS);return{intraOpNumThreads:e?1:Number.isFinite(n)&&n>0?Math.floor(n):Math.max(1,Math.min(4,Math.floor(t/4))),interOpNumThreads:1,extra:{session:{intra_op:{allow_spinning:"0"}}}}}async function at(t,{log:e=()=>{},allowDownload:r=!0,onProgress:n=()=>{}}={}){const o=await z(),s=R(t);if(o.env.allowRemoteModels=s?!1:!!r,!s&&!r)throw new Error("model not on disk and downloads disabled");const l=o.env.remoteHost,c=!dt(t);if(!s&&c)try{o.env.remoteHost="https://huggingface.co/"}catch{}s||e(`[ner] downloading model ${t} (one-time${c?", from Hugging Face":""})…`);try{const a={dtype:"q8",progress_callback:d=>{d&&(d.status==="progress"||d.status==="download"||d.status==="initiate"?n(d):d.status==="done"&&d.file&&e(`[ner] fetched ${d.file}`))},session_options:Ut()};let u;try{u=await o.pipeline("token-classification",t,a)}catch(d){if(s||c||!r)throw d;e(`[ner] mirror fetch failed (${String(d.message).slice(0,80)}) — retrying from Hugging Face…`),o.env.remoteHost="https://huggingface.co/",o.env.allowRemoteModels=!0,u=await o.pipeline("token-classification",t,a)}if(!s)try{_t(t,{modelsDir:P(),log:e})}catch(d){try{await u.dispose?.()}catch{}throw d}return{pipe:u,haveLocal:s}}finally{try{o.env.remoteHost=l}catch{}}}async function lt(t,{log:e=()=>{},allowDownload:r=!0}={}){const n=w,o=y;try{await z()}catch(l){return h="error",b=`engine load failed: ${l.message}`,e(`[ner] transformers.js not available (${l.message}) — deterministic-only`),!1}const s=R(t);if(!s&&!r)return h="error",b="model not on disk and downloads disabled",e(`[ner] model ${t} not installed and downloads disabled — deterministic-only`),!1;h=s?"loading":"downloading",s||(L={model:t,file:null,pct:0});try{const{pipe:l}=await at(t,{log:e,allowDownload:r,onProgress:c=>{L={model:t,file:c.file||L?.file||null,pct:typeof c.progress=="number"?Math.round(c.progress):L?.pct??0}}});if(w=l,y=t,h="ready",b=null,L=null,m&&(m={...m,model:t}),n&&n!==l)try{await n.dispose?.()}catch{}return e(`[ner] ready — model ${t} (in-process, no Python) — entity detection active`),$()||M?.arm(),!0}catch(l){return b=l.message,L=null,n?(w=n,y=o,h="ready"):h="error",e(`[ner] model load failed (${l.message})${n?" — keeping previous model":" — deterministic-only"}`),!1}}function jt(t={}){if(T)return T;const e=typeof t.onLog=="function"?t.onLog:()=>{};m=t,y=t.model||X,h="loading";const r=t.allowDownload!==!1;return M=Z({warmMs:t.warmMs,busy:$,log:e,unload:()=>ct({log:e})}),T=lt(y,{log:e,allowDownload:r}).then(async n=>{const o=Array.isArray(t.union)?t.union:[];$t(o);for(const s of o)await rt(s,{log:e,allowDownload:r});return O()&&!$()&&M?.arm(),n}),T}function $(){if(N>0||h==="loading"||h==="downloading")return!0;for(const t of g.values())if(t.state==="loading"||t.state==="downloading")return!0;return!1}async function ct({log:t=()=>{}}={}){if($())return!1;M?.disarm();const e=st().map(r=>r.pipe);w=null,T=null,L=null,b=null,g.clear(),h=e.length?"idle":"off";for(const r of e)try{await r.dispose?.()}catch{}return e.length&&t(`[ner] idle for ${Math.round((M?.warmMs||0)/6e4)} min — ${e.length===1?"model":`${e.length} models`} unloaded (reloads on the next turn)`),!0}async function qt(){try{h==="idle"&&(H||m)?await(H?H():jt(m)):T&&await T,O()&&await ut()}catch{}return O()}let U=null;function ut(){const t=k.filter(e=>e&&e!==y&&!g.has(e));return t.length?(U||=(async()=>{const e=typeof m?.onLog=="function"?m.onLog:()=>{};for(const r of t)g.has(r)||(j?await j(r):await rt(r,{log:e,allowDownload:m?.allowDownload!==!1}))})().catch(()=>{}).finally(()=>{U=null}),U):Promise.resolve()}let j=null;function he(t){j=t}async function me(t,e={}){const r=typeof e.onLog=="function"?e.onLog:()=>{},n=e.allowDownload!==!1;if(!t)return!1;if(t===y&&O())return!0;if(t===y&&h==="idle")return qt();const o=g.get(t);if(o?.pipe){const l=w;if(w=o.pipe,y=t,h="ready",b=null,g.delete(t),l)try{await l.dispose?.()}catch{}return r(`[ner] ${t} promoted from the union to primary`),m&&(m={...m,model:t}),!0}const s=await lt(t,{log:r,allowDownload:n});return s&&(m&&(m={...m,model:t}),await ut()),s}function ge(){h="off",y=null,w=null,b=null,T=null,E=null,L=null,_.length=0,g.clear(),F=!0,k=[],M?.disarm(),M=null,m=null,N=0,H=null,j=null,U=null}function ye(t,e){g.set(t,{pipe:e,state:"ready",error:null})}function we(t,{model:e="test/model",warmMs:r=null,reload:n=null}={}){w=t,y=e,h="ready",b=null,_.length=0,n&&(H=n),r!==null&&(M=Z({warmMs:r,busy:$,unload:()=>ct()}),t&&M.arm())}export{ge as _reset,ye as _setCompanionForTest,he as _setCompanionLoaderForTest,we as _setForTest,rt as addCompanion,Et as companions,Ot as detect,le as detectSpans,qt as ensure,z as ensureLib,pe as fetchAdapter,ie as health,jt as init,O as isReady,ce as labels,ue as maxTokens,R as modelOnDisk,P as modelRoot,re as modelsOnDisk,de as progress,fe as removeCompanion,At as resolveModelHost,Ut as sessionOptionsFor,ae as setCaseRecovery,me as setModel,$t as setUnionOrder,se as state,Ft as stats,Ct as unionSpans,ct as unload,Nt as windowsFor,oe as withModelSource};
|
|
1
|
+
import z from"node:os";import{join as S}from"node:path";import{existsSync as K,mkdirSync as ft,readdirSync as V,readFileSync as pt}from"node:fs";import{DEFAULT_MODEL as X,isMirroredModel as dt}from"./models.js";import{isLoopbackHost as ht,isPrivateHost as mt,isMetadataHost as gt}from"@chatpanel/pii";import{recaseForDetection as yt}from"@chatpanel/pii/pii-detect.js";import{recasedSpanOk as wt}from"@chatpanel/pii/recased-spans.js";import{verifyModelWeights as _t}from"./model-integrity.js";import{runtimeName as Mt}from"./model-runtime.js";import{nativeOrtFailure as xt}from"./ort.js";import{makeWarmTimer as Z}from"./warm-timer.js";import{makeModelFileCache as bt}from"./model-file-cache.js";import{modelFetch as Lt}from"./model-sources.js";import{onLane as Tt}from"./inference-lane.js";const C="https://huggingface.co/";function At(t=process.env){const e=t.CHATPANEL_MODEL_BASE_URL?"CHATPANEL_MODEL_BASE_URL":"registries.models",r=t.CHATPANEL_MODEL_BASE_URL||t.CHATPANEL_REGISTRY_MODELS;if(!r)return C;const n=l=>(console.warn(`[models] ignoring ${e} (${r}): ${l} — using ${C}`),C);let o;try{o=new URL(r)}catch{return n("not a valid URL")}if(o.protocol!=="http:"&&o.protocol!=="https:")return n(`scheme ${o.protocol} not allowed`);if(gt(o.hostname))return n("points at cloud metadata");const s=ht(o.hostname)||mt(o.hostname);return o.protocol==="http:"&&!s?n("plaintext http:// to a public host (use https or a LAN/loopback mirror)"):(console.warn(`[models] ⚠ model weights will be downloaded from ${o.origin} (${e}), not ${C}`),r.replace(/\/*$/,"/"))}const I=At();let h="off",y=null,w=null,b=null,A=null,E=null,L=null,m=null,x=null,N=0,H=null;const g=new Map;let tt=Promise.resolve();function oe({host:t=null,allowRemote:e=!1}={},r){const n=tt.then(async()=>{const o=await Y(),s=o.env.remoteHost,l=o.env.allowRemoteModels;try{o.env.allowRemoteModels=e,t&&(o.env.remoteHost=t)}catch{}try{return await r(o)}finally{try{o.env.remoteHost=s,o.env.allowRemoteModels=l}catch{}}});return tt=n.catch(()=>{}),n}function P(){return process.env.CHATPANEL_MODELS_DIR||S(z.homedir(),".chatpanel","models")}function R(t=y||X){const e=S(P(),...t.split("/"));return K(S(e,"onnx","model_quantized.onnx"))||K(S(e,"onnx","model.onnx"))}function re(){const t=P(),e=[];try{for(const r of V(t,{withFileTypes:!0}))if(r.isDirectory())for(const n of V(S(t,r.name),{withFileTypes:!0})){if(!n.isDirectory())continue;const o=`${r.name}/${n.name}`;R(o)&&St(S(t,r.name,n.name))&&e.push(o)}}catch{}return e}function St(t){try{return(JSON.parse(pt(S(t,"config.json"),"utf8")).architectures||[]).some(r=>/ForTokenClassification$/.test(String(r)))}catch{return!1}}function se(){return h}function O(){return h==="ready"&&!!w}function ie(){return{configured:h!=="off",ok:O(),state:h,model:y,error:b,runtime:Mt(),dtype:w?"q8":null,stats:Ft(),companions:Et(),warmMs:x?.warmMs??null}}async function Ot(t,{signal:e,strict:r=!1}={}){if(!O())return[];if(e?.aborted)return[];const n=String(t||""),o=await et(n,e);if(!o)return[];const s=[];for(const u of o||[]){let i=String(u.word??"");const f=u.entity_group??u.entity??"ENTITY";if(i.startsWith("##")&&s.length&&s[s.length-1].type===f){s[s.length-1].value+=i.slice(2);continue}i=i.replace(/##/g,"").trim(),i&&s.push({value:i,type:f,pass:u._pass})}const l=new Set,c=[];for(const u of s){const i=Wt(n,Dt(n,u.value.trim()));if(i.length<=1||nt(i,u.type,u.pass,r))continue;const f=`${u.type}:${i.toLowerCase()}`;l.has(f)||(l.add(f),c.push({value:i,type:u.type}))}return c}async function et(t,e){N++;try{return await vt(t,e)}finally{N--,$()||x?.arm()}}async function vt(t,e){const r=performance.now(),n=[],o=[{text:t,key:"orig"}];if(F){const s=yt(t);s.changed&&o.push({text:s.text,key:"recased"})}for(const{model:s,pipe:l}of st())for(const c of o){let u=0;for(const i of Nt(c.text,l.tokenizer)){if(e?.aborted)return null;const f=c.text.indexOf(i,u),d=await Tt(()=>l(i,{aggregation_strategy:"simple"}));for(const a of d||[])n.push({...a,_win:f<0?u:f,_winText:i,_model:s,_pass:c.key,_passText:c.text});f>=0&&(u=Math.max(u,f+1))}}return Rt(performance.now()-r,t.length,n.length),n}let F=!0;function ae(t){F=t!==!1}const nt=(t,e,r,n)=>!n&&r==="recased"&&!wt(t,e);async function le(t,{signal:e,strict:r=!1}={}){if(!O())return[];const n=String(t||""),o=await et(n,e);if(!o)return[];const s=[],l=new Set;let c=-1,u=-1,i=null,f=null;for(const a of o){const p=String(a.word??"").replace(/##/g,"").trim();if(!p)continue;(a._win!==u||a._model!==i||a._pass!==f)&&(u=a._win,i=a._model,f=a._pass,c=a._win);const v=a._passText||n;let M=v.indexOf(p,c);if(M<0&&(M=v.indexOf(p,a._win)),M<0)continue;let T=M+p.length;c=T;const B=Q=>!!Q&&/[\p{L}\p{N}'’-]/u.test(Q);for(;M>0&&B(n[M-1]);)M--;for(;T<n.length&&B(n[T]);)T++;const q=String(a.entity_group??a.entity??"ENTITY");if(nt(n.slice(M,T),q,a._pass,r))continue;const J=`${M}:${T}:${q}`;if(l.has(J))continue;l.add(J);const G=Number(a.score);s.push({value:n.slice(M,T),type:q,start:M,end:T,score:Number.isFinite(G)?Math.max(0,Math.min(1,G)):1,model:a._model})}s.sort((a,p)=>a.start-p.start||a.end-p.end);const d=[];for(const a of s){const p=d[d.length-1];if(p&&p.type===a.type&&p.end===a.start){p.end=a.end,p.value=n.slice(p.start,p.end),p.score=Math.min(p.score,a.score);continue}d.push({...a})}return g.size||F?Ct(d):d}const ot=["secret","ssn","card","iban","account","id","email","phone","address","person","org","loc"];function kt(t){const e=String(t).toLowerCase();return/secret|password|key/.test(e)?"secret":/ssn|social/.test(e)?"ssn":/card/.test(e)?"card":/iban/.test(e)?"iban":/account/.test(e)?"account":/^id|num|username|passport|licen|url|date|imei|ip$|mac$/.test(e)?"id":/email/.test(e)?"email":/phone|tel/.test(e)?"phone":/address|street|zip|post|building/.test(e)?"address":/per|name|person/.test(e)?"person":/org|company/.test(e)?"org":"loc"}function D(t){const e=ot.indexOf(kt(t.type));return e<0?ot.length:e}let k=[];function $t(t){k=Array.isArray(t)?t.slice():[],m&&(m={...m,union:k.slice()})}function W(t){if(t.model===y)return-1;const e=k.indexOf(t.model);return e<0?k.length:e}function Ct(t){const e=[...t].sort((n,o)=>n.start-o.start||o.end-n.end),r=[];for(const n of e){const o=r[r.length-1];if(o&&n.start<o.end){const s=c=>c.end-c.start;(D(n)<D(o)||D(n)===D(o)&&(s(n)>s(o)||s(n)===s(o)&&(W(n)<W(o)||W(n)===W(o)&&n.score>o.score)))&&(r[r.length-1]=n);continue}r.push(n)}return r}function ce(){const t=w?.model?.config?.id2label;if(!t)return[];const e=new Set;for(const r of Object.values(t)){const n=String(r).replace(/^[BIES]-/,"");n&&n!=="O"&&e.add(n)}return[...e]}function ue(){const t=Number(w?.tokenizer?.model_max_length);return Number.isFinite(t)&&t>0&&t<=65536?t:null}function Et(){return[...g].map(([t,e])=>({model:t,state:e.state,error:e.error||null}))}async function rt(t,{log:e=()=>{},allowDownload:r=!0}={}){if(!t||t===y)return!1;if(g.get(t)?.pipe)return!0;g.set(t,{pipe:null,state:R(t)?"loading":"downloading",error:null});try{const{pipe:o}=await at(t,{log:e,allowDownload:r});return g.set(t,{pipe:o,state:"ready",error:null}),e(`[ner] companion ready — ${t} joins the union`),!0}catch(o){return g.set(t,{pipe:null,state:"error",error:o.message}),e(`[ner] companion ${t} failed to load (${o.message}) — the union runs without it`),!1}}async function fe(t){const e=g.get(t);if(!e)return!1;g.delete(t);try{await e.pipe?.dispose?.()}catch{}return!0}function st(){const t=w?[{model:y,pipe:w}]:[];for(const[e,r]of g)r.pipe&&t.push({model:e,pipe:r.pipe});return t}const Ht=160,it=256;function Nt(t,e){if(!t||typeof e!="function")return[t];const r=Number(e.model_max_length),o=Math.min(it,Number.isFinite(r)&&r>0?r:it)-8,s=i=>{try{return e(i).input_ids.dims[1]}catch{return 1/0}};if(s(t)<=o)return[t];const l=[];let c=0,u=Math.max(64,Math.floor(o*3));for(;c<t.length;){let i=Math.min(t.length,c+u);if(i<t.length){const p=t.lastIndexOf(" ",i);p>c+u/2&&(i=p)}let f=t.slice(c,i);for(;s(f)>o&&f.length>32;){u=Math.max(32,Math.floor(f.length/2)),i=c+u;const p=t.lastIndexOf(" ",i);p>c+u/2&&(i=p),f=t.slice(c,i)}if(l.push(f),i>=t.length)break;const d=Math.max(c+1,i-Ht),a=t.indexOf(" ",d);c=a>0&&a<i?a+1:i}return l}const Pt=200,_=[];function Rt(t,e,r){_.push({ms:t,chars:e,spans:r}),_.length>Pt&&_.shift()}function Ft(){if(!_.length)return{calls:0};const t=_.map(o=>o.ms).sort((o,s)=>o-s),e=o=>t[Math.min(t.length-1,Math.floor(o*t.length))],r=_.reduce((o,s)=>o+s.chars,0),n=_.reduce((o,s)=>o+s.ms,0);return{calls:_.length,p50Ms:Math.round(e(.5)),p95Ms:Math.round(e(.95)),maxMs:Math.round(t[t.length-1]),lastMs:Math.round(_[_.length-1].ms),charsPerSec:n>0?Math.round(r/(n/1e3)):null}}function Dt(t,e){if(!e||t.includes(e))return e;const r=t.toLowerCase().indexOf(e.toLowerCase());return r<0?e:t.slice(r,r+e.length)}function Wt(t,e){if(!e)return e;const r=t.indexOf(e);if(r<0)return e;const n=l=>!!l&&/[\p{L}\p{N}'’-]/u.test(l);let o=r,s=r+e.length;for(;o>0&&n(t[o-1]);)o--;for(;s<t.length&&n(t[s]);)s++;return t.slice(o,s)}async function pe(t,e={}){let r="",n=!1;try{const s=JSON.parse(e.body||"{}");r=s.text||"",n=s.strict===!0}catch{}const o=await Ot(r,{signal:e.signal,strict:n});return new Response(JSON.stringify({entities:o}),{status:200,headers:{"content-type":"application/json"}})}function de(){return L}async function Y(){if(E)return E;const t=P();try{ft(t,{recursive:!0})}catch{}const e=globalThis.__CHATPANEL_WASM_PATHS__||null;if(e)try{Object.defineProperty(process,"release",{value:{...process.release,name:"bun"},configurable:!0})}catch{}let r;try{r=await import("@huggingface/transformers")}catch(a){throw e?a:new Error(xt(a))}const{env:n,pipeline:o,Tensor:s,AutoModel:l,AutoProcessor:c,AutoTokenizer:u,AutoModelForSequenceClassification:i,LogLevel:f}=r;if(n.cacheDir=t,e&&f)try{n.logLevel=f.ERROR}catch{}n.localModelPath=t,e||(n.useCustomCache=!0,n.customCache=bt(t,{remoteHost:()=>n.remoteHost}));try{n.remoteHost=I}catch{}if(I===C&&n.fetch&&!n.fetch.__chatpanel)try{const a=Lt(n.fetch);a.__chatpanel=!0,n.fetch=a}catch{}try{n.backends.onnx.wasm.numThreads=1}catch{}if(e)try{n.backends.onnx.wasm.proxy=!1,n.backends.onnx.wasm.wasmPaths=e}catch{}return E={env:n,pipeline:(a,p,v={})=>o(a,p,v.progress_callback&&n.allowRemoteModels===!1?{...v,progress_callback:void 0}:v),Tensor:s,AutoModel:l,AutoProcessor:c,AutoTokenizer:u,AutoModelForSequenceClassification:i,AutoModelForAudioFrameClassification:r.AutoModelForAudioFrameClassification},E}function Ut({cores:t=z.availableParallelism?.()??z.cpus().length,wasm:e=!!globalThis.__CHATPANEL_WASM_PATHS__,env:r=process.env}={}){const n=Number(r.CHATPANEL_NER_THREADS);return{intraOpNumThreads:e?1:Number.isFinite(n)&&n>0?Math.floor(n):Math.max(1,Math.min(4,Math.floor(t/4))),interOpNumThreads:1,extra:{session:{intra_op:{allow_spinning:"0"}}}}}async function at(t,{log:e=()=>{},allowDownload:r=!0,onProgress:n=()=>{}}={}){const o=await Y(),s=R(t);if(o.env.allowRemoteModels=s?!1:!!r,!s&&!r)throw new Error("model not on disk and downloads disabled");const l=o.env.remoteHost,c=!dt(t);if(!s&&c)try{o.env.remoteHost="https://huggingface.co/"}catch{}s||e(`[ner] downloading model ${t} (one-time${c?", from Hugging Face":""})…`);try{const i={dtype:"q8",progress_callback:d=>{d&&(d.status==="progress"||d.status==="download"||d.status==="initiate"?n(d):d.status==="done"&&d.file&&e(`[ner] fetched ${d.file}`))},session_options:Ut()};let f;try{f=await o.pipeline("token-classification",t,i)}catch(d){if(s||c||!r)throw d;e(`[ner] mirror fetch failed (${String(d.message).slice(0,80)}) — retrying from Hugging Face…`),o.env.remoteHost="https://huggingface.co/",o.env.allowRemoteModels=!0,f=await o.pipeline("token-classification",t,i)}if(!s)try{_t(t,{modelsDir:P(),log:e})}catch(d){try{await f.dispose?.()}catch{}throw d}return{pipe:f,haveLocal:s}}finally{try{o.env.remoteHost=l}catch{}}}async function lt(t,{log:e=()=>{},allowDownload:r=!0}={}){const n=w,o=y;try{await Y()}catch(l){return h="error",b=`engine load failed: ${l.message}`,e(`[ner] transformers.js not available (${l.message}) — deterministic-only`),!1}const s=R(t);if(!s&&!r)return h="error",b="model not on disk and downloads disabled",e(`[ner] model ${t} not installed and downloads disabled — deterministic-only`),!1;h=s?"loading":"downloading",s||(L={model:t,file:null,pct:0});try{const{pipe:l}=await at(t,{log:e,allowDownload:r,onProgress:c=>{L={model:t,file:c.file||L?.file||null,pct:typeof c.progress=="number"?Math.round(c.progress):L?.pct??0}}});if(w=l,y=t,h="ready",b=null,L=null,m&&(m={...m,model:t}),n&&n!==l)try{await n.dispose?.()}catch{}return e(`[ner] ready — model ${t} (in-process, no Python) — entity detection active`),$()||x?.arm(),!0}catch(l){return b=l.message,L=null,n?(w=n,y=o,h="ready"):h="error",e(`[ner] model load failed (${l.message})${n?" — keeping previous model":" — deterministic-only"}`),!1}}function jt(t={}){if(A)return A;const e=typeof t.onLog=="function"?t.onLog:()=>{};m=t,y=t.model||X,h="loading";const r=t.allowDownload!==!1;return x=Z({warmMs:t.warmMs,busy:$,log:e,unload:()=>ct({log:e})}),A=lt(y,{log:e,allowDownload:r}).then(async n=>{const o=Array.isArray(t.union)?t.union:[];$t(o);for(const s of o)await rt(s,{log:e,allowDownload:r});return O()&&!$()&&x?.arm(),n}),A}function $(){if(N>0||h==="loading"||h==="downloading")return!0;for(const t of g.values())if(t.state==="loading"||t.state==="downloading")return!0;return!1}async function ct({log:t=()=>{}}={}){if($())return!1;x?.disarm();const e=st().map(r=>r.pipe);w=null,A=null,L=null,b=null,g.clear(),h=e.length?"idle":"off";for(const r of e)try{await r.dispose?.()}catch{}return e.length&&t(`[ner] idle for ${Math.round((x?.warmMs||0)/6e4)} min — ${e.length===1?"model":`${e.length} models`} unloaded (reloads on the next turn)`),!0}async function qt(){try{h==="idle"&&(H||m)?await(H?H():jt(m)):A&&await A,O()&&await ut()}catch{}return O()}let U=null;function ut(){const t=k.filter(e=>e&&e!==y&&!g.has(e));return t.length?(U||=(async()=>{const e=typeof m?.onLog=="function"?m.onLog:()=>{};for(const r of t)g.has(r)||(j?await j(r):await rt(r,{log:e,allowDownload:m?.allowDownload!==!1}))})().catch(()=>{}).finally(()=>{U=null}),U):Promise.resolve()}let j=null;function he(t){j=t}async function me(t,e={}){const r=typeof e.onLog=="function"?e.onLog:()=>{},n=e.allowDownload!==!1;if(!t)return!1;if(t===y&&O())return!0;if(t===y&&h==="idle")return qt();const o=g.get(t);if(o?.pipe){const l=w;if(w=o.pipe,y=t,h="ready",b=null,g.delete(t),l)try{await l.dispose?.()}catch{}return r(`[ner] ${t} promoted from the union to primary`),m&&(m={...m,model:t}),!0}const s=await lt(t,{log:r,allowDownload:n});return s&&(m&&(m={...m,model:t}),await ut()),s}function ge(){h="off",y=null,w=null,b=null,A=null,E=null,L=null,_.length=0,g.clear(),F=!0,k=[],x?.disarm(),x=null,m=null,N=0,H=null,j=null,U=null}function ye(t,e){g.set(t,{pipe:e,state:"ready",error:null})}function we(t,{model:e="test/model",warmMs:r=null,reload:n=null}={}){w=t,y=e,h="ready",b=null,_.length=0,n&&(H=n),r!==null&&(x=Z({warmMs:r,busy:$,unload:()=>ct()}),t&&x.arm())}export{ge as _reset,ye as _setCompanionForTest,he as _setCompanionLoaderForTest,we as _setForTest,rt as addCompanion,Et as companions,Ot as detect,le as detectSpans,qt as ensure,Y as ensureLib,pe as fetchAdapter,ie as health,jt as init,O as isReady,ce as labels,ue as maxTokens,R as modelOnDisk,P as modelRoot,re as modelsOnDisk,de as progress,fe as removeCompanion,At as resolveModelHost,Ut as sessionOptionsFor,ae as setCaseRecovery,me as setModel,$t as setUnionOrder,se as state,Ft as stats,Ct as unionSpans,ct as unload,Nt as windowsFor,oe as withModelSource};
|
package/src/redact.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{createHash as
|
|
1
|
+
import{createHash as Y}from"node:crypto";import{createVault as Z,redactText as tt,detectEntities as et,gatedDictionary as nt,sanitizeUnicode as st,strictnessOf as $}from"@chatpanel/pii";import*as ot from"@chatpanel/pii";const rt=ot.consistentPlaces||(t=>t);import{ENTITIES_SCHEMA as z,entitiesFormat as it}from"./extraction.js";import{describeSchema as ct,coerce as lt}from"./structured.js";import*as q from"./ner-engine.js";const b=8e3,ut=2e6,u=new Map;let k=0,_="";const F=t=>`${Y("sha256").update(t).digest("base64")}:${t.length}`;function G(t,e,s){t!==_&&(u.clear(),k=0,_=t);const o=F(e);if(!u.has(o))for(u.set(o,{ents:s,len:e.length}),k+=e.length;k>ut&&u.size;){const[n]=u.keys();k-=u.get(n).len,u.delete(n)}}function B(t,e){return t===_?u.get(F(e))?.ents:void 0}function bt(){u.clear(),k=0,_="",f.length=0,x=0}function K(t,e=b){const s=[];for(const o of String(t||"").split(/\n[ \t]*\n/)){let n=o.trim();for(;n.length>e;){let i=n.lastIndexOf(" ",e);i<e/2&&(i=e),s.push(n.slice(0,i).trim()),n=n.slice(i).trim()}n.length>=8&&s.push(n)}return s}function ft(t){if(t<=1)return t===1?[0]:[];const e=[t-1,0];for(let s=t-2;s>0;s--)e.push(s);return e}function L(t,{useEngine:e}){const s=t.detection,o=e?{backend:"endpoint",url:"inproc:ner",transport:"in-process",timeoutMs:3e4,maxChars:b,types:s?.types,strictness:$(t)}:{...s,timeoutMs:Math.max(Number(s.timeoutMs)||0,3e4),strictness:$(t)},n=JSON.stringify([o.backend,o.url||"",o.model||"",o.strictness||"",o.types||null]);return{detection:o,sig:n}}const at=()=>({block:ct(z),format:t=>it(t),parse:t=>lt(t,z)?.value??null});async function U(t,{detection:e,fetchImpl:s,signal:o=void 0,onEgress:n=null}){let i=!1,g=null;try{g=await et(t,{detection:e},{signal:o,fetchImpl:s,onError:()=>{i=!0},onEgress:n,structured:at()})}catch{g=null}return i?null:g}const ht=64e3,f=[];let x=0,D=0,p=null;function X(t,{detection:e,fetchImpl:s,sig:o}){for(const n of t)B(o,n)||f.some(i=>i.text===n)||(f.push({text:n,detection:e,fetchImpl:s,sig:o}),x+=n.length);for(;x>ht&&f.length;)x-=f.shift().text.length}function dt(){return p||(f.length?(p=(async()=>{try{for(;f.length;){if(D>0)return;const t=f.shift();if(x-=t.text.length,B(t.sig,t.text))continue;const e=await U(t.text,t);e&&G(t.sig,t.text,e)}}finally{p=null}})(),p):Promise.resolve())}function j(){if(!f.length||p)return;setTimeout(()=>{dt().catch(()=>{})},50).unref?.()}function kt(t,e,{nerEngine:s=q}={}){if(!t||typeof t!="string"||e?.tier!=="full")return!1;const o=e.detection;if(o&&o.backend&&o.backend!=="off"||!s.isReady())return!1;const{detection:n,sig:i}=L(e,{useEngine:!0});return X(K(t,n.maxChars||b),{detection:n,fetchImpl:s.fetchAdapter,sig:i}),j(),!0}async function xt(t,e,{signal:s,isPro:o=!0,onEgress:n=null,fetchImpl:i=null,budgetChars:g=b,sanitizeOnly:J=!1,nerEngine:w=q}={}){const S=Z();let C=0;for(const r of t){const c=r.get();if(typeof c!="string"||!c)continue;const{clean:a,removed:y}=st(c);y&&(r.set(a),C+=y)}const A=t.map(r=>r.get()).filter(r=>typeof r=="string"&&r);if(A.length===0)return{vault:S,count:0,sanitized:C};if(J)return{vault:S,count:0,sanitized:C};const E=e.tier==="full"?"full":"basic",V=nt(e,o),M=e.detection,v=!!(M&&M.backend&&M.backend!=="off");E==="full"&&!v&&typeof w.ensure=="function"&&await w.ensure();const m=!v&&w.isReady();let H=[],N=0;if(E==="full"&&(v||m)){const{detection:r,sig:c}=L(e,{useEngine:m}),a=m?w.fetchAdapter:i||void 0,y=new Set,P=[],I=[];let R=g;D++;try{for(const h of ft(A.length))for(const l of K(A[h],r.maxChars||b)){if(s?.aborted)break;if(y.has(l))continue;y.add(l);let d=B(c,l);if(!d){if(l.length>R){N+=l.length,I.push(l);continue}R-=l.length,d=await U(l,{detection:r,fetchImpl:a,signal:s,onEgress:m?null:n}),d?G(c,l,d):d=[]}P.push(...d)}}finally{D--}m&&I.length&&X(I,{detection:r,fetchImpl:a,sig:c}),j();const W=rt(P,r.types),T=new Map;for(const h of W){if(!h||!h.value)continue;const l=`${h.type}:${String(h.value).toLowerCase()}`;T.has(l)||T.set(l,h)}H=[...T.values()]}const Q={tier:E,entities:H,dictionary:V};let O=0;for(const r of t){const c=r.get();if(typeof c!="string"||!c)continue;const a=tt(c,S,Q);a!==c&&O++,r.set(a)}return{vault:S,count:O,sanitized:C,unscanned:N}}function wt(t,e){return{get:t,set:e}}export{bt as clearBlockCache,K as detectBlocks,dt as flushPendingDetection,xt as redactSegments,kt as rememberAnswer,ft as scanOrder,wt as segment};
|
package/src/server.js
CHANGED
|
@@ -64,4 +64,4 @@ data: ${JSON.stringify(c)}
|
|
|
64
64
|
connection: close\r
|
|
65
65
|
content-length: 0\r
|
|
66
66
|
\r
|
|
67
|
-
`)}catch{}}),ue.once("listening",()=>{P()}),ue.linkHost=y,ue.runtimeDefaults=()=>P().ensureDefaults(),ue}function Lt(t,d){let u=d&&typeof d=="object"?d:null;if(!u&&t)try{u=JSON.parse(decodeURIComponent(String(t)))}catch{u=null}if(!u||typeof u!="object")return null;const p={};if(Array.isArray(u.grants)&&(p.grants=u.grants.map(y=>String(y).slice(0,80)).slice(0,32)),u.workspace&&typeof u.workspace=="object"&&u.workspace.repo){const y=u.workspace;p.workspace={repo:String(y.repo).slice(0,400),projectId:String(y.projectId||"").slice(0,120),jobId:String(y.jobId||"").slice(0,120),...y.base?{base:String(y.base).slice(0,120)}:{}}}if(u.connectionId&&(p.connectionId=String(u.connectionId).slice(0,64)),typeof u.workingDir=="string"&&u.workingDir.trim()&&/^([A-Za-z]:[\\/]|\/)/.test(u.workingDir.trim())&&(p.workingDir=u.workingDir.trim().slice(0,1024)),Xa.includes(u.permissionMode)&&u.permissionMode!=="default"&&(p.permissionMode=u.permissionMode),u.sandbox&&typeof u.sandbox=="object"){const y=(Array.isArray(u.sandbox.hosts)?u.sandbox.hosts:String(u.sandbox.hosts||"").split(/[\s,;]+/)).map(T=>String(T).trim().toLowerCase().slice(0,253)).filter(Boolean).slice(0,64),$=(Array.isArray(u.sandbox.write)?u.sandbox.write:[]).map(T=>String(T).slice(0,1024)).filter(Boolean).slice(0,32),B=u.sandbox.outside===!0,E=(Array.isArray(u.sandbox.signIn)?u.sandbox.signIn:[]).map(T=>String(T).trim().toLowerCase().slice(0,32)).filter(Boolean).slice(0,8);(y.length||$.length||B||E.length)&&(p.sandbox={...y.length?{hosts:y}:{},...$.length?{write:$}:{},...B?{outside:!0}:{},...E.length?{signIn:E}:{}})}const w=Kr(u.thread);return w&&(p.thread=w),u.ephemeral===!0&&(p.ephemeral=!0),u.worker===!0&&(p.worker=!0,p.ephemeral=!0),Object.keys(p).length?p:null}let Ve=null,ut=null;async function Sl(t=Wt()){Hr();let d=null;try{d=await _r()}catch(T){throw T instanceof Or&&(console.error(`[chatpanel-gateway] org policy: ${T.message}`),process.exit(78)),T}const u=d?.policy||null;u&&(Zt(t,u),console.log(`[chatpanel-gateway] ${d.label} — ${d.signed?"signed":"unsigned"} policy from ${d.source}`));const p=Tr({enabled:Xt(t)});console.log(`[chatpanel-gateway] certificates: ${p.on?`this computer's list is trusted too (${p.added} added to the runtime's own)`:`the runtime's own list only — ${p.why}`}`),kr(globalThis,{allow:u?.egress?(T,{local:x})=>Pr(u,T,{local:x}):null}),_e();const w=As(t),y=jr(t),$=tr(t);let B=!1;w.on("error",T=>{if(T&&T.code==="EADDRINUSE"){const x=ct(t.host)?"127.0.0.1":t.host;fetch(`http://${x}:${t.port}/health`,{signal:AbortSignal.timeout(1500)}).then(R=>R.ok?R.json():null).catch(()=>null).then(R=>{const j=!!(R?.version&&typeof R.tier=="string"),V=Qr({name:"gateway",self:de,holder:j?{ours:j,version:R.version}:null,managedBy:Yr(process.env),port:t.port});if(V.action==="standby"||B&&!R){if(!B)for(const P of V.lines)console.error(P);B=!0,setTimeout(()=>w.listen(t.port,t.host),Xr);return}if(j){const P=R.managedBy?` (run by ${R.managedBy})`:"";for(const[U,z]of V.lines.entries())console.error(U===0?z.replace(` on ${t.port}`,` at http://${x}:${t.port}${P}`):z)}else{const P=mn(t.port);console.error(`Port ${t.port} is held by ${P||"another program"}, which is not a ChatPanel gateway.`),console.error(`Fix: stop that program, or set a different port — edit "port" in ${le()} (or the extension's Gateway tab) and restart. The extension must point at the same port.`)}process.exit(1)});return}console.error(`Gateway server error: ${T?.message||T}`),process.exit(1)}),w.listen(t.port,t.host,()=>{B&&console.log(" standby : the other gateway is gone — this copy has the port now"),B=!1,console.log(`ChatPanel Privacy Gateway v${de} on http://${t.host}:${t.port}`),w.linkHost?.start().catch(T=>console.log(` link : not started (${T?.message||T})`)),w.runtimeDefaults?.().then(T=>{for(const x of T||[])console.log(` ${x.label.toLowerCase().padEnd(9).slice(0,9)}: ${x.ok?x.already?"running":x.adopted?"already running — adopted":"started":`not started (${x.skipped})`}`)}).catch(T=>console.log(` runtime : defaults not started (${T?.message||T})`)),console.log(` backend : ${t.backend}`+(t.backend==="bridge"?` (agent: ${t.bridge.agent}, via ${t.bridge.url})`:"")),t.bridge?.openAgentLane&&console.log(" ⚠ agents : bridge.openAgentLane is ON — any local process may drive a CLI agent through this gateway without a token");for(const T of qa(t))console.log(` ⚠ sandbox : ${T}`);console.log(` confined : ${wn(wt({stateDir:He.dirname(le())}))}`),ut={mode:"starting",version:null,pid:null,restarts:0,why:"deciding: adopt the bridge that answers, or start ours"},un(t,{childEnv:()=>({...Za(t,process.env,qe()),...Ya(t)})}).then(T=>{Ve=T}).catch(T=>{ut={mode:"off",version:null,pid:null,restarts:0,why:`not supervised (${T?.message||T})`},console.log(` bridge : not supervised (${T?.message||T})`)}),console.log(` redaction: ${t.redaction.tier}`+(t.redaction.detection?.backend&&t.redaction.detection.backend!=="off"?` + ${t.redaction.detection.backend} detector`:t.ner?.autostart?" (+ NER starting…)":"")),ct(t.host)||console.error(`⚠ SECURITY: gateway bound to NON-LOOPBACK host ${t.host}. It is reachable off-machine, and the loopback Host-header check is spoofable from the LAN. Admin routes still need the token/extension, but prefer binding 127.0.0.1 unless you intend LAN exposure on a trusted network.`)}),io()&&kt(J,ft()).then(T=>{T?.ok&&(console.log(` warm : seeded ${T.ingested} records from ${T.file}`),T.whole&&Ue())}).catch(()=>{});const E=()=>{y?.stop(),$.stop(),Ve?.stop(),is(w)};return process.on("SIGINT",E),process.on("SIGTERM",E),w}export{vs as RECORDS_MAX_BYTES,_l as VERSION,As as createGateway,_s as joinUpstream,Bt as parseAgentModel,Sl as start};
|
|
67
|
+
`)}catch{}}),ue.once("listening",()=>{P()}),ue.linkHost=y,ue.runtimeDefaults=()=>P().ensureDefaults(),ue}function Lt(t,d){let u=d&&typeof d=="object"?d:null;if(!u&&t)try{u=JSON.parse(decodeURIComponent(String(t)))}catch{u=null}if(!u||typeof u!="object")return null;const p={};if(Array.isArray(u.grants)&&(p.grants=u.grants.map(y=>String(y).slice(0,80)).slice(0,32)),u.workspace&&typeof u.workspace=="object"&&u.workspace.repo){const y=u.workspace;p.workspace={repo:String(y.repo).slice(0,400),projectId:String(y.projectId||"").slice(0,120),jobId:String(y.jobId||"").slice(0,120),...y.base?{base:String(y.base).slice(0,120)}:{}}}if(u.connectionId&&(p.connectionId=String(u.connectionId).slice(0,64)),typeof u.workingDir=="string"&&u.workingDir.trim()&&/^([A-Za-z]:[\\/]|\/)/.test(u.workingDir.trim())&&(p.workingDir=u.workingDir.trim().slice(0,1024)),Xa.includes(u.permissionMode)&&u.permissionMode!=="default"&&(p.permissionMode=u.permissionMode),u.sandbox&&typeof u.sandbox=="object"){const y=(Array.isArray(u.sandbox.hosts)?u.sandbox.hosts:String(u.sandbox.hosts||"").split(/[\s,;]+/)).map(T=>String(T).trim().toLowerCase().slice(0,253)).filter(Boolean).slice(0,64),$=(Array.isArray(u.sandbox.write)?u.sandbox.write:[]).map(T=>String(T).slice(0,1024)).filter(Boolean).slice(0,32),B=u.sandbox.outside===!0,E=(Array.isArray(u.sandbox.signIn)?u.sandbox.signIn:[]).map(T=>String(T).trim().toLowerCase().slice(0,32)).filter(Boolean).slice(0,8);(y.length||$.length||B||E.length)&&(p.sandbox={...y.length?{hosts:y}:{},...$.length?{write:$}:{},...B?{outside:!0}:{},...E.length?{signIn:E}:{}})}const w=Kr(u.thread);return w&&(p.thread=w),u.ephemeral===!0&&(p.ephemeral=!0),u.worker===!0&&(p.worker=!0,p.ephemeral=!0),u.lean===!0&&(p.lean=!0,p.ephemeral=!0),Object.keys(p).length?p:null}let Ve=null,ut=null;async function Sl(t=Wt()){Hr();let d=null;try{d=await _r()}catch(T){throw T instanceof Or&&(console.error(`[chatpanel-gateway] org policy: ${T.message}`),process.exit(78)),T}const u=d?.policy||null;u&&(Zt(t,u),console.log(`[chatpanel-gateway] ${d.label} — ${d.signed?"signed":"unsigned"} policy from ${d.source}`));const p=Tr({enabled:Xt(t)});console.log(`[chatpanel-gateway] certificates: ${p.on?`this computer's list is trusted too (${p.added} added to the runtime's own)`:`the runtime's own list only — ${p.why}`}`),kr(globalThis,{allow:u?.egress?(T,{local:x})=>Pr(u,T,{local:x}):null}),_e();const w=As(t),y=jr(t),$=tr(t);let B=!1;w.on("error",T=>{if(T&&T.code==="EADDRINUSE"){const x=ct(t.host)?"127.0.0.1":t.host;fetch(`http://${x}:${t.port}/health`,{signal:AbortSignal.timeout(1500)}).then(R=>R.ok?R.json():null).catch(()=>null).then(R=>{const j=!!(R?.version&&typeof R.tier=="string"),V=Qr({name:"gateway",self:de,holder:j?{ours:j,version:R.version}:null,managedBy:Yr(process.env),port:t.port});if(V.action==="standby"||B&&!R){if(!B)for(const P of V.lines)console.error(P);B=!0,setTimeout(()=>w.listen(t.port,t.host),Xr);return}if(j){const P=R.managedBy?` (run by ${R.managedBy})`:"";for(const[U,z]of V.lines.entries())console.error(U===0?z.replace(` on ${t.port}`,` at http://${x}:${t.port}${P}`):z)}else{const P=mn(t.port);console.error(`Port ${t.port} is held by ${P||"another program"}, which is not a ChatPanel gateway.`),console.error(`Fix: stop that program, or set a different port — edit "port" in ${le()} (or the extension's Gateway tab) and restart. The extension must point at the same port.`)}process.exit(1)});return}console.error(`Gateway server error: ${T?.message||T}`),process.exit(1)}),w.listen(t.port,t.host,()=>{B&&console.log(" standby : the other gateway is gone — this copy has the port now"),B=!1,console.log(`ChatPanel Privacy Gateway v${de} on http://${t.host}:${t.port}`),w.linkHost?.start().catch(T=>console.log(` link : not started (${T?.message||T})`)),w.runtimeDefaults?.().then(T=>{for(const x of T||[])console.log(` ${x.label.toLowerCase().padEnd(9).slice(0,9)}: ${x.ok?x.already?"running":x.adopted?"already running — adopted":"started":`not started (${x.skipped})`}`)}).catch(T=>console.log(` runtime : defaults not started (${T?.message||T})`)),console.log(` backend : ${t.backend}`+(t.backend==="bridge"?` (agent: ${t.bridge.agent}, via ${t.bridge.url})`:"")),t.bridge?.openAgentLane&&console.log(" ⚠ agents : bridge.openAgentLane is ON — any local process may drive a CLI agent through this gateway without a token");for(const T of qa(t))console.log(` ⚠ sandbox : ${T}`);console.log(` confined : ${wn(wt({stateDir:He.dirname(le())}))}`),ut={mode:"starting",version:null,pid:null,restarts:0,why:"deciding: adopt the bridge that answers, or start ours"},un(t,{childEnv:()=>({...Za(t,process.env,qe()),...Ya(t)})}).then(T=>{Ve=T}).catch(T=>{ut={mode:"off",version:null,pid:null,restarts:0,why:`not supervised (${T?.message||T})`},console.log(` bridge : not supervised (${T?.message||T})`)}),console.log(` redaction: ${t.redaction.tier}`+(t.redaction.detection?.backend&&t.redaction.detection.backend!=="off"?` + ${t.redaction.detection.backend} detector`:t.ner?.autostart?" (+ NER starting…)":"")),ct(t.host)||console.error(`⚠ SECURITY: gateway bound to NON-LOOPBACK host ${t.host}. It is reachable off-machine, and the loopback Host-header check is spoofable from the LAN. Admin routes still need the token/extension, but prefer binding 127.0.0.1 unless you intend LAN exposure on a trusted network.`)}),io()&&kt(J,ft()).then(T=>{T?.ok&&(console.log(` warm : seeded ${T.ingested} records from ${T.file}`),T.whole&&Ue())}).catch(()=>{});const E=()=>{y?.stop(),$.stop(),Ve?.stop(),is(w)};return process.on("SIGINT",E),process.on("SIGTERM",E),w}export{vs as RECORDS_MAX_BYTES,_l as VERSION,As as createGateway,_s as joinUpstream,Bt as parseAgentModel,Sl as start};
|
package/src/version.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
const o="0.
|
|
1
|
+
const o="0.120.1";export{o as VERSION};
|