@chatpanel/gateway 0.9.1 → 0.9.3
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 +2 -2
- package/src/server.js +2 -2
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@chatpanel/gateway",
|
|
3
|
-
"version": "0.9.
|
|
3
|
+
"version": "0.9.3",
|
|
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": {
|
|
@@ -21,7 +21,7 @@
|
|
|
21
21
|
"node": ">=18"
|
|
22
22
|
},
|
|
23
23
|
"dependencies": {
|
|
24
|
-
"@chatpanel/bridge": "^0.13.
|
|
24
|
+
"@chatpanel/bridge": "^0.13.3",
|
|
25
25
|
"@chatpanel/events": "^0.108.0",
|
|
26
26
|
"@chatpanel/pii": "^0.8.0",
|
|
27
27
|
"@huggingface/transformers": "^4.2.0",
|
package/src/server.js
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
|
-
import{createServer as yt}from"node:http";import{loadConfig as Be}from"./config.js";import{startEntitlementRefresh as ht,maybeRevalidate as ft}from"./entitlement-refresh.js";import{redactSegments as fe,segment as Ce}from"./redact.js";import{pipeRestoredStream as gt,pipeRestoredOpenAIStream as bt,makeTokenRestorer as De,restoreDeep as wt}from"./stream.js";import{restoreText as kt,gatedDictionary as St,narrowSpecs as vt,makeToolHarness as Tt,placeholderToolNote as _t,placeholderNote as Ot,assertEndpointUrl as Et,capRunOptions as xt,isPaired as At}from"@chatpanel/pii";import{ensureGatewayToken as ge,currentGatewayToken as Pt,isAdminAuthorized as F,callerTrustOf as ce,setPinnedExtensionIds as $t,issuePairingCode as Nt,claimPairingCode as Bt}from"./gateway-token.js";import{installEgressLedger as Ct,egressAudit as Dt}from"./egress.js";import{initPolicy as It,activePolicy as jt,applyPolicyToConfig as Ie,managedSummary as ae,PolicyLoadError as Mt}from"./policy.js";import{routeAllowed as je,agentAllowed as Rt,egressAllowed as Lt}from"@chatpanel/events/policy.js";import{resolveBridgeUrl as de}from"./bridge.js";import{secureFetch as Me}from"./secure-fetch.js";import{streamBridgeChat as Re,readBridgeToken as ie,openBridgeChat as Gt}from"./bridge.js";import{createRelaySession as zt,getRelaySession as Le,endRelaySession as ue,pumpBridgeStream as Vt,deliverToolResult as Jt,toolsToSpecs as Ht,parseToolCallId as Ge,touchRelaySession as be}from"./toolrelay.js";import{shaperFor as we}from"./shape.js";import{startNer as Ut,ensureNer as ke}from"./ner.js";import{installTimestampedConsole as Ft}from"./log.js";import{saveBackupSecret as Wt,clearBackupSecret as Kt,loadBackupSecret as ze,hasBackupSecret as Ve}from"./history-store.js";import{createMemoryStore as Zt}from"./memory-store.js";import{createPrefsStore as Yt}from"./prefs-store.js";import{createTeamStore as Xt,loadOrCreateKey as Se}from"./team-store.js";import{createScorecardStore as Qt}from"./scorecard-store.js";import{createEngineLedgerStore as qt}from"./engine-ledger-store.js";import{createProjectStore as eo}from"./project-store.js";import{applicationsFor as to,recruitPass as oo}from"./recruiting.js";import{ensureBridge as ro}from"./bridge-supervisor.js";import{checkForUpdate as no,updateStatus as so,startUpdate as ao,updateJob as io}from"./update.js";import{createHistoryStore as lo}from"./sqlite-store.js";import{ingestBackups as ve}from"./backup-ingest.js";import*as B from"./ner-engine.js";import*as x from"./stt-engine.js";import*as $ from"./diarize-engine.js";import{MODEL_CATALOG as co,isKnownModel as uo,isValidCustomModelId as mo}from"./models.js";import{STT_MODEL_CATALOG as po,isKnownSttModel as yo,isValidCustomSttId as ho,DEFAULT_STT_MODEL as Te,STT_DTYPES as fo,isValidDtype as go}from"./stt-models.js";import*as k from"./tts-engine.js";import{TTS_MODEL_CATALOG as Je,TTS_VOICES as bo,isKnownTtsModel as wo,isValidCustomTtsId as ko,isKnownVoice as He,isValidVoiceId as Ue,DEFAULT_TTS_MODEL as Fe,DEFAULT_TTS_VOICE as Y,TTS_DTYPES as So,isValidTtsDtype as vo,MAX_TTS_CHARS as We,ttsModelHasCustomVoices as To,resolveDefaultModel as Ke,POCKET_VOICES as _o,DEFAULT_POCKET_VOICE as me,isPocketVoice as pe,ttsModelEngine as ye}from"./tts-models.js";import{ttsDestination as Oo,synthesizeRemote as Eo,isValidRemoteVoice as xo}from"./tts-remote.js";import{rawOrtAvailable as _e}from"./ort.js";import*as L from"./tts-voices.js";import{resolveTtsVoice as Ao}from"./tts-voice-resolve.js";import{resolvePro as q,checkQuota as Po,consume as $o,usage as No}from"./freegate.js";import{publicConfig as Ze,applyConfigPatch as Bo,applyNerModelSelection as Co,persistConfig as te,configPath as ee,bridgeAgentOptions as Ye}from"./configstore.js";import{resolveDestination as Xe,aggregateModelsAsync as Do,listDestinations as Io}from"./router.js";import{makeAccessEvent as Qe}from"./observability.js";import{createPersistentAccessLog as jo}from"./access-log-store.js";import{planQueries as Mo,multiSearch as Ro}from"./rrf.js";import*as Oe from"./openai.js";import*as qe from"./responses.js";import*as Ee from"./anthropic.js";const W="0.9.1",N=await lo(),H=await Zt(),K=Yt(),oe=Qt({key:Se()}),re=qt({key:Se()}),G=eo({key:Se()}),C=Xt({scorecards:oe,engines:re}),xe=new Set,et=(t,i)=>{for(const d of xe)try{d({applied:t,by:i,revision:K.revision})}catch{}},Ae=jo(),tt=new Set(["codex","claude","opencode","pi","kiro","antigravity","hermes"]),Lo=16,Go=/^mcp[_-]/i,ot=t=>t&&t.function&&t.function.name||t&&t.name||"",zo=t=>t&&t.function&&t.function.description||t&&t.description||"";function rt(t){return typeof t=="string"?t:Array.isArray(t)?t.map(i=>typeof i=="string"?i:i&&(i.text||i.content)||"").join(" "):""}function Vo(t,i){if(!t)return"";if(i==="responses"){const r=t.input;return typeof r=="string"?r:Array.isArray(r)?r.map(o=>rt(o&&(o.content??o))).join(" "):""}const d=Array.isArray(t.messages)?t.messages:[];for(let r=d.length-1;r>=0;r--)if(d[r]&&d[r].role==="user")return rt(d[r].content);return""}const nt=new Set(["host","connection","content-length","transfer-encoding","accept-encoding","content-encoding","keep-alive"]);function st(t){if(!t)return!1;const i=t.replace(/:\d+$/,"").replace(/^\[|\]$/g,"");return i==="localhost"||i==="127.0.0.1"||i==="::1"}function Jo(t,i){return!t||/^chrome-extension:\/\//.test(t)||/^moz-extension:\/\//.test(t)||/^http:\/\/(localhost|127\.0\.0\.1|\[::1\])(:\d+)?$/.test(t)?!0:Array.isArray(i.allowedOrigins)&&i.allowedOrigins.includes(t)}function Ho(t,i){t.setHeader("Access-Control-Allow-Origin",i||"*"),t.setHeader("Access-Control-Allow-Methods","GET, POST, PUT, DELETE, OPTIONS"),t.setHeader("Access-Control-Allow-Headers","Content-Type, Authorization, X-ChatPanel-Token"),t.setHeader("Vary","Origin")}const at=Date.now();function Uo(t){if(!t)return"";const i={redact:"redact",upstream:"model",stream:"stream",restore:"restore",total:"total"};return Object.keys(t).map(d=>`${i[d]||d} ${t[d]}ms`).join(" · ")}function Fo(t){const i=/^(model|harness):([^/]+)(?:\/(.+))?$/.exec(String(t||""));return i?{kind:i[1],id:i[2],...i[3]?{model:i[3]}:{}}:null}function Wo(t){const i=performance.now(),d={};let r=!1;const o=(u,c)=>{d[u]=Math.round(c*10)/10};return{meta:{},timings:d,mark:o,lap(u,c){o(u,performance.now()-c)},clock(){return performance.now()},commit(){if(r)return;r=!0,o("total",performance.now()-i);const u={...this.meta,timings:d};setImmediate(()=>{t(u),console.log(`[gateway] model=${u.model||"-"} → ${u.dest?`${u.dest}(${u.type})`:"none"} · ${u.redaction==="off"?"redaction OFF (client request)":`redacted ${u.redacted||0}`}${u.sanitized?` · scrubbed ${u.sanitized} hidden`:""}${u.narrowed?` · narrowed -${u.narrowed}`:""} · ${Uo(d)}`)})}}}function it(t,i){if(!t||!t.byToken||i!=="types"&&i!=="values")return;const d=[];for(const[r,o]of t.byToken){const u=/^\[\[([A-Z][A-Z0-9]*)_\d+\]\]$/.exec(r),c=u?u[1]:"PII",y=r.replace(/^\[\[|\]\]$/g,"");d.push(i==="values"?{token:y,type:c,value:o}:{token:y,type:c})}return d}function Ko(t,i,d){return Ee.matches(t)||"anthropic-version"in i?{kind:"anthropic",adapter:Ee,redactable:Ee.matches(t),base:d.upstreams?.anthropic?.baseUrl}:qe.matches(t)?{kind:"responses",adapter:qe,redactable:!0,base:d.upstreams?.openai?.baseUrl}:{kind:"openai",adapter:Oe,redactable:Oe.matches(t),base:d.upstreams?.openai?.baseUrl}}function Pe(t,i){const d=String(t||"");if(tt.has(d))return{agent:d,agentModel:""};const r=d.indexOf("/");if(r>0){const o=d.slice(0,r);if(tt.has(o))return{agent:o,agentModel:d.slice(r+1)}}return{agent:i.bridge.agent,agentModel:""}}function lt(t,i){return Pe(t,i).agent}function Zo(t,i){if(i!=="openai"||!t)return!1;const d=Oe.extractLatestToolResult(t);if(!d)return!1;const r=Ge(d.tool_call_id);return!!(r&&Le(r.gwId))}function Yo(t,i){try{const d=new URL(t),r=d.hostname.replace(/^\[|\]$/g,""),o=r==="127.0.0.1"||r==="localhost"||r==="::1",u=d.port||(d.protocol==="https:"?"443":"80");return o&&String(u)===String(i.port)}catch{return!1}}async function v(t,i){const d=[];let r=0;for await(const o of t){if(r+=o.length,i&&r>i){const u=new Error("payload too large");throw u.code=413,u}d.push(o)}return Buffer.concat(d)}function s(t,i,d){t.writeHead(i,{"content-type":"application/json"}),t.end(JSON.stringify(d))}function ct(t){const i=t.redaction?.detection?.url;return!i||t.redaction?.detection?.backend==="off"?null:i}function $e(t){const i=t?.redaction?.detection,d=t?.redaction?.tier==="full"?"full":"basic";if(i&&i.backend&&i.backend!=="off")return{source:"external",backend:i.backend,state:"external",model:i.model||null,ready:!0,tier:d,coverage:d==="full"?"names":"patterns"};const r=B.health(),o=r.ok&&d==="full";return{source:"bundled",state:r.state,model:r.model||t?.ner?.model||null,installed:B.modelOnDisk(t?.ner?.model||void 0),error:r.error||null,ready:o,tier:d,coverage:o?"names":"patterns"}}async function dt(t){if(B.state()!=="off"){const d=B.health();return{configured:d.configured,ok:d.ok,state:d.state,model:d.model,error:d.error||null,url:d.configured?`http://${t.host}:${t.port}/ner`:null}}const i=ct(t);if(!i)return{configured:!1,ok:!1,url:null,model:null};try{const d=await Me(i.replace(/\/ner\/?$/,"")+"/health",{signal:AbortSignal.timeout(2e3)});if(!d.ok)return{configured:!0,ok:!1,url:i,model:null};const r=await d.json().catch(()=>({}));return{configured:!0,ok:!0,url:i,model:r.model||null}}catch{return{configured:!0,ok:!1,url:i,model:null}}}function Xo(t,i){const d={};for(const[r,o]of Object.entries(t)){const u=r.toLowerCase();u.startsWith("x-chatpanel-")||nt.has(u)||(d[r]=o)}d["accept-encoding"]="identity";try{d.host=new URL(i).host}catch{}return d}async function ut(t,i,d,r){const o=De(i.vault),u=r?r.clock():0;let c=u,y=!0;const g=()=>{r&&y&&(r.lap("upstream",u),c=r.clock(),y=!1)};await Vt(i,{onText:E=>{g(),be(i.id);const m=o.push(E);m&&t.write(d.sseDelta(m))},onToolRequest:({name:E,restoredArgs:m,toolId:M})=>{g(),be(i.id);const A=o.flush();A&&t.write(d.sseDelta(A)),t.write(d.sseToolCalls([{id:M,name:E,arguments:JSON.stringify(m)}])),t.write(d.sseToolFinish()),r&&r.lap("stream",c),t.end(),r?.commit()},onDone:()=>{const E=o.flush();E&&t.write(d.sseDelta(E)),t.write(d.sseTail()),r&&r.lap("stream",c),t.end(),ue(i.id),r?.commit()},onError:E=>{t.write(`data: ${JSON.stringify({error:{message:E.message,type:"bridge_error"}})}
|
|
1
|
+
import{createServer as yt}from"node:http";import{loadConfig as Be}from"./config.js";import{startEntitlementRefresh as ht,maybeRevalidate as ft}from"./entitlement-refresh.js";import{redactSegments as fe,segment as Ce}from"./redact.js";import{pipeRestoredStream as gt,pipeRestoredOpenAIStream as bt,makeTokenRestorer as De,restoreDeep as wt}from"./stream.js";import{restoreText as kt,gatedDictionary as St,narrowSpecs as vt,makeToolHarness as Tt,placeholderToolNote as _t,placeholderNote as Ot,assertEndpointUrl as Et,capRunOptions as xt,isPaired as At}from"@chatpanel/pii";import{ensureGatewayToken as ge,currentGatewayToken as Pt,isAdminAuthorized as F,callerTrustOf as ce,setPinnedExtensionIds as $t,issuePairingCode as Nt,claimPairingCode as Bt}from"./gateway-token.js";import{installEgressLedger as Ct,egressAudit as Dt}from"./egress.js";import{initPolicy as It,activePolicy as jt,applyPolicyToConfig as Ie,managedSummary as ae,PolicyLoadError as Mt}from"./policy.js";import{routeAllowed as je,agentAllowed as Rt,egressAllowed as Lt}from"@chatpanel/events/policy.js";import{resolveBridgeUrl as de}from"./bridge.js";import{secureFetch as Me}from"./secure-fetch.js";import{streamBridgeChat as Re,readBridgeToken as ie,openBridgeChat as Gt}from"./bridge.js";import{createRelaySession as zt,getRelaySession as Le,endRelaySession as ue,pumpBridgeStream as Vt,deliverToolResult as Jt,toolsToSpecs as Ht,parseToolCallId as Ge,touchRelaySession as be}from"./toolrelay.js";import{shaperFor as we}from"./shape.js";import{startNer as Ut,ensureNer as ke}from"./ner.js";import{installTimestampedConsole as Ft}from"./log.js";import{saveBackupSecret as Wt,clearBackupSecret as Kt,loadBackupSecret as ze,hasBackupSecret as Ve}from"./history-store.js";import{createMemoryStore as Zt}from"./memory-store.js";import{createPrefsStore as Yt}from"./prefs-store.js";import{createTeamStore as Xt,loadOrCreateKey as Se}from"./team-store.js";import{createScorecardStore as Qt}from"./scorecard-store.js";import{createEngineLedgerStore as qt}from"./engine-ledger-store.js";import{createProjectStore as eo}from"./project-store.js";import{applicationsFor as to,recruitPass as oo}from"./recruiting.js";import{ensureBridge as ro}from"./bridge-supervisor.js";import{checkForUpdate as no,updateStatus as so,startUpdate as ao,updateJob as io}from"./update.js";import{createHistoryStore as lo}from"./sqlite-store.js";import{ingestBackups as ve}from"./backup-ingest.js";import*as B from"./ner-engine.js";import*as x from"./stt-engine.js";import*as $ from"./diarize-engine.js";import{MODEL_CATALOG as co,isKnownModel as uo,isValidCustomModelId as mo}from"./models.js";import{STT_MODEL_CATALOG as po,isKnownSttModel as yo,isValidCustomSttId as ho,DEFAULT_STT_MODEL as Te,STT_DTYPES as fo,isValidDtype as go}from"./stt-models.js";import*as k from"./tts-engine.js";import{TTS_MODEL_CATALOG as Je,TTS_VOICES as bo,isKnownTtsModel as wo,isValidCustomTtsId as ko,isKnownVoice as He,isValidVoiceId as Ue,DEFAULT_TTS_MODEL as Fe,DEFAULT_TTS_VOICE as Y,TTS_DTYPES as So,isValidTtsDtype as vo,MAX_TTS_CHARS as We,ttsModelHasCustomVoices as To,resolveDefaultModel as Ke,POCKET_VOICES as _o,DEFAULT_POCKET_VOICE as me,isPocketVoice as pe,ttsModelEngine as ye}from"./tts-models.js";import{ttsDestination as Oo,synthesizeRemote as Eo,isValidRemoteVoice as xo}from"./tts-remote.js";import{rawOrtAvailable as _e}from"./ort.js";import*as L from"./tts-voices.js";import{resolveTtsVoice as Ao}from"./tts-voice-resolve.js";import{resolvePro as q,checkQuota as Po,consume as $o,usage as No}from"./freegate.js";import{publicConfig as Ze,applyConfigPatch as Bo,applyNerModelSelection as Co,persistConfig as te,configPath as ee,bridgeAgentOptions as Ye}from"./configstore.js";import{resolveDestination as Xe,aggregateModelsAsync as Do,listDestinations as Io}from"./router.js";import{makeAccessEvent as Qe}from"./observability.js";import{createPersistentAccessLog as jo}from"./access-log-store.js";import{planQueries as Mo,multiSearch as Ro}from"./rrf.js";import*as Oe from"./openai.js";import*as qe from"./responses.js";import*as Ee from"./anthropic.js";const W="0.9.3",N=await lo(),H=await Zt(),K=Yt(),oe=Qt({key:Se()}),re=qt({key:Se()}),G=eo({key:Se()}),C=Xt({scorecards:oe,engines:re}),xe=new Set,et=(t,i)=>{for(const d of xe)try{d({applied:t,by:i,revision:K.revision})}catch{}},Ae=jo(),tt=new Set(["codex","claude","opencode","pi","kiro","antigravity","hermes"]),Lo=16,Go=/^mcp[_-]/i,ot=t=>t&&t.function&&t.function.name||t&&t.name||"",zo=t=>t&&t.function&&t.function.description||t&&t.description||"";function rt(t){return typeof t=="string"?t:Array.isArray(t)?t.map(i=>typeof i=="string"?i:i&&(i.text||i.content)||"").join(" "):""}function Vo(t,i){if(!t)return"";if(i==="responses"){const r=t.input;return typeof r=="string"?r:Array.isArray(r)?r.map(o=>rt(o&&(o.content??o))).join(" "):""}const d=Array.isArray(t.messages)?t.messages:[];for(let r=d.length-1;r>=0;r--)if(d[r]&&d[r].role==="user")return rt(d[r].content);return""}const nt=new Set(["host","connection","content-length","transfer-encoding","accept-encoding","content-encoding","keep-alive"]);function st(t){if(!t)return!1;const i=t.replace(/:\d+$/,"").replace(/^\[|\]$/g,"");return i==="localhost"||i==="127.0.0.1"||i==="::1"}function Jo(t,i){return!t||/^chrome-extension:\/\//.test(t)||/^moz-extension:\/\//.test(t)||/^http:\/\/(localhost|127\.0\.0\.1|\[::1\])(:\d+)?$/.test(t)?!0:Array.isArray(i.allowedOrigins)&&i.allowedOrigins.includes(t)}function Ho(t,i){t.setHeader("Access-Control-Allow-Origin",i||"*"),t.setHeader("Access-Control-Allow-Methods","GET, POST, PUT, DELETE, OPTIONS"),t.setHeader("Access-Control-Allow-Headers","Content-Type, Authorization, X-ChatPanel-Token"),t.setHeader("Vary","Origin")}const at=Date.now();function Uo(t){if(!t)return"";const i={redact:"redact",upstream:"model",stream:"stream",restore:"restore",total:"total"};return Object.keys(t).map(d=>`${i[d]||d} ${t[d]}ms`).join(" · ")}function Fo(t){const i=/^(model|harness):([^/]+)(?:\/(.+))?$/.exec(String(t||""));return i?{kind:i[1],id:i[2],...i[3]?{model:i[3]}:{}}:null}function Wo(t){const i=performance.now(),d={};let r=!1;const o=(u,c)=>{d[u]=Math.round(c*10)/10};return{meta:{},timings:d,mark:o,lap(u,c){o(u,performance.now()-c)},clock(){return performance.now()},commit(){if(r)return;r=!0,o("total",performance.now()-i);const u={...this.meta,timings:d};setImmediate(()=>{t(u),console.log(`[gateway] model=${u.model||"-"} → ${u.dest?`${u.dest}(${u.type})`:"none"} · ${u.redaction==="off"?"redaction OFF (client request)":`redacted ${u.redacted||0}`}${u.sanitized?` · scrubbed ${u.sanitized} hidden`:""}${u.narrowed?` · narrowed -${u.narrowed}`:""} · ${Uo(d)}`)})}}}function it(t,i){if(!t||!t.byToken||i!=="types"&&i!=="values")return;const d=[];for(const[r,o]of t.byToken){const u=/^\[\[([A-Z][A-Z0-9]*)_\d+\]\]$/.exec(r),c=u?u[1]:"PII",y=r.replace(/^\[\[|\]\]$/g,"");d.push(i==="values"?{token:y,type:c,value:o}:{token:y,type:c})}return d}function Ko(t,i,d){return Ee.matches(t)||"anthropic-version"in i?{kind:"anthropic",adapter:Ee,redactable:Ee.matches(t),base:d.upstreams?.anthropic?.baseUrl}:qe.matches(t)?{kind:"responses",adapter:qe,redactable:!0,base:d.upstreams?.openai?.baseUrl}:{kind:"openai",adapter:Oe,redactable:Oe.matches(t),base:d.upstreams?.openai?.baseUrl}}function Pe(t,i){const d=String(t||"");if(tt.has(d))return{agent:d,agentModel:""};const r=d.indexOf("/");if(r>0){const o=d.slice(0,r);if(tt.has(o))return{agent:o,agentModel:d.slice(r+1)}}return{agent:i.bridge.agent,agentModel:""}}function lt(t,i){return Pe(t,i).agent}function Zo(t,i){if(i!=="openai"||!t)return!1;const d=Oe.extractLatestToolResult(t);if(!d)return!1;const r=Ge(d.tool_call_id);return!!(r&&Le(r.gwId))}function Yo(t,i){try{const d=new URL(t),r=d.hostname.replace(/^\[|\]$/g,""),o=r==="127.0.0.1"||r==="localhost"||r==="::1",u=d.port||(d.protocol==="https:"?"443":"80");return o&&String(u)===String(i.port)}catch{return!1}}async function v(t,i){const d=[];let r=0;for await(const o of t){if(r+=o.length,i&&r>i){const u=new Error("payload too large");throw u.code=413,u}d.push(o)}return Buffer.concat(d)}function s(t,i,d){t.writeHead(i,{"content-type":"application/json"}),t.end(JSON.stringify(d))}function ct(t){const i=t.redaction?.detection?.url;return!i||t.redaction?.detection?.backend==="off"?null:i}function $e(t){const i=t?.redaction?.detection,d=t?.redaction?.tier==="full"?"full":"basic";if(i&&i.backend&&i.backend!=="off")return{source:"external",backend:i.backend,state:"external",model:i.model||null,ready:!0,tier:d,coverage:d==="full"?"names":"patterns"};const r=B.health(),o=r.ok&&d==="full";return{source:"bundled",state:r.state,model:r.model||t?.ner?.model||null,installed:B.modelOnDisk(t?.ner?.model||void 0),error:r.error||null,ready:o,tier:d,coverage:o?"names":"patterns"}}async function dt(t){if(B.state()!=="off"){const d=B.health();return{configured:d.configured,ok:d.ok,state:d.state,model:d.model,error:d.error||null,url:d.configured?`http://${t.host}:${t.port}/ner`:null}}const i=ct(t);if(!i)return{configured:!1,ok:!1,url:null,model:null};try{const d=await Me(i.replace(/\/ner\/?$/,"")+"/health",{signal:AbortSignal.timeout(2e3)});if(!d.ok)return{configured:!0,ok:!1,url:i,model:null};const r=await d.json().catch(()=>({}));return{configured:!0,ok:!0,url:i,model:r.model||null}}catch{return{configured:!0,ok:!1,url:i,model:null}}}function Xo(t,i){const d={};for(const[r,o]of Object.entries(t)){const u=r.toLowerCase();u.startsWith("x-chatpanel-")||nt.has(u)||(d[r]=o)}d["accept-encoding"]="identity";try{d.host=new URL(i).host}catch{}return d}async function ut(t,i,d,r){const o=De(i.vault),u=r?r.clock():0;let c=u,y=!0;const g=()=>{r&&y&&(r.lap("upstream",u),c=r.clock(),y=!1)};await Vt(i,{onText:E=>{g(),be(i.id);const m=o.push(E);m&&t.write(d.sseDelta(m))},onToolRequest:({name:E,restoredArgs:m,toolId:M})=>{g(),be(i.id);const A=o.flush();A&&t.write(d.sseDelta(A)),t.write(d.sseToolCalls([{id:M,name:E,arguments:JSON.stringify(m)}])),t.write(d.sseToolFinish()),r&&r.lap("stream",c),t.end(),r?.commit()},onDone:()=>{const E=o.flush();E&&t.write(d.sseDelta(E)),t.write(d.sseTail()),r&&r.lap("stream",c),t.end(),ue(i.id),r?.commit()},onError:E=>{t.write(`data: ${JSON.stringify({error:{message:E.message,type:"bridge_error"}})}
|
|
2
2
|
|
|
3
3
|
`),t.end(),ue(i.id),r?.commit()}})}async function Qo(t,i,{kind:d,adapter:r,agent:o,run:u=null},c,y,g,E,m,M=null,A=null){const{messages:D,system:Z}=r.toTurn(c),{agentModel:R}=Pe(c?.model,g),j=Ye(g,{...R?{model:R}:{},...u||{}}),P=ie(g.bridge.token),O=we(d,c?.model||o),I={tier:g.redaction.tier==="full"?"full":"basic",dictionary:St(g.redaction,E),entities:[]},z=await de(g),T=zt({vault:y,redactOpts:I,bridgeUrl:z,token:P,harness:M});let U;try{U=await Gt({bridgeUrl:z,agent:o,token:P,messages:D,system:Z,specs:Ht(m),options:j,signal:void 0})}catch(X){return ue(T.id),A?.commit(),s(i,502,{error:{message:`bridge: ${X.message}`,type:"bridge_error"}})}return T.reader=U.body.getReader(),i.writeHead(200,{"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive"}),i.write(O.sseHead()),ut(i,T,O,A)}async function qo(t,i,d,r,o=null){be(i.id),i.rounds=(i.rounds||0)+1;try{const c=o?o.clock():0;await Jt(i,d),o&&o.lap("redact",c)}catch(c){return ue(i.id),o?.commit(),s(t,502,{error:{message:`tool-result: ${c.message}`,type:"bridge_error"}})}const u=we("openai",r||"codex");return t.writeHead(200,{"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive"}),t.write(u.sseHead()),ut(t,i,u,o)}async function er(t,i,{kind:d,adapter:r,redactable:o,pathname:u,agentOverride:c,harness:y,trace:g,run:E=null},m,M,A,D){if(!o)return g?.commit(),s(i,404,{error:`endpoint ${u} not supported by the bridge backend`});if(d==="openai"){const e=r.extractLatestToolResult(m);if(e){const a=Ge(e.tool_call_id),l=a&&Le(a.gwId);if(l)return qo(i,l,e.content,m?.model,g)}const n=r.extractTools(m);if(n.length&&m?.stream===!0)return Qo(t,i,{kind:d,adapter:r,agent:c||lt(m?.model,A),run:E},m,M,A,D,n,y,g)}const{messages:Z,system:R}=r.toTurn(m),j=c||lt(m?.model,A),P=m?.stream===!0,O=we(d,m?.model||j),I=ie(A.bridge.token),z=new AbortController;i.on("close",()=>{i.writableFinished||z.abort()});const{agentModel:T}=Pe(m?.model,A),U={bridgeUrl:await de(A),agent:j,token:I,messages:Z,system:R,signal:z.signal,options:Ye(A,{...T?{model:T}:{},...E||{}})};if(!P)try{let e="";const n=g?g.clock():0;await Re(U,p=>{e+=p}),g&&g.lap("upstream",n);const a=g?g.clock():0,l=O.full(kt(e,M));return g&&g.lap("restore",a),i.writeHead(200,{"content-type":O.contentType}),i.end(l),g?.commit()}catch(e){return g?.commit(),s(i,502,{error:{message:`bridge backend failed: ${e.message}`,type:"bridge_error"}})}i.writeHead(200,{"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive"}),i.write(O.sseHead());const X=De(M),ne=g?g.clock():0;let se=ne;try{let e=!0;await Re(U,a=>{g&&e&&(g.lap("upstream",ne),se=g.clock(),e=!1);const l=X.push(a);l&&i.write(O.sseDelta(l))},O.sseActivity?a=>{try{i.write(O.sseActivity(wt(a,M)))}catch{}}:null);const n=X.flush();n&&i.write(O.sseDelta(n)),i.write(O.sseTail())}catch(e){i.write(`data: ${JSON.stringify({error:{message:e.message,type:"bridge_error"}})}
|
|
4
4
|
|
|
5
|
-
`)}g&&g.lap("stream",se),i.end(),g?.commit()}function tr(t,i,d=""){const r=String(t||"").replace(/\/+$/,""),o=String(i||"").split("/")[1];return o&&r.endsWith(`/${o}`)?r.slice(0,-(o.length+1))+i+d:r+i+d}const or=9e4;function rr(t,i,d){if(i===d)return t;const r=i/d,o=new Float32Array(Math.floor(t.length/r));for(let u=0;u<o.length;u++){const c=u*r,y=Math.floor(c),g=Math.min(t.length-1,y+1),E=c-y;o[u]=t[y]*(1-E)+t[g]*E}return o}const nr=["/tts","/stt","/ner","/diarize","/skills","/redact","/config","/logs","/status","/admin"];async function sr(t,i,{adapter:d,kind:r,pathname:o,search:u,base:c,destKey:y,destProtocol:g,harness:E,trace:m},M,A){let D;const Z=m?m.clock():0;try{const O=Xo(t.headers,c);y&&(g==="anthropic"?(O["x-api-key"]=y,delete O.authorization):O.authorization=`Bearer ${y}`);const I=Et(tr(c,o,u)).toString();D=await fetch(I,{method:t.method,headers:O,body:["GET","HEAD"].includes(t.method)?void 0:M})}catch(O){return m?.commit(),s(i,502,{error:`upstream fetch failed: ${O.message}`})}const R=D.headers.get("content-type")||"",j={};if(D.headers.forEach((O,I)=>{nt.has(I.toLowerCase())||(j[I]=O)}),R.includes("text/event-stream")&&D.body){m&&m.lap("upstream",Z);const O=m?m.clock():0;i.writeHead(D.status,j);const I=r==="openai"?bt(D.body,i,A,E):gt(D.body,i,A);return Promise.resolve(I).finally(()=>{m&&m.lap("stream",O),m?.commit()})}const P=Buffer.from(await D.arrayBuffer());if(m&&m.lap("upstream",Z),A&&R.includes("application/json"))try{const O=m?m.clock():0,I=d.restoreResponse(JSON.parse(P.toString("utf8")),A,E);return m&&m.lap("restore",O),i.writeHead(D.status,{...j,"content-type":"application/json"}),i.end(Buffer.from(JSON.stringify(I),"utf8")),m?.commit()}catch{}i.writeHead(D.status,j),i.end(P),m?.commit()}function ar(t=Be()){$t(t.allowedExtensionIds||[]);const i=[],d=r=>{i.push(r),i.length>50&&i.shift()};return yt(async(r,o)=>{const u=new URL(r.url,"http://127.0.0.1"),c=u.pathname;if(!st(r.headers.host))return s(o,403,{error:"loopback only"});if(!Jo(r.headers.origin,t))return s(o,403,{error:"origin not allowed"});if(r.headers.origin&&Ho(o,r.headers.origin),r.method==="OPTIONS")return o.writeHead(204),o.end();if(c==="/admin/token"&&r.method==="POST")return F(r)?s(o,200,{token:ge()}):s(o,403,{error:"admin: extension origin or gateway token required"});if(c==="/pair/code"&&r.method==="POST"){if(!F(r))return s(o,403,{error:"pair/code: extension origin or gateway token required"});const e=Nt();return console.log("[gateway] pairing code issued — valid for 5 minutes, one use"),s(o,200,{ok:!0,...e})}if(c==="/pair"&&r.method==="POST"){let e=null;try{e=JSON.parse((await v(r,t.maxBodyBytes)).toString("utf8"))}catch{e=null}const n=Bt(e?.code);if(!n.ok)return console.log(`[gateway] pairing refused (${n.reason}) from ${ce(r)} caller`),s(o,403,{error:n.reason});console.log(`[gateway] paired a ${ce(r)} client${r.headers.origin?` (${r.headers.origin})`:""}`);const a=ie(t.bridge?.token);return s(o,200,{ok:!0,token:Pt()||ge(),...a?{bridgeToken:a}:{}})}if(c==="/whoami"&&r.method==="POST"){const e=ce(r);return s(o,200,{ok:!0,trust:e,paired:At(e),version:W})}if(c==="/audit"&&r.method==="GET")return F(r)?s(o,200,Dt(t,{version:W,startedAt:at,managed:ae()})):s(o,403,{error:"audit: extension origin or gateway token required"});if((c==="/config"||c==="/logs"||c==="/update")&&!F(r))return s(o,403,{error:"admin route: extension origin or gateway token required"});if(c==="/update"&&r.method==="GET"){const e=await no(W,{force:u.searchParams.get("force")==="1"}).catch(n=>({current:W,updateAvailable:!1,error:String(n?.message||n)}));return s(o,200,{ok:!0,update:e,job:io()})}if(c==="/update"&&r.method==="POST"){const e=ao(W);return s(o,e.already?409:202,{ok:!0,job:e})}if((c==="/v1/history/key"||c==="/v1/history/ingest-backup")&&r.method==="POST"&&!F(r))return s(o,403,{error:{message:"history key route: extension origin or gateway token required",type:"forbidden"}});if((c==="/v1/history/ingest"||c==="/v1/history/clear")&&r.method==="POST"&&!F(r))return s(o,403,{error:{message:"history write — extension origin or gateway token required",type:"forbidden"}});if((c==="/v1/memory/remember"||c==="/v1/memory/forget"||c==="/v1/memory/sync"||c==="/v1/memory/clear")&&r.method==="POST"&&!F(r))return s(o,403,{error:{message:"memory write — extension origin or gateway token required",type:"forbidden"}});if((c==="/v1/prefs"||c.startsWith("/v1/prefs/")||c.startsWith("/v1/teams")||c.startsWith("/v1/agents")||c.startsWith("/v1/projects"))&&!F(r))return s(o,403,{error:{message:"prefs: extension origin or gateway token required",type:"forbidden"}});if(c.startsWith("/v1/observability")&&!F(r))return s(o,403,{error:{message:"observability: extension origin or gateway token required",type:"forbidden"}});if(r.method==="GET"&&c==="/health"){const e=x.health(),n=k.health();return s(o,200,{ok:!0,version:W,backend:t.backend,tier:t.redaction.tier,pairing:!0,...ae()?{managed:ae()}:{},...process.env.CHATPANEL_MANAGED_BY?{managedBy:String(process.env.CHATPANEL_MANAGED_BY).slice(0,32)}:{},...he?{bridge:he.status()}:{},stt:{enabled:t.stt?.enabled!==!1,state:e.state,ready:e.ok,model:e.model||t.stt?.model||Te,runtime:e.runtime,dtype:e.dtype},tts:{enabled:t.tts?.enabled!==!1,state:n.state,ready:n.ok,model:n.model||t.tts?.model||Fe,voice:t.tts?.voice||Y,runtime:n.runtime,dtype:n.dtype}})}if(c==="/status"&&r.method==="GET"){ft(t);const e=await q(t.pro?.entitlementToken),n=await dt(t);return s(o,200,{ok:!0,version:W,backend:t.backend,tier:t.redaction.tier,...ae()?{managed:ae()}:{},...process.env.CHATPANEL_MANAGED_BY?{managedBy:String(process.env.CHATPANEL_MANAGED_BY).slice(0,32)}:{},ner:{autostart:!!t.ner?.autostart,configured:n.configured,ready:n.ok,model:n.model,url:n.url},detector:$e(t),pro:{unlocked:e},usage:No(t),uptimeSeconds:Math.floor((Date.now()-at)/1e3),update:so(W)})}if(c==="/v1/history/ingest"&&r.method==="POST")try{const e=JSON.parse((await v(r,t.maxBodyBytes)).toString("utf8"))||{},n=N.bulk({upserts:Array.isArray(e.upserts)?e.upserts:[],removes:Array.isArray(e.removes)?e.removes:[]});return s(o,200,{ok:!0,size:n})}catch(e){return s(o,400,{error:{message:`ingest failed: ${e.message}`,type:"ingest_error"}})}if(c==="/v1/prefs"&&r.method==="GET"){const e=String(u.searchParams.get("section")||"");return u.searchParams.get("stamps")?s(o,200,{ok:!0,revision:K.revision,stamps:K.stamps()}):s(o,200,{ok:!0,revision:K.revision,sections:K.get(e)})}if(c==="/v1/prefs"&&(r.method==="POST"||r.method==="PUT"))try{const e=JSON.parse((await v(r,t.maxBodyBytes)).toString("utf8"))||{},n=K.put(e.sections||{},{by:e.by||""});return n.applied.length&&et(n.applied,e.by||""),s(o,200,{ok:!0,...n})}catch(e){return s(o,400,{error:{message:`prefs write failed: ${e.message}`,type:"prefs_error"}})}if(c==="/v1/prefs"&&r.method==="DELETE"){const e=String(u.searchParams.get("section")||""),n=e?K.remove(e):!1;return n&&et([e],""),s(o,200,{ok:!0,removed:n})}if(c==="/v1/prefs/events"&&r.method==="GET"){o.writeHead(200,{"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive"});const e=l=>o.write(`data: ${JSON.stringify(l)}
|
|
5
|
+
`)}g&&g.lap("stream",se),i.end(),g?.commit()}function tr(t,i,d=""){const r=String(t||"").replace(/\/+$/,""),o=String(i||"").split("/")[1];return o&&r.endsWith(`/${o}`)?r.slice(0,-(o.length+1))+i+d:r+i+d}const or=9e4;function rr(t,i,d){if(i===d)return t;const r=i/d,o=new Float32Array(Math.floor(t.length/r));for(let u=0;u<o.length;u++){const c=u*r,y=Math.floor(c),g=Math.min(t.length-1,y+1),E=c-y;o[u]=t[y]*(1-E)+t[g]*E}return o}const nr=["/tts","/stt","/ner","/diarize","/skills","/redact","/config","/logs","/status","/admin"];async function sr(t,i,{adapter:d,kind:r,pathname:o,search:u,base:c,destKey:y,destProtocol:g,harness:E,trace:m},M,A){let D;const Z=m?m.clock():0;try{const O=Xo(t.headers,c);y&&(g==="anthropic"?(O["x-api-key"]=y,delete O.authorization):O.authorization=`Bearer ${y}`);const I=Et(tr(c,o,u)).toString();D=await fetch(I,{method:t.method,headers:O,body:["GET","HEAD"].includes(t.method)?void 0:M})}catch(O){return m?.commit(),s(i,502,{error:`upstream fetch failed: ${O.message}`})}const R=D.headers.get("content-type")||"",j={};if(D.headers.forEach((O,I)=>{nt.has(I.toLowerCase())||(j[I]=O)}),R.includes("text/event-stream")&&D.body){m&&m.lap("upstream",Z);const O=m?m.clock():0;i.writeHead(D.status,j);const I=r==="openai"?bt(D.body,i,A,E):gt(D.body,i,A);return Promise.resolve(I).finally(()=>{m&&m.lap("stream",O),m?.commit()})}const P=Buffer.from(await D.arrayBuffer());if(m&&m.lap("upstream",Z),A&&R.includes("application/json"))try{const O=m?m.clock():0,I=d.restoreResponse(JSON.parse(P.toString("utf8")),A,E);return m&&m.lap("restore",O),i.writeHead(D.status,{...j,"content-type":"application/json"}),i.end(Buffer.from(JSON.stringify(I),"utf8")),m?.commit()}catch{}i.writeHead(D.status,j),i.end(P),m?.commit()}function ar(t=Be()){$t(t.allowedExtensionIds||[]);const i=[],d=r=>{i.push(r),i.length>50&&i.shift()};return yt(async(r,o)=>{const u=new URL(r.url,"http://127.0.0.1"),c=u.pathname;if(!st(r.headers.host))return s(o,403,{error:"loopback only"});if(!Jo(r.headers.origin,t))return s(o,403,{error:"origin not allowed"});if(r.headers.origin&&Ho(o,r.headers.origin),r.method==="OPTIONS")return o.writeHead(204),o.end();if(c==="/admin/token"&&r.method==="POST")return F(r)?s(o,200,{token:ge()}):s(o,403,{error:"admin: extension origin or gateway token required"});if(c==="/pair/code"&&r.method==="POST"){if(!F(r))return s(o,403,{error:"pair/code: extension origin or gateway token required"});const e=Nt();return console.log("[gateway] pairing code issued — valid for 5 minutes, one use"),s(o,200,{ok:!0,...e})}if(c==="/pair"&&r.method==="POST"){let e=null;try{e=JSON.parse((await v(r,t.maxBodyBytes)).toString("utf8"))}catch{e=null}const n=Bt(e?.code);if(!n.ok)return console.log(`[gateway] pairing refused (${n.reason}) from ${ce(r)} caller`),s(o,403,{error:n.reason});console.log(`[gateway] paired a ${ce(r)} client${r.headers.origin?` (${r.headers.origin})`:""}`);const a=ie(t.bridge?.token);return s(o,200,{ok:!0,token:Pt()||ge(),...a?{bridgeToken:a}:{}})}if(c==="/whoami"&&r.method==="POST"){const e=ce(r);return s(o,200,{ok:!0,trust:e,paired:At(e),version:W})}if(c==="/audit"&&r.method==="GET")return F(r)?s(o,200,Dt(t,{version:W,startedAt:at,managed:ae()})):s(o,403,{error:"audit: extension origin or gateway token required"});if((c==="/config"||c==="/logs"||c==="/update"&&r.method!=="GET")&&!F(r))return s(o,403,{error:"admin route: extension origin or gateway token required"});if(c==="/update"&&r.method==="GET"){const e=await no(W,{force:u.searchParams.get("force")==="1"}).catch(n=>({current:W,updateAvailable:!1,error:String(n?.message||n)}));return s(o,200,{ok:!0,update:e,job:io()})}if(c==="/update"&&r.method==="POST"){const e=ao(W);return s(o,e.already?409:202,{ok:!0,job:e})}if((c==="/v1/history/key"||c==="/v1/history/ingest-backup")&&r.method==="POST"&&!F(r))return s(o,403,{error:{message:"history key route: extension origin or gateway token required",type:"forbidden"}});if((c==="/v1/history/ingest"||c==="/v1/history/clear")&&r.method==="POST"&&!F(r))return s(o,403,{error:{message:"history write — extension origin or gateway token required",type:"forbidden"}});if((c==="/v1/memory/remember"||c==="/v1/memory/forget"||c==="/v1/memory/sync"||c==="/v1/memory/clear")&&r.method==="POST"&&!F(r))return s(o,403,{error:{message:"memory write — extension origin or gateway token required",type:"forbidden"}});if((c==="/v1/prefs"||c.startsWith("/v1/prefs/")||c.startsWith("/v1/teams")||c.startsWith("/v1/agents")||c.startsWith("/v1/projects"))&&!F(r))return s(o,403,{error:{message:"prefs: extension origin or gateway token required",type:"forbidden"}});if(c.startsWith("/v1/observability")&&!F(r))return s(o,403,{error:{message:"observability: extension origin or gateway token required",type:"forbidden"}});if(r.method==="GET"&&c==="/health"){const e=x.health(),n=k.health();return s(o,200,{ok:!0,version:W,backend:t.backend,tier:t.redaction.tier,pairing:!0,...ae()?{managed:ae()}:{},...process.env.CHATPANEL_MANAGED_BY?{managedBy:String(process.env.CHATPANEL_MANAGED_BY).slice(0,32)}:{},...he?{bridge:he.status()}:{},stt:{enabled:t.stt?.enabled!==!1,state:e.state,ready:e.ok,model:e.model||t.stt?.model||Te,runtime:e.runtime,dtype:e.dtype},tts:{enabled:t.tts?.enabled!==!1,state:n.state,ready:n.ok,model:n.model||t.tts?.model||Fe,voice:t.tts?.voice||Y,runtime:n.runtime,dtype:n.dtype}})}if(c==="/status"&&r.method==="GET"){ft(t);const e=await q(t.pro?.entitlementToken),n=await dt(t);return s(o,200,{ok:!0,version:W,backend:t.backend,tier:t.redaction.tier,...ae()?{managed:ae()}:{},...process.env.CHATPANEL_MANAGED_BY?{managedBy:String(process.env.CHATPANEL_MANAGED_BY).slice(0,32)}:{},ner:{autostart:!!t.ner?.autostart,configured:n.configured,ready:n.ok,model:n.model,url:n.url},detector:$e(t),pro:{unlocked:e},usage:No(t),uptimeSeconds:Math.floor((Date.now()-at)/1e3),update:so(W)})}if(c==="/v1/history/ingest"&&r.method==="POST")try{const e=JSON.parse((await v(r,t.maxBodyBytes)).toString("utf8"))||{},n=N.bulk({upserts:Array.isArray(e.upserts)?e.upserts:[],removes:Array.isArray(e.removes)?e.removes:[]});return s(o,200,{ok:!0,size:n})}catch(e){return s(o,400,{error:{message:`ingest failed: ${e.message}`,type:"ingest_error"}})}if(c==="/v1/prefs"&&r.method==="GET"){const e=String(u.searchParams.get("section")||"");return u.searchParams.get("stamps")?s(o,200,{ok:!0,revision:K.revision,stamps:K.stamps()}):s(o,200,{ok:!0,revision:K.revision,sections:K.get(e)})}if(c==="/v1/prefs"&&(r.method==="POST"||r.method==="PUT"))try{const e=JSON.parse((await v(r,t.maxBodyBytes)).toString("utf8"))||{},n=K.put(e.sections||{},{by:e.by||""});return n.applied.length&&et(n.applied,e.by||""),s(o,200,{ok:!0,...n})}catch(e){return s(o,400,{error:{message:`prefs write failed: ${e.message}`,type:"prefs_error"}})}if(c==="/v1/prefs"&&r.method==="DELETE"){const e=String(u.searchParams.get("section")||""),n=e?K.remove(e):!1;return n&&et([e],""),s(o,200,{ok:!0,removed:n})}if(c==="/v1/prefs/events"&&r.method==="GET"){o.writeHead(200,{"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive"});const e=l=>o.write(`data: ${JSON.stringify(l)}
|
|
6
6
|
|
|
7
7
|
`);e({type:"hello",revision:K.revision,stamps:K.stamps()});const n=l=>e({type:"changed",...l});xe.add(n);const a=setInterval(()=>{try{o.write(`: keep-alive
|
|
8
8
|
|