@chatpanel/gateway 0.9.0 → 0.9.2

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/README.md CHANGED
@@ -216,7 +216,7 @@ behaviour for a trusted machine — the startup log calls it out.
216
216
 
217
217
  **Pairing** a browser the gateway does not recognise (ChatPanel's Firefox build, whose
218
218
  origin is a per-profile UUID; a dev build): `chatpanel-gateway pair` prints a one-time
219
- code (5 minutes, 5 attempts); enter it in ChatPanel → Settings → Gateway. The exchange
219
+ code (5 minutes, 5 attempts); enter it in ChatPanel → Settings → Agent Tools. The exchange
220
220
  (`POST /pair`) hands over the gateway token and, when this machine has one, the bridge
221
221
  token — one code covers both. `POST /whoami` → `{ trust, paired }` tells a client where
222
222
  it stands.
@@ -1,4 +1,4 @@
1
1
  #!/usr/bin/env node
2
- const a=process.argv[2];try{if(a==="--bridge")process.env.CHATPANEL_BRIDGE_EMBEDDED="1",process.argv.splice(2,1),await import("@chatpanel/bridge/src/server.js");else if(a==="--mcp-stdio")process.env.CHATPANEL_BRIDGE_EMBEDDED="1",await import("@chatpanel/bridge/src/server.js");else if(a==="mcp"){const{runMcpServer:t}=await import("../src/mcp.js");await t()}else if(a==="tools"||a==="call"){const{runMcpCli:t}=await import("../src/mcp-cli.js");process.exit(await t(process.argv.slice(2)))}else if(a==="policy"){const{loadPolicy:t,formatPolicy:o,PolicyLoadError:i}=await import("../src/policy.js");try{const e=await t();process.argv.includes("--json")?console.log(JSON.stringify(e?{...e,label:void 0}:null,null,2)):console.log(o(e))}catch(e){throw e instanceof i&&(console.error(`org policy: ${e.message}`),process.exit(78)),e}}else if(a==="--audit"){const{egressAudit:t,formatAudit:o}=await import("../src/egress.js"),{loadConfig:i}=await import("../src/config.js"),{readFileSync:e}=await import("node:fs"),{join:p}=await import("node:path"),n=await import("node:os"),l=i(),s=`http://127.0.0.1:${l.port||4320}`;let r=null,c=`no gateway running at ${s}`;try{const u=e(process.env.CHATPANEL_GATEWAY_TOKEN_PATH||p(n.homedir(),".chatpanel","gateway-token"),"utf8").trim(),g=await fetch(`${s}/audit`,{headers:{authorization:`Bearer ${u}`},signal:AbortSignal.timeout(2500)});if(g.ok)r=await g.json();else if(g.status===404){const d=await fetch(`${s}/health`,{signal:AbortSignal.timeout(2500)}).then(w=>w.json()).catch(()=>null);c=`the gateway running at ${s}${d?.version?` (${d.version})`:""} predates --audit (0.7.0) — restart it after updating`}else c=`the gateway at ${s} refused the audit (HTTP ${g.status}) — is ~/.chatpanel/gateway-token readable?`}catch{}if(!r){const u=JSON.parse(e(new URL("../package.json",import.meta.url),"utf8")).version;r={...t(l,{ledger:null,version:u}),observed:[]},console.log(`(${c}; showing what the current config allows)
3
- `)}process.argv.includes("--json")?console.log(JSON.stringify(r,null,2)):console.log(o(r))}else if(a==="pair"){const{loadConfig:t}=await import("../src/config.js"),{readFileSync:o}=await import("node:fs"),{join:i}=await import("node:path"),e=await import("node:os"),n=`http://127.0.0.1:${t().port||4320}`,l=process.env.CHATPANEL_GATEWAY_TOKEN_PATH||i(e.homedir(),".chatpanel","gateway-token");try{const s=o(l,"utf8").trim(),r=await fetch(`${n}/pair/code`,{method:"POST",headers:{authorization:`Bearer ${s}`},signal:AbortSignal.timeout(2500)}),c=await r.json().catch(()=>({}));if(r.status===404)throw new Error(`the gateway at ${n} predates pairing (0.9.0) — update and restart it`);if(!r.ok)throw new Error(c.error||`HTTP ${r.status}`);console.log(`Pairing code: ${c.display||c.code} (one use, expires in 5 minutes)`),console.log('Enter it in ChatPanel → Settings → Gateway → "Pair this browser".')}catch(s){console.error(`could not get a pairing code from the gateway at ${n}: ${s?.message||s}${/ENOENT/.test(String(s?.message))?` (no token at ${l} — has the gateway started once?)`:""}`),process.exit(1)}}else if(a==="local"){const{localStatus:t,formatLocalStatus:o}=await import("../src/local-status.js");process.stdout.write(o(await t()))}else if(a==="connect"){const{connectAgents:t,formatConnect:o}=await import("../src/connect-agents.js"),i=process.argv.includes("--dry-run")||process.argv.includes("-n");process.stdout.write(o(t({dryRun:i}),{dryRun:i}))}else{const{start:t,VERSION:o}=await import("../src/server.js"),{installService:i,uninstallService:e,serviceStatus:p,stopService:n}=await import("../src/service.js");switch(a){case"--stop":n(),console.log("ChatPanel Gateway: stopped (auto-start is still registered; `--install` or a login starts it again).");break;case"--version":case"-v":console.log(o);break;case"--install":i(),console.log("ChatPanel Privacy Gateway: installed login auto-start and started it.");break;case"--uninstall":e(),console.log("ChatPanel Privacy Gateway: removed login auto-start.");break;case"--status":console.log(p()?"installed (auto-start registered)":"not installed");break;case void 0:await t();break;default:console.error(`unknown option: ${a}
2
+ const a=process.argv[2];try{if(a==="--bridge")process.env.CHATPANEL_BRIDGE_EMBEDDED="1",process.argv.splice(2,1),await import("@chatpanel/bridge/src/server.js");else if(a==="--mcp-stdio")process.env.CHATPANEL_BRIDGE_EMBEDDED="1",await import("@chatpanel/bridge/src/server.js");else if(a==="mcp"){const{runMcpServer:t}=await import("../src/mcp.js");await t()}else if(a==="tools"||a==="call"){const{runMcpCli:t}=await import("../src/mcp-cli.js");process.exit(await t(process.argv.slice(2)))}else if(a==="policy"){const{loadPolicy:t,formatPolicy:o,PolicyLoadError:i}=await import("../src/policy.js");try{const e=await t();process.argv.includes("--json")?console.log(JSON.stringify(e?{...e,label:void 0}:null,null,2)):console.log(o(e))}catch(e){throw e instanceof i&&(console.error(`org policy: ${e.message}`),process.exit(78)),e}}else if(a==="--audit"){const{egressAudit:t,formatAudit:o}=await import("../src/egress.js"),{loadConfig:i}=await import("../src/config.js"),{readFileSync:e}=await import("node:fs"),{join:g}=await import("node:path"),r=await import("node:os"),l=i(),s=`http://127.0.0.1:${l.port||4320}`;let n=null,c=`no gateway running at ${s}`;try{const u=e(process.env.CHATPANEL_GATEWAY_TOKEN_PATH||g(r.homedir(),".chatpanel","gateway-token"),"utf8").trim(),p=await fetch(`${s}/audit`,{headers:{authorization:`Bearer ${u}`},signal:AbortSignal.timeout(2500)});if(p.ok)n=await p.json();else if(p.status===404){const d=await fetch(`${s}/health`,{signal:AbortSignal.timeout(2500)}).then(w=>w.json()).catch(()=>null);c=`the gateway running at ${s}${d?.version?` (${d.version})`:""} predates --audit (0.7.0) — restart it after updating`}else c=`the gateway at ${s} refused the audit (HTTP ${p.status}) — is ~/.chatpanel/gateway-token readable?`}catch{}if(!n){const u=JSON.parse(e(new URL("../package.json",import.meta.url),"utf8")).version;n={...t(l,{ledger:null,version:u}),observed:[]},console.log(`(${c}; showing what the current config allows)
3
+ `)}process.argv.includes("--json")?console.log(JSON.stringify(n,null,2)):console.log(o(n))}else if(a==="pair"){const{loadConfig:t}=await import("../src/config.js"),{readFileSync:o}=await import("node:fs"),{join:i}=await import("node:path"),e=await import("node:os"),r=`http://127.0.0.1:${t().port||4320}`,l=process.env.CHATPANEL_GATEWAY_TOKEN_PATH||i(e.homedir(),".chatpanel","gateway-token");try{const s=o(l,"utf8").trim(),n=await fetch(`${r}/pair/code`,{method:"POST",headers:{authorization:`Bearer ${s}`},signal:AbortSignal.timeout(2500)}),c=await n.json().catch(()=>({}));if(n.status===404)throw new Error(`the gateway at ${r} predates pairing (0.9.0) — update and restart it`);if(!n.ok)throw new Error(c.error||`HTTP ${n.status}`);console.log(`Pairing code: ${c.display||c.code} (one use, expires in 5 minutes)`),console.log('Enter it in ChatPanel → Settings → Agent Tools → "Pairing code".')}catch(s){console.error(`could not get a pairing code from the gateway at ${r}: ${s?.message||s}${/ENOENT/.test(String(s?.message))?` (no token at ${l} — has the gateway started once?)`:""}`),process.exit(1)}}else if(a==="local"){const{localStatus:t,formatLocalStatus:o}=await import("../src/local-status.js");process.stdout.write(o(await t()))}else if(a==="connect"){const{connectAgents:t,formatConnect:o}=await import("../src/connect-agents.js"),i=process.argv.includes("--dry-run")||process.argv.includes("-n");process.stdout.write(o(t({dryRun:i}),{dryRun:i}))}else{const{start:t,VERSION:o}=await import("../src/server.js"),{installService:i,uninstallService:e,serviceStatus:g,stopService:r}=await import("../src/service.js");switch(a){case"--stop":r(),console.log("ChatPanel Gateway: stopped (auto-start is still registered; `--install` or a login starts it again).");break;case"--version":case"-v":console.log(o);break;case"--install":i(),console.log("ChatPanel Privacy Gateway: installed login auto-start and started it.");break;case"--uninstall":e(),console.log("ChatPanel Privacy Gateway: removed login auto-start.");break;case"--status":console.log(g()?"installed (auto-start registered)":"not installed");break;case void 0:await t();break;default:console.error(`unknown option: ${a}
4
4
  Usage: chatpanel-gateway [mcp|tools list|tools schema <tool>|call <tool> '<json>'|local|connect|pair|policy|--audit|--install|--uninstall|--stop|--status|--version|--bridge]`),process.exit(2)}}}catch(t){console.error(`error: ${t.message}`),process.exit(1)}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@chatpanel/gateway",
3
- "version": "0.9.0",
3
+ "version": "0.9.2",
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.0",
24
+ "@chatpanel/bridge": "^0.13.2",
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,4 +1,4 @@
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.0",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.2",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