@chatpanel/gateway 0.11.3 → 0.11.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/package.json +1 -1
  2. package/src/server.js +14 -14
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@chatpanel/gateway",
3
- "version": "0.11.3",
3
+ "version": "0.11.5",
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": {
package/src/server.js CHANGED
@@ -1,30 +1,30 @@
1
- import{createServer as gt}from"node:http";import{loadConfig as Ie}from"./config.js";import{startEntitlementRefresh as wt,maybeRevalidate as bt}from"./entitlement-refresh.js";import{redactSegments as be,segment as je}from"./redact.js";import{pipeRestoredStream as kt,pipeRestoredOpenAIStream as St,makeTokenRestorer as Me,restoreDeep as vt}from"./stream.js";import{restoreText as Tt,gatedDictionary as Ot,narrowSpecs as _t,makeToolHarness as Et,placeholderToolNote as Pt,placeholderNote as At,assertEndpointUrl as xt,capRunOptions as $t,isPaired as Nt}from"@chatpanel/pii";import{ensureGatewayToken as ke,currentGatewayToken as Bt,isAdminAuthorized as W,callerTrustOf as ue,setPinnedExtensionIds as Dt,issuePairingCode as Ct,claimPairingCode as It}from"./gateway-token.js";import{installEgressLedger as jt,egressAudit as Mt}from"./egress.js";import{initPolicy as Rt,activePolicy as Lt,applyPolicyToConfig as Re,managedSummary as ie,PolicyLoadError as zt}from"./policy.js";import{routeAllowed as Le,agentAllowed as Gt,egressAllowed as Vt}from"@chatpanel/events/policy.js";import{resolveBridgeUrl as me}from"./bridge.js";import{secureFetch as ze}from"./secure-fetch.js";import{streamBridgeChat as Ge,readBridgeToken as le,openBridgeChat as Jt}from"./bridge.js";import{createRelaySession as Ht,getRelaySession as Ve,endRelaySession as pe,pumpBridgeStream as Ut,deliverToolResult as Ft,toolsToSpecs as Wt,parseToolCallId as Je,touchRelaySession as Se}from"./toolrelay.js";import{shaperFor as ve}from"./shape.js";import{startNer as Kt,ensureNer as Te}from"./ner.js";import{installTimestampedConsole as Zt}from"./log.js";import{saveBackupSecret as Yt,clearBackupSecret as Qt,loadBackupSecret as Oe,hasBackupSecret as He}from"./history-store.js";import{createMemoryStore as Xt}from"./memory-store.js";import{createPrefsStore as qt}from"./prefs-store.js";import{createTeamStore as eo,loadOrCreateKey as _e}from"./team-store.js";import{createScorecardStore as to}from"./scorecard-store.js";import{createEngineLedgerStore as oo}from"./engine-ledger-store.js";import{createProjectStore as ro}from"./project-store.js";import{applicationsFor as no,recruitPass as so}from"./recruiting.js";import{ensureBridge as ao}from"./bridge-supervisor.js";import{checkForUpdate as io,updateStatus as lo,startUpdate as co,updateJob as uo}from"./update.js";import{createHistoryStore as mo}from"./sqlite-store.js";import{ingestBackups as Ee}from"./backup-ingest.js";import{toSearchRecord as po}from"@chatpanel/events/library.js";import{deriveBackupKey as yo,openRecord as ho,keyCache as fo,nodeCodec as go}from"@chatpanel/events/backup-envelope.js";import wo from"node:zlib";import*as D from"./ner-engine.js";import*as A from"./stt-engine.js";import*as B from"./diarize-engine.js";import{MODEL_CATALOG as bo,isKnownModel as ko,isValidCustomModelId as So}from"./models.js";import{STT_MODEL_CATALOG as vo,isKnownSttModel as To,isValidCustomSttId as Oo,DEFAULT_STT_MODEL as Pe,STT_DTYPES as _o,isValidDtype as Eo}from"./stt-models.js";import*as S from"./tts-engine.js";import{TTS_MODEL_CATALOG as Ue,TTS_VOICES as Po,isKnownTtsModel as Ao,isValidCustomTtsId as xo,isKnownVoice as Fe,isValidVoiceId as We,DEFAULT_TTS_MODEL as Ke,DEFAULT_TTS_VOICE as X,TTS_DTYPES as $o,isValidTtsDtype as No,MAX_TTS_CHARS as Ze,ttsModelHasCustomVoices as Bo,resolveDefaultModel as Ye,POCKET_VOICES as Do,DEFAULT_POCKET_VOICE as ye,isPocketVoice as he,ttsModelEngine as fe}from"./tts-models.js";import{ttsDestination as Co,synthesizeRemote as Io,isValidRemoteVoice as jo}from"./tts-remote.js";import{rawOrtAvailable as Ae}from"./ort.js";import*as G from"./tts-voices.js";import{resolveTtsVoice as Mo}from"./tts-voice-resolve.js";import{resolvePro as ee,checkQuota as Ro,consume as Lo,usage as zo}from"./freegate.js";import{publicConfig as Qe,applyConfigPatch as Go,applyNerModelSelection as Vo,persistConfig as oe,configPath as te,bridgeAgentOptions as Xe,PERMISSION_MODES as Jo}from"./configstore.js";import{resolveDestination as qe,aggregateModelsAsync as Ho,listDestinations as Uo}from"./router.js";import{makeAccessEvent as et}from"./observability.js";import{createPersistentAccessLog as Fo}from"./access-log-store.js";import{planQueries as Wo,multiSearch as Ko}from"./rrf.js";import*as xe from"./openai.js";import*as tt from"./responses.js";import*as $e from"./anthropic.js";const K="0.11.3",_=await mo(),Q=new Set;function ge({ids:t=[]}={}){const i=_.lossless;if(!i||!Q.size)return;const d=JSON.stringify({newest:i.newest,size:i.size,ids:t.slice(0,50),at:Date.now()});for(const r of Q)try{r.write(`event: records
1
+ import{createServer as gt}from"node:http";import{loadConfig as je}from"./config.js";import{startEntitlementRefresh as bt,maybeRevalidate as wt}from"./entitlement-refresh.js";import{redactSegments as we,segment as Me}from"./redact.js";import{pipeRestoredStream as kt,pipeRestoredOpenAIStream as St,makeTokenRestorer as Re,restoreDeep as vt}from"./stream.js";import{restoreText as Tt,gatedDictionary as _t,narrowSpecs as Ot,makeToolHarness as $t,placeholderToolNote as Pt,placeholderNote as At,assertEndpointUrl as Et,capRunOptions as xt,isPaired as Nt}from"@chatpanel/pii";import{ensureGatewayToken as ke,currentGatewayToken as Bt,isAdminAuthorized as H,callerTrustOf as me,setPinnedExtensionIds as Dt,issuePairingCode as Ct,claimPairingCode as It}from"./gateway-token.js";import{installEgressLedger as jt,egressAudit as Mt}from"./egress.js";import{initPolicy as Rt,activePolicy as zt,applyPolicyToConfig as ze,managedSummary as ce,PolicyLoadError as Lt}from"./policy.js";import{routeAllowed as Le,agentAllowed as Gt,egressAllowed as Vt}from"@chatpanel/events/policy.js";import{resolveBridgeUrl as re}from"./bridge.js";import{secureFetch as Ge}from"./secure-fetch.js";import{streamBridgeChat as Ve,readBridgeToken as ee,openBridgeChat as Jt}from"./bridge.js";import{createRelaySession as Ht,getRelaySession as Je,endRelaySession as pe,pumpBridgeStream as Ut,deliverToolResult as Ft,toolsToSpecs as Wt,parseToolCallId as He,touchRelaySession as Se}from"./toolrelay.js";import{shaperFor as ve}from"./shape.js";import{startNer as Kt,ensureNer as Te}from"./ner.js";import{installTimestampedConsole as Zt}from"./log.js";import{saveBackupSecret as Yt,clearBackupSecret as Qt,loadBackupSecret as _e,hasBackupSecret as Ue}from"./history-store.js";import{createMemoryStore as Xt}from"./memory-store.js";import{createPrefsStore as qt}from"./prefs-store.js";import{createTeamStore as eo,loadOrCreateKey as Oe}from"./team-store.js";import{createScorecardStore as to}from"./scorecard-store.js";import{createEngineLedgerStore as oo}from"./engine-ledger-store.js";import{createProjectStore as ro}from"./project-store.js";import{applicationsFor as no,recruitPass as so}from"./recruiting.js";import{ensureBridge as ao}from"./bridge-supervisor.js";import{checkForUpdate as io,updateStatus as lo,startUpdate as co,updateJob as uo}from"./update.js";import{createHistoryStore as mo}from"./sqlite-store.js";import{ingestBackups as $e}from"./backup-ingest.js";import{toSearchRecord as po}from"@chatpanel/events/library.js";import{deriveBackupKey as ho,openRecord as yo,keyCache as fo,nodeCodec as go}from"@chatpanel/events/backup-envelope.js";import bo from"node:zlib";import*as D from"./ner-engine.js";import*as A from"./stt-engine.js";import*as B from"./diarize-engine.js";import{MODEL_CATALOG as wo,isKnownModel as ko,isValidCustomModelId as So}from"./models.js";import{STT_MODEL_CATALOG as vo,isKnownSttModel as To,isValidCustomSttId as _o,DEFAULT_STT_MODEL as Pe,STT_DTYPES as Oo,isValidDtype as $o}from"./stt-models.js";import*as S from"./tts-engine.js";import{TTS_MODEL_CATALOG as Fe,TTS_VOICES as Po,isKnownTtsModel as Ao,isValidCustomTtsId as Eo,isKnownVoice as We,isValidVoiceId as Ke,DEFAULT_TTS_MODEL as Ze,DEFAULT_TTS_VOICE as X,TTS_DTYPES as xo,isValidTtsDtype as No,MAX_TTS_CHARS as Ye,ttsModelHasCustomVoices as Bo,resolveDefaultModel as Qe,POCKET_VOICES as Do,DEFAULT_POCKET_VOICE as he,isPocketVoice as ye,ttsModelEngine as fe}from"./tts-models.js";import{ttsDestination as Co,synthesizeRemote as Io,isValidRemoteVoice as jo}from"./tts-remote.js";import{rawOrtAvailable as Ae}from"./ort.js";import*as G from"./tts-voices.js";import{resolveTtsVoice as Mo}from"./tts-voice-resolve.js";import{resolvePro as te,checkQuota as Ro,consume as zo,usage as Lo}from"./freegate.js";import{publicConfig as Xe,applyConfigPatch as Go,applyNerModelSelection as Vo,persistConfig as ne,configPath as oe,bridgeAgentOptions as qe,PERMISSION_MODES as Jo}from"./configstore.js";import{resolveDestination as et,aggregateModelsAsync as Ho,listDestinations as Uo}from"./router.js";import{makeAccessEvent as tt}from"./observability.js";import{createPersistentAccessLog as Fo}from"./access-log-store.js";import{planQueries as Wo,multiSearch as Ko}from"./rrf.js";import*as Ee from"./openai.js";import*as ot from"./responses.js";import*as xe from"./anthropic.js";const K="0.11.5",O=await mo(),Q=new Set;function ge({ids:t=[]}={}){const l=O.lossless;if(!l||!Q.size)return;const d=JSON.stringify({newest:l.newest,size:l.size,ids:t.slice(0,50),at:Date.now()});for(const r of Q)try{r.write(`event: records
2
2
  data: ${d}
3
3
 
4
4
  `)}catch{Q.delete(r)}}setInterval(()=>{for(const t of Q)try{t.write(`: ping
5
5
 
6
- `)}catch{Q.delete(t)}},25e3).unref?.();const H=await Xt(),U=qt(),re=to({key:_e()}),ne=oo({key:_e()}),V=ro({key:_e()}),C=eo({scorecards:re,engines:ne}),Ne=new Set,ot=(t,i)=>{for(const r of Ne)try{r({applied:t,by:i,revision:U.revision})}catch{}const d=JSON.stringify({revision:U.revision,applied:(t||[]).slice(0,50),by:i||"",at:Date.now()});for(const r of Q)try{r.write(`event: prefs
6
+ `)}catch{Q.delete(t)}},25e3).unref?.();const U=await Xt(),F=qt(),se=to({key:Oe()}),ae=oo({key:Oe()}),V=ro({key:Oe()}),C=eo({scorecards:se,engines:ae}),Ne=new Set,rt=(t,l)=>{for(const r of Ne)try{r({applied:t,by:l,revision:F.revision})}catch{}const d=JSON.stringify({revision:F.revision,applied:(t||[]).slice(0,50),by:l||"",at:Date.now()});for(const r of Q)try{r.write(`event: prefs
7
7
  data: ${d}
8
8
 
9
- `)}catch{Q.delete(r)}},Be=Fo(),rt=new Set(["codex","claude","opencode","pi","kiro","antigravity","hermes"]),Zo=16,Yo=/^mcp[_-]/i,nt=t=>t&&t.function&&t.function.name||t&&t.name||"",Qo=t=>t&&t.function&&t.function.description||t&&t.description||"";function st(t){return typeof t=="string"?t:Array.isArray(t)?t.map(i=>typeof i=="string"?i:i&&(i.text||i.content)||"").join(" "):""}function Xo(t,i){if(!t)return"";if(i==="responses"){const r=t.input;return typeof r=="string"?r:Array.isArray(r)?r.map(o=>st(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 st(d[r].content);return""}const at=new Set(["host","connection","content-length","transfer-encoding","accept-encoding","content-encoding","keep-alive"]);function it(t){if(!t)return!1;const i=t.replace(/:\d+$/,"").replace(/^\[|\]$/g,"");return i==="localhost"||i==="127.0.0.1"||i==="::1"}function qo(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 er(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 lt=Date.now();function tr(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 or(t){const i=/^(model|harness):([^/]+)(?:\/(.+))?$/.exec(String(t||""));return i?{kind:i[1],id:i[2],...i[3]?{model:i[3]}:{}}:null}function rr(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}`:""} · ${tr(d)}`)})}}}function ct(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",g=r.replace(/^\[\[|\]\]$/g,"");d.push(i==="values"?{token:g,type:c,value:o}:{token:g,type:c})}return d}function nr(t,i,d){return $e.matches(t)||"anthropic-version"in i?{kind:"anthropic",adapter:$e,redactable:$e.matches(t),base:d.upstreams?.anthropic?.baseUrl}:tt.matches(t)?{kind:"responses",adapter:tt,redactable:!0,base:d.upstreams?.openai?.baseUrl}:{kind:"openai",adapter:xe,redactable:xe.matches(t),base:d.upstreams?.openai?.baseUrl}}function De(t,i){const d=String(t||"");if(rt.has(d))return{agent:d,agentModel:""};const r=d.indexOf("/");if(r>0){const o=d.slice(0,r);if(rt.has(o))return{agent:o,agentModel:d.slice(r+1)}}return{agent:i.bridge.agent,agentModel:""}}function dt(t,i){return De(t,i).agent}function sr(t,i){if(i!=="openai"||!t)return!1;const d=xe.extractLatestToolResult(t);if(!d)return!1;const r=Je(d.tool_call_id);return!!(r&&Ve(r.gwId))}function ar(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 ut(t){const i=t.redaction?.detection?.url;return!i||t.redaction?.detection?.backend==="off"?null:i}function Ce(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=D.health(),o=r.ok&&d==="full";return{source:"bundled",state:r.state,model:r.model||t?.ner?.model||null,installed:D.modelOnDisk(t?.ner?.model||void 0),error:r.error||null,ready:o,tier:d,coverage:o?"names":"patterns"}}async function mt(t){if(D.state()!=="off"){const d=D.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=ut(t);if(!i)return{configured:!1,ok:!1,url:null,model:null};try{const d=await ze(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 ir(t,i){const d={};for(const[r,o]of Object.entries(t)){const u=r.toLowerCase();u.startsWith("x-chatpanel-")||at.has(u)||(d[r]=o)}d["accept-encoding"]="identity";try{d.host=new URL(i).host}catch{}return d}async function pt(t,i,d,r){const o=Me(i.vault),u=r?r.clock():0;let c=u,g=!0;const w=()=>{r&&g&&(r.lap("upstream",u),c=r.clock(),g=!1)};await Ut(i,{onText:P=>{w(),Se(i.id);const p=o.push(P);p&&t.write(d.sseDelta(p))},onToolRequest:({name:P,restoredArgs:p,toolId:L})=>{w(),Se(i.id);const $=o.flush();$&&t.write(d.sseDelta($)),t.write(d.sseToolCalls([{id:L,name:P,arguments:JSON.stringify(p)}])),t.write(d.sseToolFinish()),r&&r.lap("stream",c),t.end(),r?.commit()},onDone:()=>{const P=o.flush();P&&t.write(d.sseDelta(P)),t.write(d.sseTail()),r&&r.lap("stream",c),t.end(),pe(i.id),r?.commit()},onError:P=>{t.write(`data: ${JSON.stringify({error:{message:P.message,type:"bridge_error"}})}
9
+ `)}catch{Q.delete(r)}},Be=Fo(),nt=new Set(["codex","claude","opencode","pi","kiro","antigravity","hermes"]),Zo=16,Yo=/^mcp[_-]/i,st=t=>t&&t.function&&t.function.name||t&&t.name||"",Qo=t=>t&&t.function&&t.function.description||t&&t.description||"";function at(t){return typeof t=="string"?t:Array.isArray(t)?t.map(l=>typeof l=="string"?l:l&&(l.text||l.content)||"").join(" "):""}function Xo(t,l){if(!t)return"";if(l==="responses"){const r=t.input;return typeof r=="string"?r:Array.isArray(r)?r.map(o=>at(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 at(d[r].content);return""}const it=new Set(["host","connection","content-length","transfer-encoding","accept-encoding","content-encoding","keep-alive"]);function lt(t){if(!t)return!1;const l=t.replace(/:\d+$/,"").replace(/^\[|\]$/g,"");return l==="localhost"||l==="127.0.0.1"||l==="::1"}function qo(t,l){return!t||/^chrome-extension:\/\//.test(t)||/^moz-extension:\/\//.test(t)||/^http:\/\/(localhost|127\.0\.0\.1|\[::1\])(:\d+)?$/.test(t)?!0:Array.isArray(l.allowedOrigins)&&l.allowedOrigins.includes(t)}function er(t,l){t.setHeader("Access-Control-Allow-Origin",l||"*"),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 ct=Date.now();function tr(t){if(!t)return"";const l={redact:"redact",upstream:"model",stream:"stream",restore:"restore",total:"total"};return Object.keys(t).map(d=>`${l[d]||d} ${t[d]}ms`).join(" · ")}function or(t){const l=/^(model|harness):([^/]+)(?:\/(.+))?$/.exec(String(t||""));return l?{kind:l[1],id:l[2],...l[3]?{model:l[3]}:{}}:null}function rr(t){const l=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()-l);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}`:""} · ${tr(d)}`)})}}}function dt(t,l){if(!t||!t.byToken||l!=="types"&&l!=="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",g=r.replace(/^\[\[|\]\]$/g,"");d.push(l==="values"?{token:g,type:c,value:o}:{token:g,type:c})}return d}function nr(t,l,d){return xe.matches(t)||"anthropic-version"in l?{kind:"anthropic",adapter:xe,redactable:xe.matches(t),base:d.upstreams?.anthropic?.baseUrl}:ot.matches(t)?{kind:"responses",adapter:ot,redactable:!0,base:d.upstreams?.openai?.baseUrl}:{kind:"openai",adapter:Ee,redactable:Ee.matches(t),base:d.upstreams?.openai?.baseUrl}}function De(t,l){const d=String(t||"");if(nt.has(d))return{agent:d,agentModel:""};const r=d.indexOf("/");if(r>0){const o=d.slice(0,r);if(nt.has(o))return{agent:o,agentModel:d.slice(r+1)}}return{agent:l.bridge.agent,agentModel:""}}function ut(t,l){return De(t,l).agent}function sr(t,l){if(l!=="openai"||!t)return!1;const d=Ee.extractLatestToolResult(t);if(!d)return!1;const r=He(d.tool_call_id);return!!(r&&Je(r.gwId))}function ar(t,l){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(l.port)}catch{return!1}}async function v(t,l){const d=[];let r=0;for await(const o of t){if(r+=o.length,l&&r>l){const u=new Error("payload too large");throw u.code=413,u}d.push(o)}return Buffer.concat(d)}function s(t,l,d){t.writeHead(l,{"content-type":"application/json"}),t.end(JSON.stringify(d))}function mt(t){const l=t.redaction?.detection?.url;return!l||t.redaction?.detection?.backend==="off"?null:l}function Ce(t){const l=t?.redaction?.detection,d=t?.redaction?.tier==="full"?"full":"basic";if(l&&l.backend&&l.backend!=="off")return{source:"external",backend:l.backend,state:"external",model:l.model||null,ready:!0,tier:d,coverage:d==="full"?"names":"patterns"};const r=D.health(),o=r.ok&&d==="full";return{source:"bundled",state:r.state,model:r.model||t?.ner?.model||null,installed:D.modelOnDisk(t?.ner?.model||void 0),error:r.error||null,ready:o,tier:d,coverage:o?"names":"patterns"}}async function pt(t){if(D.state()!=="off"){const d=D.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 l=mt(t);if(!l)return{configured:!1,ok:!1,url:null,model:null};try{const d=await Ge(l.replace(/\/ner\/?$/,"")+"/health",{signal:AbortSignal.timeout(2e3)});if(!d.ok)return{configured:!0,ok:!1,url:l,model:null};const r=await d.json().catch(()=>({}));return{configured:!0,ok:!0,url:l,model:r.model||null}}catch{return{configured:!0,ok:!1,url:l,model:null}}}function ir(t,l){const d={};for(const[r,o]of Object.entries(t)){const u=r.toLowerCase();u.startsWith("x-chatpanel-")||it.has(u)||(d[r]=o)}d["accept-encoding"]="identity";try{d.host=new URL(l).host}catch{}return d}async function ht(t,l,d,r){const o=Re(l.vault),u=r?r.clock():0;let c=u,g=!0;const w=()=>{r&&g&&(r.lap("upstream",u),c=r.clock(),g=!1)};await Ut(l,{onText:P=>{w(),Se(l.id);const p=o.push(P);p&&t.write(d.sseDelta(p))},onToolRequest:({name:P,restoredArgs:p,toolId:z})=>{w(),Se(l.id);const x=o.flush();x&&t.write(d.sseDelta(x)),t.write(d.sseToolCalls([{id:z,name:P,arguments:JSON.stringify(p)}])),t.write(d.sseToolFinish()),r&&r.lap("stream",c),t.end(),r?.commit()},onDone:()=>{const P=o.flush();P&&t.write(d.sseDelta(P)),t.write(d.sseTail()),r&&r.lap("stream",c),t.end(),pe(l.id),r?.commit()},onError:P=>{t.write(`data: ${JSON.stringify({error:{message:P.message,type:"bridge_error"}})}
10
10
 
11
- `),t.end(),pe(i.id),r?.commit()}})}async function lr(t,i,{kind:d,adapter:r,agent:o,run:u=null},c,g,w,P,p,L=null,$=null){const{messages:I,system:Y}=r.toTurn(c),{agentModel:z}=De(c?.model,w),R=Xe(w,{...z?{model:z}:{},...u||{}}),N=le(w.bridge.token),E=ve(d,c?.model||o),j={tier:w.redaction.tier==="full"?"full":"basic",dictionary:Ot(w.redaction,P),entities:[]},J=await me(w),T=Ht({vault:g,redactOpts:j,bridgeUrl:J,token:N,harness:L});let Z;try{Z=await Jt({bridgeUrl:J,agent:o,token:N,messages:I,system:Y,specs:Wt(p),options:R,signal:void 0})}catch(q){return pe(T.id),$?.commit(),s(i,502,{error:{message:`bridge: ${q.message}`,type:"bridge_error"}})}return T.reader=Z.body.getReader(),i.writeHead(200,{"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive"}),i.write(E.sseHead()),pt(i,T,E,$)}async function cr(t,i,d,r,o=null){Se(i.id),i.rounds=(i.rounds||0)+1;try{const c=o?o.clock():0;await Ft(i,d),o&&o.lap("redact",c)}catch(c){return pe(i.id),o?.commit(),s(t,502,{error:{message:`tool-result: ${c.message}`,type:"bridge_error"}})}const u=ve("openai",r||"codex");return t.writeHead(200,{"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive"}),t.write(u.sseHead()),pt(t,i,u,o)}async function dr(t,i,{kind:d,adapter:r,redactable:o,pathname:u,agentOverride:c,harness:g,trace:w,run:P=null},p,L,$,I){if(!o)return w?.commit(),s(i,404,{error:`endpoint ${u} not supported by the bridge backend`});if(d==="openai"){const e=r.extractLatestToolResult(p);if(e){const a=Je(e.tool_call_id),l=a&&Ve(a.gwId);if(l)return cr(i,l,e.content,p?.model,w)}const n=r.extractTools(p);if(n.length&&p?.stream===!0)return lr(t,i,{kind:d,adapter:r,agent:c||dt(p?.model,$),run:P},p,L,$,I,n,g,w)}const{messages:Y,system:z}=r.toTurn(p),R=c||dt(p?.model,$),N=p?.stream===!0,E=ve(d,p?.model||R),j=le($.bridge.token),J=new AbortController;i.on("close",()=>{i.writableFinished||J.abort()});const{agentModel:T}=De(p?.model,$),Z={bridgeUrl:await me($),agent:R,token:j,messages:Y,system:z,signal:J.signal,options:Xe($,{...T?{model:T}:{},...P||{}})};if(!N)try{let e="";const n=w?w.clock():0;await Ge(Z,m=>{e+=m}),w&&w.lap("upstream",n);const a=w?w.clock():0,l=E.full(Tt(e,L));return w&&w.lap("restore",a),i.writeHead(200,{"content-type":E.contentType}),i.end(l),w?.commit()}catch(e){return w?.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(E.sseHead());const q=Me(L),se=w?w.clock():0;let ae=se;try{let e=!0;await Ge(Z,a=>{w&&e&&(w.lap("upstream",se),ae=w.clock(),e=!1);const l=q.push(a);l&&i.write(E.sseDelta(l))},E.sseActivity?a=>{try{i.write(E.sseActivity(vt(a,L)))}catch{}}:null);const n=q.flush();n&&i.write(E.sseDelta(n)),i.write(E.sseTail())}catch(e){i.write(`data: ${JSON.stringify({error:{message:e.message,type:"bridge_error"}})}
11
+ `),t.end(),pe(l.id),r?.commit()}})}async function lr(t,l,{kind:d,adapter:r,agent:o,run:u=null},c,g,w,P,p,z=null,x=null){const{messages:I,system:Y}=r.toTurn(c),{agentModel:L}=De(c?.model,w),R=qe(w,{...L?{model:L}:{},...u||{}}),N=ee(w.bridge.token),$=ve(d,c?.model||o),j={tier:w.redaction.tier==="full"?"full":"basic",dictionary:_t(w.redaction,P),entities:[]},J=await re(w),T=Ht({vault:g,redactOpts:j,bridgeUrl:J,token:N,harness:z});let Z;try{Z=await Jt({bridgeUrl:J,agent:o,token:N,messages:I,system:Y,specs:Wt(p),options:R,signal:void 0})}catch(q){return pe(T.id),x?.commit(),s(l,502,{error:{message:`bridge: ${q.message}`,type:"bridge_error"}})}return T.reader=Z.body.getReader(),l.writeHead(200,{"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive"}),l.write($.sseHead()),ht(l,T,$,x)}async function cr(t,l,d,r,o=null){Se(l.id),l.rounds=(l.rounds||0)+1;try{const c=o?o.clock():0;await Ft(l,d),o&&o.lap("redact",c)}catch(c){return pe(l.id),o?.commit(),s(t,502,{error:{message:`tool-result: ${c.message}`,type:"bridge_error"}})}const u=ve("openai",r||"codex");return t.writeHead(200,{"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive"}),t.write(u.sseHead()),ht(t,l,u,o)}async function dr(t,l,{kind:d,adapter:r,redactable:o,pathname:u,agentOverride:c,harness:g,trace:w,run:P=null},p,z,x,I){if(!o)return w?.commit(),s(l,404,{error:`endpoint ${u} not supported by the bridge backend`});if(d==="openai"){const e=r.extractLatestToolResult(p);if(e){const a=He(e.tool_call_id),i=a&&Je(a.gwId);if(i)return cr(l,i,e.content,p?.model,w)}const n=r.extractTools(p);if(n.length&&p?.stream===!0)return lr(t,l,{kind:d,adapter:r,agent:c||ut(p?.model,x),run:P},p,z,x,I,n,g,w)}const{messages:Y,system:L}=r.toTurn(p),R=c||ut(p?.model,x),N=p?.stream===!0,$=ve(d,p?.model||R),j=ee(x.bridge.token),J=new AbortController;l.on("close",()=>{l.writableFinished||J.abort()});const{agentModel:T}=De(p?.model,x),Z={bridgeUrl:await re(x),agent:R,token:j,messages:Y,system:L,signal:J.signal,options:qe(x,{...T?{model:T}:{},...P||{}})};if(!N)try{let e="";const n=w?w.clock():0;await Ve(Z,m=>{e+=m}),w&&w.lap("upstream",n);const a=w?w.clock():0,i=$.full(Tt(e,z));return w&&w.lap("restore",a),l.writeHead(200,{"content-type":$.contentType}),l.end(i),w?.commit()}catch(e){return w?.commit(),s(l,502,{error:{message:`bridge backend failed: ${e.message}`,type:"bridge_error"}})}l.writeHead(200,{"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive"}),l.write($.sseHead());const q=Re(z),ie=w?w.clock():0;let le=ie;try{let e=!0;await Ve(Z,a=>{w&&e&&(w.lap("upstream",ie),le=w.clock(),e=!1);const i=q.push(a);i&&l.write($.sseDelta(i))},$.sseActivity?a=>{try{l.write($.sseActivity(vt(a,z)))}catch{}}:null);const n=q.flush();n&&l.write($.sseDelta(n)),l.write($.sseTail())}catch(e){l.write(`data: ${JSON.stringify({error:{message:e.message,type:"bridge_error"}})}
12
12
 
13
- `)}w&&w.lap("stream",ae),i.end(),w?.commit()}function ur(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 mr=9e4;function pr(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,g=Math.floor(c),w=Math.min(t.length-1,g+1),P=c-g;o[u]=t[g]*(1-P)+t[w]*P}return o}const yr=["/tts","/stt","/ner","/diarize","/skills","/redact","/config","/logs","/status","/admin"];function yt(t,i){const d=new URLSearchParams;for(const u of t.searchParams.getAll("dir"))u&&d.append("dir",u);const r=t.searchParams.get("workdir")||String(i?.bridge?.workingDir||"").trim();r&&d.set("workdir",r);const o=d.toString();return o?`?${o}`:""}async function hr(t,i,{adapter:d,kind:r,pathname:o,search:u,base:c,destKey:g,destProtocol:w,harness:P,trace:p},L,$){let I;const Y=p?p.clock():0;try{const E=ir(t.headers,c);g&&(w==="anthropic"?(E["x-api-key"]=g,delete E.authorization):E.authorization=`Bearer ${g}`);const j=xt(ur(c,o,u)).toString();I=await fetch(j,{method:t.method,headers:E,body:["GET","HEAD"].includes(t.method)?void 0:L})}catch(E){return p?.commit(),s(i,502,{error:`upstream fetch failed: ${E.message}`})}const z=I.headers.get("content-type")||"",R={};if(I.headers.forEach((E,j)=>{at.has(j.toLowerCase())||(R[j]=E)}),z.includes("text/event-stream")&&I.body){p&&p.lap("upstream",Y);const E=p?p.clock():0;i.writeHead(I.status,R);const j=r==="openai"?St(I.body,i,$,P):kt(I.body,i,$);return Promise.resolve(j).finally(()=>{p&&p.lap("stream",E),p?.commit()})}const N=Buffer.from(await I.arrayBuffer());if(p&&p.lap("upstream",Y),$&&z.includes("application/json"))try{const E=p?p.clock():0,j=d.restoreResponse(JSON.parse(N.toString("utf8")),$,P);return p&&p.lap("restore",E),i.writeHead(I.status,{...R,"content-type":"application/json"}),i.end(Buffer.from(JSON.stringify(j),"utf8")),p?.commit()}catch{}i.writeHead(I.status,R),i.end(N),p?.commit()}function fr(t=Ie()){Dt(t.allowedExtensionIds||[]);const i=[],d=r=>{i.push(r),i.length>50&&i.shift()};return gt(async(r,o)=>{const u=new URL(r.url,"http://127.0.0.1"),c=u.pathname;if(!it(r.headers.host))return s(o,403,{error:"loopback only"});if(!qo(r.headers.origin,t))return s(o,403,{error:"origin not allowed"});if(r.headers.origin&&er(o,r.headers.origin),r.method==="OPTIONS")return o.writeHead(204),o.end();if(c==="/admin/token"&&r.method==="POST")return W(r)?s(o,200,{token:ke()}):s(o,403,{error:"admin: extension origin or gateway token required"});if(c==="/pair/code"&&r.method==="POST"){if(!W(r))return s(o,403,{error:"pair/code: extension origin or gateway token required"});const e=Ct();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=It(e?.code);if(!n.ok)return console.log(`[gateway] pairing refused (${n.reason}) from ${ue(r)} caller`),s(o,403,{error:n.reason});console.log(`[gateway] paired a ${ue(r)} client${r.headers.origin?` (${r.headers.origin})`:""}`);const a=le(t.bridge?.token);return s(o,200,{ok:!0,token:Bt()||ke(),...a?{bridgeToken:a}:{}})}if(c==="/whoami"&&r.method==="POST"){const e=ue(r);return s(o,200,{ok:!0,trust:e,paired:Nt(e),version:K})}if(c==="/audit"&&r.method==="GET")return W(r)?s(o,200,Mt(t,{version:K,startedAt:lt,managed:ie()})):s(o,403,{error:"audit: extension origin or gateway token required"});if((c==="/config"||c==="/logs"||c==="/update"&&r.method!=="GET")&&!W(r))return s(o,403,{error:"admin route: extension origin or gateway token required"});if(c==="/update"&&r.method==="GET"){const e=await io(K,{force:u.searchParams.get("force")==="1"}).catch(n=>({current:K,updateAvailable:!1,error:String(n?.message||n)}));return s(o,200,{ok:!0,update:e,job:uo()})}if(c==="/update"&&r.method==="POST"){const e=co(K);return s(o,e.already?409:202,{ok:!0,job:e})}if((c==="/v1/history/key"||c==="/v1/history/ingest-backup")&&r.method==="POST"&&!W(r))return s(o,403,{error:{message:"history key route: extension origin or gateway token required",type:"forbidden"}});if(c==="/v1/history/records"&&r.method==="PUT"&&!W(r))return s(o,403,{error:{message:"history write — extension origin or gateway token required",type:"forbidden"}});if((c==="/v1/history/ingest"||c==="/v1/history/clear")&&r.method==="POST"&&!W(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"&&!W(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"))&&!W(r))return s(o,403,{error:{message:"prefs: extension origin or gateway token required",type:"forbidden"}});if(c.startsWith("/v1/observability")&&!W(r))return s(o,403,{error:{message:"observability: extension origin or gateway token required",type:"forbidden"}});if(r.method==="GET"&&c==="/health"){const e=A.health(),n=S.health();return s(o,200,{ok:!0,version:K,backend:t.backend,tier:t.redaction.tier,pairing:!0,...ie()?{managed:ie()}:{},...process.env.CHATPANEL_MANAGED_BY?{managedBy:String(process.env.CHATPANEL_MANAGED_BY).slice(0,32)}:{},...we?{bridge:we.status()}:{},stt:{enabled:t.stt?.enabled!==!1,state:e.state,ready:e.ok,model:e.model||t.stt?.model||Pe,runtime:e.runtime,dtype:e.dtype},tts:{enabled:t.tts?.enabled!==!1,state:n.state,ready:n.ok,model:n.model||t.tts?.model||Ke,voice:t.tts?.voice||X,runtime:n.runtime,dtype:n.dtype}})}if(c==="/status"&&r.method==="GET"){bt(t);const e=await ee(t.pro?.entitlementToken),n=await mt(t);return s(o,200,{ok:!0,version:K,backend:t.backend,tier:t.redaction.tier,...ie()?{managed:ie()}:{},...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:Ce(t),pro:{unlocked:e},usage:zo(t),uptimeSeconds:Math.floor((Date.now()-lt)/1e3),update:lo(K)})}if(c==="/v1/history/ingest"&&r.method==="POST")try{const e=JSON.parse((await v(r,t.maxBodyBytes)).toString("utf8"))||{},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:U.revision,stamps:U.stamps()}):s(o,200,{ok:!0,revision:U.revision,sections:U.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=U.put(e.sections||{},{by:e.by||""});return n.applied.length&&ot(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?U.remove(e):!1;return n&&ot([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)}
13
+ `)}w&&w.lap("stream",le),l.end(),w?.commit()}function ur(t,l,d=""){const r=String(t||"").replace(/\/+$/,""),o=String(l||"").split("/")[1];return o&&r.endsWith(`/${o}`)?r.slice(0,-(o.length+1))+l+d:r+l+d}const mr=9e4;function pr(t,l,d){if(l===d)return t;const r=l/d,o=new Float32Array(Math.floor(t.length/r));for(let u=0;u<o.length;u++){const c=u*r,g=Math.floor(c),w=Math.min(t.length-1,g+1),P=c-g;o[u]=t[g]*(1-P)+t[w]*P}return o}const hr=["/tts","/stt","/ner","/diarize","/skills","/redact","/config","/logs","/status","/admin"];function Ie(t,l){const d=new URLSearchParams;for(const u of t.searchParams.getAll("dir"))u&&d.append("dir",u);const r=t.searchParams.get("workdir")||String(l?.bridge?.workingDir||"").trim();r&&d.set("workdir",r);const o=d.toString();return o?`?${o}`:""}async function yr(t,l,{adapter:d,kind:r,pathname:o,search:u,base:c,destKey:g,destProtocol:w,harness:P,trace:p},z,x){let I;const Y=p?p.clock():0;try{const $=ir(t.headers,c);g&&(w==="anthropic"?($["x-api-key"]=g,delete $.authorization):$.authorization=`Bearer ${g}`);const j=Et(ur(c,o,u)).toString();I=await fetch(j,{method:t.method,headers:$,body:["GET","HEAD"].includes(t.method)?void 0:z})}catch($){return p?.commit(),s(l,502,{error:`upstream fetch failed: ${$.message}`})}const L=I.headers.get("content-type")||"",R={};if(I.headers.forEach(($,j)=>{it.has(j.toLowerCase())||(R[j]=$)}),L.includes("text/event-stream")&&I.body){p&&p.lap("upstream",Y);const $=p?p.clock():0;l.writeHead(I.status,R);const j=r==="openai"?St(I.body,l,x,P):kt(I.body,l,x);return Promise.resolve(j).finally(()=>{p&&p.lap("stream",$),p?.commit()})}const N=Buffer.from(await I.arrayBuffer());if(p&&p.lap("upstream",Y),x&&L.includes("application/json"))try{const $=p?p.clock():0,j=d.restoreResponse(JSON.parse(N.toString("utf8")),x,P);return p&&p.lap("restore",$),l.writeHead(I.status,{...R,"content-type":"application/json"}),l.end(Buffer.from(JSON.stringify(j),"utf8")),p?.commit()}catch{}l.writeHead(I.status,R),l.end(N),p?.commit()}function fr(t=je()){Dt(t.allowedExtensionIds||[]);const l=[],d=r=>{l.push(r),l.length>50&&l.shift()};return gt(async(r,o)=>{const u=new URL(r.url,"http://127.0.0.1"),c=u.pathname;if(!lt(r.headers.host))return s(o,403,{error:"loopback only"});if(!qo(r.headers.origin,t))return s(o,403,{error:"origin not allowed"});if(r.headers.origin&&er(o,r.headers.origin),r.method==="OPTIONS")return o.writeHead(204),o.end();if(c==="/admin/token"&&r.method==="POST")return H(r)?s(o,200,{token:ke()}):s(o,403,{error:"admin: extension origin or gateway token required"});if(c==="/pair/code"&&r.method==="POST"){if(!H(r))return s(o,403,{error:"pair/code: extension origin or gateway token required"});const e=Ct();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=It(e?.code);if(!n.ok)return console.log(`[gateway] pairing refused (${n.reason}) from ${me(r)} caller`),s(o,403,{error:n.reason});console.log(`[gateway] paired a ${me(r)} client${r.headers.origin?` (${r.headers.origin})`:""}`);const a=ee(t.bridge?.token);return s(o,200,{ok:!0,token:Bt()||ke(),...a?{bridgeToken:a}:{}})}if(c==="/whoami"&&r.method==="POST"){const e=me(r);return s(o,200,{ok:!0,trust:e,paired:Nt(e),version:K})}if(c==="/audit"&&r.method==="GET")return H(r)?s(o,200,Mt(t,{version:K,startedAt:ct,managed:ce()})):s(o,403,{error:"audit: extension origin or gateway token required"});if((c==="/config"||c==="/logs"||c==="/update"&&r.method!=="GET")&&!H(r))return s(o,403,{error:"admin route: extension origin or gateway token required"});if(c==="/update"&&r.method==="GET"){const e=await io(K,{force:u.searchParams.get("force")==="1"}).catch(n=>({current:K,updateAvailable:!1,error:String(n?.message||n)}));return s(o,200,{ok:!0,update:e,job:uo()})}if(c==="/update"&&r.method==="POST"){const e=co(K);return s(o,e.already?409:202,{ok:!0,job:e})}if((c==="/v1/history/key"||c==="/v1/history/ingest-backup")&&r.method==="POST"&&!H(r))return s(o,403,{error:{message:"history key route: extension origin or gateway token required",type:"forbidden"}});if(c==="/v1/history/records"&&r.method==="PUT"&&!H(r))return s(o,403,{error:{message:"history write — extension origin or gateway token required",type:"forbidden"}});if((c==="/v1/history/ingest"||c==="/v1/history/clear")&&r.method==="POST"&&!H(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"&&!H(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"))&&!H(r))return s(o,403,{error:{message:"prefs: extension origin or gateway token required",type:"forbidden"}});if(c.startsWith("/v1/observability")&&!H(r))return s(o,403,{error:{message:"observability: extension origin or gateway token required",type:"forbidden"}});if(r.method==="GET"&&c==="/health"){const e=A.health(),n=S.health();return s(o,200,{ok:!0,version:K,backend:t.backend,tier:t.redaction.tier,pairing:!0,...ce()?{managed:ce()}:{},...process.env.CHATPANEL_MANAGED_BY?{managedBy:String(process.env.CHATPANEL_MANAGED_BY).slice(0,32)}:{},...be?{bridge:be.status()}:{},stt:{enabled:t.stt?.enabled!==!1,state:e.state,ready:e.ok,model:e.model||t.stt?.model||Pe,runtime:e.runtime,dtype:e.dtype},tts:{enabled:t.tts?.enabled!==!1,state:n.state,ready:n.ok,model:n.model||t.tts?.model||Ze,voice:t.tts?.voice||X,runtime:n.runtime,dtype:n.dtype}})}if(c==="/status"&&r.method==="GET"){wt(t);const e=await te(t.pro?.entitlementToken),n=await pt(t);return s(o,200,{ok:!0,version:K,backend:t.backend,tier:t.redaction.tier,...ce()?{managed:ce()}:{},...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:Ce(t),pro:{unlocked:e},usage:Lo(t),uptimeSeconds:Math.floor((Date.now()-ct)/1e3),update:lo(K)})}if(c==="/v1/history/ingest"&&r.method==="POST")try{const e=JSON.parse((await v(r,t.maxBodyBytes)).toString("utf8"))||{},n=O.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:F.revision,stamps:F.stamps()}):s(o,200,{ok:!0,revision:F.revision,sections:F.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=F.put(e.sections||{},{by:e.by||""});return n.applied.length&&rt(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?F.remove(e):!1;return n&&rt([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=i=>o.write(`data: ${JSON.stringify(i)}
14
14
 
15
- `);e({type:"hello",revision:U.revision,stamps:U.stamps()});const n=l=>e({type:"changed",...l});Ne.add(n);const a=setInterval(()=>{try{o.write(`: keep-alive
15
+ `);e({type:"hello",revision:F.revision,stamps:F.stamps()});const n=i=>e({type:"changed",...i});Ne.add(n);const a=setInterval(()=>{try{o.write(`: keep-alive
16
16
 
17
- `)}catch{}},25e3);o.on("close",()=>{Ne.delete(n),clearInterval(a)});return}if(c==="/v1/projects"&&r.method==="GET")return s(o,200,{ok:!0,projects:V.list({limit:u.searchParams.get("limit")||50,status:u.searchParams.get("status")||""})});if(c==="/v1/projects/jobs"&&r.method==="GET")return s(o,200,{ok:!0,jobs:V.openJobs()});if(c==="/v1/projects"&&r.method==="POST")try{const e=JSON.parse((await v(r,t.maxBodyBytes)).toString("utf8"))||{};return s(o,200,{ok:!0,project:V.create({id:e.id||e.project?.id,project:e.project||null,by:e.by})})}catch(e){return s(o,400,{error:{message:`project: ${e.message}`,type:"project_error"}})}{const e=/^\/v1\/projects\/([a-zA-Z0-9_-]{1,64})(\/events|\/jobs(?:\/([a-zA-Z0-9_-]{1,64})(\/applications|\/recruit)?)?)?$/.exec(c);if(e){const n=e[1],a=e[2]||"",l=e[3]||"",m=e[4]||"",k=()=>s(o,404,{error:{message:`no project ${n}`,type:"not_found"}});if(m){const h=V.get(n);if(!h)return k();const b=h.jobs.find(f=>f.id===l);if(!b)return s(o,404,{error:{message:`no job ${l}`,type:"not_found"}});const y={cfg:t,prefsStore:U,scorecards:re,engines:ne};if(m==="/applications"&&r.method==="GET"){const f=await no(b,{...y,reach:u.searchParams.get("reach")||"any",chatModel:u.searchParams.get("chatModel")||null});return s(o,200,{ok:!0,job:b,...f})}if(m==="/recruit"&&r.method==="POST"){if(!["open","evaluating"].includes(b.status))return s(o,400,{error:{message:`job ${l} is ${b.status}; only an open job is recruited`,type:"project_error"}});try{const f=JSON.parse((await v(r,t.maxBodyBytes)).toString("utf8"))||{},O=String(f.by||"evaluator").slice(0,80),M=await so(b,{...y,record:h,reach:f.reach||"any",chatModel:f.chatModel||null,evaluation:f.evaluation||null,text:f.text??null,by:O});let x=null;for(const F of M.events)F.type==="job.updated"?x=V.updateJob(n,l,F.job,{by:F.by||O}):x=V.append(n,[F]);return s(o,200,{ok:!0,project:x,decision:M.decision,applications:M.applications,evaluation:M.evaluation})}catch(f){return s(o,400,{error:{message:`recruit: ${f.message}`,type:"project_error"}})}}return s(o,405,{error:{message:"method not allowed",type:"project_error"}})}if(!a&&r.method==="GET"){const h=V.get(n,{events:u.searchParams.get("events")==="1"});return h?s(o,200,{ok:!0,project:h}):k()}if(!a&&r.method==="DELETE")return s(o,200,{ok:!0,removed:V.remove(n)});if(r.method==="POST"&&(a==="/events"||a.startsWith("/jobs")))try{const h=JSON.parse((await v(r,t.maxBodyBytes)).toString("utf8"))||{},b=String(h.by||"person").slice(0,80),y=a==="/events"?V.append(n,h.events||[]):l?V.updateJob(n,l,h.patch||h,{by:b}):V.postJob(n,h.job||h,{by:b});return s(o,200,{ok:!0,project:y})}catch(h){return s(o,h.message.startsWith("no ")?404:400,{error:{message:`project: ${h.message}`,type:"project_error"}})}if(a==="/events"&&r.method==="GET"){if(!V.get(n))return k();o.writeHead(200,{"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive"});const h=O=>o.write(`data: ${JSON.stringify(O)}
17
+ `)}catch{}},25e3);o.on("close",()=>{Ne.delete(n),clearInterval(a)});return}if(c==="/v1/projects"&&r.method==="GET")return s(o,200,{ok:!0,projects:V.list({limit:u.searchParams.get("limit")||50,status:u.searchParams.get("status")||""})});if(c==="/v1/projects/jobs"&&r.method==="GET")return s(o,200,{ok:!0,jobs:V.openJobs()});if(c==="/v1/projects"&&r.method==="POST")try{const e=JSON.parse((await v(r,t.maxBodyBytes)).toString("utf8"))||{};return s(o,200,{ok:!0,project:V.create({id:e.id||e.project?.id,project:e.project||null,by:e.by})})}catch(e){return s(o,400,{error:{message:`project: ${e.message}`,type:"project_error"}})}{const e=/^\/v1\/projects\/([a-zA-Z0-9_-]{1,64})(\/events|\/jobs(?:\/([a-zA-Z0-9_-]{1,64})(\/applications|\/recruit)?)?)?$/.exec(c);if(e){const n=e[1],a=e[2]||"",i=e[3]||"",m=e[4]||"",b=()=>s(o,404,{error:{message:`no project ${n}`,type:"not_found"}});if(m){const h=V.get(n);if(!h)return b();const k=h.jobs.find(f=>f.id===i);if(!k)return s(o,404,{error:{message:`no job ${i}`,type:"not_found"}});const y={cfg:t,prefsStore:F,scorecards:se,engines:ae};if(m==="/applications"&&r.method==="GET"){const f=await no(k,{...y,reach:u.searchParams.get("reach")||"any",chatModel:u.searchParams.get("chatModel")||null});return s(o,200,{ok:!0,job:k,...f})}if(m==="/recruit"&&r.method==="POST"){if(!["open","evaluating"].includes(k.status))return s(o,400,{error:{message:`job ${i} is ${k.status}; only an open job is recruited`,type:"project_error"}});try{const f=JSON.parse((await v(r,t.maxBodyBytes)).toString("utf8"))||{},_=String(f.by||"evaluator").slice(0,80),M=await so(k,{...y,record:h,reach:f.reach||"any",chatModel:f.chatModel||null,evaluation:f.evaluation||null,text:f.text??null,by:_});let E=null;for(const W of M.events)W.type==="job.updated"?E=V.updateJob(n,i,W.job,{by:W.by||_}):E=V.append(n,[W]);return s(o,200,{ok:!0,project:E,decision:M.decision,applications:M.applications,evaluation:M.evaluation})}catch(f){return s(o,400,{error:{message:`recruit: ${f.message}`,type:"project_error"}})}}return s(o,405,{error:{message:"method not allowed",type:"project_error"}})}if(!a&&r.method==="GET"){const h=V.get(n,{events:u.searchParams.get("events")==="1"});return h?s(o,200,{ok:!0,project:h}):b()}if(!a&&r.method==="DELETE")return s(o,200,{ok:!0,removed:V.remove(n)});if(r.method==="POST"&&(a==="/events"||a.startsWith("/jobs")))try{const h=JSON.parse((await v(r,t.maxBodyBytes)).toString("utf8"))||{},k=String(h.by||"person").slice(0,80),y=a==="/events"?V.append(n,h.events||[]):i?V.updateJob(n,i,h.patch||h,{by:k}):V.postJob(n,h.job||h,{by:k});return s(o,200,{ok:!0,project:y})}catch(h){return s(o,h.message.startsWith("no ")?404:400,{error:{message:`project: ${h.message}`,type:"project_error"}})}if(a==="/events"&&r.method==="GET"){if(!V.get(n))return b();o.writeHead(200,{"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive"});const h=_=>o.write(`data: ${JSON.stringify(_)}
18
18
 
19
- `);let b=u.searchParams.has("after")?Number(u.searchParams.get("after")):-1;h({seq:-1,type:"hello",at:Date.now(),payload:{project:V.get(n),after:b}});const y=V.watch(n,O=>{O.seq>b&&(b=O.seq,h(O))});for(const O of V.eventsSince(n,b))b=O.seq,h(O);const f=setInterval(()=>{try{o.write(`: keep
19
+ `);let k=u.searchParams.has("after")?Number(u.searchParams.get("after")):-1;h({seq:-1,type:"hello",at:Date.now(),payload:{project:V.get(n),after:k}});const y=V.watch(n,_=>{_.seq>k&&(k=_.seq,h(_))});for(const _ of V.eventsSince(n,k))k=_.seq,h(_);const f=setInterval(()=>{try{o.write(`: keep
20
20
 
21
- `)}catch{}},25e3);r.on("close",()=>{clearInterval(f),y()});return}}}if(c==="/v1/agents/scorecards"&&r.method==="GET")return s(o,200,{ok:!0,agents:re.list()});{const e=/^\/v1\/agents\/([a-zA-Z0-9_.:@+-]{1,120})\/scorecard$/.exec(c);if(e){const n=decodeURIComponent(e[1]);if(r.method==="GET")return s(o,200,{ok:!0,...await re.get(n)});if(r.method==="POST")try{const a=JSON.parse((await v(r,t.maxBodyBytes)).toString("utf8"))||{},l=await re.append({agentId:n,kind:"rating",runId:a.runId,taskId:a.taskId,jobId:a.jobId,rating:{by:String(a.by||"person").slice(0,40),score:a.score,note:a.note,about:a.about},refs:a.refs});return ne.fromRating(re.chains.get(n)||[],{...l,jobKind:a.jobKind?String(a.jobKind).slice(0,60):void 0}),s(o,200,{ok:!0,entry:l})}catch(a){return s(o,400,{error:{message:`scorecard: ${a.message}`,type:"scorecard_error"}})}}}if(c==="/v1/engines"&&r.method==="GET"){const e=Number(u.searchParams.get("minCalls"))||void 0;return s(o,200,{ok:!0,engines:ne.list({minCalls:e})})}{const e=/^\/v1\/engines\/(.+)\/(card|entries)$/.exec(c);if(e){const n=decodeURIComponent(e[1]).slice(0,300);if(e[2]==="card"&&r.method==="GET"){const a=Number(u.searchParams.get("minCalls"))||void 0;return s(o,200,{ok:!0,...await ne.get(n,{entries:u.searchParams.get("entries")==="1",minCalls:a})})}if(e[2]==="entries"&&r.method==="POST")try{const a=JSON.parse((await v(r,t.maxBodyBytes)).toString("utf8"))||{},l=a.engine||or(n);if(!l)return s(o,400,{error:{message:"model-ledger: engine required",type:"model_ledger_error"}});const m=await ne.append({...a,engine:l,kind:a.kind||"call"});return m.key!==n?s(o,400,{error:{message:`model-ledger: entry is for ${m.key}, not ${n}`,type:"model_ledger_error"}}):s(o,200,{ok:!0,entry:m})}catch(a){return s(o,400,{error:{message:`model-ledger: ${a.message}`,type:"model_ledger_error"}})}}}if(c==="/v1/teams/runs"&&r.method==="GET")return s(o,200,{ok:!0,runs:C.list({limit:u.searchParams.get("limit")||50,team:u.searchParams.get("team")||""})});if(c==="/v1/teams/runs"&&r.method==="POST")try{const e=JSON.parse((await v(r,t.maxBodyBytes)).toString("utf8"))||{};return s(o,200,{ok:!0,run:C.create({id:e.id,client:e.client,team:e.team,request:e.request})})}catch(e){return s(o,400,{error:{message:`team run: ${e.message}`,type:"team_error"}})}{const e=/^\/v1\/teams\/runs\/([a-zA-Z0-9_-]{4,64})(\/events|\/stop|\/answer|\/decide|\/post|\/handoff|\/checkpoint|\/claim|\/threads\/[a-zA-Z0-9_:-]{1,80})?$/.exec(c);if(e){const n=e[1],a=e[2]||"";if(!a&&r.method==="GET"){const l=C.get(n,{events:u.searchParams.get("events")==="1"});return l?s(o,200,{ok:!0,run:l}):s(o,404,{error:{message:`no run ${n}`,type:"not_found"}})}if(!a&&r.method==="DELETE")return C.stop(n),s(o,200,{ok:!0,removed:C.remove(n)});if(a==="/stop"&&r.method==="POST"){const l=C.stop(n);return l?s(o,200,{ok:!0,run:l}):s(o,404,{error:{message:`no run ${n}`,type:"not_found"}})}if(a==="/checkpoint"&&r.method==="GET")try{return s(o,200,{ok:!0,checkpoint:C.checkpoint(n)})}catch(l){return s(o,404,{error:{message:`team run: ${l.message}`,type:"team_error"}})}if((a==="/handoff"||a==="/claim")&&r.method==="POST")try{const l=JSON.parse((await v(r,t.maxBodyBytes)).toString("utf8"))||{},m=a==="/handoff"?C.handoff(n,{taskId:l.taskId,model:l.model,by:l.by,reason:l.reason}):C.claim(n,{client:l.client});return s(o,200,{ok:!0,run:m})}catch(l){return s(o,l.message.startsWith("no ")?404:400,{error:{message:`team run: ${l.message}`,type:"team_error"}})}if(a.startsWith("/threads/")&&r.method==="DELETE")try{return s(o,200,{ok:!0,run:C.removeThread(n,{threadId:a.slice(9),by:"person"})})}catch(l){return s(o,l.message.startsWith("no ")?404:400,{error:{message:`team run: ${l.message}`,type:"team_error"}})}if((a==="/answer"||a==="/decide"||a==="/post")&&r.method==="POST")try{const l=JSON.parse((await v(r,t.maxBodyBytes)).toString("utf8"))||{},m=String(l.by||"person").slice(0,40),k=a==="/answer"?C.answer(n,{threadId:l.threadId,text:l.text,by:m}):a==="/decide"?C.decide(n,{postId:l.postId,status:l.status,by:m}):C.post(n,{threadId:l.threadId,text:l.text,by:m,kind:l.kind,replyTo:l.replyTo});return s(o,200,{ok:!0,run:k})}catch(l){return s(o,l.message.startsWith("no ")?404:400,{error:{message:`team run: ${l.message}`,type:"team_error"}})}if(a==="/events"&&r.method==="POST")try{const l=JSON.parse((await v(r,t.maxBodyBytes)).toString("utf8"))||{};return s(o,200,{ok:!0,run:C.append(n,l.events||[])})}catch(l){return s(o,l.message.startsWith("no run")?404:400,{error:{message:`team run: ${l.message}`,type:"team_error"}})}if(a==="/events"&&r.method==="GET"){if(!C.get(n))return s(o,404,{error:{message:`no run ${n}`,type:"not_found"}});o.writeHead(200,{"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive"});const l=y=>o.write(`data: ${JSON.stringify(y)}
21
+ `)}catch{}},25e3);r.on("close",()=>{clearInterval(f),y()});return}}}if(c==="/v1/agents/scorecards"&&r.method==="GET")return s(o,200,{ok:!0,agents:se.list()});{const e=/^\/v1\/agents\/([a-zA-Z0-9_.:@+-]{1,120})\/scorecard$/.exec(c);if(e){const n=decodeURIComponent(e[1]);if(r.method==="GET")return s(o,200,{ok:!0,...await se.get(n)});if(r.method==="POST")try{const a=JSON.parse((await v(r,t.maxBodyBytes)).toString("utf8"))||{},i=await se.append({agentId:n,kind:"rating",runId:a.runId,taskId:a.taskId,jobId:a.jobId,rating:{by:String(a.by||"person").slice(0,40),score:a.score,note:a.note,about:a.about},refs:a.refs});return ae.fromRating(se.chains.get(n)||[],{...i,jobKind:a.jobKind?String(a.jobKind).slice(0,60):void 0}),s(o,200,{ok:!0,entry:i})}catch(a){return s(o,400,{error:{message:`scorecard: ${a.message}`,type:"scorecard_error"}})}}}if(c==="/v1/engines"&&r.method==="GET"){const e=Number(u.searchParams.get("minCalls"))||void 0;return s(o,200,{ok:!0,engines:ae.list({minCalls:e})})}{const e=/^\/v1\/engines\/(.+)\/(card|entries)$/.exec(c);if(e){const n=decodeURIComponent(e[1]).slice(0,300);if(e[2]==="card"&&r.method==="GET"){const a=Number(u.searchParams.get("minCalls"))||void 0;return s(o,200,{ok:!0,...await ae.get(n,{entries:u.searchParams.get("entries")==="1",minCalls:a})})}if(e[2]==="entries"&&r.method==="POST")try{const a=JSON.parse((await v(r,t.maxBodyBytes)).toString("utf8"))||{},i=a.engine||or(n);if(!i)return s(o,400,{error:{message:"model-ledger: engine required",type:"model_ledger_error"}});const m=await ae.append({...a,engine:i,kind:a.kind||"call"});return m.key!==n?s(o,400,{error:{message:`model-ledger: entry is for ${m.key}, not ${n}`,type:"model_ledger_error"}}):s(o,200,{ok:!0,entry:m})}catch(a){return s(o,400,{error:{message:`model-ledger: ${a.message}`,type:"model_ledger_error"}})}}}if(c==="/v1/teams/runs"&&r.method==="GET")return s(o,200,{ok:!0,runs:C.list({limit:u.searchParams.get("limit")||50,team:u.searchParams.get("team")||""})});if(c==="/v1/teams/runs"&&r.method==="POST")try{const e=JSON.parse((await v(r,t.maxBodyBytes)).toString("utf8"))||{};return s(o,200,{ok:!0,run:C.create({id:e.id,client:e.client,team:e.team,request:e.request})})}catch(e){return s(o,400,{error:{message:`team run: ${e.message}`,type:"team_error"}})}{const e=/^\/v1\/teams\/runs\/([a-zA-Z0-9_-]{4,64})(\/events|\/stop|\/answer|\/decide|\/post|\/handoff|\/checkpoint|\/claim|\/threads\/[a-zA-Z0-9_:-]{1,80})?$/.exec(c);if(e){const n=e[1],a=e[2]||"";if(!a&&r.method==="GET"){const i=C.get(n,{events:u.searchParams.get("events")==="1"});return i?s(o,200,{ok:!0,run:i}):s(o,404,{error:{message:`no run ${n}`,type:"not_found"}})}if(!a&&r.method==="DELETE")return C.stop(n),s(o,200,{ok:!0,removed:C.remove(n)});if(a==="/stop"&&r.method==="POST"){const i=C.stop(n);return i?s(o,200,{ok:!0,run:i}):s(o,404,{error:{message:`no run ${n}`,type:"not_found"}})}if(a==="/checkpoint"&&r.method==="GET")try{return s(o,200,{ok:!0,checkpoint:C.checkpoint(n)})}catch(i){return s(o,404,{error:{message:`team run: ${i.message}`,type:"team_error"}})}if((a==="/handoff"||a==="/claim")&&r.method==="POST")try{const i=JSON.parse((await v(r,t.maxBodyBytes)).toString("utf8"))||{},m=a==="/handoff"?C.handoff(n,{taskId:i.taskId,model:i.model,by:i.by,reason:i.reason}):C.claim(n,{client:i.client});return s(o,200,{ok:!0,run:m})}catch(i){return s(o,i.message.startsWith("no ")?404:400,{error:{message:`team run: ${i.message}`,type:"team_error"}})}if(a.startsWith("/threads/")&&r.method==="DELETE")try{return s(o,200,{ok:!0,run:C.removeThread(n,{threadId:a.slice(9),by:"person"})})}catch(i){return s(o,i.message.startsWith("no ")?404:400,{error:{message:`team run: ${i.message}`,type:"team_error"}})}if((a==="/answer"||a==="/decide"||a==="/post")&&r.method==="POST")try{const i=JSON.parse((await v(r,t.maxBodyBytes)).toString("utf8"))||{},m=String(i.by||"person").slice(0,40),b=a==="/answer"?C.answer(n,{threadId:i.threadId,text:i.text,by:m}):a==="/decide"?C.decide(n,{postId:i.postId,status:i.status,by:m}):C.post(n,{threadId:i.threadId,text:i.text,by:m,kind:i.kind,replyTo:i.replyTo});return s(o,200,{ok:!0,run:b})}catch(i){return s(o,i.message.startsWith("no ")?404:400,{error:{message:`team run: ${i.message}`,type:"team_error"}})}if(a==="/events"&&r.method==="POST")try{const i=JSON.parse((await v(r,t.maxBodyBytes)).toString("utf8"))||{};return s(o,200,{ok:!0,run:C.append(n,i.events||[])})}catch(i){return s(o,i.message.startsWith("no run")?404:400,{error:{message:`team run: ${i.message}`,type:"team_error"}})}if(a==="/events"&&r.method==="GET"){if(!C.get(n))return s(o,404,{error:{message:`no run ${n}`,type:"not_found"}});o.writeHead(200,{"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive"});const i=y=>o.write(`data: ${JSON.stringify(y)}
22
22
 
23
- `),m=u.searchParams.has("after")?Number(u.searchParams.get("after")):NaN;let k=Number.isFinite(m)?m:-1;l({seq:-1,type:"hello",at:Date.now(),payload:{run:C.get(n),after:k}});const h=C.watch(n,y=>{y.seq==null?l(y):y.seq>k&&(k=y.seq,l(y))});for(const y of C.eventsSince(n,k))k=y.seq,l(y);const b=setInterval(()=>{try{o.write(`: keep-alive
23
+ `),m=u.searchParams.has("after")?Number(u.searchParams.get("after")):NaN;let b=Number.isFinite(m)?m:-1;i({seq:-1,type:"hello",at:Date.now(),payload:{run:C.get(n),after:b}});const h=C.watch(n,y=>{y.seq==null?i(y):y.seq>b&&(b=y.seq,i(y))});for(const y of C.eventsSince(n,b))b=y.seq,i(y);const k=setInterval(()=>{try{o.write(`: keep-alive
24
24
 
25
- `)}catch{}},25e3);o.on("close",()=>{h(),clearInterval(b)});return}}}if(c==="/v1/memory/list"&&r.method==="GET")return s(o,200,{ok:!0,size:H.size,memories:H.list()});if(c==="/v1/memory/recall"&&r.method==="POST")try{const e=JSON.parse((await v(r,t.maxBodyBytes)).toString("utf8"))||{},n=H.recall({text:String(e.text||""),scopes:Array.isArray(e.scopes)&&e.scopes.length?e.scopes.map(String):["global"],limit:Number(e.limit)||0,maxChars:Number(e.maxChars)||0});return s(o,200,{ok:!0,size:H.size,...n})}catch(e){return s(o,400,{error:{message:`recall failed: ${e.message}`,type:"memory_error"}})}if(c==="/v1/memory/remember"&&r.method==="POST")try{const e=JSON.parse((await v(r,t.maxBodyBytes)).toString("utf8"))||{},n=H.remember({text:String(e.text||""),kind:e.kind?String(e.kind):"fact",scope:e.scope?String(e.scope):"global",tags:Array.isArray(e.tags)?e.tags.map(String):[],source:{via:String(e.source?.via||"mcp"),surface:String(e.source?.surface||"mcp"),agent:String(e.source?.agent||""),ref:String(e.source?.ref||"")}});return s(o,200,{ok:!0,action:n.action,record:n.record,replaced:n.replaces||null,size:H.size})}catch(e){return s(o,400,{error:{message:e.message,type:"memory_error"}})}if(c==="/v1/memory/forget"&&r.method==="POST")try{const e=JSON.parse((await v(r,t.maxBodyBytes)).toString("utf8"))||{},{removed:n}=H.forget(String(e.query||""));return s(o,200,{ok:!0,removed:n,size:H.size})}catch(e){return s(o,400,{error:{message:e.message,type:"memory_error"}})}if(c==="/v1/memory/sync"&&r.method==="POST")try{const e=JSON.parse((await v(r,t.maxBodyBytes)).toString("utf8"))||{},n=H.bulk({upserts:Array.isArray(e.upserts)?e.upserts:[],removes:Array.isArray(e.removes)?e.removes:[]});return s(o,200,{ok:!0,...n,memories:H.list()})}catch(e){return s(o,400,{error:{message:`memory sync failed: ${e.message}`,type:"memory_error"}})}if(c==="/v1/memory/clear"&&r.method==="POST")return s(o,200,{ok:!0,dropped:H.clear(),size:H.size});if(c==="/v1/history/clear"&&r.method==="POST"){const e=_.clear();return s(o,200,{ok:!0,dropped:e,size:_.size})}if(c==="/v1/history/search"&&r.method==="POST")try{const e=JSON.parse((await v(r,t.maxBodyBytes)).toString("utf8"))||{},n=_.search(String(e.query||""),{limit:Number(e.limit)||10,offset:Math.max(0,Number(e.offset)||0),type:e.type?String(e.type):null,since:e.since!=null?Number(e.since):null,before:e.before!=null?Number(e.before):null});return s(o,200,{ok:!0,size:_.size,newest:_.newest,results:n})}catch(e){return s(o,400,{error:{message:`search failed: ${e.message}`,type:"search_error"}})}if(c==="/v1/history/smart-search"&&r.method==="POST")try{const e=JSON.parse((await v(r,t.maxBodyBytes)).toString("utf8"))||{},n=String(e.question||e.query||""),a=Wo(n,{extra:Array.isArray(e.queries)?e.queries.map(String):[],max:Math.min(6,Math.max(1,Number(e.maxQueries)||4))}),l={type:e.type?String(e.type):null,since:e.since!=null?Number(e.since):null,before:e.before!=null?Number(e.before):null},m=Math.min(30,Math.max(5,Number(e.limit)||10)*2),k=await Ko(a,b=>_.search(b,{limit:m,...l}),{limit:Math.min(50,Math.max(1,Number(e.limit)||10))}),h=l.type?k:[...k.filter(b=>b.type==="brief"),...k.filter(b=>b.type!=="brief")];return s(o,200,{ok:!0,size:_.size,newest:_.newest,queries:a,results:h})}catch(e){return s(o,400,{error:{message:`smart search failed: ${e.message}`,type:"search_error"}})}if(c==="/v1/history/related"&&r.method==="GET"){const e=String(u.searchParams.get("id")||""),n=Math.min(30,Math.max(1,Number(u.searchParams.get("limit"))||5));return s(o,200,{ok:!0,results:_.related(e,{limit:n})})}if(c==="/v1/history/status"&&r.method==="GET")return s(o,200,{ok:!0,size:_.size,newest:_.newest,bytes:_.bytes,lossless:_.lossless?{records:_.lossless.size,newest:_.lossless.newest}:null});if(c==="/v1/observability"&&r.method==="GET"){const e=Math.min(500,Math.max(1,Number(u.searchParams.get("limit"))||200));return s(o,200,{ok:!0,storage:{warm:{records:_.size,bytes:_.bytes,newest:_.newest}},access:Be.snapshot(e)})}if(c==="/v1/observability/access"&&r.method==="POST")try{const e=JSON.parse((await v(r,t.maxBodyBytes)).toString("utf8"))||{},n=Be.push(et({ts:Date.now(),...e}));return s(o,200,{ok:!0,event:n})}catch(e){return s(o,400,{error:{message:`access log failed: ${e.message}`,type:"observability_error"}})}if(c==="/v1/history/records"&&r.method==="PUT"){const e=_.lossless;if(!e)return s(o,501,{error:{message:"lossless records need the SQLite warm store",type:"unavailable"}});try{const n=JSON.parse((await v(r,t.maxBodyBytes)).toString("utf8"))||{},a=String(n.host||"").slice(0,80),l=Number(n.at)||Date.now(),m=[];let k=0;const h={upserts:[],removes:[]},b=y=>{if(!y||y.deletedAt){y?.id&&h.removes.push(y.id);return}try{const f=po(y);f&&h.upserts.push(f)}catch{}};if(Array.isArray(n.records)){const y=e.upsert(n.records,{host:a,at:l});m.push(...y);for(const f of n.records)y.includes(f?.id)&&b(f)}if(Array.isArray(n.entries)){const y=Oe(),f=y?fo((x,F)=>yo(y,{salt:x,iterations:F})):null,O=async x=>{if(!f||!x.blob)return null;const F=await f(x.blob),ce=x.blob.compression&&x.blob.compression!=="none"?go(wo,x.blob.compression):null;return ho(x.blob,F,{codec:ce})},M=await e.upsertEntries(n.entries,{open:O});m.push(...M.written),k+=M.sealed;for(const x of M.written)b(e.get(x))}return(h.upserts.length||h.removes.length)&&_.bulk(h),m.length&&ge({ids:m}),s(o,200,{ok:!0,written:m.length,ids:m,sealed:k,size:e.size})}catch(n){return s(o,400,{error:{message:`records failed: ${n.message}`,type:"ingest_error"}})}}if(c==="/v1/history/stream"&&r.method==="GET"){const e=_.lossless;if(!e)return s(o,501,{error:{message:"lossless records need the SQLite warm store",type:"unavailable"}});o.writeHead(200,{"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive"}),o.write(`event: hello
26
- data: ${JSON.stringify({newest:e.newest,size:e.size,version:K,prefsRevision:U.revision})}
25
+ `)}catch{}},25e3);o.on("close",()=>{h(),clearInterval(k)});return}}}if(c==="/v1/memory/list"&&r.method==="GET")return s(o,200,{ok:!0,size:U.size,memories:U.list()});if(c==="/v1/memory/recall"&&r.method==="POST")try{const e=JSON.parse((await v(r,t.maxBodyBytes)).toString("utf8"))||{},n=U.recall({text:String(e.text||""),scopes:Array.isArray(e.scopes)&&e.scopes.length?e.scopes.map(String):["global"],limit:Number(e.limit)||0,maxChars:Number(e.maxChars)||0});return s(o,200,{ok:!0,size:U.size,...n})}catch(e){return s(o,400,{error:{message:`recall failed: ${e.message}`,type:"memory_error"}})}if(c==="/v1/memory/remember"&&r.method==="POST")try{const e=JSON.parse((await v(r,t.maxBodyBytes)).toString("utf8"))||{},n=U.remember({text:String(e.text||""),kind:e.kind?String(e.kind):"fact",scope:e.scope?String(e.scope):"global",tags:Array.isArray(e.tags)?e.tags.map(String):[],source:{via:String(e.source?.via||"mcp"),surface:String(e.source?.surface||"mcp"),agent:String(e.source?.agent||""),ref:String(e.source?.ref||"")}});return s(o,200,{ok:!0,action:n.action,record:n.record,replaced:n.replaces||null,size:U.size})}catch(e){return s(o,400,{error:{message:e.message,type:"memory_error"}})}if(c==="/v1/memory/forget"&&r.method==="POST")try{const e=JSON.parse((await v(r,t.maxBodyBytes)).toString("utf8"))||{},{removed:n}=U.forget(String(e.query||""));return s(o,200,{ok:!0,removed:n,size:U.size})}catch(e){return s(o,400,{error:{message:e.message,type:"memory_error"}})}if(c==="/v1/memory/sync"&&r.method==="POST")try{const e=JSON.parse((await v(r,t.maxBodyBytes)).toString("utf8"))||{},n=U.bulk({upserts:Array.isArray(e.upserts)?e.upserts:[],removes:Array.isArray(e.removes)?e.removes:[]});return s(o,200,{ok:!0,...n,memories:U.list()})}catch(e){return s(o,400,{error:{message:`memory sync failed: ${e.message}`,type:"memory_error"}})}if(c==="/v1/memory/clear"&&r.method==="POST")return s(o,200,{ok:!0,dropped:U.clear(),size:U.size});if(c==="/v1/history/clear"&&r.method==="POST"){const e=O.clear();return s(o,200,{ok:!0,dropped:e,size:O.size})}if(c==="/v1/history/search"&&r.method==="POST")try{const e=JSON.parse((await v(r,t.maxBodyBytes)).toString("utf8"))||{},n=O.search(String(e.query||""),{limit:Number(e.limit)||10,offset:Math.max(0,Number(e.offset)||0),type:e.type?String(e.type):null,since:e.since!=null?Number(e.since):null,before:e.before!=null?Number(e.before):null});return s(o,200,{ok:!0,size:O.size,newest:O.newest,results:n})}catch(e){return s(o,400,{error:{message:`search failed: ${e.message}`,type:"search_error"}})}if(c==="/v1/history/smart-search"&&r.method==="POST")try{const e=JSON.parse((await v(r,t.maxBodyBytes)).toString("utf8"))||{},n=String(e.question||e.query||""),a=Wo(n,{extra:Array.isArray(e.queries)?e.queries.map(String):[],max:Math.min(6,Math.max(1,Number(e.maxQueries)||4))}),i={type:e.type?String(e.type):null,since:e.since!=null?Number(e.since):null,before:e.before!=null?Number(e.before):null},m=Math.min(30,Math.max(5,Number(e.limit)||10)*2),b=await Ko(a,k=>O.search(k,{limit:m,...i}),{limit:Math.min(50,Math.max(1,Number(e.limit)||10))}),h=i.type?b:[...b.filter(k=>k.type==="brief"),...b.filter(k=>k.type!=="brief")];return s(o,200,{ok:!0,size:O.size,newest:O.newest,queries:a,results:h})}catch(e){return s(o,400,{error:{message:`smart search failed: ${e.message}`,type:"search_error"}})}if(c==="/v1/history/related"&&r.method==="GET"){const e=String(u.searchParams.get("id")||""),n=Math.min(30,Math.max(1,Number(u.searchParams.get("limit"))||5));return s(o,200,{ok:!0,results:O.related(e,{limit:n})})}if(c==="/v1/history/status"&&r.method==="GET")return s(o,200,{ok:!0,size:O.size,newest:O.newest,bytes:O.bytes,lossless:O.lossless?{records:O.lossless.size,newest:O.lossless.newest}:null});if(c==="/v1/observability"&&r.method==="GET"){const e=Math.min(500,Math.max(1,Number(u.searchParams.get("limit"))||200));return s(o,200,{ok:!0,storage:{warm:{records:O.size,bytes:O.bytes,newest:O.newest}},access:Be.snapshot(e)})}if(c==="/v1/observability/access"&&r.method==="POST")try{const e=JSON.parse((await v(r,t.maxBodyBytes)).toString("utf8"))||{},n=Be.push(tt({ts:Date.now(),...e}));return s(o,200,{ok:!0,event:n})}catch(e){return s(o,400,{error:{message:`access log failed: ${e.message}`,type:"observability_error"}})}if(c==="/v1/history/records"&&r.method==="PUT"){const e=O.lossless;if(!e)return s(o,501,{error:{message:"lossless records need the SQLite warm store",type:"unavailable"}});try{const n=JSON.parse((await v(r,t.maxBodyBytes)).toString("utf8"))||{},a=String(n.host||"").slice(0,80),i=Number(n.at)||Date.now(),m=[];let b=0;const h={upserts:[],removes:[]},k=y=>{if(!y||y.deletedAt){y?.id&&h.removes.push(y.id);return}try{const f=po(y);f&&h.upserts.push(f)}catch{}};if(Array.isArray(n.records)){const y=e.upsert(n.records,{host:a,at:i});m.push(...y);for(const f of n.records)y.includes(f?.id)&&k(f)}if(Array.isArray(n.entries)){const y=_e(),f=y?fo((E,W)=>ho(y,{salt:E,iterations:W})):null,_=async E=>{if(!f||!E.blob)return null;const W=await f(E.blob),de=E.blob.compression&&E.blob.compression!=="none"?go(bo,E.blob.compression):null;return yo(E.blob,W,{codec:de})},M=await e.upsertEntries(n.entries,{open:_});m.push(...M.written),b+=M.sealed;for(const E of M.written)k(e.get(E))}return(h.upserts.length||h.removes.length)&&O.bulk(h),m.length&&ge({ids:m}),s(o,200,{ok:!0,written:m.length,ids:m,sealed:b,size:e.size})}catch(n){return s(o,400,{error:{message:`records failed: ${n.message}`,type:"ingest_error"}})}}if(c==="/v1/history/stream"&&r.method==="GET"){const e=O.lossless;if(!e)return s(o,501,{error:{message:"lossless records need the SQLite warm store",type:"unavailable"}});o.writeHead(200,{"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive"}),o.write(`event: hello
26
+ data: ${JSON.stringify({newest:e.newest,size:e.size,version:K,prefsRevision:F.revision})}
27
27
 
28
- `),Q.add(o),r.on("close",()=>Q.delete(o));return}if(c==="/v1/history/records"&&r.method==="GET"){const e=_.lossless;if(!e)return s(o,501,{error:{message:"lossless records need the SQLite warm store",type:"unavailable"}});const n=e.since({since:Number(u.searchParams.get("since"))||0,cursor:u.searchParams.get("cursor")||"",limit:Number(u.searchParams.get("limit"))||200,kind:u.searchParams.get("kind")||null});return s(o,200,{ok:!0,...n,size:e.size,newest:e.newest})}if(c==="/v1/history/list"&&r.method==="GET"){const e=Math.min(500,Math.max(1,Number(u.searchParams.get("limit"))||50)),n=Math.max(0,Number(u.searchParams.get("offset"))||0),a=u.searchParams.get("type")||null;return s(o,200,{ok:!0,..._.list({limit:e,offset:n,type:a})})}if(c==="/v1/history/get"&&r.method==="GET"){const e=u.searchParams.get("maxChars")!=null?Math.max(1,Number(u.searchParams.get("maxChars"))||0):null,n=Math.max(0,Number(u.searchParams.get("offset"))||0),a=_.get(String(u.searchParams.get("id")||""),{maxChars:e,offset:n});return a?s(o,200,{ok:!0,record:a}):s(o,404,{error:{message:"no such record",type:"not_found"}})}if(c==="/v1/history/key"&&r.method==="GET")return s(o,200,{ok:!0,hasKey:He()});if(c==="/v1/history/key"&&r.method==="POST")try{const e=JSON.parse((await v(r,t.maxBodyBytes)).toString("utf8"))||{};e.passphrase?Yt(String(e.passphrase)):Qt();const n=e.passphrase?await Ee(_,String(e.passphrase)):{ok:!0,ingested:0};return n.ok&&n.whole&&ge(),s(o,200,{ok:!0,hasKey:!!e.passphrase,...n})}catch(e){return s(o,400,{error:{message:`key handoff failed: ${e.message}`,type:"key_error"}})}if(c==="/v1/history/ingest-backup"&&r.method==="POST")try{const e=await Ee(_,Oe());return e.ok&&e.whole&&ge(),s(o,e.ok?200:409,e)}catch(e){return s(o,400,{error:{message:`backup ingest failed: ${e.message}`,type:"ingest_error"}})}if(c==="/ner"){if(r.method==="GET"){const e=await mt(t);return s(o,e.ok?200:503,e)}if(r.method==="POST"){if(await Te(t),D.state()!=="off"){if(!D.isReady()){const n=D.health();return s(o,503,{error:{message:n.state==="error"?`NER model failed to load: ${n.error||"unknown error"}`:`NER model is ${n.state} — not ready yet`,type:n.state==="error"?"ner_error":"ner_loading"},state:n.state,model:n.model})}try{const n=await v(r,t.maxBodyBytes);let a="";try{a=JSON.parse(n.toString("utf8"))?.text||""}catch{}const l=await D.detect(a);return s(o,200,{entities:l})}catch(n){return s(o,500,{error:{message:`NER error: ${n.message}`,type:"ner_error"}})}}const e=ut(t);if(!e){const n=D.modelOnDisk(t.ner?.model||void 0);return s(o,503,{error:{message:n?"the bundled detector could not start — deterministic-only redaction":"no entity detector is installed — deterministic-only redaction (install one from Gateway settings)",type:n?"ner_error":"ner_not_installed"},state:D.state(),model:t.ner?.model||null})}try{const n=await v(r,t.maxBodyBytes),a=await ze(e,{method:"POST",headers:{"content-type":"application/json"},body:n,signal:AbortSignal.timeout(8e3)}),l=await a.text();return o.writeHead(a.status,{"content-type":"application/json"}),o.end(l)}catch(n){return s(o,502,{error:{message:`NER unreachable: ${n.message}`,type:"ner_unreachable"}})}}}if(c==="/redact"&&r.method==="POST"){let e="";try{e=String(JSON.parse((await v(r,t.maxBodyBytes)).toString("utf8"))?.text||"")}catch{e=""}if(!e)return s(o,200,{text:"",count:0,sanitized:0,entities:[],detector:Ce(t)});try{let n=e;const a=await ee(t.pro?.entitlementToken);await Te(t);const l=await be([je(()=>n,m=>{n=m})],t.redaction,{isPro:a});return s(o,200,{text:n,count:l.count||0,sanitized:l.sanitized||0,tier:t.redaction?.tier==="full"?"full":"basic",entities:ct(l.vault,"types")||[],detector:Ce(t)})}catch(n){return s(o,500,{error:{message:`redaction preview failed: ${n.message}`,type:"redact_error"}})}}if(c==="/ner/models"){if(r.method==="GET"){const e=D.health().model||t.ner?.model||null,n=bo.map(a=>({...a,installed:D.modelOnDisk(a.id)}));return e&&!n.some(a=>a.id===e)&&n.push({id:e,label:e,lang:"—",custom:!0,installed:D.modelOnDisk(e),note:"Custom model (from Hugging Face)."}),s(o,200,{active:e,state:D.state(),progress:D.progress(),available:n})}if(r.method==="POST"){let e=null;try{e=JSON.parse((await v(r,t.maxBodyBytes)).toString("utf8"))}catch{e=null}const n=e&&typeof e.id=="string"?e.id.trim():null;if(!n||!(ko(n)||So(n)))return s(o,400,{error:{message:"unknown or invalid model id",type:"bad_model"}});Vo(t,n);try{oe(t,te())}catch{}return D.setModel(n,{onLog:a=>console.log(a)}).then(a=>{a&&t.ner?.enableFullTier&&t.redaction.tier!=="full"&&(t.redaction.tier="full")}),s(o,202,{accepted:!0,active:n,state:D.state(),progress:D.progress()})}}if(c==="/stt/models"){if(r.method==="GET"){const e=A.health().model||t.stt?.model||Pe,n=vo.map(a=>({...a,installed:A.modelOnDisk(a.id)}));return e&&!n.some(a=>a.id===e)&&n.push({id:e,label:e,lang:"—",tier:"custom",custom:!0,installed:A.modelOnDisk(e),note:"Custom model (from Hugging Face)."}),s(o,200,{active:e,state:A.state(),progress:A.progress(),available:n,dtype:t.stt?.dtype||"auto",loadedDtype:A.health().dtype,runtime:A.health().runtime,dtypes:_o})}if(r.method==="POST"){let e=null;try{e=JSON.parse((await v(r,t.maxBodyBytes)).toString("utf8"))}catch{e=null}const n=e&&typeof e.id=="string"?e.id.trim():null;if(!n||!(To(n)||Oo(n)))return s(o,400,{error:{message:"unknown or invalid model id",type:"bad_model"}});const a=typeof e.dtype=="string"&&Eo(e.dtype)?e.dtype:void 0;t.stt?t.stt.model=n:t.stt={enabled:!0,model:n,allowDownload:!0},a&&(t.stt.dtype=a==="auto"?null:a);try{oe(t,te())}catch{}return A.setModel(n,{onLog:l=>console.log(l),dtype:a||t.stt.dtype||"auto"}),s(o,202,{accepted:!0,active:n,dtype:t.stt.dtype||"auto",state:A.state(),progress:A.progress()})}}if(c==="/diarize/model"){if(r.method==="GET"){const e=B.health();return s(o,200,{active:B.DIARIZE_MODEL,state:e.state,progress:B.progress(),available:[{id:B.DIARIZE_MODEL,label:"Speaker embeddings (wavlm)",lang:"any",approxMB:100,note:"Tells voices apart for meeting transcription (who said what).",installed:B.modelOnDisk()}]})}if(r.method==="POST")return B.download({onLog:e=>console.log(e)}),s(o,202,{accepted:!0,active:B.DIARIZE_MODEL,state:B.state(),progress:B.progress()})}if(c==="/tts/models"){if(r.method==="GET"){const e=S.health().model||t.tts?.model||Ye(Ae()),n=Ae(),a=Ue.find(m=>m.id===e)||null,l=Ue.map(m=>({...m,installed:S.modelOnDisk(m.id),unavailable:m.requiresNative&&!n?"needs the npm gateway — the standalone binary cannot load this engine":void 0}));return e&&!l.some(m=>m.id===e)&&l.push({id:e,label:e,lang:"—",tier:"custom",custom:!0,installed:S.modelOnDisk(e),note:"Custom model (from Hugging Face)."}),s(o,200,{active:e,state:S.state(),progress:S.progress(),available:l,voice:t.tts?.voice||(fe(e)==="pocket-tts"?ye:X),arch:S.arch(),supportsVoices:S.arch()?S.supportsVoices():a?a.arch==="style-tts2"&&!!a.voices:!0,supportsCustomVoices:S.arch()?S.supportsCustomVoices():!!a?.customVoices,sampleRate:S.sampleRate(),voices:S.isPocket()||!S.arch()&&fe(e)==="pocket-tts"?(S.builtinVoices().length?S.builtinVoices():Do).map(m=>({id:m,label:m[0].toUpperCase()+m.slice(1),lang:"en",installed:S.builtinVoices().includes(m)})):S.arch()&&S.arch()!=="style-tts2"?[]:Po.map(m=>({...m,installed:S.voiceOnDisk(m.id,e)})),dtype:t.tts?.dtype||"auto",loadedDtype:S.health().dtype,runtime:S.health().runtime,dtypes:$o})}if(r.method==="POST"){let e=null;try{e=JSON.parse((await v(r,t.maxBodyBytes)).toString("utf8"))}catch{e=null}const n=e&&typeof e.id=="string"?e.id.trim():null;if(n&&!(Ao(n)||xo(n)))return s(o,400,{error:{message:"unknown or invalid model id",type:"bad_model"}});const a=e&&typeof e.voice=="string"?e.voice.trim():null;if(a){const m=G.parseCustomVoice(a);if(!(m?!!G.getVoice(m):he(a)||Fe(a)&&We(a)))return s(o,400,{error:{message:"unknown or invalid voice",type:"bad_voice"}})}const l=e&&typeof e.dtype=="string"&&No(e.dtype)?e.dtype:void 0;if(t.tts||(t.tts={enabled:!0,model:Ke,voice:X,allowDownload:!0}),n&&(t.tts.model=n),a&&(t.tts.voice=a),n&&!a){const m=Bo(n),k=G.parseCustomVoice(t.tts.voice||""),h=!!(k&&G.getVoice(k));if(m&&!h)if(fe(n)==="pocket-tts")t.tts.voice=ye;else{const y=G.listVoices();t.tts.voice=y.length?`custom:${y[0].id}`:""}else!m&&h&&(t.tts.voice=X);const b=fe(n)==="pocket-tts";b&&!G.parseCustomVoice(t.tts.voice||"")&&!he(t.tts.voice)&&(t.tts.voice=ye),!b&&he(t.tts.voice)&&(t.tts.voice=X)}l&&(t.tts.dtype=l==="auto"?null:l);try{oe(t,te())}catch{}return n&&S.setModel(n,{onLog:m=>console.log(m),dtype:l||t.tts.dtype||"auto"}),s(o,202,{accepted:!0,active:t.tts.model,voice:t.tts.voice,dtype:t.tts.dtype||"auto",state:S.state(),progress:S.progress()})}}if(c==="/tts/voices"){if(r.method==="GET")return s(o,200,{voices:G.listVoices(),usable:S.supportsCustomVoices(),embedder:B.DIARIZE_MODEL,embedderReady:B.isReady()});if(r.method==="POST"){let e=null;try{e=JSON.parse((await v(r,t.maxBodyBytes)).toString("utf8"))}catch{e=null}const n=e&&typeof e.name=="string"?e.name.trim():"",a=e&&Array.isArray(e.pcm)?e.pcm:null,l=e&&typeof e.id=="string"?e.id.trim():"";if(l){if(!G.getVoice(l))return s(o,404,{error:{message:"no such saved voice",type:"bad_voice"}});if(!a){if(!n)return s(o,400,{error:{message:"a name is required",type:"bad_request"}});try{return s(o,200,{...G.renameVoice(l,n),usable:S.supportsCustomVoices()})}catch(m){return s(o,400,{error:{message:m.message,type:"rename_failed"}})}}if(a.length<16e3)return s(o,400,{error:{message:"need at least 1 second of 16 kHz mono audio",type:"sample_too_short"}})}else if(!n)return s(o,400,{error:{message:"a name is required",type:"bad_request"}});if(!a||a.length<16e3)return s(o,400,{error:{message:"need at least 1 second of 16 kHz mono audio",type:"sample_too_short"}});try{if(!B.isReady()){const f=B.download({onLog:x=>console.log(x)}),O=Symbol("timeout"),M=await Promise.race([f.then(()=>null).catch(x=>x),new Promise(x=>setTimeout(()=>x(O),mr))]);if(M===O||!B.isReady())return s(o,503,{error:{message:M===O?"the speaker model is still downloading (~100 MB) — your recording was kept, press Save again shortly":`the speaker model failed to load: ${B.health().error||"unknown error"}`,type:"embedder_not_ready"},progress:B.progress()})}const m=Float32Array.from(a),k=await B.embed(m);let h=null;try{const f=await S.pocketForEncoding({allowDownload:t.tts?.allowDownload!==!1,log:O=>console.log(O)});f&&(h=await f.encodeVoice(pr(m,16e3,24e3)))}catch(f){console.log(`[tts] pocket conditioning unavailable for this voice (${f.message})`)}const b=l?G.replaceVoice(l,{vec:k,pocket:h}):G.saveVoice({name:n,vec:k,pocket:h}),y=l&&n&&n!==b.name?G.renameVoice(l,n):b;return console.log(`[tts] ${l?"re-recorded":"saved"} custom voice "${y.name}" (${(b.kinds||[]).join(" + ")}, sample discarded)`),s(o,l?200:201,{...b,...y,usable:S.supportsCustomVoices()})}catch(m){return s(o,400,{error:{message:m.message,type:"save_failed"}})}}if(r.method==="DELETE"){const e=u.searchParams.get("id")||"",n=G.deleteVoice(e);if(n&&t.tts?.voice===`custom:${e}`){const a=G.listVoices();t.tts.voice=a.length?`custom:${a[0].id}`:X;try{oe(t,te())}catch{}}return s(o,200,{deleted:n,voice:t.tts?.voice})}}if((c==="/tts"||c==="/v1/audio/speech")&&r.method==="POST"){if(t.tts?.enabled===!1)return s(o,503,{error:{message:"tts is disabled in gateway config",type:"tts_disabled"}});let e=null;try{e=JSON.parse((await v(r,t.maxBodyBytes)).toString("utf8"))}catch{e=null}const n=e&&typeof(e.input??e.text)=="string"?String(e.input??e.text).trim():"";if(!n)return s(o,400,{error:{message:"text is required",type:"bad_request"}});if(n.length>Ze)return s(o,413,{error:{message:`text too long (max ${Ze} chars)`,type:"too_long"}});const a=Number.isFinite(e.speed)?Math.min(2,Math.max(.5,e.speed)):1,l=Co(t),m=e&&typeof e.voice=="string"&&e.voice.trim()?e.voice.trim():null,k=m||(l?l.voice:t.tts?.voice||X);if(l&&!jo(k))return s(o,400,{error:{message:"unknown or invalid voice",type:"bad_voice"}});const h=e&&typeof e.response_format=="string"?e.response_format.toLowerCase():"wav";if(h!=="wav"&&h!=="pcm")return s(o,400,{error:{message:`unsupported response_format "${h}" — this gateway synthesizes wav`,type:"bad_format"}});try{if(l){const{audio:de,contentType:ht,redacted:ft}=await Io({dest:l,text:n,voice:k,speed:a,auth:r.headers.authorization||r.headers["xi-api-key"]||"",redaction:t.redaction,isPro:await ee(t.pro?.entitlementToken)});return o.writeHead(200,{"Content-Type":ht,"Content-Length":String(de.length),"Cache-Control":"no-store","X-Tts-Provider":l.kind,"X-Tts-Redacted":String(ft)}),o.end(de)}if(!await S.ready({onLog:de=>console.log(de),allowDownload:t.tts?.allowDownload!==!1,model:t.tts?.model||Ye(Ae()),dtype:t.tts?.dtype||"auto"}))return s(o,503,{error:{message:S.health().error||"tts model not ready",type:"tts_unavailable"}});const y=Mo({requested:m,configured:k,engine:S,voices:G,isPocketVoice:he,isKnownVoice:Fe,isValidVoiceId:We,defaultVoice:X,defaultPocketVoice:ye});if(!y.ok)return s(o,y.status,{error:{message:y.message,type:y.type}});const{voice:f,customId:O,speakerEmbedding:M}=y,x=await S.synth(n,{voice:f,speed:a,speakerEmbedding:M}),F=S.sampleRate(),ce=h==="pcm"?Buffer.from(new Float32Array(x).buffer):S.toWav(x,F);return o.writeHead(200,{"Content-Type":h==="pcm"?"application/octet-stream":"audio/wav","Content-Length":String(ce.length),"Cache-Control":"no-store","X-Tts-Sample-Rate":String(F),...O||S.isPocket()||S.supportsVoices()?{"X-Tts-Voice":f}:{}}),o.end(ce)}catch(b){return s(o,500,{error:{message:b.message,type:"tts_failed"}})}}if(c==="/stt/sessions"&&r.method==="POST"){if(t.stt?.enabled===!1)return s(o,403,{error:{message:"STT disabled in gateway config",type:"stt_disabled"}});let e=null;try{e=JSON.parse((await v(r,t.maxBodyBytes)).toString("utf8")||"{}")}catch{e=null}A.isReady()||A.init({model:t.stt?.model||Pe,allowDownload:t.stt?.allowDownload!==!1,dtype:t.stt?.dtype||void 0,onLog:a=>console.log(a)});const n=e?.diarize===!0&&t.stt?.diarize!==!1;n&&!B.isReady()&&B.init({allowDownload:t.stt?.allowDownload!==!1,onLog:a=>console.log(a)});try{const{id:a}=A.createSession({lang:e?.lang,redact:e?.redact===!0,diarize:n,speakerLabel:e?.speakerLabel,endSilenceMs:e?.endSilenceMs});return s(o,201,{id:a,state:A.state()})}catch(a){return s(o,a.code==="too_many_sessions"?429:500,{error:{message:a.message,type:a.code||"stt_error"}})}}{const e=c.match(/^\/stt\/sessions\/([0-9a-f-]{36})(\/audio|\/events)?$/);if(e){const n=e[1];if(e[2]==="/audio"&&r.method==="POST")try{const a=await v(r,t.maxBodyBytes);return A.pushAudio(n,A.toFloat32(a)),s(o,200,{ok:!0,state:A.state()})}catch(a){return s(o,a.code==="no_session"?404:400,{error:{message:a.message,type:a.code||"stt_error"}})}if(e[2]==="/events"&&r.method==="GET"){const a=A.getSession(n);if(!a)return s(o,404,{error:{message:"no such session",type:"no_session"}});o.writeHead(200,{"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive"});const l=f=>o.write(`data: ${JSON.stringify(f)}
28
+ `),Q.add(o),r.on("close",()=>Q.delete(o));return}if(c==="/v1/history/records"&&r.method==="GET"){const e=O.lossless;if(!e)return s(o,501,{error:{message:"lossless records need the SQLite warm store",type:"unavailable"}});const n=e.since({since:Number(u.searchParams.get("since"))||0,cursor:u.searchParams.get("cursor")||"",limit:Number(u.searchParams.get("limit"))||200,kind:u.searchParams.get("kind")||null});return s(o,200,{ok:!0,...n,size:e.size,newest:e.newest})}if(c==="/v1/history/list"&&r.method==="GET"){const e=Math.min(500,Math.max(1,Number(u.searchParams.get("limit"))||50)),n=Math.max(0,Number(u.searchParams.get("offset"))||0),a=u.searchParams.get("type")||null;return s(o,200,{ok:!0,...O.list({limit:e,offset:n,type:a})})}if(c==="/v1/history/get"&&r.method==="GET"){const e=u.searchParams.get("maxChars")!=null?Math.max(1,Number(u.searchParams.get("maxChars"))||0):null,n=Math.max(0,Number(u.searchParams.get("offset"))||0),a=O.get(String(u.searchParams.get("id")||""),{maxChars:e,offset:n});return a?s(o,200,{ok:!0,record:a}):s(o,404,{error:{message:"no such record",type:"not_found"}})}if(c==="/v1/history/key"&&r.method==="GET")return s(o,200,{ok:!0,hasKey:Ue()});if(c==="/v1/history/key"&&r.method==="POST")try{const e=JSON.parse((await v(r,t.maxBodyBytes)).toString("utf8"))||{};e.passphrase?Yt(String(e.passphrase)):Qt();const n=e.passphrase?await $e(O,String(e.passphrase)):{ok:!0,ingested:0};return n.ok&&n.whole&&ge(),s(o,200,{ok:!0,hasKey:!!e.passphrase,...n})}catch(e){return s(o,400,{error:{message:`key handoff failed: ${e.message}`,type:"key_error"}})}if(c==="/v1/history/ingest-backup"&&r.method==="POST")try{const e=await $e(O,_e());return e.ok&&e.whole&&ge(),s(o,e.ok?200:409,e)}catch(e){return s(o,400,{error:{message:`backup ingest failed: ${e.message}`,type:"ingest_error"}})}if(c==="/ner"){if(r.method==="GET"){const e=await pt(t);return s(o,e.ok?200:503,e)}if(r.method==="POST"){if(await Te(t),D.state()!=="off"){if(!D.isReady()){const n=D.health();return s(o,503,{error:{message:n.state==="error"?`NER model failed to load: ${n.error||"unknown error"}`:`NER model is ${n.state} — not ready yet`,type:n.state==="error"?"ner_error":"ner_loading"},state:n.state,model:n.model})}try{const n=await v(r,t.maxBodyBytes);let a="";try{a=JSON.parse(n.toString("utf8"))?.text||""}catch{}const i=await D.detect(a);return s(o,200,{entities:i})}catch(n){return s(o,500,{error:{message:`NER error: ${n.message}`,type:"ner_error"}})}}const e=mt(t);if(!e){const n=D.modelOnDisk(t.ner?.model||void 0);return s(o,503,{error:{message:n?"the bundled detector could not start — deterministic-only redaction":"no entity detector is installed — deterministic-only redaction (install one from Gateway settings)",type:n?"ner_error":"ner_not_installed"},state:D.state(),model:t.ner?.model||null})}try{const n=await v(r,t.maxBodyBytes),a=await Ge(e,{method:"POST",headers:{"content-type":"application/json"},body:n,signal:AbortSignal.timeout(8e3)}),i=await a.text();return o.writeHead(a.status,{"content-type":"application/json"}),o.end(i)}catch(n){return s(o,502,{error:{message:`NER unreachable: ${n.message}`,type:"ner_unreachable"}})}}}if(c==="/redact"&&r.method==="POST"){let e="";try{e=String(JSON.parse((await v(r,t.maxBodyBytes)).toString("utf8"))?.text||"")}catch{e=""}if(!e)return s(o,200,{text:"",count:0,sanitized:0,entities:[],detector:Ce(t)});try{let n=e;const a=await te(t.pro?.entitlementToken);await Te(t);const i=await we([Me(()=>n,m=>{n=m})],t.redaction,{isPro:a});return s(o,200,{text:n,count:i.count||0,sanitized:i.sanitized||0,tier:t.redaction?.tier==="full"?"full":"basic",entities:dt(i.vault,"types")||[],detector:Ce(t)})}catch(n){return s(o,500,{error:{message:`redaction preview failed: ${n.message}`,type:"redact_error"}})}}if(c==="/ner/models"){if(r.method==="GET"){const e=D.health().model||t.ner?.model||null,n=wo.map(a=>({...a,installed:D.modelOnDisk(a.id)}));return e&&!n.some(a=>a.id===e)&&n.push({id:e,label:e,lang:"—",custom:!0,installed:D.modelOnDisk(e),note:"Custom model (from Hugging Face)."}),s(o,200,{active:e,state:D.state(),progress:D.progress(),available:n})}if(r.method==="POST"){let e=null;try{e=JSON.parse((await v(r,t.maxBodyBytes)).toString("utf8"))}catch{e=null}const n=e&&typeof e.id=="string"?e.id.trim():null;if(!n||!(ko(n)||So(n)))return s(o,400,{error:{message:"unknown or invalid model id",type:"bad_model"}});Vo(t,n);try{ne(t,oe())}catch{}return D.setModel(n,{onLog:a=>console.log(a)}).then(a=>{a&&t.ner?.enableFullTier&&t.redaction.tier!=="full"&&(t.redaction.tier="full")}),s(o,202,{accepted:!0,active:n,state:D.state(),progress:D.progress()})}}if(c==="/stt/models"){if(r.method==="GET"){const e=A.health().model||t.stt?.model||Pe,n=vo.map(a=>({...a,installed:A.modelOnDisk(a.id)}));return e&&!n.some(a=>a.id===e)&&n.push({id:e,label:e,lang:"—",tier:"custom",custom:!0,installed:A.modelOnDisk(e),note:"Custom model (from Hugging Face)."}),s(o,200,{active:e,state:A.state(),progress:A.progress(),available:n,dtype:t.stt?.dtype||"auto",loadedDtype:A.health().dtype,runtime:A.health().runtime,dtypes:Oo})}if(r.method==="POST"){let e=null;try{e=JSON.parse((await v(r,t.maxBodyBytes)).toString("utf8"))}catch{e=null}const n=e&&typeof e.id=="string"?e.id.trim():null;if(!n||!(To(n)||_o(n)))return s(o,400,{error:{message:"unknown or invalid model id",type:"bad_model"}});const a=typeof e.dtype=="string"&&$o(e.dtype)?e.dtype:void 0;t.stt?t.stt.model=n:t.stt={enabled:!0,model:n,allowDownload:!0},a&&(t.stt.dtype=a==="auto"?null:a);try{ne(t,oe())}catch{}return A.setModel(n,{onLog:i=>console.log(i),dtype:a||t.stt.dtype||"auto"}),s(o,202,{accepted:!0,active:n,dtype:t.stt.dtype||"auto",state:A.state(),progress:A.progress()})}}if(c==="/diarize/model"){if(r.method==="GET"){const e=B.health();return s(o,200,{active:B.DIARIZE_MODEL,state:e.state,progress:B.progress(),available:[{id:B.DIARIZE_MODEL,label:"Speaker embeddings (wavlm)",lang:"any",approxMB:100,note:"Tells voices apart for meeting transcription (who said what).",installed:B.modelOnDisk()}]})}if(r.method==="POST")return B.download({onLog:e=>console.log(e)}),s(o,202,{accepted:!0,active:B.DIARIZE_MODEL,state:B.state(),progress:B.progress()})}if(c==="/tts/models"){if(r.method==="GET"){const e=S.health().model||t.tts?.model||Qe(Ae()),n=Ae(),a=Fe.find(m=>m.id===e)||null,i=Fe.map(m=>({...m,installed:S.modelOnDisk(m.id),unavailable:m.requiresNative&&!n?"needs the npm gateway — the standalone binary cannot load this engine":void 0}));return e&&!i.some(m=>m.id===e)&&i.push({id:e,label:e,lang:"—",tier:"custom",custom:!0,installed:S.modelOnDisk(e),note:"Custom model (from Hugging Face)."}),s(o,200,{active:e,state:S.state(),progress:S.progress(),available:i,voice:t.tts?.voice||(fe(e)==="pocket-tts"?he:X),arch:S.arch(),supportsVoices:S.arch()?S.supportsVoices():a?a.arch==="style-tts2"&&!!a.voices:!0,supportsCustomVoices:S.arch()?S.supportsCustomVoices():!!a?.customVoices,sampleRate:S.sampleRate(),voices:S.isPocket()||!S.arch()&&fe(e)==="pocket-tts"?(S.builtinVoices().length?S.builtinVoices():Do).map(m=>({id:m,label:m[0].toUpperCase()+m.slice(1),lang:"en",installed:S.builtinVoices().includes(m)})):S.arch()&&S.arch()!=="style-tts2"?[]:Po.map(m=>({...m,installed:S.voiceOnDisk(m.id,e)})),dtype:t.tts?.dtype||"auto",loadedDtype:S.health().dtype,runtime:S.health().runtime,dtypes:xo})}if(r.method==="POST"){let e=null;try{e=JSON.parse((await v(r,t.maxBodyBytes)).toString("utf8"))}catch{e=null}const n=e&&typeof e.id=="string"?e.id.trim():null;if(n&&!(Ao(n)||Eo(n)))return s(o,400,{error:{message:"unknown or invalid model id",type:"bad_model"}});const a=e&&typeof e.voice=="string"?e.voice.trim():null;if(a){const m=G.parseCustomVoice(a);if(!(m?!!G.getVoice(m):ye(a)||We(a)&&Ke(a)))return s(o,400,{error:{message:"unknown or invalid voice",type:"bad_voice"}})}const i=e&&typeof e.dtype=="string"&&No(e.dtype)?e.dtype:void 0;if(t.tts||(t.tts={enabled:!0,model:Ze,voice:X,allowDownload:!0}),n&&(t.tts.model=n),a&&(t.tts.voice=a),n&&!a){const m=Bo(n),b=G.parseCustomVoice(t.tts.voice||""),h=!!(b&&G.getVoice(b));if(m&&!h)if(fe(n)==="pocket-tts")t.tts.voice=he;else{const y=G.listVoices();t.tts.voice=y.length?`custom:${y[0].id}`:""}else!m&&h&&(t.tts.voice=X);const k=fe(n)==="pocket-tts";k&&!G.parseCustomVoice(t.tts.voice||"")&&!ye(t.tts.voice)&&(t.tts.voice=he),!k&&ye(t.tts.voice)&&(t.tts.voice=X)}i&&(t.tts.dtype=i==="auto"?null:i);try{ne(t,oe())}catch{}return n&&S.setModel(n,{onLog:m=>console.log(m),dtype:i||t.tts.dtype||"auto"}),s(o,202,{accepted:!0,active:t.tts.model,voice:t.tts.voice,dtype:t.tts.dtype||"auto",state:S.state(),progress:S.progress()})}}if(c==="/tts/voices"){if(r.method==="GET")return s(o,200,{voices:G.listVoices(),usable:S.supportsCustomVoices(),embedder:B.DIARIZE_MODEL,embedderReady:B.isReady()});if(r.method==="POST"){let e=null;try{e=JSON.parse((await v(r,t.maxBodyBytes)).toString("utf8"))}catch{e=null}const n=e&&typeof e.name=="string"?e.name.trim():"",a=e&&Array.isArray(e.pcm)?e.pcm:null,i=e&&typeof e.id=="string"?e.id.trim():"";if(i){if(!G.getVoice(i))return s(o,404,{error:{message:"no such saved voice",type:"bad_voice"}});if(!a){if(!n)return s(o,400,{error:{message:"a name is required",type:"bad_request"}});try{return s(o,200,{...G.renameVoice(i,n),usable:S.supportsCustomVoices()})}catch(m){return s(o,400,{error:{message:m.message,type:"rename_failed"}})}}if(a.length<16e3)return s(o,400,{error:{message:"need at least 1 second of 16 kHz mono audio",type:"sample_too_short"}})}else if(!n)return s(o,400,{error:{message:"a name is required",type:"bad_request"}});if(!a||a.length<16e3)return s(o,400,{error:{message:"need at least 1 second of 16 kHz mono audio",type:"sample_too_short"}});try{if(!B.isReady()){const f=B.download({onLog:E=>console.log(E)}),_=Symbol("timeout"),M=await Promise.race([f.then(()=>null).catch(E=>E),new Promise(E=>setTimeout(()=>E(_),mr))]);if(M===_||!B.isReady())return s(o,503,{error:{message:M===_?"the speaker model is still downloading (~100 MB) — your recording was kept, press Save again shortly":`the speaker model failed to load: ${B.health().error||"unknown error"}`,type:"embedder_not_ready"},progress:B.progress()})}const m=Float32Array.from(a),b=await B.embed(m);let h=null;try{const f=await S.pocketForEncoding({allowDownload:t.tts?.allowDownload!==!1,log:_=>console.log(_)});f&&(h=await f.encodeVoice(pr(m,16e3,24e3)))}catch(f){console.log(`[tts] pocket conditioning unavailable for this voice (${f.message})`)}const k=i?G.replaceVoice(i,{vec:b,pocket:h}):G.saveVoice({name:n,vec:b,pocket:h}),y=i&&n&&n!==k.name?G.renameVoice(i,n):k;return console.log(`[tts] ${i?"re-recorded":"saved"} custom voice "${y.name}" (${(k.kinds||[]).join(" + ")}, sample discarded)`),s(o,i?200:201,{...k,...y,usable:S.supportsCustomVoices()})}catch(m){return s(o,400,{error:{message:m.message,type:"save_failed"}})}}if(r.method==="DELETE"){const e=u.searchParams.get("id")||"",n=G.deleteVoice(e);if(n&&t.tts?.voice===`custom:${e}`){const a=G.listVoices();t.tts.voice=a.length?`custom:${a[0].id}`:X;try{ne(t,oe())}catch{}}return s(o,200,{deleted:n,voice:t.tts?.voice})}}if((c==="/tts"||c==="/v1/audio/speech")&&r.method==="POST"){if(t.tts?.enabled===!1)return s(o,503,{error:{message:"tts is disabled in gateway config",type:"tts_disabled"}});let e=null;try{e=JSON.parse((await v(r,t.maxBodyBytes)).toString("utf8"))}catch{e=null}const n=e&&typeof(e.input??e.text)=="string"?String(e.input??e.text).trim():"";if(!n)return s(o,400,{error:{message:"text is required",type:"bad_request"}});if(n.length>Ye)return s(o,413,{error:{message:`text too long (max ${Ye} chars)`,type:"too_long"}});const a=Number.isFinite(e.speed)?Math.min(2,Math.max(.5,e.speed)):1,i=Co(t),m=e&&typeof e.voice=="string"&&e.voice.trim()?e.voice.trim():null,b=m||(i?i.voice:t.tts?.voice||X);if(i&&!jo(b))return s(o,400,{error:{message:"unknown or invalid voice",type:"bad_voice"}});const h=e&&typeof e.response_format=="string"?e.response_format.toLowerCase():"wav";if(h!=="wav"&&h!=="pcm")return s(o,400,{error:{message:`unsupported response_format "${h}" — this gateway synthesizes wav`,type:"bad_format"}});try{if(i){const{audio:ue,contentType:yt,redacted:ft}=await Io({dest:i,text:n,voice:b,speed:a,auth:r.headers.authorization||r.headers["xi-api-key"]||"",redaction:t.redaction,isPro:await te(t.pro?.entitlementToken)});return o.writeHead(200,{"Content-Type":yt,"Content-Length":String(ue.length),"Cache-Control":"no-store","X-Tts-Provider":i.kind,"X-Tts-Redacted":String(ft)}),o.end(ue)}if(!await S.ready({onLog:ue=>console.log(ue),allowDownload:t.tts?.allowDownload!==!1,model:t.tts?.model||Qe(Ae()),dtype:t.tts?.dtype||"auto"}))return s(o,503,{error:{message:S.health().error||"tts model not ready",type:"tts_unavailable"}});const y=Mo({requested:m,configured:b,engine:S,voices:G,isPocketVoice:ye,isKnownVoice:We,isValidVoiceId:Ke,defaultVoice:X,defaultPocketVoice:he});if(!y.ok)return s(o,y.status,{error:{message:y.message,type:y.type}});const{voice:f,customId:_,speakerEmbedding:M}=y,E=await S.synth(n,{voice:f,speed:a,speakerEmbedding:M}),W=S.sampleRate(),de=h==="pcm"?Buffer.from(new Float32Array(E).buffer):S.toWav(E,W);return o.writeHead(200,{"Content-Type":h==="pcm"?"application/octet-stream":"audio/wav","Content-Length":String(de.length),"Cache-Control":"no-store","X-Tts-Sample-Rate":String(W),..._||S.isPocket()||S.supportsVoices()?{"X-Tts-Voice":f}:{}}),o.end(de)}catch(k){return s(o,500,{error:{message:k.message,type:"tts_failed"}})}}if(c==="/stt/sessions"&&r.method==="POST"){if(t.stt?.enabled===!1)return s(o,403,{error:{message:"STT disabled in gateway config",type:"stt_disabled"}});let e=null;try{e=JSON.parse((await v(r,t.maxBodyBytes)).toString("utf8")||"{}")}catch{e=null}A.isReady()||A.init({model:t.stt?.model||Pe,allowDownload:t.stt?.allowDownload!==!1,dtype:t.stt?.dtype||void 0,onLog:a=>console.log(a)});const n=e?.diarize===!0&&t.stt?.diarize!==!1;n&&!B.isReady()&&B.init({allowDownload:t.stt?.allowDownload!==!1,onLog:a=>console.log(a)});try{const{id:a}=A.createSession({lang:e?.lang,redact:e?.redact===!0,diarize:n,speakerLabel:e?.speakerLabel,endSilenceMs:e?.endSilenceMs});return s(o,201,{id:a,state:A.state()})}catch(a){return s(o,a.code==="too_many_sessions"?429:500,{error:{message:a.message,type:a.code||"stt_error"}})}}{const e=c.match(/^\/stt\/sessions\/([0-9a-f-]{36})(\/audio|\/events)?$/);if(e){const n=e[1];if(e[2]==="/audio"&&r.method==="POST")try{const a=await v(r,t.maxBodyBytes);return A.pushAudio(n,A.toFloat32(a)),s(o,200,{ok:!0,state:A.state()})}catch(a){return s(o,a.code==="no_session"?404:400,{error:{message:a.message,type:a.code||"stt_error"}})}if(e[2]==="/events"&&r.method==="GET"){const a=A.getSession(n);if(!a)return s(o,404,{error:{message:"no such session",type:"no_session"}});o.writeHead(200,{"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive"});const i=f=>o.write(`data: ${JSON.stringify(f)}
29
29
 
30
- `),m=a.redact?await ee(t.pro?.entitlementToken):!0,k=async f=>{if(f.type!=="final"||!a.redact)return f;try{let O=f.text;return await be([je(()=>O,M=>{O=M})],t.redaction,{isPro:m}),{...f,text:O}}catch{return f}};l({type:"state",state:A.state()});const h=setInterval(()=>{const f=A.state();if(f==="downloading"||f==="loading"){l({type:"progress",state:f,...A.progress()||{}});return}if(f==="error"){l({type:"error",code:"model_failed",message:A.health().error||"model failed to load",fatal:!0}),clearInterval(h);return}if(a.diarize){const O=B.state();if(O==="downloading"||O==="loading"){l({type:"diarize-progress",state:O,...B.progress()||{}});return}}l({type:"state",state:f}),clearInterval(h)},500);h.unref?.();let b=Promise.resolve();const y=A.subscribe(n,f=>{b=b.then(async()=>{l(await k(f)),f.type==="end"&&(clearInterval(h),o.end())}).catch(()=>{})});r.on("close",()=>{clearInterval(h),y?.()});return}if(!e[2]&&r.method==="DELETE")return await A.endSession(n),s(o,200,{ok:!0})}}if(c==="/logs"&&r.method==="GET")return s(o,200,{entries:[...i].reverse()});if(c==="/config"&&r.method==="GET"){const e=await ee(t.pro?.entitlementToken);return s(o,200,Qe(t,{proUnlocked:e}))}if(c==="/config"&&r.method==="POST"){let e=null;try{e=JSON.parse((await v(r,t.maxBodyBytes)).toString("utf8"))}catch{e=null}if(!e||typeof e!="object")return s(o,400,{error:"invalid config patch"});Go(t,e),Re(t);try{oe(t,te())}catch(k){return s(o,500,{error:`could not persist config: ${k.message}`})}const n=t.redaction?.detection,a=!n||!n.backend||n.backend==="off",l=D.state();t.ner?.autostart&&a&&l!=="ready"&&l!=="loading"&&l!=="downloading"&&D.setModel(t.ner.model,{onLog:k=>console.log(k)}).then(k=>{k&&t.ner?.enableFullTier&&t.redaction.tier!=="full"&&(t.redaction.tier="full")});const m=await ee(t.pro?.entitlementToken);return s(o,200,Qe(t,{proUnlocked:m}))}if(r.method==="GET"&&c==="/skills"){const e=await me(t);if(!e)return s(o,503,{error:{message:"no bridge is configured",type:"no_bridge"}});const n=le(t.bridge?.token);try{const a=await fetch(`${e}/skills${yt(u,t)}`,{headers:{Accept:"application/json",...n?{Authorization:`Bearer ${n}`}:{}},signal:AbortSignal.timeout(8e3)}),l=await a.json().catch(()=>({}));return a.ok?s(o,200,{skills:Array.isArray(l?.skills)?l.skills:[]}):s(o,a.status,{error:{message:l?.error||`bridge ${a.status}`,type:"bridge_error"}})}catch(a){return s(o,502,{error:{message:`bridge unreachable: ${a.message}`,type:"bridge_unreachable"}})}}if(r.method==="GET"&&/^\/skills\/[^/]+$/.test(c)){const e=decodeURIComponent(c.slice(8));if(!e||e==="."||e===".."||e.includes("/")||e.includes("\\"))return s(o,400,{error:{message:"not a skill id",type:"invalid_request"}});const n=await me(t);if(!n)return s(o,503,{error:{message:"no bridge is configured",type:"no_bridge"}});const a=le(t.bridge?.token);try{const l=await fetch(`${n}/skills/${encodeURIComponent(e)}${yt(u,t)}`,{headers:{Accept:"application/json",...a?{Authorization:`Bearer ${a}`}:{}},signal:AbortSignal.timeout(8e3)}),m=await l.json().catch(()=>({}));return l.ok?s(o,200,{skill:m?.skill||null}):s(o,l.status,{error:{message:m?.error||`bridge ${l.status}`,type:"bridge_error"}})}catch(l){return s(o,502,{error:{message:`bridge unreachable: ${l.message}`,type:"bridge_unreachable"}})}}if(r.method==="GET"&&/\/models$/.test(c))return s(o,200,await Ho(t));if(yr.some(e=>c===e||c.startsWith(`${e}/`)))return s(o,404,{error:{message:`this gateway (${K}) has no ${c} — update it to use this feature`,type:"unknown_endpoint"}});const g=nr(c,r.headers,t);let w;try{w=await v(r,t.maxBodyBytes)}catch(e){s(o,e.code===413?413:400,{error:e.code===413?"payload too large":"bad request"}),r.destroy();return}let P=null,p=null,L=w,$=0,I=0,Y=0,z=!1,R=!0;const N=t.logRequests&&g.redactable&&r.method==="POST"?rr(d):null;if(g.redactable&&r.method==="POST"&&w.length){try{p=JSON.parse(w.toString("utf8"))}catch{p=null}if(p&&sr(p,g.kind))L=w;else if(p){const e=t.tools||{};if(e.autoNarrow!==!1&&Array.isArray(p.tools)&&p.tools.length){const y=Number(e.maxPerTurn)>0?Number(e.maxPerTurn):Zo,f=e.narrowAll?null:M=>!Yo.test(nt(M)),O=p.tools.length;p.tools=_t(p.tools,Xo(p,g.kind),{cap:y,keep:f,name:nt,description:Qo}),Y=O-p.tools.length}R=await ee(t.pro?.entitlementToken);const n=Ro(t,R);if(!n.allowed)return s(o,402,{error:{message:`ChatPanel Gateway free trial used up (${n.cap} redactions). Add a ChatPanel Pro entitlement token to unlock unlimited full-tier redaction (names/orgs).`,type:"free_limit_reached"}});z=String(r.headers["x-chatpanel-redaction"]||"").trim().toLowerCase()==="off"&&W(r),z||await Te(t);const a=z?[]:g.adapter.collectSegments(p,t.redaction),l=new AbortController;o.on("close",()=>{o.writableFinished||l.abort()});const m=N?N.clock():0,{vault:k,count:h,sanitized:b}=z?{vault:null,count:0,sanitized:0}:await be(a,t.redaction,{signal:l.signal,isPro:R,onEgress:y=>Be.push(et({ts:Date.now(),client:"redaction",tool:`detect:${y.backend}@${y.host||"local"}`,ok:y.ok,ms:y.ms,error:y.error}))});if(N&&N.lap("redact",m),P=k,$=h,I=b||0,!R&&h>0){Lo(t,R);try{oe(t,te())}catch{}}if(!z&&Array.isArray(p.tools)&&p.tools.length&&typeof g.adapter.injectSystemNote=="function"){const y=qe(p?.model,t,g.kind,{destination:String(r.headers["x-chatpanel-destination"]||p?.chatpanel?.destination||"").trim()}),f=!(y&&y.type==="api");g.adapter.injectSystemNote(p,Pt({toolData:t.tools?.toolData,ownTools:f}))}else!z&&h>0&&typeof g.adapter.injectSystemNote=="function"&&g.adapter.injectSystemNote(p,At());L=Buffer.from(JSON.stringify(p),"utf8")}}const E=Et({vault:P,toolData:t.tools?.toolData}),j=p&&typeof p.chatpanel=="object"&&p.chatpanel||null;j&&(delete p.chatpanel,L=Buffer.from(JSON.stringify(p),"utf8"));const J={destination:String(r.headers["x-chatpanel-destination"]||j?.destination||"").trim(),reach:String(r.headers["x-chatpanel-reach"]||j?.reach||"").trim(),run:gr(r.headers["x-chatpanel-run"],j?.run)},T=qe(p?.model,t,g.kind,{destination:J.destination});if(J.destination&&(!T||T.id!==J.destination))return N?.commit(),s(o,404,{error:{message:`no destination "${J.destination}" is configured on this gateway`,type:"unknown_destination",known:Uo(t).map(e=>e.id)}});N&&(N.meta={t:Date.now(),model:p?.model||null,dest:T?T.id:null,type:T?T.type:null,redacted:$,sanitized:I,narrowed:Y,detail:ct(P,t.logDetail),redaction:z?"off":t.redaction.tier||"basic"});const Z=Lt();if(Z&&T){const e=T.type==="api"?Le(Z,{model:p?.model||"",endpoint:T.baseUrl||""}):Gt(Z,T.agent||T.id)?Le(Z,{model:p?.model||""}):{ok:!1,reason:`agent "${T.agent||T.id}" is not allowed by your organisation’s policy`};if(!e.ok)return N?.commit(),s(o,403,{error:{message:e.reason,type:"policy",code:"org_policy"}})}if(T&&T.type==="api")return T.baseUrl?ar(T.baseUrl,t)?(N?.commit(),s(o,508,{error:{message:`destination "${T.id}" points back at the gateway (${T.baseUrl}) — refusing to forward (would loop).`,type:"loop_detected"}})):hr(r,o,{...g,pathname:c,search:u.search,base:T.baseUrl,destKey:T.apiKey,destProtocol:T.protocol,harness:E,trace:N},L,P):(N?.commit(),s(o,502,{error:`destination "${T.id}" has no baseUrl`}));const q=ue(r),se=q==="local"&&t.bridge?.openAgentLane?"token":q;if(se==="local")return N?.commit(),s(o,401,{error:{message:"agent destinations require the gateway token: send `Authorization: Bearer $(cat ~/.chatpanel/gateway-token)`, or pair this client with `chatpanel-gateway pair`",type:"auth",code:"agent_lane_token_required"}});const ae=$t({...J.run||{},...J.reach?{reach:J.reach}:{}},se);return dr(r,o,{...g,pathname:c,agentOverride:T?.agent,harness:E,trace:N,run:Object.keys(ae).length?ae:null},p,P,t,R)})}function gr(t,i){let d=i&&typeof i=="object"?i:null;if(!d&&t)try{d=JSON.parse(decodeURIComponent(String(t)))}catch{d=null}if(!d||typeof d!="object")return null;const r={};if(Array.isArray(d.grants)&&(r.grants=d.grants.map(o=>String(o).slice(0,80)).slice(0,32)),d.workspace&&typeof d.workspace=="object"&&d.workspace.repo){const o=d.workspace;r.workspace={repo:String(o.repo).slice(0,400),projectId:String(o.projectId||"").slice(0,120),jobId:String(o.jobId||"").slice(0,120),...o.base?{base:String(o.base).slice(0,120)}:{}}}return d.connectionId&&(r.connectionId=String(d.connectionId).slice(0,64)),typeof d.workingDir=="string"&&d.workingDir.trim()&&/^([A-Za-z]:[\\/]|\/)/.test(d.workingDir.trim())&&(r.workingDir=d.workingDir.trim().slice(0,1024)),Jo.includes(d.permissionMode)&&d.permissionMode!=="default"&&(r.permissionMode=d.permissionMode),Object.keys(r).length?r:null}let we=null;async function dn(t=Ie()){Zt();let i=null;try{i=await Rt()}catch(g){throw g instanceof zt&&(console.error(`[chatpanel-gateway] org policy: ${g.message}`),process.exit(78)),g}const d=i?.policy||null;d&&(Re(t,d),console.log(`[chatpanel-gateway] ${i.label} — ${i.signed?"signed":"unsigned"} policy from ${i.source}`)),jt(globalThis,{allow:d?.egress?(g,{local:w})=>Vt(d,g,{local:w}):null}),ke();const r=fr(t),o=Kt(t),u=wt(t);r.on("error",g=>{g&&g.code==="EADDRINUSE"&&(console.error(`Port ${t.port} is already in use — another app (or a second gateway) has it.`),console.error(`Fix: free the port, or set a different one — edit "port" in ${te()} (or the extension's Gateway tab) and restart. The extension must point at the same port.`),process.exit(1)),console.error(`Gateway server error: ${g?.message||g}`),process.exit(1)}),r.listen(t.port,t.host,()=>{console.log(`ChatPanel Privacy Gateway v${K} on http://${t.host}:${t.port}`),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"),ao(t).then(g=>{we=g}).catch(g=>console.log(` bridge : not supervised (${g?.message||g})`)),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…)":"")),it(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.`)}),He()&&Ee(_,Oe()).then(g=>{g?.ok&&(console.log(` warm : seeded ${g.ingested} records from ${g.file}`),g.whole&&ge())}).catch(()=>{});const c=()=>{o?.stop(),u.stop(),we?.stop(),r.close(()=>process.exit(0))};return process.on("SIGINT",c),process.on("SIGTERM",c),r}export{K as VERSION,fr as createGateway,ur as joinUpstream,De as parseAgentModel,dn as start};
30
+ `),m=a.redact?await te(t.pro?.entitlementToken):!0,b=async f=>{if(f.type!=="final"||!a.redact)return f;try{let _=f.text;return await we([Me(()=>_,M=>{_=M})],t.redaction,{isPro:m}),{...f,text:_}}catch{return f}};i({type:"state",state:A.state()});const h=setInterval(()=>{const f=A.state();if(f==="downloading"||f==="loading"){i({type:"progress",state:f,...A.progress()||{}});return}if(f==="error"){i({type:"error",code:"model_failed",message:A.health().error||"model failed to load",fatal:!0}),clearInterval(h);return}if(a.diarize){const _=B.state();if(_==="downloading"||_==="loading"){i({type:"diarize-progress",state:_,...B.progress()||{}});return}}i({type:"state",state:f}),clearInterval(h)},500);h.unref?.();let k=Promise.resolve();const y=A.subscribe(n,f=>{k=k.then(async()=>{i(await b(f)),f.type==="end"&&(clearInterval(h),o.end())}).catch(()=>{})});r.on("close",()=>{clearInterval(h),y?.()});return}if(!e[2]&&r.method==="DELETE")return await A.endSession(n),s(o,200,{ok:!0})}}if(c==="/logs"&&r.method==="GET")return s(o,200,{entries:[...l].reverse()});if(c==="/config"&&r.method==="GET"){const e=await te(t.pro?.entitlementToken);return s(o,200,Xe(t,{proUnlocked:e}))}if(c==="/config"&&r.method==="POST"){let e=null;try{e=JSON.parse((await v(r,t.maxBodyBytes)).toString("utf8"))}catch{e=null}if(!e||typeof e!="object")return s(o,400,{error:"invalid config patch"});Go(t,e),ze(t);try{ne(t,oe())}catch(b){return s(o,500,{error:`could not persist config: ${b.message}`})}const n=t.redaction?.detection,a=!n||!n.backend||n.backend==="off",i=D.state();t.ner?.autostart&&a&&i!=="ready"&&i!=="loading"&&i!=="downloading"&&D.setModel(t.ner.model,{onLog:b=>console.log(b)}).then(b=>{b&&t.ner?.enableFullTier&&t.redaction.tier!=="full"&&(t.redaction.tier="full")});const m=await te(t.pro?.entitlementToken);return s(o,200,Xe(t,{proUnlocked:m}))}if(r.method==="GET"&&c==="/skills"){const e=await re(t);if(!e)return s(o,503,{error:{message:"no bridge is configured",type:"no_bridge"}});const n=ee(t.bridge?.token);try{const a=await fetch(`${e}/skills${Ie(u,t)}`,{headers:{Accept:"application/json",...n?{Authorization:`Bearer ${n}`}:{}},signal:AbortSignal.timeout(8e3)}),i=await a.json().catch(()=>({}));return a.ok?s(o,200,{skills:Array.isArray(i?.skills)?i.skills:[]}):s(o,a.status,{error:{message:i?.error||`bridge ${a.status}`,type:"bridge_error"}})}catch(a){return s(o,502,{error:{message:`bridge unreachable: ${a.message}`,type:"bridge_unreachable"}})}}if(r.method==="GET"&&/^\/skills\/[^/]+$/.test(c)){const e=decodeURIComponent(c.slice(8));if(!e||e==="."||e===".."||e.includes("/")||e.includes("\\"))return s(o,400,{error:{message:"not a skill id",type:"invalid_request"}});const n=await re(t);if(!n)return s(o,503,{error:{message:"no bridge is configured",type:"no_bridge"}});const a=ee(t.bridge?.token);try{const i=await fetch(`${n}/skills/${encodeURIComponent(e)}${Ie(u,t)}`,{headers:{Accept:"application/json",...a?{Authorization:`Bearer ${a}`}:{}},signal:AbortSignal.timeout(8e3)}),m=await i.json().catch(()=>({}));return i.ok?s(o,200,{skill:m?.skill||null}):s(o,i.status,{error:{message:m?.error||`bridge ${i.status}`,type:"bridge_error"}})}catch(i){return s(o,502,{error:{message:`bridge unreachable: ${i.message}`,type:"bridge_unreachable"}})}}if(c==="/channels"||/^\/channels\/(connect|pair|unpair|settings|disconnect)$/.test(c)){if(!H(r))return s(o,403,{error:{message:"channels: extension origin or gateway token required",type:"forbidden"}});if(!(c==="/channels"&&r.method==="GET"||c!=="/channels"&&r.method==="POST"))return s(o,405,{error:{message:"method not allowed",type:"invalid_request"}});const e=await re(t);if(!e)return s(o,503,{error:{message:"no bridge is configured",type:"no_bridge"}});const n=ee(t.bridge?.token);try{const a=r.method==="POST"?(await v(r,t.maxBodyBytes)).toString("utf8"):"",i=await fetch(`${e}${c}`,{method:r.method,headers:{Accept:"application/json",...r.method==="POST"?{"content-type":"application/json"}:{},...n?{Authorization:`Bearer ${n}`}:{}},...r.method==="POST"?{body:a||"{}"}:{},signal:AbortSignal.timeout(15e3)}),m=await i.json().catch(()=>({}));return s(o,i.status,m)}catch(a){return s(o,502,{error:{message:`bridge unreachable: ${a.message}`,type:"bridge_unreachable"}})}}if(r.method==="GET"&&/^\/skills\/[^/]+\/file\/.+/.test(c)){const e=/^\/skills\/([^/]+)\/file\/(.+)$/.exec(c),n=decodeURIComponent(e[1]),a=e[2];if(!n||n==="."||n===".."||n.includes("/")||n.includes("\\")||/(^|\/)\.\.(\/|$)/.test(decodeURIComponent(a)))return s(o,400,{error:{message:"not a skill file",type:"invalid_request"}});const i=await re(t);if(!i)return s(o,503,{error:{message:"no bridge is configured",type:"no_bridge"}});const m=ee(t.bridge?.token);try{const b=await fetch(`${i}/skills/${encodeURIComponent(n)}/file/${a}${Ie(u,t)}`,{headers:{Accept:"application/json",...m?{Authorization:`Bearer ${m}`}:{}},signal:AbortSignal.timeout(8e3)}),h=await b.json().catch(()=>({}));return b.ok?s(o,200,h):s(o,b.status,{error:{message:h?.error||`bridge ${b.status}`,type:"bridge_error"}})}catch(b){return s(o,502,{error:{message:`bridge unreachable: ${b.message}`,type:"bridge_unreachable"}})}}if(r.method==="GET"&&/\/models$/.test(c))return s(o,200,await Ho(t));if(hr.some(e=>c===e||c.startsWith(`${e}/`)))return s(o,404,{error:{message:`this gateway (${K}) has no ${c} — update it to use this feature`,type:"unknown_endpoint"}});const g=nr(c,r.headers,t);let w;try{w=await v(r,t.maxBodyBytes)}catch(e){s(o,e.code===413?413:400,{error:e.code===413?"payload too large":"bad request"}),r.destroy();return}let P=null,p=null,z=w,x=0,I=0,Y=0,L=!1,R=!0;const N=t.logRequests&&g.redactable&&r.method==="POST"?rr(d):null;if(g.redactable&&r.method==="POST"&&w.length){try{p=JSON.parse(w.toString("utf8"))}catch{p=null}if(p&&sr(p,g.kind))z=w;else if(p){const e=t.tools||{};if(e.autoNarrow!==!1&&Array.isArray(p.tools)&&p.tools.length){const y=Number(e.maxPerTurn)>0?Number(e.maxPerTurn):Zo,f=e.narrowAll?null:M=>!Yo.test(st(M)),_=p.tools.length;p.tools=Ot(p.tools,Xo(p,g.kind),{cap:y,keep:f,name:st,description:Qo}),Y=_-p.tools.length}R=await te(t.pro?.entitlementToken);const n=Ro(t,R);if(!n.allowed)return s(o,402,{error:{message:`ChatPanel Gateway free trial used up (${n.cap} redactions). Add a ChatPanel Pro entitlement token to unlock unlimited full-tier redaction (names/orgs).`,type:"free_limit_reached"}});L=String(r.headers["x-chatpanel-redaction"]||"").trim().toLowerCase()==="off"&&H(r),L||await Te(t);const a=L?[]:g.adapter.collectSegments(p,t.redaction),i=new AbortController;o.on("close",()=>{o.writableFinished||i.abort()});const m=N?N.clock():0,{vault:b,count:h,sanitized:k}=L?{vault:null,count:0,sanitized:0}:await we(a,t.redaction,{signal:i.signal,isPro:R,onEgress:y=>Be.push(tt({ts:Date.now(),client:"redaction",tool:`detect:${y.backend}@${y.host||"local"}`,ok:y.ok,ms:y.ms,error:y.error}))});if(N&&N.lap("redact",m),P=b,x=h,I=k||0,!R&&h>0){zo(t,R);try{ne(t,oe())}catch{}}if(!L&&Array.isArray(p.tools)&&p.tools.length&&typeof g.adapter.injectSystemNote=="function"){const y=et(p?.model,t,g.kind,{destination:String(r.headers["x-chatpanel-destination"]||p?.chatpanel?.destination||"").trim()}),f=!(y&&y.type==="api");g.adapter.injectSystemNote(p,Pt({toolData:t.tools?.toolData,ownTools:f}))}else!L&&h>0&&typeof g.adapter.injectSystemNote=="function"&&g.adapter.injectSystemNote(p,At());z=Buffer.from(JSON.stringify(p),"utf8")}}const $=$t({vault:P,toolData:t.tools?.toolData}),j=p&&typeof p.chatpanel=="object"&&p.chatpanel||null;j&&(delete p.chatpanel,z=Buffer.from(JSON.stringify(p),"utf8"));const J={destination:String(r.headers["x-chatpanel-destination"]||j?.destination||"").trim(),reach:String(r.headers["x-chatpanel-reach"]||j?.reach||"").trim(),run:gr(r.headers["x-chatpanel-run"],j?.run)},T=et(p?.model,t,g.kind,{destination:J.destination});if(J.destination&&(!T||T.id!==J.destination))return N?.commit(),s(o,404,{error:{message:`no destination "${J.destination}" is configured on this gateway`,type:"unknown_destination",known:Uo(t).map(e=>e.id)}});N&&(N.meta={t:Date.now(),model:p?.model||null,dest:T?T.id:null,type:T?T.type:null,redacted:x,sanitized:I,narrowed:Y,detail:dt(P,t.logDetail),redaction:L?"off":t.redaction.tier||"basic"});const Z=zt();if(Z&&T){const e=T.type==="api"?Le(Z,{model:p?.model||"",endpoint:T.baseUrl||""}):Gt(Z,T.agent||T.id)?Le(Z,{model:p?.model||""}):{ok:!1,reason:`agent "${T.agent||T.id}" is not allowed by your organisation’s policy`};if(!e.ok)return N?.commit(),s(o,403,{error:{message:e.reason,type:"policy",code:"org_policy"}})}if(T&&T.type==="api")return T.baseUrl?ar(T.baseUrl,t)?(N?.commit(),s(o,508,{error:{message:`destination "${T.id}" points back at the gateway (${T.baseUrl}) — refusing to forward (would loop).`,type:"loop_detected"}})):yr(r,o,{...g,pathname:c,search:u.search,base:T.baseUrl,destKey:T.apiKey,destProtocol:T.protocol,harness:$,trace:N},z,P):(N?.commit(),s(o,502,{error:`destination "${T.id}" has no baseUrl`}));const q=me(r),ie=q==="local"&&t.bridge?.openAgentLane?"token":q;if(ie==="local")return N?.commit(),s(o,401,{error:{message:"agent destinations require the gateway token: send `Authorization: Bearer $(cat ~/.chatpanel/gateway-token)`, or pair this client with `chatpanel-gateway pair`",type:"auth",code:"agent_lane_token_required"}});const le=xt({...J.run||{},...J.reach?{reach:J.reach}:{}},ie);return dr(r,o,{...g,pathname:c,agentOverride:T?.agent,harness:$,trace:N,run:Object.keys(le).length?le:null},p,P,t,R)})}function gr(t,l){let d=l&&typeof l=="object"?l:null;if(!d&&t)try{d=JSON.parse(decodeURIComponent(String(t)))}catch{d=null}if(!d||typeof d!="object")return null;const r={};if(Array.isArray(d.grants)&&(r.grants=d.grants.map(o=>String(o).slice(0,80)).slice(0,32)),d.workspace&&typeof d.workspace=="object"&&d.workspace.repo){const o=d.workspace;r.workspace={repo:String(o.repo).slice(0,400),projectId:String(o.projectId||"").slice(0,120),jobId:String(o.jobId||"").slice(0,120),...o.base?{base:String(o.base).slice(0,120)}:{}}}return d.connectionId&&(r.connectionId=String(d.connectionId).slice(0,64)),typeof d.workingDir=="string"&&d.workingDir.trim()&&/^([A-Za-z]:[\\/]|\/)/.test(d.workingDir.trim())&&(r.workingDir=d.workingDir.trim().slice(0,1024)),Jo.includes(d.permissionMode)&&d.permissionMode!=="default"&&(r.permissionMode=d.permissionMode),Object.keys(r).length?r:null}let be=null;async function dn(t=je()){Zt();let l=null;try{l=await Rt()}catch(g){throw g instanceof Lt&&(console.error(`[chatpanel-gateway] org policy: ${g.message}`),process.exit(78)),g}const d=l?.policy||null;d&&(ze(t,d),console.log(`[chatpanel-gateway] ${l.label} — ${l.signed?"signed":"unsigned"} policy from ${l.source}`)),jt(globalThis,{allow:d?.egress?(g,{local:w})=>Vt(d,g,{local:w}):null}),ke();const r=fr(t),o=Kt(t),u=bt(t);r.on("error",g=>{g&&g.code==="EADDRINUSE"&&(console.error(`Port ${t.port} is already in use — another app (or a second gateway) has it.`),console.error(`Fix: free the port, or set a different one — edit "port" in ${oe()} (or the extension's Gateway tab) and restart. The extension must point at the same port.`),process.exit(1)),console.error(`Gateway server error: ${g?.message||g}`),process.exit(1)}),r.listen(t.port,t.host,()=>{console.log(`ChatPanel Privacy Gateway v${K} on http://${t.host}:${t.port}`),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"),ao(t).then(g=>{be=g}).catch(g=>console.log(` bridge : not supervised (${g?.message||g})`)),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…)":"")),lt(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.`)}),Ue()&&$e(O,_e()).then(g=>{g?.ok&&(console.log(` warm : seeded ${g.ingested} records from ${g.file}`),g.whole&&ge())}).catch(()=>{});const c=()=>{o?.stop(),u.stop(),be?.stop(),r.close(()=>process.exit(0))};return process.on("SIGINT",c),process.on("SIGTERM",c),r}export{K as VERSION,fr as createGateway,ur as joinUpstream,De as parseAgentModel,dn as start};