@chatpanel/gateway 0.75.0 → 0.85.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/server.js CHANGED
@@ -1,52 +1,57 @@
1
- import{createServer as ho}from"node:http";import{loadConfig as vt}from"./config.js";import{startEntitlementRefresh as yo,maybeRevalidate as fo}from"./entitlement-refresh.js";import{redactSegments as Ie,segment as Xe}from"./redact.js";import{pipeRestoredStream as go,pipeRestoredOpenAIStream as wo,makeTokenRestorer as St,restoreDeep as bo}from"./stream.js";import{restoreText as ko,gatedDictionary as vo,narrowSpecs as So,makeToolHarness as To,placeholderToolNote as xo,placeholderNote as Oo,assertEndpointUrl as _o,capRunOptions as Eo,isPaired as $o}from"@chatpanel/pii";import{ensureGatewayToken as Se,currentGatewayToken as je,isAdminAuthorized as z,callerTrustOf as Le,setPinnedExtensionIds as Po,issuePairingCode as Ao,claimPairingCode as No}from"./gateway-token.js";import{installEgressLedger as Bo,egressAudit as Mo}from"./egress.js";import{initPolicy as Do,activePolicy as Co,applyPolicyToConfig as Tt,managedSummary as Ee,PolicyLoadError as Ro}from"./policy.js";import{routeAllowed as xt,agentAllowed as Io,egressAllowed as jo}from"@chatpanel/events/policy.js";import{resolveBridgeUrl as $e}from"./bridge.js";import{secureFetch as Je}from"./secure-fetch.js";import{fetchCard as ze,forgetCard as Lo,sendMessage as Jo,streamMessage as zo,getTask as Go,cancelTask as Ho,knownAgents as Uo,A2AError as Ot}from"./a2a.js";import{streamBridgeChat as _t,readBridgeToken as Pe,openBridgeChat as Vo,acceptedBridgeToken as Fo}from"./bridge.js";import{createRelaySession as Wo,getRelaySession as Et,endRelaySession as Ae,pumpBridgeStream as Ko,deliverToolResult as Qo,toolsToSpecs as Yo,wantsApprovals as Xo,parseToolCallId as $t,touchRelaySession as Ze}from"./toolrelay.js";import{shaperFor as qe}from"./shape.js";import{startNer as Zo,ensureNer as Ge,unionForThisMachine as qo,skippedCompanions as er}from"./ner.js";import{recommendDetector as Pt}from"@chatpanel/pii/detector-router.js";import{installTimestampedConsole as tr}from"./log.js";import{saveBackupSecret as or,clearBackupSecret as rr,loadBackupSecret as et,hasBackupSecret as At}from"./history-store.js";import{createMemoryStore as nr}from"./memory-store.js";import{createPrefsStore as ar}from"./prefs-store.js";import{agentCardFor as sr,runHintFor as ir}from"@chatpanel/events/agent-run-hint.js";import{normalizeThread as lr}from"@chatpanel/events/agent-thread.js";import{portClashPlan as dr,serviceManagerOf as cr,STANDBY_POLL_MS as ur}from"@chatpanel/events/service-standby.js";import{threadTarget as mr,frameQuestion as pr,wireMessages as hr,appendExchange as yr,MAX_MESSAGE as Nt}from"@chatpanel/events/thread-send.js";import{researchStore as fr,researchResponse as gr}from"./research.js";import{createTeamStore as wr,loadOrCreateKey as tt}from"./team-store.js";import{createScorecardStore as br}from"./scorecard-store.js";import{createEngineLedgerStore as kr}from"./engine-ledger-store.js";import{createProjectStore as vr}from"./project-store.js";import{applicationsFor as Sr,recruitPass as Tr}from"./recruiting.js";import{ensureBridge as xr,holderOf as Or}from"./bridge-supervisor.js";import{checkForUpdate as _r,updateStatus as Er,startUpdate as $r,updateJob as Pr}from"./update.js";import{createHistoryStore as Ar}from"./sqlite-store.js";import{createEventStore as Nr}from"./event-store.js";import{ingestCloudEvents as Br,cursorOf as Bt}from"./event-sync.js";import{eventStats as Mr,projectYear as Dr}from"./event-stats.js";import{toCloudEvent as ot}from"./cloudevents.js";import{fusionsDocument as Cr,resolveFusionModel as Rr}from"./fusions.js";import{ingestBackups as rt}from"./backup-ingest.js";import{toSearchRecord as Mt}from"@chatpanel/events/library.js";import{deriveBackupKey as Ir,openRecord as jr,keyCache as Lr,nodeCodec as Jr}from"@chatpanel/events/backup-envelope.js";import zr from"node:zlib";import*as N from"./ner-engine.js";import Dt from"node:os";import{capabilitiesDocument as Gr,handleDetect as Hr}from"./capabilities.js";import{createExtractService as Ur}from"./extract/service.js";import{workerSandbox as Vr,disposeWorkerSandbox as Fr}from"./worker-sandbox.js";import{createRuntime as Wr}from"./runtime.js";import{createCapabilityProxy as Kr}from"./capability-proxy.js";import{createEmbeddedCapabilities as Qr}from"./capability-embedded.js";import{EMBEDDED_MODELS as Yr,EMBEDDED_IDS as Xr}from"./embedded-models.js";import{handleExtract as Zr}from"./extract/handler.js";import{MAX_DOCUMENT_BYTES as qr}from"./extract-capability.js";import{createReader as en}from"./retrieval/read.js";import{createBrowserRelayHost as tn}from"./browser-relay.js";import{createLinkHost as on}from"./link-host.js";import{checkLinkRoute as rn,tunnelHeader as nn,LINK_TUNNEL_ROOM_PATH as an}from"@chatpanel/events/link-routes.js";import{createSearcher as sn,toJinaSearch as ln,SEARCH_DEFAULTS as dn}from"./retrieval/search.js";import{createSearxng as cn}from"./retrieval/search-searxng.js";import{toJinaText as un}from"./read-document.js";import*as C from"./stt-engine.js";import*as A from"./diarize-engine.js";import{DIARIZE_MODEL_CATALOG as mn,DEFAULT_DIARIZE_MODEL as pn,isKnownDiarizeModel as Ct}from"./diarize-models.js";import{providerOf as nt}from"./providers.js";import{createRemoteTranscriber as Rt}from"./stt-remote.js";import{parseMultipart as hn,decodeAudioFile as yn}from"./audio-file.js";import{MODEL_CATALOG as It,isKnownModel as jt,isValidCustomModelId as Lt,recommendFor as fn}from"./models.js";import{STT_MODEL_CATALOG as gn,isKnownSttModel as wn,isValidCustomSttId as bn,DEFAULT_STT_MODEL as He,STT_DTYPES as kn,isValidDtype as vn}from"./stt-models.js";import*as $ from"./tts-engine.js";import{TTS_MODEL_CATALOG as Jt,TTS_VOICES as Sn,isKnownTtsModel as Tn,isValidCustomTtsId as xn,isKnownVoice as zt,isValidVoiceId as Gt,DEFAULT_TTS_MODEL as Ht,DEFAULT_TTS_VOICE as fe,TTS_DTYPES as On,isValidTtsDtype as _n,MAX_TTS_CHARS as Ut,ttsModelHasCustomVoices as En,resolveDefaultModel as Vt,POCKET_VOICES as $n,DEFAULT_POCKET_VOICE as Ue,isPocketVoice as Ve,ttsModelEngine as Fe}from"./tts-models.js";import{ttsDestination as Pn,synthesizeRemote as An,isValidRemoteVoice as Nn}from"./tts-remote.js";import{rawOrtAvailable as at}from"./ort.js";import*as X from"./tts-voices.js";import{resolveTtsVoice as Bn}from"./tts-voice-resolve.js";import{resolvePro as we,checkQuota as Mn,consume as Dn,usage as Cn}from"./freegate.js";import{publicConfig as Ft,applyConfigPatch as Rn,registryChildEnv as In,applyNerModelSelection as Wt,persistConfig as me,configPath as se,bridgeAgentOptions as Kt,PERMISSION_MODES as jn,sandboxEnvFor as Ln}from"./configstore.js";import Qt from"node:path";import{resolveDestination as st,aggregateModelsAsync as Jn,listDestinations as zn,ensureModelCatalog as Gn,agentOwnsModel as Hn}from"./router.js";import{makeAccessEvent as Yt}from"./observability.js";import{createPersistentAccessLog as Un}from"./access-log-store.js";import{planQueries as Vn,multiSearch as Fn}from"./rrf.js";import*as it from"./openai.js";import*as Xt from"./responses.js";import*as lt from"./anthropic.js";import{closeAndExit as Wn}from"./shutdown.js";import{VERSION as Z}from"./version.js";import{VERSION as Ws}from"./version.js";const B=await Ar(),ye=new Set;function Ne({ids:t=[]}={}){const d=B.lossless;if(!d||!ye.size)return;const c=JSON.stringify({newest:d.newest,rev:d.rev,size:d.size,ids:t.slice(0,50),at:Date.now()});for(const m of ye)try{m.write(`event: records
2
- data: ${c}
1
+ import{createServer as So}from"node:http";import{loadConfig as _t}from"./config.js";import{startEntitlementRefresh as To,maybeRevalidate as xo}from"./entitlement-refresh.js";import{redactSegments as ze,segment as qe}from"./redact.js";import{pipeRestoredStream as Oo,pipeRestoredOpenAIStream as _o,makeTokenRestorer as Et,restoreDeep as Eo}from"./stream.js";import{restoreText as $o,gatedDictionary as Po,narrowSpecs as Ao,makeToolHarness as No,placeholderToolNote as Bo,placeholderNote as Mo,assertEndpointUrl as Do,capRunOptions as Co,isPaired as $t}from"@chatpanel/pii";import{ensureGatewayToken as ve,currentGatewayToken as Pe,isAdminAuthorized as G,callerTrustOf as Ae,setPinnedExtensionIds as Ro,issuePairingCode as Io,claimPairingCode as jo}from"./gateway-token.js";import{createPairAsk as Lo,nativeConfirm as Jo}from"./pair-prompt.js";import{createEngineProbe as zo}from"./local-engine-probe.js";import{randomUUID as Go}from"node:crypto";import{installEgressLedger as Uo,egressAudit as Ho}from"./egress.js";import{initPolicy as Vo,activePolicy as Fo,applyPolicyToConfig as Pt,managedSummary as Ne,PolicyLoadError as Wo}from"./policy.js";import{routeAllowed as At,agentAllowed as Ko,egressAllowed as Qo}from"@chatpanel/events/policy.js";import{resolveBridgeUrl as Be}from"./bridge.js";import{secureFetch as Ge}from"./secure-fetch.js";import{fetchCard as Ue,forgetCard as Yo,sendMessage as Xo,streamMessage as Zo,getTask as qo,cancelTask as er,knownAgents as tr,A2AError as Nt}from"./a2a.js";import{streamBridgeChat as Bt,readBridgeToken as Me,openBridgeChat as or,acceptedBridgeToken as Mt}from"./bridge.js";import{createRelaySession as rr,getRelaySession as Dt,endRelaySession as De,pumpBridgeStream as nr,deliverToolResult as ar,toolsToSpecs as sr,wantsApprovals as ir,parseToolCallId as Ct,touchRelaySession as et}from"./toolrelay.js";import{shaperFor as tt}from"./shape.js";import{startNer as lr,ensureNer as He,unionForThisMachine as dr,skippedCompanions as cr}from"./ner.js";import{recommendDetector as Rt}from"@chatpanel/pii/detector-router.js";import{installTimestampedConsole as ur}from"./log.js";import{saveBackupSecret as mr,clearBackupSecret as pr,loadBackupSecret as ot,hasBackupSecret as It}from"./history-store.js";import{createMemoryStore as hr}from"./memory-store.js";import{createPrefsStore as yr}from"./prefs-store.js";import{agentCardFor as fr,runHintFor as gr}from"@chatpanel/events/agent-run-hint.js";import{normalizeThread as wr}from"@chatpanel/events/agent-thread.js";import{portClashPlan as br,serviceManagerOf as kr,STANDBY_POLL_MS as vr}from"@chatpanel/events/service-standby.js";import{threadTarget as Sr,frameQuestion as Tr,wireMessages as xr,appendExchange as Or,MAX_MESSAGE as jt}from"@chatpanel/events/thread-send.js";import{researchStore as _r,researchResponse as Er}from"./research.js";import{createTeamStore as $r,loadOrCreateKey as rt}from"./team-store.js";import{createScorecardStore as Pr}from"./scorecard-store.js";import{createEngineLedgerStore as Ar}from"./engine-ledger-store.js";import{createProjectStore as Nr}from"./project-store.js";import{applicationsFor as Br,recruitPass as Mr}from"./recruiting.js";import{ensureBridge as Dr,holderOf as Cr}from"./bridge-supervisor.js";import{checkForUpdate as Rr,updateStatus as Ir,startUpdate as jr,updateJob as Lr}from"./update.js";import{createHistoryStore as Jr}from"./sqlite-store.js";import{createEventStore as zr}from"./event-store.js";import{ingestCloudEvents as Gr,cursorOf as Lt}from"./event-sync.js";import{eventStats as Ur,projectYear as Hr}from"./event-stats.js";import{toCloudEvent as nt}from"./cloudevents.js";import{fusionsDocument as Vr,resolveFusionModel as Fr}from"./fusions.js";import{ingestBackups as at}from"./backup-ingest.js";import{toSearchRecord as Jt}from"@chatpanel/events/library.js";import{deriveBackupKey as Wr,openRecord as Kr,keyCache as Qr,nodeCodec as Yr}from"@chatpanel/events/backup-envelope.js";import Xr from"node:zlib";import*as C from"./ner-engine.js";import zt from"node:os";import{capabilitiesDocument as Zr,handleDetect as qr}from"./capabilities.js";import{createExtractService as en}from"./extract/service.js";import{workerSandbox as tn,disposeWorkerSandbox as on}from"./worker-sandbox.js";import{createRuntime as rn,SERVICES as nn}from"./runtime.js";import{createCapabilityProxy as an}from"./capability-proxy.js";import{createEmbeddedCapabilities as sn}from"./capability-embedded.js";import{EMBEDDED_MODELS as ln,EMBEDDED_IDS as dn}from"./embedded-models.js";import{handleExtract as cn}from"./extract/handler.js";import{MAX_DOCUMENT_BYTES as un}from"./extract-capability.js";import{createReader as mn}from"./retrieval/read.js";import{createBrowserRelayHost as pn}from"./browser-relay.js";import{createLinkHost as hn}from"./link-host.js";import{checkLinkRoute as yn,tunnelHeader as fn,LINK_TUNNEL_ROOM_PATH as gn}from"@chatpanel/events/link-routes.js";import{createSearcher as wn,toJinaSearch as bn,SEARCH_DEFAULTS as kn}from"./retrieval/search.js";import{createSearxng as vn}from"./retrieval/search-searxng.js";import{searchEngines as Sn}from"./retrieval/search-apis.js";import{toJinaText as Tn}from"./read-document.js";import*as $ from"./stt-engine.js";import*as P from"./diarize-engine.js";import{DIARIZE_MODEL_CATALOG as xn,DEFAULT_DIARIZE_MODEL as On,isKnownDiarizeModel as Gt}from"./diarize-models.js";import{providerOf as st}from"./providers.js";import{createRemoteTranscriber as Ut}from"./stt-remote.js";import{parseMultipart as _n,decodeAudioFile as En}from"./audio-file.js";import{MODEL_CATALOG as Ht,isKnownModel as Vt,isValidCustomModelId as Ft,recommendFor as $n}from"./models.js";import{STT_MODEL_CATALOG as Pn,isKnownSttModel as An,isValidCustomSttId as Nn,DEFAULT_STT_MODEL as Ve,STT_DTYPES as Bn,isValidDtype as Mn}from"./stt-models.js";import*as N from"./tts-engine.js";import{TTS_MODEL_CATALOG as Wt,TTS_VOICES as Dn,isKnownTtsModel as Cn,isValidCustomTtsId as Rn,isKnownVoice as Kt,isValidVoiceId as Qt,DEFAULT_TTS_MODEL as Yt,DEFAULT_TTS_VOICE as be,TTS_DTYPES as In,isValidTtsDtype as jn,MAX_TTS_CHARS as Xt,ttsModelHasCustomVoices as Ln,resolveDefaultModel as Zt,POCKET_VOICES as Jn,DEFAULT_POCKET_VOICE as Fe,isPocketVoice as We,ttsModelEngine as Ke}from"./tts-models.js";import{ttsDestination as zn,synthesizeRemote as Gn,isValidRemoteVoice as Un}from"./tts-remote.js";import{rawOrtAvailable as it}from"./ort.js";import*as ee from"./tts-voices.js";import{resolveTtsVoice as Hn}from"./tts-voice-resolve.js";import{resolvePro as ke,checkQuota as Vn,consume as Fn,usage as Wn}from"./freegate.js";import{publicConfig as qt,applyConfigPatch as Kn,registryChildEnv as Qn,applyNerModelSelection as eo,persistConfig as ue,configPath as ae,bridgeAgentOptions as to,PERMISSION_MODES as Yn,sandboxEnvFor as Xn}from"./configstore.js";import oo from"node:path";import{resolveDestination as Qe,aggregateModelsAsync as Zn,listDestinations as qn,ensureModelCatalog as ea,agentOwnsModel as ta}from"./router.js";import{makeAccessEvent as ro}from"./observability.js";import{createPersistentAccessLog as oa}from"./access-log-store.js";import{planQueries as ra,multiSearch as na}from"./rrf.js";import*as lt from"./openai.js";import*as no from"./responses.js";import*as dt from"./anthropic.js";import{closeAndExit as aa}from"./shutdown.js";import{VERSION as X}from"./version.js";import{VERSION as di}from"./version.js";const R=await Jr(),fe=new Set;function Ce({ids:t=[]}={}){const c=R.lossless;if(!c||!fe.size)return;const u=JSON.stringify({newest:c.newest,rev:c.rev,size:c.size,ids:t.slice(0,50),at:Date.now()});for(const m of fe)try{m.write(`event: records
2
+ data: ${u}
3
3
 
4
- `)}catch{ye.delete(m)}}setInterval(()=>{for(const t of ye)try{t.write(`: ping
4
+ `)}catch{fe.delete(m)}}setInterval(()=>{for(const t of fe)try{t.write(`: ping
5
5
 
6
- `)}catch{ye.delete(t)}},25e3).unref?.();const K=await Nr(),be=new Set;K?.watch(t=>{if(!be.size)return;const d=`event: cloudevent
7
- data: ${JSON.stringify(ot(t))}
6
+ `)}catch{fe.delete(t)}},25e3).unref?.();const Q=await zr(),Se=new Set;Q?.watch(t=>{if(!Se.size)return;const c=`event: cloudevent
7
+ data: ${JSON.stringify(nt(t))}
8
8
 
9
- `;for(const c of be)try{c.write(d)}catch{be.delete(c)}}),setInterval(()=>{for(const t of be)try{t.write(`: ping
9
+ `;for(const u of Se)try{u.write(c)}catch{Se.delete(u)}}),setInterval(()=>{for(const t of Se)try{t.write(`: ping
10
10
 
11
- `)}catch{be.delete(t)}},25e3).unref?.();const ie=await nr(),q=ar(),Te=br({key:tt()}),xe=kr({key:tt()}),ee=vr({key:tt()}),W=wr({scorecards:Te,engines:xe}),dt=new Set,Zt=(t,d)=>{for(const m of dt)try{m({applied:t,by:d,revision:q.revision})}catch{}const c=JSON.stringify({revision:q.revision,applied:(t||[]).slice(0,50),by:d||"",at:Date.now()});for(const m of ye)try{m.write(`event: prefs
12
- data: ${c}
11
+ `)}catch{Se.delete(t)}},25e3).unref?.();const se=await hr(),te=yr(),Oe=Pr({key:rt()}),_e=Ar({key:rt()}),oe=Nr({key:rt()}),W=$r({scorecards:Oe,engines:_e}),ct=new Set,ao=(t,c)=>{for(const m of ct)try{m({applied:t,by:c,revision:te.revision})}catch{}const u=JSON.stringify({revision:te.revision,applied:(t||[]).slice(0,50),by:c||"",at:Date.now()});for(const m of fe)try{m.write(`event: prefs
12
+ data: ${u}
13
13
 
14
- `)}catch{ye.delete(m)}},ct=Un(),qt=new Set(["codex","claude","opencode","pi","kiro","antigravity","hermes"]),Kn=16,Qn=/^mcp[_-]/i,eo=t=>t&&t.function&&t.function.name||t&&t.name||"",Yn=t=>t&&t.function&&t.function.description||t&&t.description||"";function to(t){return typeof t=="string"?t:Array.isArray(t)?t.map(d=>typeof d=="string"?d:d&&(d.text||d.content)||"").join(" "):""}function Xn(t,d){if(!t)return"";if(d==="responses"){const m=t.input;return typeof m=="string"?m:Array.isArray(m)?m.map(w=>to(w&&(w.content??w))).join(" "):""}const c=Array.isArray(t.messages)?t.messages:[];for(let m=c.length-1;m>=0;m--)if(c[m]&&c[m].role==="user")return to(c[m].content);return""}const oo=new Set(["host","connection","content-length","transfer-encoding","accept-encoding","content-encoding","keep-alive"]);function We(t){if(!t)return!1;const d=t.replace(/:\d+$/,"").replace(/^\[|\]$/g,"");return d==="localhost"||d==="127.0.0.1"||d==="::1"}function Zn(t,d){return!t||/^chrome-extension:\/\//.test(t)||/^moz-extension:\/\//.test(t)||/^http:\/\/(localhost|127\.0\.0\.1|\[::1\])(:\d+)?$/.test(t)?!0:Array.isArray(d.allowedOrigins)&&d.allowedOrigins.includes(t)}function qn(t,d){t.setHeader("Access-Control-Allow-Origin",d||"*"),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 ro=Date.now();function ea(t){if(!t)return"";const d={redact:"redact",upstream:"model",stream:"stream",restore:"restore",total:"total"};return Object.keys(t).map(c=>`${d[c]||c} ${t[c]}ms`).join(" · ")}function ta(t){const d=/^(model|harness):([^/]+)(?:\/(.+))?$/.exec(String(t||""));return d?{kind:d[1],id:d[2],...d[3]?{model:d[3]}:{}}:null}function oa(t){const d=performance.now(),c={};let m=!1;const w=(g,E)=>{c[g]=Math.round(E*10)/10};return{meta:{},timings:c,mark:w,lap(g,E){w(g,performance.now()-E)},clock(){return performance.now()},commit(){if(m)return;m=!0,w("total",performance.now()-d);const g={...this.meta,timings:c};setImmediate(()=>{t(g),console.log(`[gateway] model=${g.model||"-"} → ${g.dest?`${g.dest}(${g.type})`:"none"} · ${g.redaction==="off"?"redaction OFF (client request)":`redacted ${g.redacted||0}`}${g.sanitized?` · scrubbed ${g.sanitized} hidden`:""}${g.narrowed?` · narrowed -${g.narrowed}`:""} · ${ea(c)}`)})}}}function no(t,d){if(!t||!t.byToken||d!=="types"&&d!=="values")return;const c=[];for(const[m,w]of t.byToken){const g=/^\[\[([A-Z][A-Z0-9]*)_\d+\]\]$/.exec(m),E=g?g[1]:"PII",P=m.replace(/^\[\[|\]\]$/g,"");c.push(d==="values"?{token:P,type:E,value:w}:{token:P,type:E})}return c}function ra(t,d,c){return lt.matches(t)||"anthropic-version"in d?{kind:"anthropic",adapter:lt,redactable:lt.matches(t),base:c.upstreams?.anthropic?.baseUrl}:Xt.matches(t)?{kind:"responses",adapter:Xt,redactable:!0,base:c.upstreams?.openai?.baseUrl}:{kind:"openai",adapter:it,redactable:it.matches(t),base:c.upstreams?.openai?.baseUrl}}function ut(t,d){const c=String(t||"");if(qt.has(c))return{agent:c,agentModel:""};const m=c.indexOf("/");if(m>0){const w=c.slice(0,m);if(qt.has(w))return{agent:w,agentModel:c.slice(m+1)}}return{agent:d.bridge.agent,agentModel:""}}function ao(t,d){return ut(t,d).agent}function na(t,d){if(d!=="openai"||!t)return!1;const c=it.extractLatestToolResult(t);if(!c)return!1;const m=$t(c.tool_call_id);return!!(m&&Et(m.gwId))}function aa(t,d){try{const c=new URL(t),m=c.hostname.replace(/^\[|\]$/g,""),w=m==="127.0.0.1"||m==="localhost"||m==="::1",g=c.port||(c.protocol==="https:"?"443":"80");return w&&String(g)===String(d.port)}catch{return!1}}const sa=25*1024*1024;async function v(t,d){const c=[];let m=0;for await(const w of t){if(m+=w.length,d&&m>d){const g=new Error("payload too large");throw g.code=413,g}c.push(w)}return Buffer.concat(c)}function a(t,d,c){t.writeHead(d,{"content-type":"application/json"}),t.end(JSON.stringify(c))}function so(t){const d=t.redaction?.detection?.url;return!d||t.redaction?.detection?.backend==="off"?null:d}function mt(t){const d=t?.redaction?.detection,c=t?.redaction?.tier==="full"?"full":"basic";if(d&&d.backend&&d.backend!=="off")return{source:"external",backend:d.backend,state:"external",model:d.model||null,ready:!0,tier:c,coverage:c==="full"?"names":"patterns"};const m=N.health(),w=m.ok&&c==="full";return{source:"bundled",state:m.state,model:m.model||t?.ner?.model||null,installed:N.modelOnDisk(t?.ner?.model||void 0),error:m.error||null,ready:w,tier:c,coverage:w?"names":"patterns"}}async function io(t){if(N.state()!=="off"){const c=N.health();return{configured:c.configured,ok:c.ok,state:c.state,model:c.model,error:c.error||null,url:c.configured?`http://${t.host}:${t.port}/ner`:null,stats:c.stats,companions:c.companions}}const d=so(t);if(!d)return{configured:!1,ok:!1,url:null,model:null};try{const c=await Je(d.replace(/\/ner\/?$/,"")+"/health",{signal:AbortSignal.timeout(2e3)});if(!c.ok)return{configured:!0,ok:!1,url:d,model:null};const m=await c.json().catch(()=>({}));return{configured:!0,ok:!0,url:d,model:m.model||null}}catch{return{configured:!0,ok:!1,url:d,model:null}}}function ia(t,d){const c={};for(const[m,w]of Object.entries(t)){const g=m.toLowerCase();g.startsWith("x-chatpanel-")||oo.has(g)||(c[m]=w)}c["accept-encoding"]="identity";try{c.host=new URL(d).host}catch{}return c}async function lo(t,d,c,m){const w=St(d.vault),g=pt();t.on("close",()=>{t.writableFinished||Ae(d.id)});const E=m?m.clock():0;let P=E,y=!0;const J=()=>{m&&y&&(m.lap("upstream",E),P=m.clock(),y=!1)};await Ko(d,{onText:b=>{J(),Ze(d.id);const M=w.push(b);M&&t.write(c.sseDelta(M))},onToolRequest:({name:b,restoredArgs:M,toolId:j})=>{J(),Ze(d.id);const L=w.flush();L&&t.write(c.sseDelta(L)),t.write(c.sseToolCalls([{id:j,name:b,arguments:JSON.stringify(M)}])),t.write(c.sseToolFinish(g.value)),m&&m.lap("stream",P),t.end(),m?.commit()},onDone:()=>{const b=w.flush();b&&t.write(c.sseDelta(b)),t.write(c.sseTail(g.value)),m&&m.lap("stream",P),t.end(),Ae(d.id),m?.commit()},onError:b=>{t.write(`data: ${JSON.stringify({error:{message:b.message,type:"bridge_error"}})}
14
+ `)}catch{fe.delete(m)}},ut=oa(),so=new Set(["codex","claude","opencode","pi","kiro","antigravity","hermes"]),sa=16,ia=/^mcp[_-]/i,io=t=>t&&t.function&&t.function.name||t&&t.name||"",la=t=>t&&t.function&&t.function.description||t&&t.description||"";function lo(t){return typeof t=="string"?t:Array.isArray(t)?t.map(c=>typeof c=="string"?c:c&&(c.text||c.content)||"").join(" "):""}function da(t,c){if(!t)return"";if(c==="responses"){const m=t.input;return typeof m=="string"?m:Array.isArray(m)?m.map(g=>lo(g&&(g.content??g))).join(" "):""}const u=Array.isArray(t.messages)?t.messages:[];for(let m=u.length-1;m>=0;m--)if(u[m]&&u[m].role==="user")return lo(u[m].content);return""}const co=new Set(["host","connection","content-length","transfer-encoding","accept-encoding","content-encoding","keep-alive"]);function Ye(t){if(!t)return!1;const c=t.replace(/:\d+$/,"").replace(/^\[|\]$/g,"");return c==="localhost"||c==="127.0.0.1"||c==="::1"}function ca(t,c){return!t||/^chrome-extension:\/\//.test(t)||/^moz-extension:\/\//.test(t)||/^http:\/\/(localhost|127\.0\.0\.1|\[::1\])(:\d+)?$/.test(t)?!0:Array.isArray(c.allowedOrigins)&&c.allowedOrigins.includes(t)}function ua(t,c){t.setHeader("Access-Control-Allow-Origin",c||"*"),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 uo=Date.now();function ma(t){if(!t)return"";const c={redact:"redact",upstream:"model",stream:"stream",restore:"restore",total:"total"};return Object.keys(t).map(u=>`${c[u]||u} ${t[u]}ms`).join(" · ")}function pa(t){const c=/^(model|harness):([^/]+)(?:\/(.+))?$/.exec(String(t||""));return c?{kind:c[1],id:c[2],...c[3]?{model:c[3]}:{}}:null}function ha(t){const c=performance.now(),u={};let m=!1;const g=(k,_)=>{u[k]=Math.round(_*10)/10};return{meta:{},timings:u,mark:g,lap(k,_){g(k,performance.now()-_)},clock(){return performance.now()},commit(){if(m)return;m=!0,g("total",performance.now()-c);const k={...this.meta,timings:u};setImmediate(()=>{t(k),console.log(`[gateway] model=${k.model||"-"} → ${k.dest?`${k.dest}(${k.type})`:"none"} · ${k.redaction==="off"?"redaction OFF (client request)":`redacted ${k.redacted||0}`}${k.sanitized?` · scrubbed ${k.sanitized} hidden`:""}${k.narrowed?` · narrowed -${k.narrowed}`:""} · ${ma(u)}`)})}}}function mo(t,c){if(!t||!t.byToken||c!=="types"&&c!=="values")return;const u=[];for(const[m,g]of t.byToken){const k=/^\[\[([A-Z][A-Z0-9]*)_\d+\]\]$/.exec(m),_=k?k[1]:"PII",B=m.replace(/^\[\[|\]\]$/g,"");u.push(c==="values"?{token:B,type:_,value:g}:{token:B,type:_})}return u}function ya(t,c,u){return dt.matches(t)||"anthropic-version"in c?{kind:"anthropic",adapter:dt,redactable:dt.matches(t),base:u.upstreams?.anthropic?.baseUrl}:no.matches(t)?{kind:"responses",adapter:no,redactable:!0,base:u.upstreams?.openai?.baseUrl}:{kind:"openai",adapter:lt,redactable:lt.matches(t),base:u.upstreams?.openai?.baseUrl}}function mt(t,c){const u=String(t||"");if(so.has(u))return{agent:u,agentModel:""};const m=u.indexOf("/");if(m>0){const g=u.slice(0,m);if(so.has(g))return{agent:g,agentModel:u.slice(m+1)}}return{agent:c.bridge.agent,agentModel:""}}function po(t,c){return mt(t,c).agent}function fa(t,c){if(c!=="openai"||!t)return!1;const u=lt.extractLatestToolResult(t);if(!u)return!1;const m=Ct(u.tool_call_id);return!!(m&&Dt(m.gwId))}function ga(t,c){try{const u=new URL(t),m=u.hostname.replace(/^\[|\]$/g,""),g=m==="127.0.0.1"||m==="localhost"||m==="::1",k=u.port||(u.protocol==="https:"?"443":"80");return g&&String(k)===String(c.port)}catch{return!1}}const wa=25*1024*1024;async function S(t,c){const u=[];let m=0;for await(const g of t){if(m+=g.length,c&&m>c){const k=new Error("payload too large");throw k.code=413,k}u.push(g)}return Buffer.concat(u)}function a(t,c,u){t.writeHead(c,{"content-type":"application/json"}),t.end(JSON.stringify(u))}function ho(t){const c=t.redaction?.detection?.url;return!c||t.redaction?.detection?.backend==="off"?null:c}function pt(t){const c=t?.redaction?.detection,u=t?.redaction?.tier==="full"?"full":"basic";if(c&&c.backend&&c.backend!=="off")return{source:"external",backend:c.backend,state:"external",model:c.model||null,ready:!0,tier:u,coverage:u==="full"?"names":"patterns"};const m=C.health(),g=m.ok&&u==="full";return{source:"bundled",state:m.state,model:m.model||t?.ner?.model||null,installed:C.modelOnDisk(t?.ner?.model||void 0),error:m.error||null,ready:g,tier:u,coverage:g?"names":"patterns"}}async function yo(t){if(C.state()!=="off"){const u=C.health();return{configured:u.configured,ok:u.ok,state:u.state,model:u.model,error:u.error||null,url:u.configured?`http://${t.host}:${t.port}/ner`:null,stats:u.stats,companions:u.companions}}const c=ho(t);if(!c)return{configured:!1,ok:!1,url:null,model:null};try{const u=await Ge(c.replace(/\/ner\/?$/,"")+"/health",{signal:AbortSignal.timeout(2e3)});if(!u.ok)return{configured:!0,ok:!1,url:c,model:null};const m=await u.json().catch(()=>({}));return{configured:!0,ok:!0,url:c,model:m.model||null}}catch{return{configured:!0,ok:!1,url:c,model:null}}}function ba(t,c){const u={};for(const[m,g]of Object.entries(t)){const k=m.toLowerCase();k.startsWith("x-chatpanel-")||co.has(k)||(u[m]=g)}u["accept-encoding"]="identity";try{u.host=new URL(c).host}catch{}return u}async function fo(t,c,u,m){const g=Et(c.vault),k=ht();t.on("close",()=>{t.writableFinished||De(c.id)});const _=m?m.clock():0;let B=_,y=!0;const M=()=>{m&&y&&(m.lap("upstream",_),B=m.clock(),y=!1)};await nr(c,{onText:v=>{M(),et(c.id);const J=g.push(v);J&&t.write(u.sseDelta(J))},onToolRequest:({name:v,restoredArgs:J,toolId:L})=>{M(),et(c.id);const A=g.flush();A&&t.write(u.sseDelta(A)),t.write(u.sseToolCalls([{id:L,name:v,arguments:JSON.stringify(J)}])),t.write(u.sseToolFinish(k.value)),m&&m.lap("stream",B),t.end(),m?.commit()},onDone:()=>{const v=g.flush();v&&t.write(u.sseDelta(v)),t.write(u.sseTail(k.value)),m&&m.lap("stream",B),t.end(),De(c.id),m?.commit()},onError:v=>{t.write(`data: ${JSON.stringify({error:{message:v.message,type:"bridge_error"}})}
15
15
 
16
- `),t.end(),Ae(d.id),m?.commit()},onUsage:b=>g.add(b)})}async function la(t,d,{kind:c,adapter:m,agent:w,run:g=null},E,P,y,J,b,M=null,j=null){const{messages:L,system:de}=m.toTurn(E),{agentModel:re}=ut(E?.model,y),te=Kt(y,{...re?{model:re}:{},...g||{}}),he=Pe(y.bridge.token),R=qe(c,E?.model||w),oe={tier:y.redaction.tier==="full"?"full":"basic",dictionary:vo(y.redaction,J),entities:[]},ce=await $e(y),n=Wo({vault:P,redactOpts:oe,bridgeUrl:ce,token:he,harness:M});let o;try{o=await Vo({bridgeUrl:ce,agent:w,token:he,messages:L,system:de,specs:Yo(b),options:te,signal:void 0,approvals:Xo(b)})}catch(f){return Ae(n.id),j?.commit(),a(d,502,{error:{message:`bridge: ${f.message}`,type:"bridge_error"}})}return n.reader=o.body.getReader(),d.writeHead(200,{"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive"}),d.write(R.sseHead()),lo(d,n,R,j)}async function da(t,d,c,m,w=null){Ze(d.id),d.rounds=(d.rounds||0)+1;try{const E=w?w.clock():0;await Qo(d,c),w&&w.lap("redact",E)}catch(E){return Ae(d.id),w?.commit(),a(t,502,{error:{message:`tool-result: ${E.message}`,type:"bridge_error"}})}const g=qe("openai",m||"codex");return t.writeHead(200,{"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive"}),t.write(g.sseHead()),lo(t,d,g,w)}function pt(){let t=!1;const d={inputTokens:0,outputTokens:0,cacheReadTokens:0,cacheWriteTokens:0};return{add(c){t=!0;for(const m of Object.keys(d))d[m]+=Math.max(0,Number(c?.[m])||0)},get value(){return t?d:null}}}async function ca(t,d,{kind:c,adapter:m,redactable:w,pathname:g,agentOverride:E,harness:P,trace:y,run:J=null},b,M,j,L){if(!w)return y?.commit(),a(d,404,{error:`endpoint ${g} not supported by the bridge backend`});if(c==="openai"){const H=m.extractLatestToolResult(b);if(H){const S=$t(H.tool_call_id),ne=S&&Et(S.gwId);if(ne)return da(d,ne,H.content,b?.model,y)}const U=m.extractTools(b);if(U.length&&b?.stream===!0)return la(t,d,{kind:c,adapter:m,agent:E||ao(b?.model,j),run:J},b,M,j,L,U,P,y)}const{messages:de,system:re}=m.toTurn(b),te=E||ao(b?.model,j),he=b?.stream===!0,R=qe(c,b?.model||te),oe=Pe(j.bridge.token),ce=new AbortController;d.on("close",()=>{d.writableFinished||ce.abort()});const{agentModel:n}=ut(b?.model,j),o={bridgeUrl:await $e(j),agent:te,token:oe,messages:de,system:re,signal:ce.signal,options:Kt(j,{...n?{model:n}:{},...J||{}})};if(!he)try{let H="";const U=pt(),S=y?y.clock():0;await _t(o,ke=>{H+=ke},null,ke=>U.add(ke)),y&&y.lap("upstream",S);const ne=y?y.clock():0,Me=R.full(ko(H,M),U.value);return y&&y.lap("restore",ne),d.writeHead(200,{"content-type":R.contentType}),d.end(Me),y?.commit()}catch(H){return y?.commit(),a(d,502,{error:{message:`bridge backend failed: ${H.message}`,type:"bridge_error"}})}d.writeHead(200,{"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive"}),d.write(R.sseHead());const f=St(M),i=y?y.clock():0;let le=i;const V=pt();try{let H=!0;await _t(o,S=>{y&&H&&(y.lap("upstream",i),le=y.clock(),H=!1);const ne=f.push(S);ne&&d.write(R.sseDelta(ne))},R.sseActivity?S=>{try{d.write(R.sseActivity(bo(S,M)))}catch{}}:null,S=>V.add(S));const U=f.flush();U&&d.write(R.sseDelta(U)),d.write(R.sseTail(V.value))}catch(H){d.write(`data: ${JSON.stringify({error:{message:H.message,type:"bridge_error"}})}
16
+ `),t.end(),De(c.id),m?.commit()},onUsage:v=>k.add(v)})}async function ka(t,c,{kind:u,adapter:m,agent:g,run:k=null},_,B,y,M,v,J=null,L=null){const{messages:A,system:ie}=m.toTurn(_),{agentModel:re}=mt(_?.model,y),le=to(y,{...re?{model:re}:{},...k||{}}),pe=Me(y.bridge.token),j=tt(u,_?.model||g),Z={tier:y.redaction.tier==="full"?"full":"basic",dictionary:Po(y.redaction,M),entities:[]},he=await Be(y),ge=rr({vault:B,redactOpts:Z,bridgeUrl:he,token:pe,harness:J});let de;try{de=await or({bridgeUrl:he,agent:g,token:pe,messages:A,system:ie,specs:sr(v),options:le,signal:void 0,approvals:ir(v)})}catch(n){return De(ge.id),L?.commit(),a(c,502,{error:{message:`bridge: ${n.message}`,type:"bridge_error"}})}return ge.reader=de.body.getReader(),c.writeHead(200,{"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive"}),c.write(j.sseHead()),fo(c,ge,j,L)}async function va(t,c,u,m,g=null){et(c.id),c.rounds=(c.rounds||0)+1;try{const _=g?g.clock():0;await ar(c,u),g&&g.lap("redact",_)}catch(_){return De(c.id),g?.commit(),a(t,502,{error:{message:`tool-result: ${_.message}`,type:"bridge_error"}})}const k=tt("openai",m||"codex");return t.writeHead(200,{"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive"}),t.write(k.sseHead()),fo(t,c,k,g)}function ht(){let t=!1;const c={inputTokens:0,outputTokens:0,cacheReadTokens:0,cacheWriteTokens:0};return{add(u){t=!0;for(const m of Object.keys(c))c[m]+=Math.max(0,Number(u?.[m])||0)},get value(){return t?c:null}}}async function Sa(t,c,{kind:u,adapter:m,redactable:g,pathname:k,agentOverride:_,harness:B,trace:y,run:M=null},v,J,L,A){if(!g)return y?.commit(),a(c,404,{error:`endpoint ${k} not supported by the bridge backend`});if(u==="openai"){const U=m.extractLatestToolResult(v);if(U){const K=Ct(U.tool_call_id),V=K&&Dt(K.gwId);if(V)return va(c,V,U.content,v?.model,y)}const z=m.extractTools(v);if(z.length&&v?.stream===!0)return ka(t,c,{kind:u,adapter:m,agent:_||po(v?.model,L),run:M},v,J,L,A,z,B,y)}const{messages:ie,system:re}=m.toTurn(v),le=_||po(v?.model,L),pe=v?.stream===!0,j=tt(u,v?.model||le),Z=Me(L.bridge.token),he=new AbortController;c.on("close",()=>{c.writableFinished||he.abort()});const{agentModel:ge}=mt(v?.model,L),de={bridgeUrl:await Be(L),agent:le,token:Z,messages:ie,system:re,signal:he.signal,options:to(L,{...ge?{model:ge}:{},...M||{}})};if(!pe)try{let U="";const z=ht(),K=y?y.clock():0;await Bt(de,ye=>{U+=ye},null,ye=>z.add(ye)),y&&y.lap("upstream",K);const V=y?y.clock():0,O=j.full($o(U,J),z.value);return y&&y.lap("restore",V),c.writeHead(200,{"content-type":j.contentType}),c.end(O),y?.commit()}catch(U){return y?.commit(),a(c,502,{error:{message:`bridge backend failed: ${U.message}`,type:"bridge_error"}})}c.writeHead(200,{"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive"}),c.write(j.sseHead());const n=Et(J),o=y?y.clock():0;let f=o;const i=ht();try{let U=!0;await Bt(de,K=>{y&&U&&(y.lap("upstream",o),f=y.clock(),U=!1);const V=n.push(K);V&&c.write(j.sseDelta(V))},j.sseActivity?K=>{try{c.write(j.sseActivity(Eo(K,J)))}catch{}}:null,K=>i.add(K));const z=n.flush();z&&c.write(j.sseDelta(z)),c.write(j.sseTail(i.value))}catch(U){c.write(`data: ${JSON.stringify({error:{message:U.message,type:"bridge_error"}})}
17
17
 
18
- `)}y&&y.lap("stream",le),d.end(),y?.commit()}function ua(t,d,c=""){const m=String(t||"").replace(/\/+$/,""),w=String(d||"").split("/")[1];return w&&m.endsWith(`/${w}`)?m.slice(0,-(w.length+1))+d+c:m+d+c}const ma=9e4;function pa(t,d,c){if(d===c)return t;const m=d/c,w=new Float32Array(Math.floor(t.length/m));for(let g=0;g<w.length;g++){const E=g*m,P=Math.floor(E),y=Math.min(t.length-1,P+1),J=E-P;w[g]=t[P]*(1-J)+t[y]*J}return w}const ha=["/tts","/stt","/ner","/diarize","/skills","/agent-defs","/agent-sessions","/a2a","/redact","/config","/logs","/status","/admin","/v1/browser","/v1/link"];function ht(t,{installing:d=!1}={}){return t.stt?.diarize===!1?"off":d&&t.stt?.allowDownload!==!1?"download":"ondisk"}async function pe(t,d,c,m,{method:w="GET",timeoutMs:g=8e3,pick:E=P=>P}={}){const P=await $e(c);if(!P)return a(d,503,{error:{message:"no bridge is configured",type:"no_bridge"}});const y=Pe(c.bridge?.token),J=w!=="GET"&&w!=="DELETE";try{const b=J?(await v(t,c.maxBodyBytes)).toString("utf8"):"",M=await fetch(`${P}${m}`,{method:w,headers:{Accept:"application/json",...J?{"content-type":"application/json"}:{},...y?{Authorization:`Bearer ${y}`}:{}},...J?{body:b||"{}"}:{},signal:AbortSignal.timeout(g)}),j=await M.json().catch(()=>({}));return M.ok?a(d,200,E(j)):a(d,M.status,{error:{message:j?.error||`bridge ${M.status}`,type:"bridge_error"}})}catch(b){return a(d,502,{error:{message:`bridge unreachable: ${b.message}`,type:"bridge_unreachable"}})}}function yt(t){return!t||t==="."||t===".."||t.includes("/")||t.includes("\\")}function Oe(t,d){const c=new URLSearchParams;for(const g of t.searchParams.getAll("dir"))g&&c.append("dir",g);const m=t.searchParams.get("workdir")||String(d?.bridge?.workingDir||"").trim();m&&c.set("workdir",m);const w=c.toString();return w?`?${w}`:""}async function ya(t,d,{adapter:c,kind:m,pathname:w,search:g,base:E,destKey:P,destProtocol:y,harness:J,trace:b},M,j){let L;const de=b?b.clock():0;try{const R=ia(t.headers,E);P&&(y==="anthropic"?(R["x-api-key"]=P,delete R.authorization):R.authorization=`Bearer ${P}`);const oe=_o(ua(E,w,g)).toString();L=await fetch(oe,{method:t.method,headers:R,body:["GET","HEAD"].includes(t.method)?void 0:M})}catch(R){return b?.commit(),a(d,502,{error:`upstream fetch failed: ${R.message}`})}const re=L.headers.get("content-type")||"",te={};if(L.headers.forEach((R,oe)=>{oo.has(oe.toLowerCase())||(te[oe]=R)}),re.includes("text/event-stream")&&L.body){b&&b.lap("upstream",de);const R=b?b.clock():0;d.writeHead(L.status,te);const oe=m==="openai"?wo(L.body,d,j,J):go(L.body,d,j);return Promise.resolve(oe).finally(()=>{b&&b.lap("stream",R),b?.commit()})}const he=Buffer.from(await L.arrayBuffer());if(b&&b.lap("upstream",de),j&&re.includes("application/json"))try{const R=b?b.clock():0,oe=c.restoreResponse(JSON.parse(he.toString("utf8")),j,J);return b&&b.lap("restore",R),d.writeHead(L.status,{...te,"content-type":"application/json"}),d.end(Buffer.from(JSON.stringify(oe),"utf8")),b?.commit()}catch{}d.writeHead(L.status,te),d.end(he),b?.commit()}function fa(t=vt()){const d=tn({version:Z}),c=t.link?.enabled===!1?null:on({settings:t.link||{},port:t.port,...t.link?.path?{path:t.link.path}:{},dispatch:({method:n,path:o,headers:f,body:i,device:le})=>fetch(`http://127.0.0.1:${t.port}${o}`,{method:n,body:i,headers:{...f,"x-chatpanel-token":je()||Se(),"x-chatpanel-link-device":String(le||"")}}),log:n=>console.log(` ${n}`)});t.stt?.diarizeModel&&t.stt.diarizeModel!==A.activeModel()&&(Ct(t.stt.diarizeModel)?A.setModel(t.stt.diarizeModel,{log:n=>console.log(n)}):console.warn(`[diarize] config names an unknown speaker model (${t.stt.diarizeModel}) — using ${pn}`));let m=null;const w=()=>{if(!m){const n=t.read||{};m=en({remote:n.remote?.url?{url:n.remote.url,key:n.remote.key||""}:null,defaultProvider:n.provider||"defuddle"})}return m};let g=null;const E=()=>(g||(g=Ur({wrap:(n,o,f,i)=>Vr().wrap(n,o,f,i),onLog:n=>console.warn(`[extract worker] ${n}`)})),g);let P={at:0,fn:()=>"unknown"},y=null;async function J(){if(Date.now()-P.at<1e4)return P.fn;let n=new Map;try{const i=await M().health();for(const[le,V]of Object.entries(i)){const H=(t.destinations||[]).filter(U=>U?.service===le).flatMap(U=>[U.id,...U.models||[]]);for(const U of[le,...H])n.set(U,V)}}catch{n=new Map}const o=i=>n.get(i)||"unknown",f=new Map((t.destinations||[]).filter(i=>i?.service).map(i=>[i.id,i.service]));return o.window=i=>{try{return M().contextWindow(f.get(i)||i)}catch{return null}},o.card=i=>{try{return M().modelCard(f.get(i)||i)}catch{return null}},o.sig=JSON.stringify([...n.entries()].sort()),P={at:Date.now(),fn:o},P.fn}let b=null;const M=()=>(b||(b=Wr({cfg:t,bridgeHealth:async()=>{const n=await $e(t);if(!n)return null;const o=Pe(t.bridge?.token),f=await fetch(`${n}/health`,{headers:{Accept:"application/json",...o?{Authorization:`Bearer ${o}`}:{}},signal:AbortSignal.timeout(4e3)});return f.ok?f.json():null},persist:()=>{try{me(t,se())}catch(n){console.warn(`[runtime] could not persist config: ${n.message}`)}},stateDir:Qt.join(Qt.dirname(se()),"runtime"),workers:()=>{const n=g?.status();return n?.running?[{id:"extract",kind:"worker",engine:"extract",command:"extract worker",label:"document extractor",pid:n.pid,sandbox:n.sandbox,refused:[]}]:[]},log:n=>console.log(n)})),b),j=Number(t.runtime?.idleMinutes),L=Qr({warmMs:(Number.isFinite(j)&&j>=0?j:10)*6e4,log:n=>console.log(n)}),de=Kr({cfg:t,wake:(n,o)=>M().wake(n,o),embedded:L}),re=()=>{t.search?.searxng?.url&&M().wake("searxng").catch(()=>{})};let te=null;const he=()=>{if(!te){const n=t.search||{},o=n.searxng?.url?cn({url:n.searxng.url,token:n.searxng.token||"",engines:n.searxng.engines||"",safesearch:n.searxng.safesearch??null}):null;te=sn({reader:w(),searxng:o,defaultProvider:n.provider||"auto",redact:async f=>{let i=f;return await Ie([Xe(()=>i,le=>{i=le})],{...t.redaction,tier:"basic"},{isPro:!0}),i}})}return te};Po(t.allowedExtensionIds||[]);const R=[],oe=n=>{R.push(n),R.length>50&&R.shift()},ce=ho(async(n,o)=>{const f=new URL(n.url,"http://127.0.0.1"),i=f.pathname;if(!We(n.headers.host))return a(o,403,{error:"loopback only"});if(!Zn(n.headers.origin,t))return a(o,403,{error:"origin not allowed"});if(We(t.host)&&nn(n.headers))return a(o,403,{error:{message:"this gateway answers a tunnel only on its Link path (/v1/link)",type:"forbidden"}});if(n.headers.origin&&qn(o,n.headers.origin),n.method==="OPTIONS")return o.writeHead(204),o.end();if(i==="/admin/token"&&n.method==="POST")return z(n)?a(o,200,{token:Se()}):a(o,403,{error:"admin: extension origin or gateway token required"});if(i==="/pair/code"&&n.method==="POST"){if(!z(n))return a(o,403,{error:"pair/code: extension origin or gateway token required"});const e=Ao();return console.log("[gateway] pairing code issued — valid for 5 minutes, one use"),a(o,200,{ok:!0,...e})}if(i==="/pair"&&n.method==="POST"){let e=null;try{e=JSON.parse((await v(n,t.maxBodyBytes)).toString("utf8"))}catch{e=null}const r=No(e?.code);if(!r.ok)return console.log(`[gateway] pairing refused (${r.reason}) from ${Le(n)} caller`),a(o,403,{error:r.reason});console.log(`[gateway] paired a ${Le(n)} client${n.headers.origin?` (${n.headers.origin})`:""}`);const{token:s,refused:l}=await Fo(t);return l&&console.log(`[gateway] pairing: the bridge at ${l.url}${l.version?` (v${l.version})`:""} accepts none of the tokens this gateway holds — not handing one over`),a(o,200,{ok:!0,token:je()||Se(),...s?{bridgeToken:s}:{},...l?{bridgeRefused:l}:{}})}if(i==="/whoami"&&n.method==="POST"){const e=Le(n);return a(o,200,{ok:!0,trust:e,paired:$o(e),version:Z})}if(i==="/audit"&&n.method==="GET")return z(n)?a(o,200,Mo(t,{version:Z,startedAt:ro,managed:Ee()})):a(o,403,{error:"audit: extension origin or gateway token required"});if((i==="/config"||i==="/logs"||i==="/update"&&n.method!=="GET")&&!z(n))return a(o,403,{error:"admin route: extension origin or gateway token required"});if(i==="/update"&&n.method==="GET"){const e=await _r(Z,{force:f.searchParams.get("force")==="1"}).catch(r=>({current:Z,updateAvailable:!1,error:String(r?.message||r)}));return a(o,200,{ok:!0,update:e,job:Pr()})}if(i==="/update"&&n.method==="POST"){const e=$r(Z);return a(o,e.already?409:202,{ok:!0,job:e})}if((i==="/v1/history/key"||i==="/v1/history/ingest-backup")&&n.method==="POST"&&!z(n))return a(o,403,{error:{message:"history key route: extension origin or gateway token required",type:"forbidden"}});if(i==="/v1/history/records"&&n.method==="PUT"&&!z(n))return a(o,403,{error:{message:"history write — extension origin or gateway token required",type:"forbidden"}});if((i==="/v1/history/ingest"||i==="/v1/history/clear")&&n.method==="POST"&&!z(n))return a(o,403,{error:{message:"history write — extension origin or gateway token required",type:"forbidden"}});if((i==="/v1/memory/remember"||i==="/v1/memory/forget"||i==="/v1/memory/sync"||i==="/v1/memory/clear")&&n.method==="POST"&&!z(n))return a(o,403,{error:{message:"memory write — extension origin or gateway token required",type:"forbidden"}});if((i==="/v1/prefs"||i.startsWith("/v1/prefs/")||i.startsWith("/v1/teams")||i.startsWith("/v1/agents")||i.startsWith("/v1/projects"))&&!z(n))return a(o,403,{error:{message:"prefs: extension origin or gateway token required",type:"forbidden"}});if((i==="/v1/browser"||i.startsWith("/v1/browser/"))&&!z(n))return a(o,403,{error:{message:"browser: extension origin or gateway token required",type:"forbidden"}});if((i==="/v1/link"||i.startsWith("/v1/link/"))&&!z(n))return a(o,403,{error:{message:"link: extension origin or gateway token required",type:"forbidden"}});if((i==="/v1/events"||i.startsWith("/v1/events/"))&&!z(n))return a(o,403,{error:{message:"events: extension origin or gateway token required",type:"forbidden"}});if(i.startsWith("/v1/observability")&&!z(n))return a(o,403,{error:{message:"observability: extension origin or gateway token required",type:"forbidden"}});if(n.method==="GET"&&i==="/health"){const e=C.health(),r=$.health();return a(o,200,{ok:!0,version:Z,backend:t.backend,tier:t.redaction.tier,pairing:!0,...Ee()?{managed:Ee()}:{},...process.env.CHATPANEL_MANAGED_BY?{managedBy:String(process.env.CHATPANEL_MANAGED_BY).slice(0,32)}:{},...Be?{bridge:Be.status()}:Ke?{bridge:Ke}:{},search:{provider:t.search?.provider||"auto",searxng:!!t.search?.searxng?.url},stt:{enabled:t.stt?.enabled!==!1,state:e.state,ready:e.ok,model:e.model||t.stt?.model||He,runtime:e.runtime,dtype:e.dtype},tts:{enabled:t.tts?.enabled!==!1,state:r.state,ready:r.ok,model:r.model||t.tts?.model||Ht,voice:t.tts?.voice||fe,runtime:r.runtime,dtype:r.dtype},events:K?{count:K.count(),hosts:K.hosts().length}:null,browser:d.health()})}if(i==="/status"&&n.method==="GET"){fo(t);const e=await we(t.pro?.entitlementToken),r=await io(t);return a(o,200,{ok:!0,version:Z,backend:t.backend,tier:t.redaction.tier,search:{provider:t.search?.provider||"auto",searxng:!!t.search?.searxng?.url},...Ee()?{managed:Ee()}:{},...process.env.CHATPANEL_MANAGED_BY?{managedBy:String(process.env.CHATPANEL_MANAGED_BY).slice(0,32)}:{},ner:{autostart:!!t.ner?.autostart,configured:r.configured,ready:r.ok,model:r.model,url:r.url},detector:mt(t),pro:{unlocked:e},usage:Cn(t),uptimeSeconds:Math.floor((Date.now()-ro)/1e3),update:Er(Z)})}if(i==="/v1/history/ingest"&&n.method==="POST")try{const e=JSON.parse((await v(n,t.maxBodyBytes)).toString("utf8"))||{},r=B.bulk({upserts:Array.isArray(e.upserts)?e.upserts:[],removes:Array.isArray(e.removes)?e.removes:[]});return a(o,200,{ok:!0,size:r})}catch(e){return a(o,400,{error:{message:`ingest failed: ${e.message}`,type:"ingest_error"}})}if(i==="/v1/prefs"&&n.method==="GET"){const e=String(f.searchParams.get("section")||"");return f.searchParams.get("stamps")?a(o,200,{ok:!0,revision:q.revision,stamps:q.stamps()}):a(o,200,{ok:!0,revision:q.revision,sections:q.get(e)})}if(i==="/v1/prefs"&&(n.method==="POST"||n.method==="PUT"))try{const e=JSON.parse((await v(n,t.maxBodyBytes)).toString("utf8"))||{},r=q.put(e.sections||{},{by:e.by||""});return r.applied.length&&Zt(r.applied,e.by||""),a(o,200,{ok:!0,...r})}catch(e){return a(o,400,{error:{message:`prefs write failed: ${e.message}`,type:"prefs_error"}})}if(i==="/v1/prefs"&&n.method==="DELETE"){const e=String(f.searchParams.get("section")||""),r=e?q.remove(e):!1;return r&&Zt([e],""),a(o,200,{ok:!0,removed:r})}if(i==="/v1/prefs/events"&&n.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)}
18
+ `)}y&&y.lap("stream",f),c.end(),y?.commit()}function Ta(t,c,u=""){const m=String(t||"").replace(/\/+$/,""),g=String(c||"").split("/")[1];return g&&m.endsWith(`/${g}`)?m.slice(0,-(g.length+1))+c+u:m+c+u}const xa=9e4;function Oa(t,c,u){if(c===u)return t;const m=c/u,g=new Float32Array(Math.floor(t.length/m));for(let k=0;k<g.length;k++){const _=k*m,B=Math.floor(_),y=Math.min(t.length-1,B+1),M=_-B;g[k]=t[B]*(1-M)+t[y]*M}return g}const go=new WeakMap,_a=["/tts","/stt","/ner","/diarize","/skills","/agent-defs","/agent-sessions","/a2a","/redact","/config","/logs","/status","/admin","/v1/browser","/v1/link"];function yt(t,{installing:c=!1}={}){return t.stt?.diarize===!1?"off":c&&t.stt?.allowDownload!==!1?"download":"ondisk"}async function me(t,c,u,m,{method:g="GET",timeoutMs:k=8e3,pick:_=B=>B}={}){const B=await Be(u);if(!B)return a(c,503,{error:{message:"no bridge is configured",type:"no_bridge"}});const y=Me(u.bridge?.token),M=g!=="GET"&&g!=="DELETE";try{const v=M?(await S(t,u.maxBodyBytes)).toString("utf8"):"",J=await fetch(`${B}${m}`,{method:g,headers:{Accept:"application/json",...M?{"content-type":"application/json"}:{},...y?{Authorization:`Bearer ${y}`}:{}},...M?{body:v||"{}"}:{},signal:AbortSignal.timeout(k)}),L=await J.json().catch(()=>({}));return J.ok?a(c,200,_(L)):a(c,J.status,{error:{message:L?.error||`bridge ${J.status}`,type:"bridge_error"}})}catch(v){return a(c,502,{error:{message:`bridge unreachable: ${v.message}`,type:"bridge_unreachable"}})}}function ft(t){return!t||t==="."||t===".."||t.includes("/")||t.includes("\\")}function Ee(t,c){const u=new URLSearchParams;for(const k of t.searchParams.getAll("dir"))k&&u.append("dir",k);const m=t.searchParams.get("workdir")||String(c?.bridge?.workingDir||"").trim();m&&u.set("workdir",m);const g=u.toString();return g?`?${g}`:""}async function Ea(t,c,{adapter:u,kind:m,pathname:g,search:k,base:_,destKey:B,destProtocol:y,harness:M,trace:v},J,L){let A;const ie=v?v.clock():0;try{const j=ba(t.headers,_);B&&(y==="anthropic"?(j["x-api-key"]=B,delete j.authorization):j.authorization=`Bearer ${B}`);const Z=Do(Ta(_,g,k)).toString();A=await fetch(Z,{method:t.method,headers:j,body:["GET","HEAD"].includes(t.method)?void 0:J})}catch(j){return v?.commit(),a(c,502,{error:`upstream fetch failed: ${j.message}`})}const re=A.headers.get("content-type")||"",le={};if(A.headers.forEach((j,Z)=>{co.has(Z.toLowerCase())||(le[Z]=j)}),re.includes("text/event-stream")&&A.body){v&&v.lap("upstream",ie);const j=v?v.clock():0;c.writeHead(A.status,le);const Z=m==="openai"?_o(A.body,c,L,M):Oo(A.body,c,L);return Promise.resolve(Z).finally(()=>{v&&v.lap("stream",j),v?.commit()})}const pe=Buffer.from(await A.arrayBuffer());if(v&&v.lap("upstream",ie),L&&re.includes("application/json"))try{const j=v?v.clock():0,Z=u.restoreResponse(JSON.parse(pe.toString("utf8")),L,M);return v&&v.lap("restore",j),c.writeHead(A.status,{...le,"content-type":"application/json"}),c.end(Buffer.from(JSON.stringify(Z),"utf8")),v?.commit()}catch{}c.writeHead(A.status,le),c.end(pe),v?.commit()}function $a(t=_t()){const c=zo({first:async n=>{const o=Number(new URL(n).port),f=nn.find(i=>i.port===o&&(i.provides||[]).includes("chat"));return f&&(await J())(f.id)==="up"?{engine:f.id,label:f.label,models:null}:null}}),u=Lo({confirm:n=>typeof t.pairing?.confirm=="function"?t.pairing.confirm(n):Jo(n),newId:()=>Go()}),m=pn({version:X}),g=t.link?.enabled===!1?null:hn({settings:t.link||{},port:t.port,...t.link?.path?{path:t.link.path}:{},dispatch:({method:n,path:o,headers:f,body:i,device:U})=>fetch(`http://127.0.0.1:${t.port}${o}`,{method:n,body:i,headers:{...f,"x-chatpanel-token":Pe()||ve(),"x-chatpanel-link-device":String(U||"")}}),log:n=>console.log(` ${n}`)});t.stt?.diarizeModel&&t.stt.diarizeModel!==P.activeModel()&&(Gt(t.stt.diarizeModel)?P.setModel(t.stt.diarizeModel,{log:n=>console.log(n)}):console.warn(`[diarize] config names an unknown speaker model (${t.stt.diarizeModel}) — using ${On}`));let k=null;const _=()=>{if(!k){const n=t.read||{};k=mn({remote:n.remote?.url?{url:n.remote.url,key:n.remote.key||""}:null,defaultProvider:n.provider||"defuddle"})}return k};let B=null;const y=()=>(B||(B=en({wrap:(n,o,f,i)=>tn().wrap(n,o,f,i),onLog:n=>console.warn(`[extract worker] ${n}`)})),B);let M={at:0,fn:()=>"unknown"},v=null;async function J(){if(Date.now()-M.at<1e4)return M.fn;let n=new Map;try{const i=await A().health();for(const[U,z]of Object.entries(i)){const K=(t.destinations||[]).filter(V=>V?.service===U).flatMap(V=>[V.id,...V.models||[]]);for(const V of[U,...K])n.set(V,z)}}catch{n=new Map}const o=i=>n.get(i)||"unknown",f=new Map((t.destinations||[]).filter(i=>i?.service).map(i=>[i.id,i.service]));return o.window=i=>{try{return A().contextWindow(f.get(i)||i)}catch{return null}},o.card=i=>{try{return A().modelCard(f.get(i)||i)}catch{return null}},o.sig=JSON.stringify([...n.entries()].sort()),M={at:Date.now(),fn:o},M.fn}let L=null;const A=()=>(L||(L=rn({cfg:t,bridgeHealth:async()=>{const n=await Be(t);if(!n)return null;const o=Me(t.bridge?.token),f=await fetch(`${n}/health`,{headers:{Accept:"application/json",...o?{Authorization:`Bearer ${o}`}:{}},signal:AbortSignal.timeout(4e3)});return f.ok?f.json():null},persist:()=>{try{ue(t,ae())}catch(n){console.warn(`[runtime] could not persist config: ${n.message}`)}},stateDir:oo.join(oo.dirname(ae()),"runtime"),workers:()=>{const n=B?.status();return n?.running?[{id:"extract",kind:"worker",engine:"extract",command:"extract worker",label:"document extractor",pid:n.pid,sandbox:n.sandbox,refused:[]}]:[]},log:n=>console.log(n)})),L),ie=Number(t.runtime?.idleMinutes),re=sn({warmMs:(Number.isFinite(ie)&&ie>=0?ie:10)*6e4,log:n=>console.log(n)}),le=an({cfg:t,wake:(n,o)=>A().wake(n,o),embedded:re}),pe=()=>{t.search?.searxng?.url&&A().wake("searxng").catch(()=>{})};let j=null;const Z=()=>{if(!j){const n=t.search||{},o=n.searxng?.url?vn({url:n.searxng.url,token:n.searxng.token||"",engines:n.searxng.engines||"",safesearch:n.searxng.safesearch??null}):null;j=wn({reader:_(),searxng:o,engines:()=>Sn(t),wakeSearxng:()=>A().wake("searxng"),defaultProvider:n.provider||"auto",redact:async f=>{let i=f;return await ze([qe(()=>i,U=>{i=U})],{...t.redaction,tier:"basic"},{isPro:!0}),i}})}return j};Ro(t.allowedExtensionIds||[]);const he=[],ge=n=>{he.push(n),he.length>50&&he.shift()},de=So(async(n,o)=>{const f=new URL(n.url,"http://127.0.0.1"),i=f.pathname;if(!Ye(n.headers.host))return a(o,403,{error:"loopback only"});if(!ca(n.headers.origin,t))return a(o,403,{error:"origin not allowed"});if(Ye(t.host)&&fn(n.headers))return a(o,403,{error:{message:"this gateway answers a tunnel only on its Link path (/v1/link)",type:"forbidden"}});if(n.headers.origin&&ua(o,n.headers.origin),n.method==="OPTIONS")return o.writeHead(204),o.end();if(i==="/admin/token"&&n.method==="POST")return G(n)?a(o,200,{token:ve()}):a(o,403,{error:"admin: extension origin or gateway token required"});if(i==="/pair/code"&&n.method==="POST"){if(!G(n))return a(o,403,{error:"pair/code: extension origin or gateway token required"});const e=Io();return console.log("[gateway] pairing code issued — valid for 5 minutes, one use"),a(o,200,{ok:!0,...e})}if(i==="/pair"&&n.method==="POST"){let e=null;try{e=JSON.parse((await S(n,t.maxBodyBytes)).toString("utf8"))}catch{e=null}const r=jo(e?.code);if(!r.ok)return console.log(`[gateway] pairing refused (${r.reason}) from ${Ae(n)} caller`),a(o,403,{error:r.reason});console.log(`[gateway] paired a ${Ae(n)} client${n.headers.origin?` (${n.headers.origin})`:""}`);const{token:s,refused:l}=await Mt(t);return l&&console.log(`[gateway] pairing: the bridge at ${l.url}${l.version?` (v${l.version})`:""} accepts none of the tokens this gateway holds — not handing one over`),a(o,200,{ok:!0,token:Pe()||ve(),...s?{bridgeToken:s}:{},...l?{bridgeRefused:l}:{}})}if(i==="/pair/ask"&&n.method==="POST"){const e=Ae(n);if(t.pairing?.prompt===!1)return a(o,403,{error:"pairing by confirmation is switched off on this gateway — use a pairing code",type:"disabled"});if($t(e))return a(o,409,{error:"this client is already trusted by the gateway",type:"already"});if(e!=="unpaired")return a(o,403,{error:"pair/ask: only a browser extension may ask to be paired",type:"forbidden"});let r=null;try{r=JSON.parse((await S(n,t.maxBodyBytes)).toString("utf8")||"{}")}catch{r=null}const s=u.ask({browser:r?.browser,who:n.headers.origin||""});if(!s.ok){const l=s.reason==="busy"?"a pairing question is already on screen — answer it, or wait a minute":"too many pairing questions — wait a few minutes, or use a pairing code";return a(o,429,{error:l,type:s.reason})}return console.log(`[gateway] pairing: an unrecognised extension (${n.headers.origin}) asked — the question is on screen`),a(o,202,{ok:!0,id:s.id,number:s.number,expiresAt:s.expiresAt})}if(i==="/pair/ask/result"&&n.method==="POST"){let e=null;try{e=JSON.parse((await S(n,t.maxBodyBytes)).toString("utf8")||"{}")}catch{e=null}const{status:r}=u.result(e?.id,{who:n.headers.origin||""});if(r!=="allowed")return a(o,200,{ok:!0,status:r});console.log(`[gateway] paired ${n.headers.origin} — allowed in the dialog on this computer`);const{token:s,refused:l}=await Mt(t);return a(o,200,{ok:!0,status:r,token:Pe()||ve(),...s?{bridgeToken:s}:{},...l?{bridgeRefused:l}:{}})}if(i==="/whoami"&&n.method==="POST"){const e=Ae(n);return a(o,200,{ok:!0,trust:e,paired:$t(e),version:X})}if(i==="/audit"&&n.method==="GET")return G(n)?a(o,200,Ho(t,{version:X,startedAt:uo,managed:Ne()})):a(o,403,{error:"audit: extension origin or gateway token required"});if((i==="/config"||i==="/logs"||i==="/update"&&n.method!=="GET")&&!G(n))return a(o,403,{error:"admin route: extension origin or gateway token required"});if(i==="/update"&&n.method==="GET"){const e=await Rr(X,{force:f.searchParams.get("force")==="1"}).catch(r=>({current:X,updateAvailable:!1,error:String(r?.message||r)}));return a(o,200,{ok:!0,update:e,job:Lr()})}if(i==="/update"&&n.method==="POST"){const e=jr(X);return a(o,e.already?409:202,{ok:!0,job:e})}if((i==="/v1/history/key"||i==="/v1/history/ingest-backup")&&n.method==="POST"&&!G(n))return a(o,403,{error:{message:"history key route: extension origin or gateway token required",type:"forbidden"}});if(i==="/v1/history/records"&&n.method==="PUT"&&!G(n))return a(o,403,{error:{message:"history write — extension origin or gateway token required",type:"forbidden"}});if((i==="/v1/history/ingest"||i==="/v1/history/clear")&&n.method==="POST"&&!G(n))return a(o,403,{error:{message:"history write — extension origin or gateway token required",type:"forbidden"}});if((i==="/v1/memory/remember"||i==="/v1/memory/forget"||i==="/v1/memory/sync"||i==="/v1/memory/clear")&&n.method==="POST"&&!G(n))return a(o,403,{error:{message:"memory write — extension origin or gateway token required",type:"forbidden"}});if((i==="/v1/prefs"||i.startsWith("/v1/prefs/")||i.startsWith("/v1/teams")||i.startsWith("/v1/agents")||i.startsWith("/v1/projects"))&&!G(n))return a(o,403,{error:{message:"prefs: extension origin or gateway token required",type:"forbidden"}});if((i==="/v1/browser"||i.startsWith("/v1/browser/"))&&!G(n))return a(o,403,{error:{message:"browser: extension origin or gateway token required",type:"forbidden"}});if((i==="/v1/link"||i.startsWith("/v1/link/"))&&!G(n))return a(o,403,{error:{message:"link: extension origin or gateway token required",type:"forbidden"}});if((i==="/v1/events"||i.startsWith("/v1/events/"))&&!G(n))return a(o,403,{error:{message:"events: extension origin or gateway token required",type:"forbidden"}});if(i.startsWith("/v1/observability")&&!G(n))return a(o,403,{error:{message:"observability: extension origin or gateway token required",type:"forbidden"}});if(n.method==="GET"&&i==="/")return o.writeHead(200,{"content-type":"text/plain; charset=utf-8","cache-control":"no-store"}),o.end(`ChatPanel Privacy Gateway v${X} is running.
19
19
 
20
- `);e({type:"hello",revision:q.revision,stamps:q.stamps()});const r=l=>e({type:"changed",...l});dt.add(r);const s=setInterval(()=>{try{o.write(`: keep-alive
20
+ This address is for ChatPanel's apps, not a web page — there is nothing to open here.
21
+ Use ChatPanel itself (the browser extension's Settings, or the desktop app).
22
+ In a terminal, \`chatpanel-gateway --status\` shows what is running.
23
+ `);if(n.method==="GET"&&i==="/health"){const e=$.health(),r=N.health();return a(o,200,{ok:!0,version:X,backend:t.backend,tier:t.redaction.tier,pairing:!0,pairPrompt:t.pairing?.prompt!==!1,...Ne()?{managed:Ne()}:{},...process.env.CHATPANEL_MANAGED_BY?{managedBy:String(process.env.CHATPANEL_MANAGED_BY).slice(0,32)}:{},...Re?{bridge:Re.status()}:Xe?{bridge:Xe}:{},search:{provider:t.search?.provider||"auto",searxng:!!t.search?.searxng?.url},stt:{enabled:t.stt?.enabled!==!1,state:e.state,ready:e.ok,model:e.model||t.stt?.model||Ve,runtime:e.runtime,dtype:e.dtype},tts:{enabled:t.tts?.enabled!==!1,state:r.state,ready:r.ok,model:r.model||t.tts?.model||Yt,voice:t.tts?.voice||be,runtime:r.runtime,dtype:r.dtype},events:Q?{count:Q.count(),hosts:Q.hosts().length}:null,browser:m.health()})}if(i==="/status"&&n.method==="GET"){xo(t);const e=await ke(t.pro?.entitlementToken),r=await yo(t);return a(o,200,{ok:!0,version:X,backend:t.backend,tier:t.redaction.tier,search:{provider:t.search?.provider||"auto",searxng:!!t.search?.searxng?.url},...Ne()?{managed:Ne()}:{},...process.env.CHATPANEL_MANAGED_BY?{managedBy:String(process.env.CHATPANEL_MANAGED_BY).slice(0,32)}:{},ner:{autostart:!!t.ner?.autostart,configured:r.configured,ready:r.ok,model:r.model,url:r.url},detector:pt(t),pro:{unlocked:e},usage:Wn(t),uptimeSeconds:Math.floor((Date.now()-uo)/1e3),update:Ir(X)})}if(i==="/v1/history/ingest"&&n.method==="POST")try{const e=JSON.parse((await S(n,t.maxBodyBytes)).toString("utf8"))||{},r=R.bulk({upserts:Array.isArray(e.upserts)?e.upserts:[],removes:Array.isArray(e.removes)?e.removes:[]});return a(o,200,{ok:!0,size:r})}catch(e){return a(o,400,{error:{message:`ingest failed: ${e.message}`,type:"ingest_error"}})}if(i==="/v1/prefs"&&n.method==="GET"){const e=String(f.searchParams.get("section")||"");return f.searchParams.get("stamps")?a(o,200,{ok:!0,revision:te.revision,stamps:te.stamps()}):a(o,200,{ok:!0,revision:te.revision,sections:te.get(e)})}if(i==="/v1/prefs"&&(n.method==="POST"||n.method==="PUT"))try{const e=JSON.parse((await S(n,t.maxBodyBytes)).toString("utf8"))||{},r=te.put(e.sections||{},{by:e.by||""});return r.applied.length&&ao(r.applied,e.by||""),a(o,200,{ok:!0,...r})}catch(e){return a(o,400,{error:{message:`prefs write failed: ${e.message}`,type:"prefs_error"}})}if(i==="/v1/prefs"&&n.method==="DELETE"){const e=String(f.searchParams.get("section")||""),r=e?te.remove(e):!1;return r&&ao([e],""),a(o,200,{ok:!0,removed:r})}if(i==="/v1/prefs/events"&&n.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)}
21
24
 
22
- `)}catch{}},25e3);o.on("close",()=>{dt.delete(r),clearInterval(s)});return}if(i==="/v1/projects"&&n.method==="GET")return a(o,200,{ok:!0,projects:ee.list({limit:f.searchParams.get("limit")||50,status:f.searchParams.get("status")||""})});if(i==="/v1/projects/jobs"&&n.method==="GET")return a(o,200,{ok:!0,jobs:ee.openJobs()});if(i==="/v1/projects"&&n.method==="POST")try{const e=JSON.parse((await v(n,t.maxBodyBytes)).toString("utf8"))||{};return a(o,200,{ok:!0,project:ee.create({id:e.id||e.project?.id,project:e.project||null,by:e.by})})}catch(e){return a(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(i);if(e){const r=e[1],s=e[2]||"",l=e[3]||"",u=e[4]||"",k=()=>a(o,404,{error:{message:`no project ${r}`,type:"not_found"}});if(u){const h=ee.get(r);if(!h)return k();const x=h.jobs.find(p=>p.id===l);if(!x)return a(o,404,{error:{message:`no job ${l}`,type:"not_found"}});const T={cfg:t,prefsStore:q,scorecards:Te,engines:xe};if(u==="/applications"&&n.method==="GET"){const p=await Sr(x,{...T,reach:f.searchParams.get("reach")||"any",chatModel:f.searchParams.get("chatModel")||null});return a(o,200,{ok:!0,job:x,...p})}if(u==="/recruit"&&n.method==="POST"){if(!["open","evaluating"].includes(x.status))return a(o,400,{error:{message:`job ${l} is ${x.status}; only an open job is recruited`,type:"project_error"}});try{const p=JSON.parse((await v(n,t.maxBodyBytes)).toString("utf8"))||{},O=String(p.by||"evaluator").slice(0,80),_=await Tr(x,{...T,record:h,reach:p.reach||"any",chatModel:p.chatModel||null,evaluation:p.evaluation||null,text:p.text??null,by:O});let I=null;for(const Q of _.events)Q.type==="job.updated"?I=ee.updateJob(r,l,Q.job,{by:Q.by||O}):I=ee.append(r,[Q]);return a(o,200,{ok:!0,project:I,decision:_.decision,applications:_.applications,evaluation:_.evaluation})}catch(p){return a(o,400,{error:{message:`recruit: ${p.message}`,type:"project_error"}})}}return a(o,405,{error:{message:"method not allowed",type:"project_error"}})}if(!s&&n.method==="GET"){const h=ee.get(r,{events:f.searchParams.get("events")==="1"});return h?a(o,200,{ok:!0,project:h}):k()}if(!s&&n.method==="DELETE")return a(o,200,{ok:!0,removed:ee.remove(r)});if(n.method==="POST"&&(s==="/events"||s.startsWith("/jobs")))try{const h=JSON.parse((await v(n,t.maxBodyBytes)).toString("utf8"))||{},x=String(h.by||"person").slice(0,80),T=s==="/events"?ee.append(r,h.events||[]):l?ee.updateJob(r,l,h.patch||h,{by:x}):ee.postJob(r,h.job||h,{by:x});return a(o,200,{ok:!0,project:T})}catch(h){return a(o,h.message.startsWith("no ")?404:400,{error:{message:`project: ${h.message}`,type:"project_error"}})}if(s==="/events"&&n.method==="GET"){if(!ee.get(r))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)}
25
+ `);e({type:"hello",revision:te.revision,stamps:te.stamps()});const r=l=>e({type:"changed",...l});ct.add(r);const s=setInterval(()=>{try{o.write(`: keep-alive
23
26
 
24
- `);let x=f.searchParams.has("after")?Number(f.searchParams.get("after")):-1;h({seq:-1,type:"hello",at:Date.now(),payload:{project:ee.get(r),after:x}});const T=ee.watch(r,O=>{O.seq>x&&(x=O.seq,h(O))});for(const O of ee.eventsSince(r,x))x=O.seq,h(O);const p=setInterval(()=>{try{o.write(`: keep
27
+ `)}catch{}},25e3);o.on("close",()=>{ct.delete(r),clearInterval(s)});return}if(i==="/v1/projects"&&n.method==="GET")return a(o,200,{ok:!0,projects:oe.list({limit:f.searchParams.get("limit")||50,status:f.searchParams.get("status")||""})});if(i==="/v1/projects/jobs"&&n.method==="GET")return a(o,200,{ok:!0,jobs:oe.openJobs()});if(i==="/v1/projects"&&n.method==="POST")try{const e=JSON.parse((await S(n,t.maxBodyBytes)).toString("utf8"))||{};return a(o,200,{ok:!0,project:oe.create({id:e.id||e.project?.id,project:e.project||null,by:e.by})})}catch(e){return a(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(i);if(e){const r=e[1],s=e[2]||"",l=e[3]||"",d=e[4]||"",h=()=>a(o,404,{error:{message:`no project ${r}`,type:"not_found"}});if(d){const p=oe.get(r);if(!p)return h();const T=p.jobs.find(b=>b.id===l);if(!T)return a(o,404,{error:{message:`no job ${l}`,type:"not_found"}});const w={cfg:t,prefsStore:te,scorecards:Oe,engines:_e,engineAt:c.engineAt};if(d==="/applications"&&n.method==="GET"){const b=await Br(T,{...w,reach:f.searchParams.get("reach")||"any",chatModel:f.searchParams.get("chatModel")||null});return a(o,200,{ok:!0,job:T,...b})}if(d==="/recruit"&&n.method==="POST"){if(!["open","evaluating"].includes(T.status))return a(o,400,{error:{message:`job ${l} is ${T.status}; only an open job is recruited`,type:"project_error"}});try{const b=JSON.parse((await S(n,t.maxBodyBytes)).toString("utf8"))||{},E=String(b.by||"evaluator").slice(0,80),x=await Mr(T,{...w,record:p,reach:b.reach||"any",chatModel:b.chatModel||null,evaluation:b.evaluation||null,text:b.text??null,by:E});let I=null;for(const Y of x.events)Y.type==="job.updated"?I=oe.updateJob(r,l,Y.job,{by:Y.by||E}):I=oe.append(r,[Y]);return a(o,200,{ok:!0,project:I,decision:x.decision,applications:x.applications,evaluation:x.evaluation})}catch(b){return a(o,400,{error:{message:`recruit: ${b.message}`,type:"project_error"}})}}return a(o,405,{error:{message:"method not allowed",type:"project_error"}})}if(!s&&n.method==="GET"){const p=oe.get(r,{events:f.searchParams.get("events")==="1"});return p?a(o,200,{ok:!0,project:p}):h()}if(!s&&n.method==="DELETE")return a(o,200,{ok:!0,removed:oe.remove(r)});if(n.method==="POST"&&(s==="/events"||s.startsWith("/jobs")))try{const p=JSON.parse((await S(n,t.maxBodyBytes)).toString("utf8"))||{},T=String(p.by||"person").slice(0,80),w=s==="/events"?oe.append(r,p.events||[]):l?oe.updateJob(r,l,p.patch||p,{by:T}):oe.postJob(r,p.job||p,{by:T});return a(o,200,{ok:!0,project:w})}catch(p){return a(o,p.message.startsWith("no ")?404:400,{error:{message:`project: ${p.message}`,type:"project_error"}})}if(s==="/events"&&n.method==="GET"){if(!oe.get(r))return h();o.writeHead(200,{"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive"});const p=E=>o.write(`data: ${JSON.stringify(E)}
25
28
 
26
- `)}catch{}},25e3);n.on("close",()=>{clearInterval(p),T()});return}}}if(i==="/v1/agents/scorecards"&&n.method==="GET")return a(o,200,{ok:!0,agents:Te.list()});{const e=/^\/v1\/agents\/([a-zA-Z0-9_.:@+-]{1,120})\/scorecard$/.exec(i);if(e){const r=decodeURIComponent(e[1]);if(n.method==="GET")return a(o,200,{ok:!0,...await Te.get(r)});if(n.method==="POST")try{const s=JSON.parse((await v(n,t.maxBodyBytes)).toString("utf8"))||{},l=await Te.append({agentId:r,kind:"rating",runId:s.runId,taskId:s.taskId,jobId:s.jobId,rating:{by:String(s.by||"person").slice(0,40),score:s.score,note:s.note,about:s.about},refs:s.refs});return xe.fromRating(Te.chains.get(r)||[],{...l,jobKind:s.jobKind?String(s.jobKind).slice(0,60):void 0}),a(o,200,{ok:!0,entry:l})}catch(s){return a(o,400,{error:{message:`scorecard: ${s.message}`,type:"scorecard_error"}})}}}if(i==="/v1/capabilities"&&n.method==="GET")return a(o,200,Gr(t,{version:Z,reader:m,searcher:te,extract:E(),proxy:de}));if(i==="/v1/fusions"&&n.method==="GET"){const e={active:N.health().model||t.ner?.model||null,companions:N.companions()};let r=null;try{r=await M().status()}catch{r=null}return a(o,200,Cr({cfg:t,ner:e,runtimeDoc:r}))}if(i==="/v1/runtime"&&n.method==="GET"){const e=Object.fromEntries(Xr.map(r=>{const s=nt(t,r);return[r,{provider:s.kind,model:s.kind==="embedded"?s.model:null,models:Yr[r],threads:L.threads,...s.kind==="embedded"?L.health(r,s.model):{}}]}));return a(o,200,{...await M().status(),inProcess:e})}if(i==="/v1/runtime/plan"&&n.method==="GET"){const e=new URL(n.url,"http://x").searchParams,r=await M().plan(String(e.get("service")||"mlx"),{model:e.get("model")||void 0,ctx:e.get("ctx"),needMB:e.get("need_mb")});return a(o,r.ok?200:400,r)}{const e=/^\/v1\/runtime\/(engines|services)\/([a-z0-9-]+)$/.exec(i);if(e&&n.method==="POST"){if(!z(n))return a(o,403,{error:"runtime: extension origin or gateway token required"});let r={};try{r=JSON.parse((await v(n,t.maxBodyBytes)).toString("utf8")||"{}")}catch{r={}}const s=String(r.action||"start"),l=M(),u=e[1]==="engines"?s==="start"?await l.startEngine(e[2]):{ok:!1,error:`unknown action ${s}`}:s==="start"?await l.startService(e[2],{force:r.force===!0}):s==="stop"?await l.stopService(e[2]):s==="model"?await l.setModel(e[2],r.model):s==="tune"?await l.setTunings(e[2],r.tunings):s==="profile"?await l.setProfile(e[2],r.profile):s==="pull"?await l.pullModel(e[2]):s==="install"?await l.installRunner(e[2]):s==="cancel"?l.cancelJob(e[2]):{ok:!1,error:`unknown action ${s}`};return a(o,u.ok?200:400,u)}}if((i==="/v1/rerank"||i==="/v1/decide")&&n.method==="POST"){const e=i.slice(4);let r;try{r=JSON.parse((await v(n,t.maxBodyBytes)).toString("utf8"))}catch{return a(o,400,{error:{message:`${e}: body must be JSON`,type:"invalid_request"}})}const s=await de.call(e,r);return a(o,s.status,s.body)}if(i==="/v1/detect"&&n.method==="POST"){let e;try{e=JSON.parse((await v(n,t.maxBodyBytes)).toString("utf8"))}catch{return a(o,400,{error:{message:"detect: body must be JSON",type:"invalid_request"}})}try{const r=await Hr(e,{ensure:()=>Ge(t),model:N.health().model});return a(o,r.status,r.body)}catch(r){return a(o,500,{error:{message:`detect: ${r.message}`,type:"detector_error"}})}}if(i==="/v1/extract"&&n.method==="POST"){let e;try{e=JSON.parse((await v(n,Math.max(t.maxBodyBytes,Math.ceil(qr*4/3)+1024))).toString("utf8"))}catch{return a(o,400,{error:{message:"extract: body must be JSON",type:"invalid_request"}})}const r=await Zr(e,{service:E()});return a(o,r.status,r.body)}if(i==="/v1/read"&&n.method==="POST"){let e;try{e=JSON.parse((await v(n,t.maxBodyBytes)).toString("utf8"))}catch{return a(o,400,{error:{message:"read: body must be JSON",type:"invalid_request"}})}const r=await w().read(e);return a(o,r.status,r.body)}if(i==="/v1/search"&&n.method==="POST"){let e;try{e=JSON.parse((await v(n,t.maxBodyBytes)).toString("utf8"))}catch{return a(o,400,{error:{message:"search: body must be JSON",type:"invalid_request"}})}re();const r=await he().search(e);return a(o,r.status,r.body)}if(/^\/v1\/search\/./.test(i)&&n.method==="GET"){let e;try{e=decodeURIComponent(i.slice(11))}catch{e=i.slice(11)}const r=f.searchParams.has("read")?Math.max(0,Math.min(10,Number(f.searchParams.get("read"))||0)):dn.aliasRead;re();const s=await he().search({q:e,read:r,limit:Math.max(r,5)});return a(o,s.status,s.status===200?ln(s.body):s.body)}if(/^\/v1\/read\/./.test(i)&&n.method==="GET"){const e=String(n.url||"").slice(9),r=/^https?:\/\//i.test(e)?e:decodeURIComponent(e),s=/application\/json/i.test(n.headers.accept||""),l=/^text$/i.test(n.headers["x-return-format"]||"")?"text":"markdown",u=await w().read({url:r,format:l});return u.status!==200||s?a(o,u.status,u.status===200?{code:200,status:2e4,data:u.body}:u.body):(o.writeHead(200,{"content-type":"text/plain; charset=utf-8","x-chatpanel-provider":u.body.provider}),o.end(un(u.body)))}if(i==="/v1/engines"&&n.method==="GET"){const e=Number(f.searchParams.get("minCalls"))||void 0;return a(o,200,{ok:!0,engines:xe.list({minCalls:e})})}{const e=/^\/v1\/engines\/(.+)\/(card|entries)$/.exec(i);if(e){const r=decodeURIComponent(e[1]).slice(0,300);if(e[2]==="card"&&n.method==="GET"){const s=Number(f.searchParams.get("minCalls"))||void 0;return a(o,200,{ok:!0,...await xe.get(r,{entries:f.searchParams.get("entries")==="1",minCalls:s})})}if(e[2]==="entries"&&n.method==="POST")try{const s=JSON.parse((await v(n,t.maxBodyBytes)).toString("utf8"))||{},l=s.engine||ta(r);if(!l)return a(o,400,{error:{message:"model-ledger: engine required",type:"model_ledger_error"}});const u=await xe.append({...s,engine:l,kind:s.kind||"call"});return u.key!==r?a(o,400,{error:{message:`model-ledger: entry is for ${u.key}, not ${r}`,type:"model_ledger_error"}}):a(o,200,{ok:!0,entry:u})}catch(s){return a(o,400,{error:{message:`model-ledger: ${s.message}`,type:"model_ledger_error"}})}}}if(i==="/v1/teams/stream"&&n.method==="GET"){o.writeHead(200,{"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive"});const e=l=>{try{o.write(`data: ${JSON.stringify(l)}
29
+ `);let T=f.searchParams.has("after")?Number(f.searchParams.get("after")):-1;p({seq:-1,type:"hello",at:Date.now(),payload:{project:oe.get(r),after:T}});const w=oe.watch(r,E=>{E.seq>T&&(T=E.seq,p(E))});for(const E of oe.eventsSince(r,T))T=E.seq,p(E);const b=setInterval(()=>{try{o.write(`: keep
30
+
31
+ `)}catch{}},25e3);n.on("close",()=>{clearInterval(b),w()});return}}}if(i==="/v1/agents/scorecards"&&n.method==="GET")return a(o,200,{ok:!0,agents:Oe.list()});{const e=/^\/v1\/agents\/([a-zA-Z0-9_.:@+-]{1,120})\/scorecard$/.exec(i);if(e){const r=decodeURIComponent(e[1]);if(n.method==="GET")return a(o,200,{ok:!0,...await Oe.get(r)});if(n.method==="POST")try{const s=JSON.parse((await S(n,t.maxBodyBytes)).toString("utf8"))||{},l=await Oe.append({agentId:r,kind:"rating",runId:s.runId,taskId:s.taskId,jobId:s.jobId,rating:{by:String(s.by||"person").slice(0,40),score:s.score,note:s.note,about:s.about},refs:s.refs});return _e.fromRating(Oe.chains.get(r)||[],{...l,jobKind:s.jobKind?String(s.jobKind).slice(0,60):void 0}),a(o,200,{ok:!0,entry:l})}catch(s){return a(o,400,{error:{message:`scorecard: ${s.message}`,type:"scorecard_error"}})}}}if(i==="/v1/capabilities"&&n.method==="GET")return a(o,200,Zr(t,{version:X,reader:k,searcher:j,extract:y(),proxy:le}));if(i==="/v1/fusions"&&n.method==="GET"){const e={active:C.health().model||t.ner?.model||null,companions:C.companions()};let r=null;try{r=await A().status()}catch{r=null}return a(o,200,Vr({cfg:t,ner:e,runtimeDoc:r}))}if(i==="/v1/runtime"&&n.method==="GET"){const e=Object.fromEntries(dn.map(r=>{const s=st(t,r);return[r,{provider:s.kind,model:s.kind==="embedded"?s.model:null,models:ln[r],threads:re.threads,...s.kind==="embedded"?re.health(r,s.model):{}}]}));return a(o,200,{...await A().status(),inProcess:e})}if(i==="/v1/runtime/plan"&&n.method==="GET"){const e=new URL(n.url,"http://x").searchParams,r=await A().plan(String(e.get("service")||"mlx"),{model:e.get("model")||void 0,ctx:e.get("ctx"),needMB:e.get("need_mb")});return a(o,r.ok?200:400,r)}{const e=/^\/v1\/runtime\/(engines|services)\/([a-z0-9-]+)$/.exec(i);if(e&&n.method==="POST"){if(!G(n))return a(o,403,{error:"runtime: extension origin or gateway token required"});let r={};try{r=JSON.parse((await S(n,t.maxBodyBytes)).toString("utf8")||"{}")}catch{r={}}const s=String(r.action||"start"),l=A(),d=e[1]==="engines"?s==="start"?await l.startEngine(e[2]):{ok:!1,error:`unknown action ${s}`}:s==="start"?await l.startService(e[2],{force:r.force===!0}):s==="stop"?await l.stopService(e[2]):s==="model"?await l.setModel(e[2],r.model):s==="tune"?await l.setTunings(e[2],r.tunings):s==="profile"?await l.setProfile(e[2],r.profile):s==="pull"?await l.pullModel(e[2]):s==="install"?await l.installRunner(e[2]):s==="cancel"?l.cancelJob(e[2]):{ok:!1,error:`unknown action ${s}`};return a(o,d.ok?200:400,d)}}if((i==="/v1/rerank"||i==="/v1/decide")&&n.method==="POST"){const e=i.slice(4);let r;try{r=JSON.parse((await S(n,t.maxBodyBytes)).toString("utf8"))}catch{return a(o,400,{error:{message:`${e}: body must be JSON`,type:"invalid_request"}})}const s=await le.call(e,r);return a(o,s.status,s.body)}if(i==="/v1/detect"&&n.method==="POST"){let e;try{e=JSON.parse((await S(n,t.maxBodyBytes)).toString("utf8"))}catch{return a(o,400,{error:{message:"detect: body must be JSON",type:"invalid_request"}})}try{const r=await qr(e,{ensure:()=>He(t),model:C.health().model});return a(o,r.status,r.body)}catch(r){return a(o,500,{error:{message:`detect: ${r.message}`,type:"detector_error"}})}}if(i==="/v1/extract"&&n.method==="POST"){let e;try{e=JSON.parse((await S(n,Math.max(t.maxBodyBytes,Math.ceil(un*4/3)+1024))).toString("utf8"))}catch{return a(o,400,{error:{message:"extract: body must be JSON",type:"invalid_request"}})}const r=await cn(e,{service:y()});return a(o,r.status,r.body)}if(i==="/v1/read"&&n.method==="POST"){let e;try{e=JSON.parse((await S(n,t.maxBodyBytes)).toString("utf8"))}catch{return a(o,400,{error:{message:"read: body must be JSON",type:"invalid_request"}})}const r=await _().read(e);return a(o,r.status,r.body)}if(i==="/v1/search"&&n.method==="POST"){let e;try{e=JSON.parse((await S(n,t.maxBodyBytes)).toString("utf8"))}catch{return a(o,400,{error:{message:"search: body must be JSON",type:"invalid_request"}})}pe();const r=await Z().search(e);return a(o,r.status,r.body)}if(/^\/v1\/search\/./.test(i)&&n.method==="GET"){let e;try{e=decodeURIComponent(i.slice(11))}catch{e=i.slice(11)}const r=f.searchParams.has("read")?Math.max(0,Math.min(10,Number(f.searchParams.get("read"))||0)):kn.aliasRead;pe();const s=await Z().search({q:e,read:r,limit:Math.max(r,5)});return a(o,s.status,s.status===200?bn(s.body):s.body)}if(/^\/v1\/read\/./.test(i)&&n.method==="GET"){const e=String(n.url||"").slice(9),r=/^https?:\/\//i.test(e)?e:decodeURIComponent(e),s=/application\/json/i.test(n.headers.accept||""),l=/^text$/i.test(n.headers["x-return-format"]||"")?"text":"markdown",d=await _().read({url:r,format:l});return d.status!==200||s?a(o,d.status,d.status===200?{code:200,status:2e4,data:d.body}:d.body):(o.writeHead(200,{"content-type":"text/plain; charset=utf-8","x-chatpanel-provider":d.body.provider}),o.end(Tn(d.body)))}if(i==="/v1/engines"&&n.method==="GET"){const e=Number(f.searchParams.get("minCalls"))||void 0;return a(o,200,{ok:!0,engines:_e.list({minCalls:e})})}{const e=/^\/v1\/engines\/(.+)\/(card|entries)$/.exec(i);if(e){const r=decodeURIComponent(e[1]).slice(0,300);if(e[2]==="card"&&n.method==="GET"){const s=Number(f.searchParams.get("minCalls"))||void 0;return a(o,200,{ok:!0,...await _e.get(r,{entries:f.searchParams.get("entries")==="1",minCalls:s})})}if(e[2]==="entries"&&n.method==="POST")try{const s=JSON.parse((await S(n,t.maxBodyBytes)).toString("utf8"))||{},l=s.engine||pa(r);if(!l)return a(o,400,{error:{message:"model-ledger: engine required",type:"model_ledger_error"}});const d=await _e.append({...s,engine:l,kind:s.kind||"call"});return d.key!==r?a(o,400,{error:{message:`model-ledger: entry is for ${d.key}, not ${r}`,type:"model_ledger_error"}}):a(o,200,{ok:!0,entry:d})}catch(s){return a(o,400,{error:{message:`model-ledger: ${s.message}`,type:"model_ledger_error"}})}}}if(i==="/v1/teams/stream"&&n.method==="GET"){o.writeHead(200,{"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive"});const e=l=>{try{o.write(`data: ${JSON.stringify(l)}
27
32
 
28
33
  `)}catch{}};e({type:"hello",at:Date.now()});const r=W.watchAll(l=>e({type:"run",id:l.id,removed:!!l.removed})),s=setInterval(()=>{try{o.write(`: keep-alive
29
34
 
30
- `)}catch{}},25e3);o.on("close",()=>{r(),clearInterval(s)});return}if(i==="/v1/teams/runs"&&n.method==="GET")return a(o,200,{ok:!0,runs:W.list({limit:f.searchParams.get("limit")||50,team:f.searchParams.get("team")||""})});if(i==="/v1/teams/runs"&&n.method==="POST")try{const e=JSON.parse((await v(n,t.maxBodyBytes)).toString("utf8"))||{};return a(o,200,{ok:!0,run:W.create({id:e.id,client:e.client,team:e.team,request:e.request})})}catch(e){return a(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(i);if(e){const r=e[1],s=e[2]||"";if(!s&&n.method==="GET"){const l=W.get(r,{events:f.searchParams.get("events")==="1"});return l?a(o,200,{ok:!0,run:l}):a(o,404,{error:{message:`no run ${r}`,type:"not_found"}})}if(!s&&n.method==="DELETE")return W.stop(r),a(o,200,{ok:!0,removed:W.remove(r)});if(s==="/stop"&&n.method==="POST"){const l=W.stop(r);return l?a(o,200,{ok:!0,run:l}):a(o,404,{error:{message:`no run ${r}`,type:"not_found"}})}if(s==="/checkpoint"&&n.method==="GET")try{return a(o,200,{ok:!0,checkpoint:W.checkpoint(r)})}catch(l){return a(o,404,{error:{message:`team run: ${l.message}`,type:"team_error"}})}if((s==="/handoff"||s==="/claim")&&n.method==="POST")try{const l=JSON.parse((await v(n,t.maxBodyBytes)).toString("utf8"))||{},u=s==="/handoff"?W.handoff(r,{taskId:l.taskId,model:l.model,by:l.by,reason:l.reason}):W.claim(r,{client:l.client});return a(o,200,{ok:!0,run:u})}catch(l){return a(o,l.message.startsWith("no ")?404:400,{error:{message:`team run: ${l.message}`,type:"team_error"}})}if(s.startsWith("/threads/")&&n.method==="DELETE")try{return a(o,200,{ok:!0,run:W.removeThread(r,{threadId:s.slice(9),by:"person"})})}catch(l){return a(o,l.message.startsWith("no ")?404:400,{error:{message:`team run: ${l.message}`,type:"team_error"}})}if((s==="/answer"||s==="/decide"||s==="/post")&&n.method==="POST")try{const l=JSON.parse((await v(n,t.maxBodyBytes)).toString("utf8"))||{},u=String(l.by||"person").slice(0,40),k=s==="/answer"?W.answer(r,{threadId:l.threadId,text:l.text,by:u}):s==="/decide"?W.decide(r,{postId:l.postId,status:l.status,by:u}):W.post(r,{threadId:l.threadId,text:l.text,by:u,kind:l.kind,replyTo:l.replyTo});return a(o,200,{ok:!0,run:k})}catch(l){return a(o,l.message.startsWith("no ")?404:400,{error:{message:`team run: ${l.message}`,type:"team_error"}})}if(s==="/events"&&n.method==="POST")try{const l=JSON.parse((await v(n,t.maxBodyBytes)).toString("utf8"))||{};return a(o,200,{ok:!0,run:W.append(r,l.events||[])})}catch(l){return a(o,l.message.startsWith("no run")?404:400,{error:{message:`team run: ${l.message}`,type:"team_error"}})}if(s==="/events"&&n.method==="GET"){if(!W.get(r))return a(o,404,{error:{message:`no run ${r}`,type:"not_found"}});o.writeHead(200,{"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive"});const l=T=>o.write(`data: ${JSON.stringify(T)}
35
+ `)}catch{}},25e3);o.on("close",()=>{r(),clearInterval(s)});return}if(i==="/v1/teams/runs"&&n.method==="GET")return a(o,200,{ok:!0,runs:W.list({limit:f.searchParams.get("limit")||50,team:f.searchParams.get("team")||""})});if(i==="/v1/teams/runs"&&n.method==="POST")try{const e=JSON.parse((await S(n,t.maxBodyBytes)).toString("utf8"))||{};return a(o,200,{ok:!0,run:W.create({id:e.id,client:e.client,team:e.team,request:e.request})})}catch(e){return a(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(i);if(e){const r=e[1],s=e[2]||"";if(!s&&n.method==="GET"){const l=W.get(r,{events:f.searchParams.get("events")==="1"});return l?a(o,200,{ok:!0,run:l}):a(o,404,{error:{message:`no run ${r}`,type:"not_found"}})}if(!s&&n.method==="DELETE")return W.stop(r),a(o,200,{ok:!0,removed:W.remove(r)});if(s==="/stop"&&n.method==="POST"){const l=W.stop(r);return l?a(o,200,{ok:!0,run:l}):a(o,404,{error:{message:`no run ${r}`,type:"not_found"}})}if(s==="/checkpoint"&&n.method==="GET")try{return a(o,200,{ok:!0,checkpoint:W.checkpoint(r)})}catch(l){return a(o,404,{error:{message:`team run: ${l.message}`,type:"team_error"}})}if((s==="/handoff"||s==="/claim")&&n.method==="POST")try{const l=JSON.parse((await S(n,t.maxBodyBytes)).toString("utf8"))||{},d=s==="/handoff"?W.handoff(r,{taskId:l.taskId,model:l.model,by:l.by,reason:l.reason}):W.claim(r,{client:l.client});return a(o,200,{ok:!0,run:d})}catch(l){return a(o,l.message.startsWith("no ")?404:400,{error:{message:`team run: ${l.message}`,type:"team_error"}})}if(s.startsWith("/threads/")&&n.method==="DELETE")try{return a(o,200,{ok:!0,run:W.removeThread(r,{threadId:s.slice(9),by:"person"})})}catch(l){return a(o,l.message.startsWith("no ")?404:400,{error:{message:`team run: ${l.message}`,type:"team_error"}})}if((s==="/answer"||s==="/decide"||s==="/post")&&n.method==="POST")try{const l=JSON.parse((await S(n,t.maxBodyBytes)).toString("utf8"))||{},d=String(l.by||"person").slice(0,40),h=s==="/answer"?W.answer(r,{threadId:l.threadId,text:l.text,by:d}):s==="/decide"?W.decide(r,{postId:l.postId,status:l.status,by:d}):W.post(r,{threadId:l.threadId,text:l.text,by:d,kind:l.kind,replyTo:l.replyTo});return a(o,200,{ok:!0,run:h})}catch(l){return a(o,l.message.startsWith("no ")?404:400,{error:{message:`team run: ${l.message}`,type:"team_error"}})}if(s==="/events"&&n.method==="POST")try{const l=JSON.parse((await S(n,t.maxBodyBytes)).toString("utf8"))||{};return a(o,200,{ok:!0,run:W.append(r,l.events||[])})}catch(l){return a(o,l.message.startsWith("no run")?404:400,{error:{message:`team run: ${l.message}`,type:"team_error"}})}if(s==="/events"&&n.method==="GET"){if(!W.get(r))return a(o,404,{error:{message:`no run ${r}`,type:"not_found"}});o.writeHead(200,{"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive"});const l=w=>o.write(`data: ${JSON.stringify(w)}
31
36
 
32
- `),u=f.searchParams.has("after")?Number(f.searchParams.get("after")):NaN;let k=Number.isFinite(u)?u:-1;l({seq:-1,type:"hello",at:Date.now(),payload:{run:W.get(r),after:k}});const h=W.watch(r,T=>{T.seq==null?l(T):T.seq>k&&(k=T.seq,l(T))});for(const T of W.eventsSince(r,k))k=T.seq,l(T);const x=setInterval(()=>{try{o.write(`: keep-alive
37
+ `),d=f.searchParams.has("after")?Number(f.searchParams.get("after")):NaN;let h=Number.isFinite(d)?d:-1;l({seq:-1,type:"hello",at:Date.now(),payload:{run:W.get(r),after:h}});const p=W.watch(r,w=>{w.seq==null?l(w):w.seq>h&&(h=w.seq,l(w))});for(const w of W.eventsSince(r,h))h=w.seq,l(w);const T=setInterval(()=>{try{o.write(`: keep-alive
33
38
 
34
- `)}catch{}},25e3);o.on("close",()=>{h(),clearInterval(x)});return}}}if(i==="/v1/memory/list"&&n.method==="GET")return a(o,200,{ok:!0,size:ie.size,memories:ie.list()});if(i==="/v1/memory/recall"&&n.method==="POST")try{const e=JSON.parse((await v(n,t.maxBodyBytes)).toString("utf8"))||{},r=ie.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 a(o,200,{ok:!0,size:ie.size,...r})}catch(e){return a(o,400,{error:{message:`recall failed: ${e.message}`,type:"memory_error"}})}if(i==="/v1/memory/remember"&&n.method==="POST")try{const e=JSON.parse((await v(n,t.maxBodyBytes)).toString("utf8"))||{},r=ie.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 a(o,200,{ok:!0,action:r.action,record:r.record,replaced:r.replaces||null,size:ie.size})}catch(e){return a(o,400,{error:{message:e.message,type:"memory_error"}})}if(i==="/v1/memory/forget"&&n.method==="POST")try{const e=JSON.parse((await v(n,t.maxBodyBytes)).toString("utf8"))||{},{removed:r}=ie.forget(String(e.query||""));return a(o,200,{ok:!0,removed:r,size:ie.size})}catch(e){return a(o,400,{error:{message:e.message,type:"memory_error"}})}if(i==="/v1/memory/sync"&&n.method==="POST")try{const e=JSON.parse((await v(n,t.maxBodyBytes)).toString("utf8"))||{},r=ie.bulk({upserts:Array.isArray(e.upserts)?e.upserts:[],removes:Array.isArray(e.removes)?e.removes:[]});return a(o,200,{ok:!0,...r,memories:ie.list()})}catch(e){return a(o,400,{error:{message:`memory sync failed: ${e.message}`,type:"memory_error"}})}if(i==="/v1/memory/clear"&&n.method==="POST")return a(o,200,{ok:!0,dropped:ie.clear(),size:ie.size});if(i==="/v1/history/clear"&&n.method==="POST"){const e=B.clear();return a(o,200,{ok:!0,dropped:e,size:B.size})}if(i==="/v1/history/search"&&n.method==="POST")try{const e=JSON.parse((await v(n,t.maxBodyBytes)).toString("utf8"))||{},r=B.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 a(o,200,{ok:!0,size:B.size,newest:B.newest,results:r})}catch(e){return a(o,400,{error:{message:`search failed: ${e.message}`,type:"search_error"}})}if(i==="/v1/history/smart-search"&&n.method==="POST")try{const e=JSON.parse((await v(n,t.maxBodyBytes)).toString("utf8"))||{},r=String(e.question||e.query||""),s=Vn(r,{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},u=Math.min(30,Math.max(5,Number(e.limit)||10)*2),k=await Fn(s,x=>B.search(x,{limit:u,...l}),{limit:Math.min(50,Math.max(1,Number(e.limit)||10))}),h=l.type?k:[...k.filter(x=>x.type==="brief"),...k.filter(x=>x.type!=="brief")];return a(o,200,{ok:!0,size:B.size,newest:B.newest,queries:s,results:h})}catch(e){return a(o,400,{error:{message:`smart search failed: ${e.message}`,type:"search_error"}})}if(i==="/v1/research"&&n.method==="POST"){let e;try{e=JSON.parse((await v(n,t.maxBodyBytes)).toString("utf8")||"{}")||{}}catch{return a(o,400,{error:{message:"research: the body must be JSON",type:"invalid_request_error"}})}const r=String(e.question||"").trim();if(!r)return a(o,400,{error:{message:"research: `question` is required",type:"invalid_request_error"}});const s=typeof e.model=="string"?e.model.trim():"";if(s&&!z(n))return a(o,403,{error:{message:"research with a model: extension origin or gateway token required",type:"forbidden"}});const l=`http://127.0.0.1:${n.socket.localPort}`,u=s?async(T,{maxTokens:p=220}={})=>{const O=new AbortController,_=setTimeout(()=>O.abort(),3e4);try{const I=je()||Se(),Q=await fetch(`${l}/v1/chat/completions`,{method:"POST",signal:O.signal,headers:{"content-type":"application/json",...I?{Authorization:`Bearer ${I}`}:{},"X-ChatPanel-Client":"research"},body:JSON.stringify({model:s,messages:[{role:"user",content:T}],stream:!1,max_tokens:p,temperature:.2})}),ue=await Q.json().catch(()=>({}));return Q.ok?String(ue?.choices?.[0]?.message?.content||""):""}finally{clearTimeout(_)}}:null,k=q.get("identity")?.identity?.value||{},h=e.previous&&typeof e.previous=="object"&&e.previous.plan&&typeof e.previous.plan=="object"?{plan:e.previous.plan,top:typeof e.previous.top=="string"?e.previous.top:null,answer:String(e.previous.answer||"").slice(0,4e3)}:null,x=await fr(r,{store:B,memories:ie.list(),complete:u,previous:h,self:String(k.selfName||"").trim(),excludeId:typeof e.excludeId=="string"?e.excludeId:null,parallel:3});return a(o,200,gr(r,x,{size:B.size,newest:B.newest}))}if(i==="/v1/history/related"&&n.method==="GET"){const e=String(f.searchParams.get("id")||""),r=Math.min(30,Math.max(1,Number(f.searchParams.get("limit"))||5));return a(o,200,{ok:!0,results:B.related(e,{limit:r})})}if(i==="/v1/history/status"&&n.method==="GET")return a(o,200,{ok:!0,size:B.size,newest:B.newest,bytes:B.bytes,lossless:B.lossless?{records:B.lossless.size,newest:B.lossless.newest}:null});if(i==="/v1/observability"&&n.method==="GET"){const e=Math.min(500,Math.max(1,Number(f.searchParams.get("limit"))||200));return a(o,200,{ok:!0,storage:{warm:{records:B.size,bytes:B.bytes,newest:B.newest}},access:ct.snapshot(e)})}if(i==="/v1/observability/access"&&n.method==="POST")try{const e=JSON.parse((await v(n,t.maxBodyBytes)).toString("utf8"))||{},r=ct.push(Yt({ts:Date.now(),...e}));return a(o,200,{ok:!0,event:r})}catch(e){return a(o,400,{error:{message:`access log failed: ${e.message}`,type:"observability_error"}})}if(i==="/v1/history/records"&&n.method==="PUT"){const e=B.lossless;if(!e)return a(o,501,{error:{message:"lossless records need the SQLite warm store",type:"unavailable"}});try{const r=JSON.parse((await v(n,Math.max(t.maxBodyBytes||0,sa))).toString("utf8"))||{},s=String(r.host||"").slice(0,80),l=Number(r.at)||Date.now(),u=[];let k=0,h={},x=[],T=[];const p={upserts:[],removes:[]},O=_=>{if(!_||_.deletedAt){_?.id&&p.removes.push(_.id);return}try{const I=Mt(_);I&&p.upserts.push(I)}catch{}};if(Array.isArray(r.records)){const _=e.write(r.records,{host:s,at:l,merge:r.merge===!0});u.push(..._.written),h=_.revs,x=_.conflicts,T=_.merged;for(const I of _.written)O(e.get(I))}if(Array.isArray(r.entries)){const _=et(),I=_?Lr((F,G)=>Ir(_,{salt:F,iterations:G})):null,Q=async F=>{if(!I||!F.blob)return null;const G=await I(F.blob),_e=F.blob.compression&&F.blob.compression!=="none"?Jr(zr,F.blob.compression):null;return jr(F.blob,G,{codec:_e})},ue=await e.upsertEntries(r.entries,{open:Q});u.push(...ue.written),k+=ue.sealed;for(const F of ue.written)O(e.get(F))}return(p.upserts.length||p.removes.length)&&B.bulk(p),u.length&&Ne({ids:u}),a(o,200,{ok:!0,written:u.length,ids:u,revs:h,conflicts:x,merged:T,sealed:k,size:e.size,rev:e.rev})}catch(r){return a(o,400,{error:{message:`records failed: ${r.message}`,type:"ingest_error"}})}}if(i==="/v1/events"&&n.method==="POST"){if(!K)return a(o,501,{error:{message:"the event log needs SQLite",type:"unavailable"}});try{const e=JSON.parse((await v(n,t.maxBodyBytes)).toString("utf8"))||{},r=Array.isArray(e)?e:e.events;if(!Array.isArray(r))return a(o,400,{error:{message:"events: an array of CloudEvents (or { events: [...] }) required",type:"invalid_request_error"}});if(r.length>2e3)return a(o,413,{error:{message:"events: at most 2000 per batch",type:"invalid_request_error"}});const s=Br(K,r);return a(o,200,{ok:!0,appended:s.appended,duplicates:s.duplicates,rejected:s.rejected,cursor:K.cursor()})}catch(e){return a(o,400,{error:{message:`events: ${e?.message||e}`,type:"invalid_request_error"}})}}if(i==="/v1/events/cursor"&&n.method==="GET")return K?a(o,200,{ok:!0,cursor:K.cursor(),count:K.count()}):a(o,501,{error:{message:"the event log needs SQLite",type:"unavailable"}});if(i==="/v1/events/stats"&&n.method==="GET"){if(!K)return a(o,501,{error:{message:"the event log needs SQLite",type:"unavailable"}});const e=Mr(K.all());return a(o,200,{ok:!0,stats:e,year:Dr(e)})}if(i==="/v1/events"&&n.method==="GET"){if(!K)return a(o,501,{error:{message:"the event log needs SQLite",type:"unavailable"}});let e={};try{e=Bt(JSON.parse(f.searchParams.get("cursor")||"{}"))}catch{return a(o,400,{error:{message:"events: cursor must be JSON { host: seq }",type:"invalid_request_error"}})}const r=K.since(e,{limit:Number(f.searchParams.get("limit"))||void 0,host:f.searchParams.get("host")||null});return a(o,200,{ok:!0,events:r.events.map(s=>ot(s)),cursor:r.cursor,more:r.more})}if(i==="/v1/events/stream"&&n.method==="GET"){if(!K)return a(o,501,{error:{message:"the event log needs SQLite",type:"unavailable"}});let e=null;if(f.searchParams.has("cursor"))try{e=Bt(JSON.parse(f.searchParams.get("cursor")||"{}"))}catch{e={}}if(o.writeHead(200,{"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive"}),o.write(`event: hello
35
- data: ${JSON.stringify({cursor:K.cursor(),count:K.count(),version:Z})}
39
+ `)}catch{}},25e3);o.on("close",()=>{p(),clearInterval(T)});return}}}if(i==="/v1/memory/list"&&n.method==="GET")return a(o,200,{ok:!0,size:se.size,memories:se.list()});if(i==="/v1/memory/recall"&&n.method==="POST")try{const e=JSON.parse((await S(n,t.maxBodyBytes)).toString("utf8"))||{},r=se.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 a(o,200,{ok:!0,size:se.size,...r})}catch(e){return a(o,400,{error:{message:`recall failed: ${e.message}`,type:"memory_error"}})}if(i==="/v1/memory/remember"&&n.method==="POST")try{const e=JSON.parse((await S(n,t.maxBodyBytes)).toString("utf8"))||{},r=se.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 a(o,200,{ok:!0,action:r.action,record:r.record,replaced:r.replaces||null,size:se.size})}catch(e){return a(o,400,{error:{message:e.message,type:"memory_error"}})}if(i==="/v1/memory/forget"&&n.method==="POST")try{const e=JSON.parse((await S(n,t.maxBodyBytes)).toString("utf8"))||{},{removed:r}=se.forget(String(e.query||""));return a(o,200,{ok:!0,removed:r,size:se.size})}catch(e){return a(o,400,{error:{message:e.message,type:"memory_error"}})}if(i==="/v1/memory/sync"&&n.method==="POST")try{const e=JSON.parse((await S(n,t.maxBodyBytes)).toString("utf8"))||{},r=se.bulk({upserts:Array.isArray(e.upserts)?e.upserts:[],removes:Array.isArray(e.removes)?e.removes:[]});return a(o,200,{ok:!0,...r,memories:se.list()})}catch(e){return a(o,400,{error:{message:`memory sync failed: ${e.message}`,type:"memory_error"}})}if(i==="/v1/memory/clear"&&n.method==="POST")return a(o,200,{ok:!0,dropped:se.clear(),size:se.size});if(i==="/v1/history/clear"&&n.method==="POST"){const e=R.clear();return a(o,200,{ok:!0,dropped:e,size:R.size})}if(i==="/v1/history/search"&&n.method==="POST")try{const e=JSON.parse((await S(n,t.maxBodyBytes)).toString("utf8"))||{},r=R.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 a(o,200,{ok:!0,size:R.size,newest:R.newest,results:r})}catch(e){return a(o,400,{error:{message:`search failed: ${e.message}`,type:"search_error"}})}if(i==="/v1/history/smart-search"&&n.method==="POST")try{const e=JSON.parse((await S(n,t.maxBodyBytes)).toString("utf8"))||{},r=String(e.question||e.query||""),s=ra(r,{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},d=Math.min(30,Math.max(5,Number(e.limit)||10)*2),h=await na(s,T=>R.search(T,{limit:d,...l}),{limit:Math.min(50,Math.max(1,Number(e.limit)||10))}),p=l.type?h:[...h.filter(T=>T.type==="brief"),...h.filter(T=>T.type!=="brief")];return a(o,200,{ok:!0,size:R.size,newest:R.newest,queries:s,results:p})}catch(e){return a(o,400,{error:{message:`smart search failed: ${e.message}`,type:"search_error"}})}if(i==="/v1/research"&&n.method==="POST"){let e;try{e=JSON.parse((await S(n,t.maxBodyBytes)).toString("utf8")||"{}")||{}}catch{return a(o,400,{error:{message:"research: the body must be JSON",type:"invalid_request_error"}})}const r=String(e.question||"").trim();if(!r)return a(o,400,{error:{message:"research: `question` is required",type:"invalid_request_error"}});const s=typeof e.model=="string"?e.model.trim():"";if(s&&!G(n))return a(o,403,{error:{message:"research with a model: extension origin or gateway token required",type:"forbidden"}});const l=`http://127.0.0.1:${n.socket.localPort}`,d=s?async(w,{maxTokens:b=220}={})=>{const E=new AbortController,x=setTimeout(()=>E.abort(),3e4);try{const I=Pe()||ve(),Y=await fetch(`${l}/v1/chat/completions`,{method:"POST",signal:E.signal,headers:{"content-type":"application/json",...I?{Authorization:`Bearer ${I}`}:{},"X-ChatPanel-Client":"research"},body:JSON.stringify({model:s,messages:[{role:"user",content:w}],stream:!1,max_tokens:b,temperature:.2})}),ce=await Y.json().catch(()=>({}));return Y.ok?String(ce?.choices?.[0]?.message?.content||""):""}finally{clearTimeout(x)}}:null,h=te.get("identity")?.identity?.value||{},p=e.previous&&typeof e.previous=="object"&&e.previous.plan&&typeof e.previous.plan=="object"?{plan:e.previous.plan,top:typeof e.previous.top=="string"?e.previous.top:null,answer:String(e.previous.answer||"").slice(0,4e3)}:null,T=await _r(r,{store:R,memories:se.list(),complete:d,previous:p,self:String(h.selfName||"").trim(),excludeId:typeof e.excludeId=="string"?e.excludeId:null,parallel:3});return a(o,200,Er(r,T,{size:R.size,newest:R.newest}))}if(i==="/v1/history/related"&&n.method==="GET"){const e=String(f.searchParams.get("id")||""),r=Math.min(30,Math.max(1,Number(f.searchParams.get("limit"))||5));return a(o,200,{ok:!0,results:R.related(e,{limit:r})})}if(i==="/v1/history/status"&&n.method==="GET")return a(o,200,{ok:!0,size:R.size,newest:R.newest,bytes:R.bytes,lossless:R.lossless?{records:R.lossless.size,newest:R.lossless.newest}:null});if(i==="/v1/observability"&&n.method==="GET"){const e=Math.min(500,Math.max(1,Number(f.searchParams.get("limit"))||200));return a(o,200,{ok:!0,storage:{warm:{records:R.size,bytes:R.bytes,newest:R.newest}},access:ut.snapshot(e)})}if(i==="/v1/observability/access"&&n.method==="POST")try{const e=JSON.parse((await S(n,t.maxBodyBytes)).toString("utf8"))||{},r=ut.push(ro({ts:Date.now(),...e}));return a(o,200,{ok:!0,event:r})}catch(e){return a(o,400,{error:{message:`access log failed: ${e.message}`,type:"observability_error"}})}if(i==="/v1/history/records"&&n.method==="PUT"){const e=R.lossless;if(!e)return a(o,501,{error:{message:"lossless records need the SQLite warm store",type:"unavailable"}});try{const r=JSON.parse((await S(n,Math.max(t.maxBodyBytes||0,wa))).toString("utf8"))||{},s=String(r.host||"").slice(0,80),l=Number(r.at)||Date.now(),d=[];let h=0,p={},T=[],w=[];const b={upserts:[],removes:[]},E=x=>{if(!x||x.deletedAt){x?.id&&b.removes.push(x.id);return}try{const I=Jt(x);I&&b.upserts.push(I)}catch{}};if(Array.isArray(r.records)){const x=e.write(r.records,{host:s,at:l,merge:r.merge===!0});d.push(...x.written),p=x.revs,T=x.conflicts,w=x.merged;for(const I of x.written)E(e.get(I))}if(Array.isArray(r.entries)){const x=ot(),I=x?Qr((F,H)=>Wr(x,{salt:F,iterations:H})):null,Y=async F=>{if(!I||!F.blob)return null;const H=await I(F.blob),$e=F.blob.compression&&F.blob.compression!=="none"?Yr(Xr,F.blob.compression):null;return Kr(F.blob,H,{codec:$e})},ce=await e.upsertEntries(r.entries,{open:Y});d.push(...ce.written),h+=ce.sealed;for(const F of ce.written)E(e.get(F))}return(b.upserts.length||b.removes.length)&&R.bulk(b),d.length&&Ce({ids:d}),a(o,200,{ok:!0,written:d.length,ids:d,revs:p,conflicts:T,merged:w,sealed:h,size:e.size,rev:e.rev})}catch(r){return a(o,400,{error:{message:`records failed: ${r.message}`,type:"ingest_error"}})}}if(i==="/v1/events"&&n.method==="POST"){if(!Q)return a(o,501,{error:{message:"the event log needs SQLite",type:"unavailable"}});try{const e=JSON.parse((await S(n,t.maxBodyBytes)).toString("utf8"))||{},r=Array.isArray(e)?e:e.events;if(!Array.isArray(r))return a(o,400,{error:{message:"events: an array of CloudEvents (or { events: [...] }) required",type:"invalid_request_error"}});if(r.length>2e3)return a(o,413,{error:{message:"events: at most 2000 per batch",type:"invalid_request_error"}});const s=Gr(Q,r);return a(o,200,{ok:!0,appended:s.appended,duplicates:s.duplicates,rejected:s.rejected,cursor:Q.cursor()})}catch(e){return a(o,400,{error:{message:`events: ${e?.message||e}`,type:"invalid_request_error"}})}}if(i==="/v1/events/cursor"&&n.method==="GET")return Q?a(o,200,{ok:!0,cursor:Q.cursor(),count:Q.count()}):a(o,501,{error:{message:"the event log needs SQLite",type:"unavailable"}});if(i==="/v1/events/stats"&&n.method==="GET"){if(!Q)return a(o,501,{error:{message:"the event log needs SQLite",type:"unavailable"}});const e=Ur(Q.all());return a(o,200,{ok:!0,stats:e,year:Hr(e)})}if(i==="/v1/events"&&n.method==="GET"){if(!Q)return a(o,501,{error:{message:"the event log needs SQLite",type:"unavailable"}});let e={};try{e=Lt(JSON.parse(f.searchParams.get("cursor")||"{}"))}catch{return a(o,400,{error:{message:"events: cursor must be JSON { host: seq }",type:"invalid_request_error"}})}const r=Q.since(e,{limit:Number(f.searchParams.get("limit"))||void 0,host:f.searchParams.get("host")||null});return a(o,200,{ok:!0,events:r.events.map(s=>nt(s)),cursor:r.cursor,more:r.more})}if(i==="/v1/events/stream"&&n.method==="GET"){if(!Q)return a(o,501,{error:{message:"the event log needs SQLite",type:"unavailable"}});let e=null;if(f.searchParams.has("cursor"))try{e=Lt(JSON.parse(f.searchParams.get("cursor")||"{}"))}catch{e={}}if(o.writeHead(200,{"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive"}),o.write(`event: hello
40
+ data: ${JSON.stringify({cursor:Q.cursor(),count:Q.count(),version:X})}
36
41
 
37
- `),be.add(o),n.on("close",()=>be.delete(o)),e){let r={cursor:e,more:!0};for(;r.more;){r=K.since(r.cursor);for(const s of r.events)o.write(`event: cloudevent
38
- data: ${JSON.stringify(ot(s))}
42
+ `),Se.add(o),n.on("close",()=>Se.delete(o)),e){let r={cursor:e,more:!0};for(;r.more;){r=Q.since(r.cursor);for(const s of r.events)o.write(`event: cloudevent
43
+ data: ${JSON.stringify(nt(s))}
39
44
 
40
- `)}}return}if(i==="/v1/link"&&n.method==="GET")return a(o,200,{...c?{enabled:!0,...c.status()}:{enabled:!1,devices:[],pairing:null},agentSessions:t.link?.agentSessions!==!1});if(i==="/v1/link/settings"&&n.method==="POST"){if(n.headers["x-chatpanel-link-device"])return a(o,403,{error:{message:"a paired phone cannot change what it may reach",type:"forbidden"}});let e={};try{e=JSON.parse((await v(n,t.maxBodyBytes)).toString("utf8")||"{}")||{}}catch{e={}}if(typeof e.agentSessions!="boolean")return a(o,400,{error:{message:"link settings: { agentSessions: true|false }",type:"invalid_request"}});t.link={...t.link||{},agentSessions:e.agentSessions};try{me(t,se())}catch(r){console.warn(`[link] could not persist the settings: ${r.message}`)}return a(o,200,{ok:!0,agentSessions:t.link.agentSessions})}if(i==="/v1/link/pair"&&n.method==="POST"){if(!c)return a(o,409,{error:{message:"link is off (link.enabled: false)",type:"disabled"}});if(n.headers["x-chatpanel-link-device"])return a(o,403,{error:{message:"a paired phone cannot pair another",type:"forbidden"}});let e={};try{e=JSON.parse((await v(n,t.maxBodyBytes)).toString("utf8")||"{}")||{}}catch{e={}}try{return a(o,200,await c.pair({name:String(e?.name||"").slice(0,60)||void 0}))}catch(r){return a(o,502,{error:{message:r?.message||String(r),type:"relay"}})}}if(i==="/v1/link/route"&&n.method==="POST"){if(!c)return a(o,409,{error:{message:"link is off (link.enabled: false)",type:"disabled"}});if(n.headers["x-chatpanel-link-device"])return a(o,403,{error:{message:"a paired phone cannot change the route",type:"forbidden"}});let e={};try{e=JSON.parse((await v(n,t.maxBodyBytes)).toString("utf8")||"{}")||{}}catch{e={}}let r;try{r=rn({id:String(e.route||"link"),url:String(e.url||"")})}catch(l){return a(o,400,{error:{message:l.message,type:"bad_route"}})}const s={...t.link||{},route:r.id,fallback:e.fallback!==!1};r.id==="relay"?s.relayUrl=r.url:r.id==="link"&&delete s.relayUrl,(r.id==="tailscale"||r.id==="cloudflare")&&(s.tunnelUrl=r.url),t.link=s;try{me(t,se())}catch(l){console.warn(`[link] could not persist the route: ${l.message}`)}return a(o,200,{enabled:!0,...await c.applySettings(s)})}if(i.startsWith("/v1/link/devices/")&&n.method==="DELETE"){if(!c)return a(o,404,{error:{message:"link is off",type:"disabled"}});const e=decodeURIComponent(i.slice(17));return await c.remove(e)?a(o,200,{ok:!0}):a(o,404,{error:{message:"no such device",type:"not_found"}})}if(i==="/v1/browser"&&n.method==="GET")return a(o,200,d.status());if(i==="/v1/browser/stream"&&n.method==="GET"){d.stream(n,o);return}if((i==="/v1/browser/call"||i==="/v1/browser/announce"||i==="/v1/browser/result")&&n.method==="POST"){let e;try{e=JSON.parse((await v(n,t.maxBodyBytes)).toString("utf8"))}catch{return a(o,400,{error:{message:"browser: body must be JSON",type:"invalid_request"}})}const r=i==="/v1/browser/call"?await d.call(e,n):i==="/v1/browser/announce"?d.announce(e):d.result(e);return a(o,r.status,r.body)}if(i==="/v1/history/stream"&&n.method==="GET"){const e=B.lossless;if(!e)return a(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
41
- data: ${JSON.stringify({newest:e.newest,rev:e.rev,size:e.size,version:Z,prefsRevision:q.revision})}
45
+ `)}}return}if(i==="/v1/link"&&n.method==="GET")return a(o,200,{...g?{enabled:!0,...g.status()}:{enabled:!1,devices:[],pairing:null},agentSessions:t.link?.agentSessions!==!1});if(i==="/v1/link/settings"&&n.method==="POST"){if(n.headers["x-chatpanel-link-device"])return a(o,403,{error:{message:"a paired phone cannot change what it may reach",type:"forbidden"}});let e={};try{e=JSON.parse((await S(n,t.maxBodyBytes)).toString("utf8")||"{}")||{}}catch{e={}}if(typeof e.agentSessions!="boolean")return a(o,400,{error:{message:"link settings: { agentSessions: true|false }",type:"invalid_request"}});t.link={...t.link||{},agentSessions:e.agentSessions};try{ue(t,ae())}catch(r){console.warn(`[link] could not persist the settings: ${r.message}`)}return a(o,200,{ok:!0,agentSessions:t.link.agentSessions})}if(i==="/v1/link/pair"&&n.method==="POST"){if(!g)return a(o,409,{error:{message:"link is off (link.enabled: false)",type:"disabled"}});if(n.headers["x-chatpanel-link-device"])return a(o,403,{error:{message:"a paired phone cannot pair another",type:"forbidden"}});let e={};try{e=JSON.parse((await S(n,t.maxBodyBytes)).toString("utf8")||"{}")||{}}catch{e={}}try{return a(o,200,await g.pair({name:String(e?.name||"").slice(0,60)||void 0}))}catch(r){return a(o,502,{error:{message:r?.message||String(r),type:"relay"}})}}if(i==="/v1/link/route"&&n.method==="POST"){if(!g)return a(o,409,{error:{message:"link is off (link.enabled: false)",type:"disabled"}});if(n.headers["x-chatpanel-link-device"])return a(o,403,{error:{message:"a paired phone cannot change the route",type:"forbidden"}});let e={};try{e=JSON.parse((await S(n,t.maxBodyBytes)).toString("utf8")||"{}")||{}}catch{e={}}let r;try{r=yn({id:String(e.route||"link"),url:String(e.url||"")})}catch(l){return a(o,400,{error:{message:l.message,type:"bad_route"}})}const s={...t.link||{},route:r.id,fallback:e.fallback!==!1};r.id==="relay"?s.relayUrl=r.url:r.id==="link"&&delete s.relayUrl,(r.id==="tailscale"||r.id==="cloudflare")&&(s.tunnelUrl=r.url),t.link=s;try{ue(t,ae())}catch(l){console.warn(`[link] could not persist the route: ${l.message}`)}return a(o,200,{enabled:!0,...await g.applySettings(s)})}if(i.startsWith("/v1/link/devices/")&&n.method==="DELETE"){if(!g)return a(o,404,{error:{message:"link is off",type:"disabled"}});const e=decodeURIComponent(i.slice(17));return await g.remove(e)?a(o,200,{ok:!0}):a(o,404,{error:{message:"no such device",type:"not_found"}})}if(i==="/v1/browser"&&n.method==="GET")return a(o,200,m.status());if(i==="/v1/browser/stream"&&n.method==="GET"){m.stream(n,o);return}if((i==="/v1/browser/call"||i==="/v1/browser/announce"||i==="/v1/browser/result")&&n.method==="POST"){let e;try{e=JSON.parse((await S(n,t.maxBodyBytes)).toString("utf8"))}catch{return a(o,400,{error:{message:"browser: body must be JSON",type:"invalid_request"}})}const r=i==="/v1/browser/call"?await m.call(e,n):i==="/v1/browser/announce"?m.announce(e):m.result(e);return a(o,r.status,r.body)}if(i==="/v1/history/stream"&&n.method==="GET"){const e=R.lossless;if(!e)return a(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
46
+ data: ${JSON.stringify({newest:e.newest,rev:e.rev,size:e.size,version:X,prefsRevision:te.revision})}
42
47
 
43
- `),ye.add(o),n.on("close",()=>ye.delete(o));return}if(i==="/v1/history/records"&&n.method==="GET"){const e=B.lossless;if(!e)return a(o,501,{error:{message:"lossless records need the SQLite warm store",type:"unavailable"}});const r=e.since({since:Number(f.searchParams.get("since"))||0,cursor:f.searchParams.get("cursor")||"",limit:Number(f.searchParams.get("limit"))||200,kind:f.searchParams.get("kind")||null,bytes:Number(f.searchParams.get("bytes"))||0,afterRev:f.searchParams.has("after_rev")?Number(f.searchParams.get("after_rev"))||0:null});return a(o,200,{ok:!0,...r,size:e.size,newest:e.newest})}if(i==="/v1/history/list"&&n.method==="GET"){const e=Math.min(500,Math.max(1,Number(f.searchParams.get("limit"))||50)),r=Math.max(0,Number(f.searchParams.get("offset"))||0),s=f.searchParams.get("type")||null;return a(o,200,{ok:!0,...B.list({limit:e,offset:r,type:s})})}if(i==="/v1/history/get"&&n.method==="GET"){const e=f.searchParams.get("maxChars")!=null?Math.max(1,Number(f.searchParams.get("maxChars"))||0):null,r=Math.max(0,Number(f.searchParams.get("offset"))||0),s=B.get(String(f.searchParams.get("id")||""),{maxChars:e,offset:r});return s?a(o,200,{ok:!0,record:s}):a(o,404,{error:{message:"no such record",type:"not_found"}})}if(i==="/v1/history/key"&&n.method==="GET")return a(o,200,{ok:!0,hasKey:At()});if(i==="/v1/history/key"&&n.method==="POST")try{const e=JSON.parse((await v(n,t.maxBodyBytes)).toString("utf8"))||{};e.passphrase?or(String(e.passphrase)):rr();const r=e.passphrase?await rt(B,String(e.passphrase)):{ok:!0,ingested:0};return r.ok&&r.whole&&Ne(),a(o,200,{ok:!0,hasKey:!!e.passphrase,...r})}catch(e){return a(o,400,{error:{message:`key handoff failed: ${e.message}`,type:"key_error"}})}if(i==="/v1/history/ingest-backup"&&n.method==="POST")try{const e=await rt(B,et());return e.ok&&e.whole&&Ne(),a(o,e.ok?200:409,e)}catch(e){return a(o,400,{error:{message:`backup ingest failed: ${e.message}`,type:"ingest_error"}})}if(i==="/ner"){if(n.method==="GET"){const e=await io(t);return a(o,e.ok?200:503,e)}if(n.method==="POST"){if(await Ge(t),N.state()!=="off"){if(!N.isReady()){const r=N.health();return a(o,503,{error:{message:r.state==="error"?`NER model failed to load: ${r.error||"unknown error"}`:`NER model is ${r.state} — not ready yet`,type:r.state==="error"?"ner_error":"ner_loading"},state:r.state,model:r.model})}try{const r=await v(n,t.maxBodyBytes);let s="";try{s=JSON.parse(r.toString("utf8"))?.text||""}catch{}const l=await N.detect(s);return a(o,200,{entities:l})}catch(r){return a(o,500,{error:{message:`NER error: ${r.message}`,type:"ner_error"}})}}const e=so(t);if(!e){const r=N.modelOnDisk(t.ner?.model||void 0);return a(o,503,{error:{message:r?"the bundled detector could not start — deterministic-only redaction":"no entity detector is installed — deterministic-only redaction (install one from Gateway settings)",type:r?"ner_error":"ner_not_installed"},state:N.state(),model:t.ner?.model||null})}try{const r=await v(n,t.maxBodyBytes),s=await Je(e,{method:"POST",headers:{"content-type":"application/json"},body:r,signal:AbortSignal.timeout(8e3)}),l=await s.text();return o.writeHead(s.status,{"content-type":"application/json"}),o.end(l)}catch(r){return a(o,502,{error:{message:`NER unreachable: ${r.message}`,type:"ner_unreachable"}})}}}if(i==="/redact"&&n.method==="POST"){let e="";try{e=String(JSON.parse((await v(n,t.maxBodyBytes)).toString("utf8"))?.text||"")}catch{e=""}if(!e)return a(o,200,{text:"",count:0,sanitized:0,entities:[],detector:mt(t)});try{let r=e;const s=await we(t.pro?.entitlementToken);await Ge(t);const l=await Ie([Xe(()=>r,u=>{r=u})],t.redaction,{isPro:s});return a(o,200,{text:r,count:l.count||0,sanitized:l.sanitized||0,tier:t.redaction?.tier==="full"?"full":"basic",entities:no(l.vault,"types")||[],detector:mt(t)})}catch(r){return a(o,500,{error:{message:`redaction preview failed: ${r.message}`,type:"redact_error"}})}}if(i==="/ner/models"){if(n.method==="GET"){const e=N.health().model||t.ner?.model||null,r=Math.round(Dt.totalmem()/1048576),s=fn(It,{totalRamMB:r}).map(l=>({...l,installed:N.modelOnDisk(l.id)}));for(const l of[e,...N.modelsOnDisk()])!l||s.some(u=>u.id===l)||s.push({id:l,label:l,lang:"—",custom:!0,installed:N.modelOnDisk(l),note:"Custom model (from Hugging Face)."});return a(o,200,{active:e,companions:N.companions(),union:Array.isArray(t.ner?.union)?t.ner.union:[],machine:{totalRamMB:r},skipped:er(),recommendation:Pt(s,{totalRamMB:r},[]),state:N.state(),progress:N.progress(),available:s})}if(n.method==="POST"){let e=null;try{e=JSON.parse((await v(n,t.maxBodyBytes)).toString("utf8"))}catch{e=null}if(e&&e.recommended===!0){const s=Math.round(Dt.totalmem()/1048576),l=Pt(It.map(u=>({...u,installed:N.modelOnDisk(u.id)})),{totalRamMB:s},[]);e={id:l.primary,union:l.union}}const r=e&&typeof e.id=="string"?e.id.trim():null;if(e&&Array.isArray(e.union)){const s=[...new Set(e.union.map(u=>String(u||"").trim()).filter(Boolean))];for(const u of s)if(!(jt(u)||Lt(u)))return a(o,400,{error:{message:`unknown or invalid model id in union: ${u}`,type:"bad_model"}});const l=r||t.ner?.model||N.health().model;t.ner=t.ner||{allowDownload:!0,enableFullTier:!0},t.ner.union=s.filter(u=>u!==l),r&&Wt(t,r);try{me(t,se())}catch{}return(async()=>{r&&await N.setModel(r,{onLog:k=>console.log(k)});const u=qo(t.ner,{log:k=>console.log(k)});for(const k of N.companions())u.includes(k.model)||await N.removeCompanion(k.model);for(const k of u)await N.addCompanion(k,{onLog:h=>console.log(h),allowDownload:t.ner.allowDownload!==!1});N.setUnionOrder(u)})().catch(u=>console.log(`[ner] union update failed: ${u.message}`)),a(o,202,{accepted:!0,active:l,union:t.ner.union,companions:N.companions(),state:N.state()})}if(!r||!(jt(r)||Lt(r)))return a(o,400,{error:{message:"unknown or invalid model id",type:"bad_model"}});Wt(t,r);try{me(t,se())}catch{}return N.setModel(r,{onLog:s=>console.log(s)}).then(s=>{s&&t.ner?.enableFullTier&&t.redaction.tier!=="full"&&(t.redaction.tier="full")}),a(o,202,{accepted:!0,active:r,state:N.state(),progress:N.progress()})}}if(i==="/stt/models"){if(n.method==="GET"){const e=C.health().model||t.stt?.model||He,r=gn.map(s=>({...s,installed:C.modelOnDisk(s.id)}));return e&&!r.some(s=>s.id===e)&&r.push({id:e,label:e,lang:"—",tier:"custom",custom:!0,installed:C.modelOnDisk(e),note:"Custom model (from Hugging Face)."}),a(o,200,{active:e,state:C.state(),progress:C.progress(),available:r,dtype:t.stt?.dtype||"auto",loadedDtype:C.health().dtype,runtime:C.health().runtime,dtypes:kn})}if(n.method==="POST"){let e=null;try{e=JSON.parse((await v(n,t.maxBodyBytes)).toString("utf8"))}catch{e=null}const r=e&&typeof e.id=="string"?e.id.trim():null;if(!r||!(wn(r)||bn(r)))return a(o,400,{error:{message:"unknown or invalid model id",type:"bad_model"}});const s=typeof e.dtype=="string"&&vn(e.dtype)?e.dtype:void 0;t.stt?t.stt.model=r:t.stt={enabled:!0,model:r,allowDownload:!0},s&&(t.stt.dtype=s==="auto"?null:s);try{me(t,se())}catch{}return C.setModel(r,{onLog:l=>console.log(l),dtype:s||t.stt.dtype||"auto",warmMs:t.stt.warmMs,speaker:ht(t,{installing:!0})}),a(o,202,{accepted:!0,active:r,dtype:t.stt.dtype||"auto",state:C.state(),progress:C.progress(),speaker:{id:A.activeModel(),state:A.state(),installed:A.modelOnDisk()}})}}if(i==="/diarize/model"){if(n.method==="GET"){const e=A.activeModel(),r=mn.map(s=>({...s,installed:A.modelOnDisk(s.id)})).sort((s,l)=>(l.id===e?1:0)-(s.id===e?1:0));return a(o,200,{active:e,state:A.state(),threshold:A.activeThreshold(),progress:A.progress(),available:r})}if(n.method==="POST"){let e=null;try{e=JSON.parse((await v(n,t.maxBodyBytes)).toString("utf8")||"{}")}catch{e=null}const r=e&&typeof e.id=="string"?e.id.trim():null;if(r){if(!Ct(r))return a(o,400,{error:{message:"unknown speaker model id",type:"bad_model"}});if(!await A.setModel(r,{log:s=>console.log(s)}))return a(o,409,{error:{message:"a diarizing session is using the current speaker model — try again when it ends",type:"model_busy"}});t.stt?t.stt.diarizeModel=r:t.stt={enabled:!0,diarize:!0,diarizeModel:r};try{me(t,se())}catch{}return A.init({allowDownload:t.stt?.allowDownload!==!1,warmMs:t.stt?.warmMs,onLog:s=>console.log(s)}),a(o,202,{accepted:!0,active:A.activeModel(),state:A.state(),threshold:A.activeThreshold(),progress:A.progress()})}return A.download({onLog:s=>console.log(s)}),a(o,202,{accepted:!0,active:A.activeModel(),state:A.state(),threshold:A.activeThreshold(),progress:A.progress()})}}if(i==="/tts/models"){if(n.method==="GET"){const e=$.health().model||t.tts?.model||Vt(at()),r=at(),s=Jt.find(u=>u.id===e)||null,l=Jt.map(u=>({...u,installed:$.modelOnDisk(u.id),unavailable:u.requiresNative&&!r?"needs the npm gateway — the standalone binary cannot load this engine":void 0}));return e&&!l.some(u=>u.id===e)&&l.push({id:e,label:e,lang:"—",tier:"custom",custom:!0,installed:$.modelOnDisk(e),note:"Custom model (from Hugging Face)."}),a(o,200,{active:e,state:$.state(),progress:$.progress(),available:l,voice:t.tts?.voice||(Fe(e)==="pocket-tts"?Ue:fe),arch:$.arch(),supportsVoices:$.arch()?$.supportsVoices():s?s.arch==="style-tts2"&&!!s.voices:!0,supportsCustomVoices:$.arch()?$.supportsCustomVoices():!!s?.customVoices,sampleRate:$.sampleRate(),voices:$.isPocket()||!$.arch()&&Fe(e)==="pocket-tts"?($.builtinVoices().length?$.builtinVoices():$n).map(u=>({id:u,label:u[0].toUpperCase()+u.slice(1),lang:"en",installed:$.builtinVoices().includes(u)})):$.arch()&&$.arch()!=="style-tts2"?[]:Sn.map(u=>({...u,installed:$.voiceOnDisk(u.id,e)})),dtype:t.tts?.dtype||"auto",loadedDtype:$.health().dtype,runtime:$.health().runtime,dtypes:On})}if(n.method==="POST"){let e=null;try{e=JSON.parse((await v(n,t.maxBodyBytes)).toString("utf8"))}catch{e=null}const r=e&&typeof e.id=="string"?e.id.trim():null;if(r&&!(Tn(r)||xn(r)))return a(o,400,{error:{message:"unknown or invalid model id",type:"bad_model"}});const s=e&&typeof e.voice=="string"?e.voice.trim():null;if(s){const u=X.parseCustomVoice(s);if(!(u?!!X.getVoice(u):Ve(s)||zt(s)&&Gt(s)))return a(o,400,{error:{message:"unknown or invalid voice",type:"bad_voice"}})}const l=e&&typeof e.dtype=="string"&&_n(e.dtype)?e.dtype:void 0;if(t.tts||(t.tts={enabled:!0,model:Ht,voice:fe,allowDownload:!0}),r&&(t.tts.model=r),s&&(t.tts.voice=s),r&&!s){const u=En(r),k=X.parseCustomVoice(t.tts.voice||""),h=!!(k&&X.getVoice(k));if(u&&!h)if(Fe(r)==="pocket-tts")t.tts.voice=Ue;else{const T=X.listVoices();t.tts.voice=T.length?`custom:${T[0].id}`:""}else!u&&h&&(t.tts.voice=fe);const x=Fe(r)==="pocket-tts";x&&!X.parseCustomVoice(t.tts.voice||"")&&!Ve(t.tts.voice)&&(t.tts.voice=Ue),!x&&Ve(t.tts.voice)&&(t.tts.voice=fe)}l&&(t.tts.dtype=l==="auto"?null:l);try{me(t,se())}catch{}return r&&$.setModel(r,{onLog:u=>console.log(u),dtype:l||t.tts.dtype||"auto"}),a(o,202,{accepted:!0,active:t.tts.model,voice:t.tts.voice,dtype:t.tts.dtype||"auto",state:$.state(),progress:$.progress()})}}if(i==="/tts/voices"){if(n.method==="GET")return a(o,200,{voices:X.listVoices(),usable:$.supportsCustomVoices(),embedder:A.activeModel(),embedderReady:A.isReady()});if(n.method==="POST"){let e=null;try{e=JSON.parse((await v(n,t.maxBodyBytes)).toString("utf8"))}catch{e=null}const r=e&&typeof e.name=="string"?e.name.trim():"",s=e&&Array.isArray(e.pcm)?e.pcm:null,l=e&&typeof e.id=="string"?e.id.trim():"";if(l){if(!X.getVoice(l))return a(o,404,{error:{message:"no such saved voice",type:"bad_voice"}});if(!s){if(!r)return a(o,400,{error:{message:"a name is required",type:"bad_request"}});try{return a(o,200,{...X.renameVoice(l,r),usable:$.supportsCustomVoices()})}catch(u){return a(o,400,{error:{message:u.message,type:"rename_failed"}})}}if(s.length<16e3)return a(o,400,{error:{message:"need at least 1 second of 16 kHz mono audio",type:"sample_too_short"}})}else if(!r)return a(o,400,{error:{message:"a name is required",type:"bad_request"}});if(!s||s.length<16e3)return a(o,400,{error:{message:"need at least 1 second of 16 kHz mono audio",type:"sample_too_short"}});try{if(!A.isReady()){const p=A.download({onLog:I=>console.log(I)}),O=Symbol("timeout"),_=await Promise.race([p.then(()=>null).catch(I=>I),new Promise(I=>setTimeout(()=>I(O),ma))]);if(_===O||!A.isReady())return a(o,503,{error:{message:_===O?"the speaker model is still downloading (~100 MB) — your recording was kept, press Save again shortly":`the speaker model failed to load: ${A.health().error||"unknown error"}`,type:"embedder_not_ready"},progress:A.progress()})}const u=Float32Array.from(s),k=await A.embed(u);let h=null;try{const p=await $.pocketForEncoding({allowDownload:t.tts?.allowDownload!==!1,log:O=>console.log(O)});p&&(h=await p.encodeVoice(pa(u,16e3,24e3)))}catch(p){console.log(`[tts] pocket conditioning unavailable for this voice (${p.message})`)}const x=l?X.replaceVoice(l,{vec:k,pocket:h}):X.saveVoice({name:r,vec:k,pocket:h}),T=l&&r&&r!==x.name?X.renameVoice(l,r):x;return console.log(`[tts] ${l?"re-recorded":"saved"} custom voice "${T.name}" (${(x.kinds||[]).join(" + ")}, sample discarded)`),a(o,l?200:201,{...x,...T,usable:$.supportsCustomVoices()})}catch(u){return a(o,400,{error:{message:u.message,type:"save_failed"}})}}if(n.method==="DELETE"){const e=f.searchParams.get("id")||"",r=X.deleteVoice(e);if(r&&t.tts?.voice===`custom:${e}`){const s=X.listVoices();t.tts.voice=s.length?`custom:${s[0].id}`:fe;try{me(t,se())}catch{}}return a(o,200,{deleted:r,voice:t.tts?.voice})}}if((i==="/tts"||i==="/v1/audio/speech")&&n.method==="POST"){if(t.tts?.enabled===!1)return a(o,503,{error:{message:"tts is disabled in gateway config",type:"tts_disabled"}});let e=null;try{e=JSON.parse((await v(n,t.maxBodyBytes)).toString("utf8"))}catch{e=null}const r=e&&typeof(e.input??e.text)=="string"?String(e.input??e.text).trim():"";if(!r)return a(o,400,{error:{message:"text is required",type:"bad_request"}});if(r.length>Ut)return a(o,413,{error:{message:`text too long (max ${Ut} chars)`,type:"too_long"}});const s=Number.isFinite(e.speed)?Math.min(2,Math.max(.5,e.speed)):1,l=Pn(t),u=e&&typeof e.voice=="string"&&e.voice.trim()?e.voice.trim():null,k=u||(l?l.voice:t.tts?.voice||fe);if(l&&!Nn(k))return a(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 a(o,400,{error:{message:`unsupported response_format "${h}" — this gateway synthesizes wav`,type:"bad_format"}});try{if(l){const{audio:F,contentType:G,redacted:_e}=await An({dest:l,text:r,voice:k,speed:s,auth:n.headers.authorization||n.headers["xi-api-key"]||"",redaction:t.redaction,isPro:await we(t.pro?.entitlementToken)});return o.writeHead(200,{"Content-Type":G,"Content-Length":String(F.length),"Cache-Control":"no-store","X-Tts-Provider":l.kind,"X-Tts-Redacted":String(_e)}),o.end(F)}if(!await $.ready({onLog:F=>console.log(F),allowDownload:t.tts?.allowDownload!==!1,model:t.tts?.model||Vt(at()),dtype:t.tts?.dtype||"auto"}))return a(o,503,{error:{message:$.health().error||"tts model not ready",type:"tts_unavailable"}});const T=Bn({requested:u,configured:k,engine:$,voices:X,isPocketVoice:Ve,isKnownVoice:zt,isValidVoiceId:Gt,defaultVoice:fe,defaultPocketVoice:Ue});if(!T.ok)return a(o,T.status,{error:{message:T.message,type:T.type}});const{voice:p,customId:O,speakerEmbedding:_}=T,I=await $.synth(r,{voice:p,speed:s,speakerEmbedding:_}),Q=$.sampleRate(),ue=h==="pcm"?Buffer.from(new Float32Array(I).buffer):$.toWav(I,Q);return o.writeHead(200,{"Content-Type":h==="pcm"?"application/octet-stream":"audio/wav","Content-Length":String(ue.length),"Cache-Control":"no-store","X-Tts-Sample-Rate":String(Q),...O||$.isPocket()||$.supportsVoices()?{"X-Tts-Voice":p}:{}}),o.end(ue)}catch(x){return a(o,500,{error:{message:x.message,type:"tts_failed"}})}}if(i==="/v1/audio/transcriptions"&&n.method==="POST"){if(t.stt?.enabled===!1)return a(o,403,{error:{message:"STT disabled in gateway config",type:"stt_disabled"}});let e;try{e=hn(await v(n,Math.max(t.maxBodyBytes||0,64*1024*1024)),n.headers["content-type"])}catch(p){return a(o,p.code===413?413:415,{error:{message:p.message,type:"bad_request"}})}const r=p=>e.find(O=>O.name===p&&!O.filename)?.data.toString("utf8").trim()||"",s=e.find(p=>p.name==="file"&&p.filename)||e.find(p=>p.filename);if(!s?.data?.length)return a(o,400,{error:{message:"a `file` part is required",type:"bad_request"}});let l;try{l=await yn(s.data)}catch(p){return a(o,p.code===415?415:500,{error:{message:p.message,type:"unsupported_media"}})}const u=["json","text","verbose_json"].includes(r("response_format"))?r("response_format"):"json",k=nt(t,"stt");let h=null;if(k.kind==="remote"||k.kind==="container")try{h=Rt(k,{fetchImpl:Je})}catch(p){return a(o,500,{error:{message:`stt provider: ${p.message}`,type:"bad_provider"}})}!h&&!C.isReady()&&C.init({model:t.stt?.model||He,allowDownload:t.stt?.allowDownload!==!1,dtype:t.stt?.dtype||void 0,warmMs:t.stt?.warmMs,speaker:ht(t),onLog:p=>console.log(p)});const x=r("diarize")==="true"&&t.stt?.diarize!==!1;x&&!A.isReady()&&A.init({allowDownload:t.stt?.allowDownload!==!1,warmMs:t.stt?.warmMs,onLog:p=>console.log(p)});const T=Date.now();try{const{id:p}=C.createSession({lang:r("language")||void 0,diarize:x,interims:!1,remote:h}),O=[];let _=null;C.subscribe(p,G=>{G.type==="final"&&G.text?O.push(G):G.type==="language"&&(_=G.lang)});const I=16e3*5;for(let G=0;G<l.pcm.length;G+=I)C.pushAudio(p,l.pcm.subarray(G,Math.min(l.pcm.length,G+I)));await C.endSession(p);let Q=0;const ue=O.map((G,_e)=>{const mo=Q,po=(G.durationMs||0)/1e3;return Q+=po,{id:_e,start:Math.round(mo*100)/100,end:Math.round(Q*100)/100,text:G.text,...G.speaker?{speaker:G.speaker}:{}}}),F=ue.map(G=>G.text).join(" ").replace(/\s+/g," ").trim();return u==="text"?(o.writeHead(200,{"content-type":"text/plain; charset=utf-8"}),o.end(F)):u==="verbose_json"?a(o,200,{task:"transcribe",language:_||r("language")||null,duration:Math.round(l.seconds*100)/100,text:F,segments:ue,provider:k.kind,took_ms:Date.now()-T}):a(o,200,{text:F})}catch(p){return a(o,p.code==="too_many_sessions"?429:500,{error:{message:p.message,type:p.code||"stt_error"}})}}if(i==="/stt/sessions"&&n.method==="POST"){if(t.stt?.enabled===!1)return a(o,403,{error:{message:"STT disabled in gateway config",type:"stt_disabled"}});let e=null;try{e=JSON.parse((await v(n,t.maxBodyBytes)).toString("utf8")||"{}")}catch{e=null}const r=nt(t,"stt");let s=null;if(r.kind==="remote"||r.kind==="container")try{s=Rt(r,{fetchImpl:Je})}catch(u){return a(o,500,{error:{message:`stt provider: ${u.message}`,type:"bad_provider"}})}!s&&!C.isReady()&&C.init({model:t.stt?.model||He,allowDownload:t.stt?.allowDownload!==!1,dtype:t.stt?.dtype||void 0,warmMs:t.stt?.warmMs,speaker:ht(t),onLog:u=>console.log(u)});const l=e?.diarize===!0&&t.stt?.diarize!==!1;l&&!A.isReady()&&A.init({allowDownload:t.stt?.allowDownload!==!1,warmMs:t.stt?.warmMs,onLog:u=>console.log(u)});try{const{id:u}=C.createSession({lang:e?.lang,redact:e?.redact===!0,diarize:l,speakerLabel:e?.speakerLabel,endSilenceMs:e?.endSilenceMs,interims:e?.interims!==!1,remote:s});return a(o,201,{id:u,state:C.state()})}catch(u){return a(o,u.code==="too_many_sessions"?429:500,{error:{message:u.message,type:u.code||"stt_error"}})}}{const e=i.match(/^\/stt\/sessions\/([0-9a-f-]{36})(\/audio|\/events)?$/);if(e){const r=e[1];if(e[2]==="/audio"&&n.method==="POST")try{const s=await v(n,t.maxBodyBytes);return C.pushAudio(r,C.toFloat32(s)),a(o,200,{ok:!0,state:C.state()})}catch(s){return a(o,s.code==="no_session"?404:400,{error:{message:s.message,type:s.code||"stt_error"}})}if(e[2]==="/events"&&n.method==="GET"){const s=C.getSession(r);if(!s)return a(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=p=>o.write(`data: ${JSON.stringify(p)}
48
+ `),fe.add(o),n.on("close",()=>fe.delete(o));return}if(i==="/v1/history/records"&&n.method==="GET"){const e=R.lossless;if(!e)return a(o,501,{error:{message:"lossless records need the SQLite warm store",type:"unavailable"}});const r=e.since({since:Number(f.searchParams.get("since"))||0,cursor:f.searchParams.get("cursor")||"",limit:Number(f.searchParams.get("limit"))||200,kind:f.searchParams.get("kind")||null,bytes:Number(f.searchParams.get("bytes"))||0,afterRev:f.searchParams.has("after_rev")?Number(f.searchParams.get("after_rev"))||0:null});return a(o,200,{ok:!0,...r,size:e.size,newest:e.newest})}if(i==="/v1/history/list"&&n.method==="GET"){const e=Math.min(500,Math.max(1,Number(f.searchParams.get("limit"))||50)),r=Math.max(0,Number(f.searchParams.get("offset"))||0),s=f.searchParams.get("type")||null;return a(o,200,{ok:!0,...R.list({limit:e,offset:r,type:s})})}if(i==="/v1/history/get"&&n.method==="GET"){const e=f.searchParams.get("maxChars")!=null?Math.max(1,Number(f.searchParams.get("maxChars"))||0):null,r=Math.max(0,Number(f.searchParams.get("offset"))||0),s=R.get(String(f.searchParams.get("id")||""),{maxChars:e,offset:r});return s?a(o,200,{ok:!0,record:s}):a(o,404,{error:{message:"no such record",type:"not_found"}})}if(i==="/v1/history/key"&&n.method==="GET")return a(o,200,{ok:!0,hasKey:It()});if(i==="/v1/history/key"&&n.method==="POST")try{const e=JSON.parse((await S(n,t.maxBodyBytes)).toString("utf8"))||{};e.passphrase?mr(String(e.passphrase)):pr();const r=e.passphrase?await at(R,String(e.passphrase)):{ok:!0,ingested:0};return r.ok&&r.whole&&Ce(),a(o,200,{ok:!0,hasKey:!!e.passphrase,...r})}catch(e){return a(o,400,{error:{message:`key handoff failed: ${e.message}`,type:"key_error"}})}if(i==="/v1/history/ingest-backup"&&n.method==="POST")try{const e=await at(R,ot());return e.ok&&e.whole&&Ce(),a(o,e.ok?200:409,e)}catch(e){return a(o,400,{error:{message:`backup ingest failed: ${e.message}`,type:"ingest_error"}})}if(i==="/ner"){if(n.method==="GET"){const e=await yo(t);return a(o,e.ok?200:503,e)}if(n.method==="POST"){if(await He(t),C.state()!=="off"){if(!C.isReady()){const r=C.health();return a(o,503,{error:{message:r.state==="error"?`NER model failed to load: ${r.error||"unknown error"}`:`NER model is ${r.state} — not ready yet`,type:r.state==="error"?"ner_error":"ner_loading"},state:r.state,model:r.model})}try{const r=await S(n,t.maxBodyBytes);let s="",l=!1;try{const h=JSON.parse(r.toString("utf8"));s=h?.text||"",l=h?.strict===!0}catch{}const d=await C.detect(s,{strict:l});return a(o,200,{entities:d})}catch(r){return a(o,500,{error:{message:`NER error: ${r.message}`,type:"ner_error"}})}}const e=ho(t);if(!e){const r=C.modelOnDisk(t.ner?.model||void 0);return a(o,503,{error:{message:r?"the bundled detector could not start — deterministic-only redaction":"no entity detector is installed — deterministic-only redaction (install one from Gateway settings)",type:r?"ner_error":"ner_not_installed"},state:C.state(),model:t.ner?.model||null})}try{const r=await S(n,t.maxBodyBytes),s=await Ge(e,{method:"POST",headers:{"content-type":"application/json"},body:r,signal:AbortSignal.timeout(8e3)}),l=await s.text();return o.writeHead(s.status,{"content-type":"application/json"}),o.end(l)}catch(r){return a(o,502,{error:{message:`NER unreachable: ${r.message}`,type:"ner_unreachable"}})}}}if(i==="/redact"&&n.method==="POST"){let e="";try{e=String(JSON.parse((await S(n,t.maxBodyBytes)).toString("utf8"))?.text||"")}catch{e=""}if(!e)return a(o,200,{text:"",count:0,sanitized:0,entities:[],detector:pt(t)});try{let r=e;const s=await ke(t.pro?.entitlementToken);await He(t);const l=await ze([qe(()=>r,d=>{r=d})],t.redaction,{isPro:s});return a(o,200,{text:r,count:l.count||0,sanitized:l.sanitized||0,tier:t.redaction?.tier==="full"?"full":"basic",entities:mo(l.vault,"types")||[],detector:pt(t)})}catch(r){return a(o,500,{error:{message:`redaction preview failed: ${r.message}`,type:"redact_error"}})}}if(i==="/ner/models"){if(n.method==="GET"){const e=C.health().model||t.ner?.model||null,r=Math.round(zt.totalmem()/1048576),s=$n(Ht,{totalRamMB:r}).map(l=>({...l,installed:C.modelOnDisk(l.id)}));for(const l of[e,...C.modelsOnDisk()])!l||s.some(d=>d.id===l)||s.push({id:l,label:l,lang:"—",custom:!0,installed:C.modelOnDisk(l),note:"Custom model (from Hugging Face)."});return a(o,200,{active:e,companions:C.companions(),union:Array.isArray(t.ner?.union)?t.ner.union:[],machine:{totalRamMB:r},skipped:cr(),recommendation:Rt(s,{totalRamMB:r},[]),state:C.state(),progress:C.progress(),available:s})}if(n.method==="POST"){let e=null;try{e=JSON.parse((await S(n,t.maxBodyBytes)).toString("utf8"))}catch{e=null}if(e&&e.recommended===!0){const s=Math.round(zt.totalmem()/1048576),l=Rt(Ht.map(d=>({...d,installed:C.modelOnDisk(d.id)})),{totalRamMB:s},[]);e={id:l.primary,union:l.union}}const r=e&&typeof e.id=="string"?e.id.trim():null;if(e&&Array.isArray(e.union)){const s=[...new Set(e.union.map(d=>String(d||"").trim()).filter(Boolean))];for(const d of s)if(!(Vt(d)||Ft(d)))return a(o,400,{error:{message:`unknown or invalid model id in union: ${d}`,type:"bad_model"}});const l=r||t.ner?.model||C.health().model;t.ner=t.ner||{allowDownload:!0,enableFullTier:!0},t.ner.union=s.filter(d=>d!==l),r&&eo(t,r);try{ue(t,ae())}catch{}return(async()=>{r&&await C.setModel(r,{onLog:h=>console.log(h)});const d=dr(t.ner,{log:h=>console.log(h)});for(const h of C.companions())d.includes(h.model)||await C.removeCompanion(h.model);for(const h of d)await C.addCompanion(h,{onLog:p=>console.log(p),allowDownload:t.ner.allowDownload!==!1});C.setUnionOrder(d)})().catch(d=>console.log(`[ner] union update failed: ${d.message}`)),a(o,202,{accepted:!0,active:l,union:t.ner.union,companions:C.companions(),state:C.state()})}if(!r||!(Vt(r)||Ft(r)))return a(o,400,{error:{message:"unknown or invalid model id",type:"bad_model"}});eo(t,r);try{ue(t,ae())}catch{}return C.setModel(r,{onLog:s=>console.log(s)}).then(s=>{s&&t.ner?.enableFullTier&&t.redaction.tier!=="full"&&(t.redaction.tier="full")}),a(o,202,{accepted:!0,active:r,state:C.state(),progress:C.progress()})}}if(i==="/stt/models"){if(n.method==="GET"){const e=$.health().model||t.stt?.model||Ve,r=Pn.map(s=>({...s,installed:$.modelOnDisk(s.id)}));return e&&!r.some(s=>s.id===e)&&r.push({id:e,label:e,lang:"—",tier:"custom",custom:!0,installed:$.modelOnDisk(e),note:"Custom model (from Hugging Face)."}),a(o,200,{active:e,state:$.state(),progress:$.progress(),available:r,dtype:t.stt?.dtype||"auto",loadedDtype:$.health().dtype,runtime:$.health().runtime,dtypes:Bn})}if(n.method==="POST"){let e=null;try{e=JSON.parse((await S(n,t.maxBodyBytes)).toString("utf8"))}catch{e=null}const r=e&&typeof e.id=="string"?e.id.trim():null;if(!r||!(An(r)||Nn(r)))return a(o,400,{error:{message:"unknown or invalid model id",type:"bad_model"}});const s=typeof e.dtype=="string"&&Mn(e.dtype)?e.dtype:void 0;t.stt?t.stt.model=r:t.stt={enabled:!0,model:r,allowDownload:!0},s&&(t.stt.dtype=s==="auto"?null:s);try{ue(t,ae())}catch{}return $.setModel(r,{onLog:l=>console.log(l),dtype:s||t.stt.dtype||"auto",warmMs:t.stt.warmMs,speaker:yt(t,{installing:!0})}),a(o,202,{accepted:!0,active:r,dtype:t.stt.dtype||"auto",state:$.state(),progress:$.progress(),speaker:{id:P.activeModel(),state:P.state(),installed:P.modelOnDisk()}})}}if(i==="/diarize/model"){if(n.method==="GET"){const e=P.activeModel(),r=xn.map(s=>({...s,installed:P.modelOnDisk(s.id)})).sort((s,l)=>(l.id===e?1:0)-(s.id===e?1:0));return a(o,200,{active:e,state:P.state(),threshold:P.activeThreshold(),progress:P.progress(),available:r})}if(n.method==="POST"){let e=null;try{e=JSON.parse((await S(n,t.maxBodyBytes)).toString("utf8")||"{}")}catch{e=null}const r=e&&typeof e.id=="string"?e.id.trim():null;if(r){if(!Gt(r))return a(o,400,{error:{message:"unknown speaker model id",type:"bad_model"}});if(!await P.setModel(r,{log:s=>console.log(s)}))return a(o,409,{error:{message:"a diarizing session is using the current speaker model — try again when it ends",type:"model_busy"}});t.stt?t.stt.diarizeModel=r:t.stt={enabled:!0,diarize:!0,diarizeModel:r};try{ue(t,ae())}catch{}return P.init({allowDownload:t.stt?.allowDownload!==!1,warmMs:t.stt?.warmMs,onLog:s=>console.log(s)}),a(o,202,{accepted:!0,active:P.activeModel(),state:P.state(),threshold:P.activeThreshold(),progress:P.progress()})}return P.download({onLog:s=>console.log(s)}),a(o,202,{accepted:!0,active:P.activeModel(),state:P.state(),threshold:P.activeThreshold(),progress:P.progress()})}}if(i==="/tts/models"){if(n.method==="GET"){const e=N.health().model||t.tts?.model||Zt(it()),r=it(),s=Wt.find(d=>d.id===e)||null,l=Wt.map(d=>({...d,installed:N.modelOnDisk(d.id),unavailable:d.requiresNative&&!r?"needs the npm gateway — the standalone binary cannot load this engine":void 0}));return e&&!l.some(d=>d.id===e)&&l.push({id:e,label:e,lang:"—",tier:"custom",custom:!0,installed:N.modelOnDisk(e),note:"Custom model (from Hugging Face)."}),a(o,200,{active:e,state:N.state(),progress:N.progress(),available:l,voice:t.tts?.voice||(Ke(e)==="pocket-tts"?Fe:be),arch:N.arch(),supportsVoices:N.arch()?N.supportsVoices():s?s.arch==="style-tts2"&&!!s.voices:!0,supportsCustomVoices:N.arch()?N.supportsCustomVoices():!!s?.customVoices,sampleRate:N.sampleRate(),voices:N.isPocket()||!N.arch()&&Ke(e)==="pocket-tts"?(N.builtinVoices().length?N.builtinVoices():Jn).map(d=>({id:d,label:d[0].toUpperCase()+d.slice(1),lang:"en",installed:N.builtinVoices().includes(d)})):N.arch()&&N.arch()!=="style-tts2"?[]:Dn.map(d=>({...d,installed:N.voiceOnDisk(d.id,e)})),dtype:t.tts?.dtype||"auto",loadedDtype:N.health().dtype,runtime:N.health().runtime,dtypes:In})}if(n.method==="POST"){let e=null;try{e=JSON.parse((await S(n,t.maxBodyBytes)).toString("utf8"))}catch{e=null}const r=e&&typeof e.id=="string"?e.id.trim():null;if(r&&!(Cn(r)||Rn(r)))return a(o,400,{error:{message:"unknown or invalid model id",type:"bad_model"}});const s=e&&typeof e.voice=="string"?e.voice.trim():null;if(s){const d=ee.parseCustomVoice(s);if(!(d?!!ee.getVoice(d):We(s)||Kt(s)&&Qt(s)))return a(o,400,{error:{message:"unknown or invalid voice",type:"bad_voice"}})}const l=e&&typeof e.dtype=="string"&&jn(e.dtype)?e.dtype:void 0;if(t.tts||(t.tts={enabled:!0,model:Yt,voice:be,allowDownload:!0}),r&&(t.tts.model=r),s&&(t.tts.voice=s),r&&!s){const d=Ln(r),h=ee.parseCustomVoice(t.tts.voice||""),p=!!(h&&ee.getVoice(h));if(d&&!p)if(Ke(r)==="pocket-tts")t.tts.voice=Fe;else{const w=ee.listVoices();t.tts.voice=w.length?`custom:${w[0].id}`:""}else!d&&p&&(t.tts.voice=be);const T=Ke(r)==="pocket-tts";T&&!ee.parseCustomVoice(t.tts.voice||"")&&!We(t.tts.voice)&&(t.tts.voice=Fe),!T&&We(t.tts.voice)&&(t.tts.voice=be)}l&&(t.tts.dtype=l==="auto"?null:l);try{ue(t,ae())}catch{}return r&&N.setModel(r,{onLog:d=>console.log(d),dtype:l||t.tts.dtype||"auto"}),a(o,202,{accepted:!0,active:t.tts.model,voice:t.tts.voice,dtype:t.tts.dtype||"auto",state:N.state(),progress:N.progress()})}}if(i==="/tts/voices"){if(n.method==="GET")return a(o,200,{voices:ee.listVoices(),usable:N.supportsCustomVoices(),embedder:P.activeModel(),embedderReady:P.isReady()});if(n.method==="POST"){let e=null;try{e=JSON.parse((await S(n,t.maxBodyBytes)).toString("utf8"))}catch{e=null}const r=e&&typeof e.name=="string"?e.name.trim():"",s=e&&Array.isArray(e.pcm)?e.pcm:null,l=e&&typeof e.id=="string"?e.id.trim():"";if(l){if(!ee.getVoice(l))return a(o,404,{error:{message:"no such saved voice",type:"bad_voice"}});if(!s){if(!r)return a(o,400,{error:{message:"a name is required",type:"bad_request"}});try{return a(o,200,{...ee.renameVoice(l,r),usable:N.supportsCustomVoices()})}catch(d){return a(o,400,{error:{message:d.message,type:"rename_failed"}})}}if(s.length<16e3)return a(o,400,{error:{message:"need at least 1 second of 16 kHz mono audio",type:"sample_too_short"}})}else if(!r)return a(o,400,{error:{message:"a name is required",type:"bad_request"}});if(!s||s.length<16e3)return a(o,400,{error:{message:"need at least 1 second of 16 kHz mono audio",type:"sample_too_short"}});try{if(!P.isReady()){const b=P.download({onLog:I=>console.log(I)}),E=Symbol("timeout"),x=await Promise.race([b.then(()=>null).catch(I=>I),new Promise(I=>setTimeout(()=>I(E),xa))]);if(x===E||!P.isReady())return a(o,503,{error:{message:x===E?"the speaker model is still downloading (~100 MB) — your recording was kept, press Save again shortly":`the speaker model failed to load: ${P.health().error||"unknown error"}`,type:"embedder_not_ready"},progress:P.progress()})}const d=Float32Array.from(s),h=await P.embed(d);let p=null;try{const b=await N.pocketForEncoding({allowDownload:t.tts?.allowDownload!==!1,log:E=>console.log(E)});b&&(p=await b.encodeVoice(Oa(d,16e3,24e3)))}catch(b){console.log(`[tts] pocket conditioning unavailable for this voice (${b.message})`)}const T=l?ee.replaceVoice(l,{vec:h,pocket:p}):ee.saveVoice({name:r,vec:h,pocket:p}),w=l&&r&&r!==T.name?ee.renameVoice(l,r):T;return console.log(`[tts] ${l?"re-recorded":"saved"} custom voice "${w.name}" (${(T.kinds||[]).join(" + ")}, sample discarded)`),a(o,l?200:201,{...T,...w,usable:N.supportsCustomVoices()})}catch(d){return a(o,400,{error:{message:d.message,type:"save_failed"}})}}if(n.method==="DELETE"){const e=f.searchParams.get("id")||"",r=ee.deleteVoice(e);if(r&&t.tts?.voice===`custom:${e}`){const s=ee.listVoices();t.tts.voice=s.length?`custom:${s[0].id}`:be;try{ue(t,ae())}catch{}}return a(o,200,{deleted:r,voice:t.tts?.voice})}}if((i==="/tts"||i==="/v1/audio/speech")&&n.method==="POST"){if(t.tts?.enabled===!1)return a(o,503,{error:{message:"tts is disabled in gateway config",type:"tts_disabled"}});let e=null;try{e=JSON.parse((await S(n,t.maxBodyBytes)).toString("utf8"))}catch{e=null}const r=e&&typeof(e.input??e.text)=="string"?String(e.input??e.text).trim():"";if(!r)return a(o,400,{error:{message:"text is required",type:"bad_request"}});if(r.length>Xt)return a(o,413,{error:{message:`text too long (max ${Xt} chars)`,type:"too_long"}});const s=Number.isFinite(e.speed)?Math.min(2,Math.max(.5,e.speed)):1,l=zn(t),d=e&&typeof e.voice=="string"&&e.voice.trim()?e.voice.trim():null,h=d||(l?l.voice:t.tts?.voice||be);if(l&&!Un(h))return a(o,400,{error:{message:"unknown or invalid voice",type:"bad_voice"}});const p=e&&typeof e.response_format=="string"?e.response_format.toLowerCase():"wav";if(p!=="wav"&&p!=="pcm")return a(o,400,{error:{message:`unsupported response_format "${p}" — this gateway synthesizes wav`,type:"bad_format"}});try{if(l){const{audio:F,contentType:H,redacted:$e}=await Gn({dest:l,text:r,voice:h,speed:s,auth:n.headers.authorization||n.headers["xi-api-key"]||"",redaction:t.redaction,isPro:await ke(t.pro?.entitlementToken)});return o.writeHead(200,{"Content-Type":H,"Content-Length":String(F.length),"Cache-Control":"no-store","X-Tts-Provider":l.kind,"X-Tts-Redacted":String($e)}),o.end(F)}if(!await N.ready({onLog:F=>console.log(F),allowDownload:t.tts?.allowDownload!==!1,model:t.tts?.model||Zt(it()),dtype:t.tts?.dtype||"auto"}))return a(o,503,{error:{message:N.health().error||"tts model not ready",type:"tts_unavailable"}});const w=Hn({requested:d,configured:h,engine:N,voices:ee,isPocketVoice:We,isKnownVoice:Kt,isValidVoiceId:Qt,defaultVoice:be,defaultPocketVoice:Fe});if(!w.ok)return a(o,w.status,{error:{message:w.message,type:w.type}});const{voice:b,customId:E,speakerEmbedding:x}=w,I=await N.synth(r,{voice:b,speed:s,speakerEmbedding:x}),Y=N.sampleRate(),ce=p==="pcm"?Buffer.from(new Float32Array(I).buffer):N.toWav(I,Y);return o.writeHead(200,{"Content-Type":p==="pcm"?"application/octet-stream":"audio/wav","Content-Length":String(ce.length),"Cache-Control":"no-store","X-Tts-Sample-Rate":String(Y),...E||N.isPocket()||N.supportsVoices()?{"X-Tts-Voice":b}:{}}),o.end(ce)}catch(T){return a(o,500,{error:{message:T.message,type:"tts_failed"}})}}if(i==="/v1/audio/transcriptions"&&n.method==="POST"){if(t.stt?.enabled===!1)return a(o,403,{error:{message:"STT disabled in gateway config",type:"stt_disabled"}});let e;try{e=_n(await S(n,Math.max(t.maxBodyBytes||0,64*1024*1024)),n.headers["content-type"])}catch(b){return a(o,b.code===413?413:415,{error:{message:b.message,type:"bad_request"}})}const r=b=>e.find(E=>E.name===b&&!E.filename)?.data.toString("utf8").trim()||"",s=e.find(b=>b.name==="file"&&b.filename)||e.find(b=>b.filename);if(!s?.data?.length)return a(o,400,{error:{message:"a `file` part is required",type:"bad_request"}});let l;try{l=await En(s.data)}catch(b){return a(o,b.code===415?415:500,{error:{message:b.message,type:"unsupported_media"}})}const d=["json","text","verbose_json"].includes(r("response_format"))?r("response_format"):"json",h=st(t,"stt");let p=null;if(h.kind==="remote"||h.kind==="container")try{p=Ut(h,{fetchImpl:Ge})}catch(b){return a(o,500,{error:{message:`stt provider: ${b.message}`,type:"bad_provider"}})}!p&&!$.isReady()&&$.init({model:t.stt?.model||Ve,allowDownload:t.stt?.allowDownload!==!1,dtype:t.stt?.dtype||void 0,warmMs:t.stt?.warmMs,speaker:yt(t),onLog:b=>console.log(b)});const T=r("diarize")==="true"&&t.stt?.diarize!==!1;T&&!P.isReady()&&P.init({allowDownload:t.stt?.allowDownload!==!1,warmMs:t.stt?.warmMs,onLog:b=>console.log(b)});const w=Date.now();try{const{id:b}=$.createSession({lang:r("language")||void 0,diarize:T,interims:!1,remote:p}),E=[];let x=null;$.subscribe(b,H=>{H.type==="final"&&H.text?E.push(H):H.type==="language"&&(x=H.lang)});const I=16e3*5;for(let H=0;H<l.pcm.length;H+=I)$.pushAudio(b,l.pcm.subarray(H,Math.min(l.pcm.length,H+I)));await $.endSession(b);let Y=0;const ce=E.map((H,$e)=>{const ko=Y,vo=(H.durationMs||0)/1e3;return Y+=vo,{id:$e,start:Math.round(ko*100)/100,end:Math.round(Y*100)/100,text:H.text,...H.speaker?{speaker:H.speaker}:{}}}),F=ce.map(H=>H.text).join(" ").replace(/\s+/g," ").trim();return d==="text"?(o.writeHead(200,{"content-type":"text/plain; charset=utf-8"}),o.end(F)):d==="verbose_json"?a(o,200,{task:"transcribe",language:x||r("language")||null,duration:Math.round(l.seconds*100)/100,text:F,segments:ce,provider:h.kind,took_ms:Date.now()-w}):a(o,200,{text:F})}catch(b){return a(o,b.code==="too_many_sessions"?429:500,{error:{message:b.message,type:b.code||"stt_error"}})}}if(i==="/stt/sessions"&&n.method==="POST"){if(t.stt?.enabled===!1)return a(o,403,{error:{message:"STT disabled in gateway config",type:"stt_disabled"}});let e=null;try{e=JSON.parse((await S(n,t.maxBodyBytes)).toString("utf8")||"{}")}catch{e=null}const r=st(t,"stt");let s=null;if(r.kind==="remote"||r.kind==="container")try{s=Ut(r,{fetchImpl:Ge})}catch(d){return a(o,500,{error:{message:`stt provider: ${d.message}`,type:"bad_provider"}})}!s&&!$.isReady()&&$.init({model:t.stt?.model||Ve,allowDownload:t.stt?.allowDownload!==!1,dtype:t.stt?.dtype||void 0,warmMs:t.stt?.warmMs,speaker:yt(t),onLog:d=>console.log(d)});const l=e?.diarize===!0&&t.stt?.diarize!==!1;l&&!P.isReady()&&P.init({allowDownload:t.stt?.allowDownload!==!1,warmMs:t.stt?.warmMs,onLog:d=>console.log(d)});try{const d=e?.poll===!0,{id:h}=$.createSession({lang:e?.lang,redact:e?.redact===!0,diarize:l,speakerLabel:e?.speakerLabel,endSilenceMs:e?.endSilenceMs,interims:e?.interims!==!1,remote:s,poll:d});return a(o,201,{id:h,state:$.state(),...d?{poll:!0}:{}})}catch(d){return a(o,d.code==="too_many_sessions"?429:500,{error:{message:d.message,type:d.code||"stt_error"}})}}{const e=i.match(/^\/stt\/sessions\/([0-9a-f-]{36})(\/audio|\/events)?$/);if(e){const r=e[1],s=async(d,h,p)=>{if(h.type!=="final"||!d.redact)return h;try{let T=h.text;return await ze([qe(()=>T,w=>{T=w})],t.redaction,{isPro:p}),{...h,text:T}}catch{return h}},l=async d=>{const h=$.drainEvents(r);if(!h)return null;const p=[];if(d&&!d.closed){const w=d.remote?"ready":$.state();w==="downloading"||w==="loading"?p.push({type:"progress",state:w,...$.progress()||{}}):w==="error"?p.push({type:"error",code:"model_failed",message:$.health().error||"model failed to load",fatal:!0}):d.diarize&&["downloading","loading"].includes(P.state())?p.push({type:"diarize-progress",state:P.state(),...P.progress()||{}}):go.get(d)!==w&&(go.set(d,w),p.push({type:"state",state:w}))}const T=d?.redact?await ke(t.pro?.entitlementToken):!0;for(const w of h)d?p.push(await s(d,w,T)):w.type!=="final"&&w.type!=="interim"&&p.push(w);return p};if(e[2]==="/audio"&&n.method==="POST"){const d=$.getSession(r)||$.endedSession(r);try{const h=await S(n,t.maxBodyBytes);$.pushAudio(r,$.toFloat32(h));const p=await l(d);return a(o,200,{ok:!0,state:$.state(),...p?{events:p}:{}})}catch(h){const p=h.code==="no_session"?await l(d).catch(()=>null):null;return a(o,h.code==="no_session"?404:400,{error:{message:h.message,type:h.code||"stt_error"},...p?{events:p}:{}})}}if(e[2]==="/events"&&n.method==="GET"){const d=$.getSession(r);if(!d)return a(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 h=x=>o.write(`data: ${JSON.stringify(x)}
44
49
 
45
- `),u=s.redact?await we(t.pro?.entitlementToken):!0,k=async p=>{if(p.type!=="final"||!s.redact)return p;try{let O=p.text;return await Ie([Xe(()=>O,_=>{O=_})],t.redaction,{isPro:u}),{...p,text:O}}catch{return p}};l({type:"state",state:s.remote?"ready":C.state()});const h=setInterval(()=>{const p=s.remote?"ready":C.state();if(p==="downloading"||p==="loading"){l({type:"progress",state:p,...C.progress()||{}});return}if(p==="error"){l({type:"error",code:"model_failed",message:C.health().error||"model failed to load",fatal:!0}),clearInterval(h);return}if(s.diarize){const O=A.state();if(O==="downloading"||O==="loading"){l({type:"diarize-progress",state:O,...A.progress()||{}});return}}l({type:"state",state:p}),clearInterval(h)},500);h.unref?.();let x=Promise.resolve();const T=C.subscribe(r,p=>{x=x.then(async()=>{l(await k(p)),p.type==="end"&&(clearInterval(h),o.end())}).catch(()=>{})});n.on("close",()=>{clearInterval(h),T?.()});return}if(!e[2]&&n.method==="DELETE")return await C.endSession(r),a(o,200,{ok:!0})}}if(i==="/logs"&&n.method==="GET")return a(o,200,{entries:[...R].reverse()});if(i==="/config"&&n.method==="GET"){const e=await we(t.pro?.entitlementToken);return a(o,200,Ft(t,{proUnlocked:e}))}if(i==="/config"&&n.method==="POST"){let e=null;try{e=JSON.parse((await v(n,t.maxBodyBytes)).toString("utf8"))}catch{e=null}if(!e||typeof e!="object")return a(o,400,{error:"invalid config patch"});const r=JSON.stringify(t.sandbox||null);try{Rn(t,e)}catch(h){if(h?.code==="SHAPE")return a(o,400,{error:h.message});throw h}Tt(t),JSON.stringify(t.sandbox||null)!==r&&Be?.restart("sandbox settings changed");try{me(t,se())}catch(h){return a(o,500,{error:`could not persist config: ${h.message}`})}const s=t.redaction?.detection,l=!s||!s.backend||s.backend==="off",u=N.state();t.ner?.autostart&&l&&u!=="ready"&&u!=="loading"&&u!=="downloading"&&N.setModel(t.ner.model,{onLog:h=>console.log(h)}).then(h=>{h&&t.ner?.enableFullTier&&t.redaction.tier!=="full"&&(t.redaction.tier="full")});const k=await we(t.pro?.entitlementToken);return a(o,200,Ft(t,{proUnlocked:k}))}if(n.method==="GET"&&i==="/skills")return pe(n,o,t,`/skills${Oe(f,t)}`,{pick:e=>({skills:Array.isArray(e?.skills)?e.skills:[]})});if(n.method==="POST"&&i==="/v1/threads/send"){if(!z(n))return a(o,403,{error:{message:"asking another chat: extension origin or gateway token required",type:"forbidden"}});if(n.headers["x-chatpanel-link-device"])return a(o,403,{error:{message:"asking another chat is not available from a linked phone yet",type:"forbidden"}});const e=B.lossless;if(!e)return a(o,501,{error:{message:"asking another chat needs the SQLite warm store",type:"unavailable"}});let r={};try{r=JSON.parse((await v(n,t.maxBodyBytes)).toString("utf8")||"{}")||{}}catch{return a(o,400,{error:{message:"threads/send: body must be JSON",type:"invalid_request"}})}const s=String(r.to||""),l=String(r.message||"").trim();if(!l||l.length>Nt)return a(o,400,{error:{message:`threads/send: a message of 1–${Nt} characters`,type:"invalid_request"}});const u=r.from&&typeof r.from=="object"?{id:String(r.from.id||"").slice(0,200),title:String(r.from.title||"").slice(0,200)}:null,k=e.get(s);if(!k||k.deletedAt)return a(o,404,{error:{message:"no such chat on this computer — it may not have synced here yet",type:"not_found"}});const h=mr(k,{cards:q.get("agentTools").agentTools?.value?.agents||[]});if(h.error)return a(o,409,{error:{message:h.error,type:"no_model"}});if(r.dryRun===!0)return a(o,200,{ok:!0,title:k.title,model:h.model});const x=pr({fromTitle:u?.title,message:l}),T={thread:{id:h.thread,...k.title?{title:k.title}:{}},...h.workingDir?{workingDir:h.workingDir}:{}};let p="";try{const _=await fetch(`http://127.0.0.1:${n.socket.localPort}/v1/chat/completions`,{method:"POST",headers:{"content-type":"application/json","x-chatpanel-token":je()||Se(),"x-chatpanel-run":encodeURIComponent(JSON.stringify(T))},body:JSON.stringify({model:h.model,messages:[...hr(k),{role:"user",content:x}],stream:!1}),signal:AbortSignal.timeout(6e5)}),I=await _.json().catch(()=>null);if(!_.ok)return a(o,502,{error:{message:`that chat's ${h.model} did not answer: ${I?.error?.message||`HTTP ${_.status}`}`,type:"upstream"}});p=String(I?.choices?.[0]?.message?.content||"")}catch(_){return a(o,502,{error:{message:`that chat's ${h.model} did not answer: ${_?.message||_}`,type:"upstream"}})}const O=yr(e.get(s)||k,{question:x,reply:p,model:h.model,from:u});e.write([O],{host:"gateway",at:Date.now()});try{const _=Mt(e.get(s));_&&B.bulk({upserts:[_],removes:[]})}catch{}return Ne({ids:[s]}),a(o,200,{ok:!0,title:k.title,model:h.model,reply:p})}const le=/^(?:\/v1)?(\/agent-sessions(?:\/read|\/adopt|\/catchup)?)$/.exec(i)?.[1];if(n.method==="POST"&&le)return z(n)?n.headers["x-chatpanel-link-device"]&&t.link?.agentSessions===!1?a(o,403,{error:{message:"this computer does not share its coding agents' sessions with a linked phone — Settings › Your phone",type:"forbidden"}}):pe(n,o,t,le,{method:"POST",timeoutMs:3e4}):a(o,403,{error:{message:"the agents' own sessions: extension origin or gateway token required",type:"forbidden"}});if(n.method==="GET"&&i==="/skills-quarantined")return pe(n,o,t,`/skills-quarantined${Oe(f,t)}`,{pick:e=>({quarantined:Array.isArray(e?.quarantined)?e.quarantined:[]})});if(i==="/skills"&&n.method==="POST")return z(n)?pe(n,o,t,"/skills",{method:"POST",timeoutMs:15e3}):a(o,403,{error:{message:"writing a skill: extension origin or gateway token required",type:"forbidden"}});if(/^\/skills\/[^/]+$/.test(i)&&n.method==="DELETE"){const e=decodeURIComponent(i.slice(8));return yt(e)?a(o,400,{error:{message:"not a skill id",type:"invalid_request"}}):z(n)?pe(n,o,t,`/skills/${encodeURIComponent(e)}`,{method:"DELETE"}):a(o,403,{error:{message:"deleting a skill: extension origin or gateway token required",type:"forbidden"}})}if(/^\/skills\/[^/]+\/file\/.+/.test(i)&&n.method==="PUT"){const e=/^\/skills\/([^/]+)\/file\/(.+)$/.exec(i),r=decodeURIComponent(e[1]);return yt(r)||/(^|\/)\.\.(\/|$)/.test(decodeURIComponent(e[2]))?a(o,400,{error:{message:"not a skill file",type:"invalid_request"}}):z(n)?pe(n,o,t,`/skills/${encodeURIComponent(r)}/file/${e[2]}`,{method:"PUT",timeoutMs:15e3}):a(o,403,{error:{message:"writing a skill file: extension origin or gateway token required",type:"forbidden"}})}if(n.method==="GET"&&i==="/agent-defs")return pe(n,o,t,`/agent-defs${Oe(f,t)}`,{pick:e=>({agents:Array.isArray(e?.agents)?e.agents:[],...e?.quarantined?{quarantined:e.quarantined}:{},...e?.problems?{problems:e.problems}:{}})});if(n.method==="GET"&&/^\/agent-defs\/[^/]+$/.test(i)){const e=decodeURIComponent(i.slice(12));return yt(e)?a(o,400,{error:{message:"not an agent id",type:"invalid_request"}}):pe(n,o,t,`/agent-defs/${encodeURIComponent(e)}${Oe(f,t)}`)}if(i.startsWith("/a2a/")){if(!z(n))return a(o,403,{error:{message:"a2a: extension origin or gateway token required",type:"forbidden"}});try{if(n.method==="GET"&&i==="/a2a/agents")return a(o,200,{agents:Uo()});if(n.method==="POST"&&i==="/a2a/card"){const e=JSON.parse((await v(n,t.maxBodyBytes)).toString("utf8")||"{}");e.forget&&Lo(e.url||"");const r=await ze(e.url,{force:!!e.force,auth:String(e.auth||"")});return a(o,200,{ok:!0,card:r.card,fingerprint:r.fingerprint,fresh:r.fresh,changed:!!r.changed,url:r.url})}if(n.method==="POST"&&i==="/a2a/message"){const e=JSON.parse((await v(n,t.maxBodyBytes)).toString("utf8")||"{}"),r=e.card||(await ze(e.url,{auth:String(e.auth||"")})).card,s=await Jo({card:r,message:e.message||{messageId:`cp_${Date.now().toString(36)}`,role:"ROLE_USER",parts:[{text:String(e.text||"")}]},auth:String(e.auth||""),returnImmediately:!!e.returnImmediately,contextId:String(e.contextId||""),taskId:String(e.taskId||"")});return a(o,200,{ok:!0,...s})}if(n.method==="POST"&&i==="/a2a/message/stream"){const e=JSON.parse((await v(n,t.maxBodyBytes)).toString("utf8")||"{}"),r=e.card||(await ze(e.url,{auth:String(e.auth||"")})).card;o.writeHead(200,{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"});const s=(l,u)=>o.write(`event: ${l}
46
- data: ${JSON.stringify(u)}
50
+ `),p=d.redact?await ke(t.pro?.entitlementToken):!0,T=x=>s(d,x,p);h({type:"state",state:d.remote?"ready":$.state()});const w=setInterval(()=>{const x=d.remote?"ready":$.state();if(x==="downloading"||x==="loading"){h({type:"progress",state:x,...$.progress()||{}});return}if(x==="error"){h({type:"error",code:"model_failed",message:$.health().error||"model failed to load",fatal:!0}),clearInterval(w);return}if(d.diarize){const I=P.state();if(I==="downloading"||I==="loading"){h({type:"diarize-progress",state:I,...P.progress()||{}});return}}h({type:"state",state:x}),clearInterval(w)},500);w.unref?.();let b=Promise.resolve();const E=$.subscribe(r,x=>{b=b.then(async()=>{h(await T(x)),x.type==="end"&&(clearInterval(w),o.end())}).catch(()=>{})});n.on("close",()=>{clearInterval(w),E?.()});return}if(!e[2]&&n.method==="DELETE"){const d=$.getSession(r);await $.endSession(r);const h=d?.poll?await l(d).catch(()=>null):null;return a(o,200,{ok:!0,...h?{events:h}:{}})}}}if(i==="/logs"&&n.method==="GET")return a(o,200,{entries:[...he].reverse()});if(i==="/config"&&n.method==="GET"){const e=await ke(t.pro?.entitlementToken);return a(o,200,qt(t,{proUnlocked:e}))}if(i==="/config"&&n.method==="POST"){let e=null;try{e=JSON.parse((await S(n,t.maxBodyBytes)).toString("utf8"))}catch{e=null}if(!e||typeof e!="object")return a(o,400,{error:"invalid config patch"});const r=JSON.stringify(t.sandbox||null);try{Kn(t,e)}catch(p){if(p?.code==="SHAPE")return a(o,400,{error:p.message});throw p}Pt(t),JSON.stringify(t.sandbox||null)!==r&&Re?.restart("sandbox settings changed");try{ue(t,ae())}catch(p){return a(o,500,{error:`could not persist config: ${p.message}`})}const s=t.redaction?.detection,l=!s||!s.backend||s.backend==="off",d=C.state();t.ner?.autostart&&l&&d!=="ready"&&d!=="loading"&&d!=="downloading"&&C.setModel(t.ner.model,{onLog:p=>console.log(p)}).then(p=>{p&&t.ner?.enableFullTier&&t.redaction.tier!=="full"&&(t.redaction.tier="full")});const h=await ke(t.pro?.entitlementToken);return a(o,200,qt(t,{proUnlocked:h}))}if(n.method==="GET"&&i==="/skills")return me(n,o,t,`/skills${Ee(f,t)}`,{pick:e=>({skills:Array.isArray(e?.skills)?e.skills:[]})});if(n.method==="POST"&&i==="/v1/threads/send"){if(!G(n))return a(o,403,{error:{message:"asking another chat: extension origin or gateway token required",type:"forbidden"}});if(n.headers["x-chatpanel-link-device"])return a(o,403,{error:{message:"asking another chat is not available from a linked phone yet",type:"forbidden"}});const e=R.lossless;if(!e)return a(o,501,{error:{message:"asking another chat needs the SQLite warm store",type:"unavailable"}});let r={};try{r=JSON.parse((await S(n,t.maxBodyBytes)).toString("utf8")||"{}")||{}}catch{return a(o,400,{error:{message:"threads/send: body must be JSON",type:"invalid_request"}})}const s=String(r.to||""),l=String(r.message||"").trim();if(!l||l.length>jt)return a(o,400,{error:{message:`threads/send: a message of 1–${jt} characters`,type:"invalid_request"}});const d=r.from&&typeof r.from=="object"?{id:String(r.from.id||"").slice(0,200),title:String(r.from.title||"").slice(0,200)}:null,h=e.get(s);if(!h||h.deletedAt)return a(o,404,{error:{message:"no such chat on this computer — it may not have synced here yet",type:"not_found"}});const p=Sr(h,{cards:te.get("agentTools").agentTools?.value?.agents||[]});if(p.error)return a(o,409,{error:{message:p.error,type:"no_model"}});if(r.dryRun===!0)return a(o,200,{ok:!0,title:h.title,model:p.model});const T=Tr({fromTitle:d?.title,message:l}),w={thread:{id:p.thread,...h.title?{title:h.title}:{}},...p.workingDir?{workingDir:p.workingDir}:{}};let b="";try{const x=await fetch(`http://127.0.0.1:${n.socket.localPort}/v1/chat/completions`,{method:"POST",headers:{"content-type":"application/json","x-chatpanel-token":Pe()||ve(),"x-chatpanel-run":encodeURIComponent(JSON.stringify(w))},body:JSON.stringify({model:p.model,messages:[...xr(h),{role:"user",content:T}],stream:!1}),signal:AbortSignal.timeout(6e5)}),I=await x.json().catch(()=>null);if(!x.ok)return a(o,502,{error:{message:`that chat's ${p.model} did not answer: ${I?.error?.message||`HTTP ${x.status}`}`,type:"upstream"}});b=String(I?.choices?.[0]?.message?.content||"")}catch(x){return a(o,502,{error:{message:`that chat's ${p.model} did not answer: ${x?.message||x}`,type:"upstream"}})}const E=Or(e.get(s)||h,{question:T,reply:b,model:p.model,from:d});e.write([E],{host:"gateway",at:Date.now()});try{const x=Jt(e.get(s));x&&R.bulk({upserts:[x],removes:[]})}catch{}return Ce({ids:[s]}),a(o,200,{ok:!0,title:h.title,model:p.model,reply:b})}const U=/^(?:\/v1)?(\/agent-sessions(?:\/read|\/adopt|\/catchup)?)$/.exec(i)?.[1];if(n.method==="POST"&&U)return G(n)?n.headers["x-chatpanel-link-device"]&&t.link?.agentSessions===!1?a(o,403,{error:{message:"this computer does not share its coding agents' sessions with a linked phone — Settings › Your phone",type:"forbidden"}}):me(n,o,t,U,{method:"POST",timeoutMs:3e4}):a(o,403,{error:{message:"the agents' own sessions: extension origin or gateway token required",type:"forbidden"}});if(n.method==="GET"&&i==="/skills-quarantined")return me(n,o,t,`/skills-quarantined${Ee(f,t)}`,{pick:e=>({quarantined:Array.isArray(e?.quarantined)?e.quarantined:[]})});if(i==="/skills"&&n.method==="POST")return G(n)?me(n,o,t,"/skills",{method:"POST",timeoutMs:15e3}):a(o,403,{error:{message:"writing a skill: extension origin or gateway token required",type:"forbidden"}});if(/^\/skills\/[^/]+$/.test(i)&&n.method==="DELETE"){const e=decodeURIComponent(i.slice(8));return ft(e)?a(o,400,{error:{message:"not a skill id",type:"invalid_request"}}):G(n)?me(n,o,t,`/skills/${encodeURIComponent(e)}`,{method:"DELETE"}):a(o,403,{error:{message:"deleting a skill: extension origin or gateway token required",type:"forbidden"}})}if(/^\/skills\/[^/]+\/file\/.+/.test(i)&&n.method==="PUT"){const e=/^\/skills\/([^/]+)\/file\/(.+)$/.exec(i),r=decodeURIComponent(e[1]);return ft(r)||/(^|\/)\.\.(\/|$)/.test(decodeURIComponent(e[2]))?a(o,400,{error:{message:"not a skill file",type:"invalid_request"}}):G(n)?me(n,o,t,`/skills/${encodeURIComponent(r)}/file/${e[2]}`,{method:"PUT",timeoutMs:15e3}):a(o,403,{error:{message:"writing a skill file: extension origin or gateway token required",type:"forbidden"}})}if(n.method==="GET"&&i==="/agent-defs")return me(n,o,t,`/agent-defs${Ee(f,t)}`,{pick:e=>({agents:Array.isArray(e?.agents)?e.agents:[],...e?.quarantined?{quarantined:e.quarantined}:{},...e?.problems?{problems:e.problems}:{}})});if(n.method==="GET"&&/^\/agent-defs\/[^/]+$/.test(i)){const e=decodeURIComponent(i.slice(12));return ft(e)?a(o,400,{error:{message:"not an agent id",type:"invalid_request"}}):me(n,o,t,`/agent-defs/${encodeURIComponent(e)}${Ee(f,t)}`)}if(i.startsWith("/a2a/")){if(!G(n))return a(o,403,{error:{message:"a2a: extension origin or gateway token required",type:"forbidden"}});try{if(n.method==="GET"&&i==="/a2a/agents")return a(o,200,{agents:tr()});if(n.method==="POST"&&i==="/a2a/card"){const e=JSON.parse((await S(n,t.maxBodyBytes)).toString("utf8")||"{}");e.forget&&Yo(e.url||"");const r=await Ue(e.url,{force:!!e.force,auth:String(e.auth||"")});return a(o,200,{ok:!0,card:r.card,fingerprint:r.fingerprint,fresh:r.fresh,changed:!!r.changed,url:r.url})}if(n.method==="POST"&&i==="/a2a/message"){const e=JSON.parse((await S(n,t.maxBodyBytes)).toString("utf8")||"{}"),r=e.card||(await Ue(e.url,{auth:String(e.auth||"")})).card,s=await Xo({card:r,message:e.message||{messageId:`cp_${Date.now().toString(36)}`,role:"ROLE_USER",parts:[{text:String(e.text||"")}]},auth:String(e.auth||""),returnImmediately:!!e.returnImmediately,contextId:String(e.contextId||""),taskId:String(e.taskId||"")});return a(o,200,{ok:!0,...s})}if(n.method==="POST"&&i==="/a2a/message/stream"){const e=JSON.parse((await S(n,t.maxBodyBytes)).toString("utf8")||"{}"),r=e.card||(await Ue(e.url,{auth:String(e.auth||"")})).card;o.writeHead(200,{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"});const s=(l,d)=>o.write(`event: ${l}
51
+ data: ${JSON.stringify(d)}
47
52
 
48
- `);try{const l=await zo({card:r,message:e.message||{messageId:`cp_${Date.now().toString(36)}`,role:"ROLE_USER",parts:[{text:String(e.text||"")}]},auth:String(e.auth||""),contextId:String(e.contextId||""),taskId:String(e.taskId||""),onEvent:u=>s(u.kind,{kind:u.kind,task:u.task,message:u.message})});s("done",l)}catch(l){s("error",{code:l.code||"ERROR",message:l.message})}return o.end()}if(n.method==="POST"&&i==="/a2a/task"){const e=JSON.parse((await v(n,t.maxBodyBytes)).toString("utf8")||"{}"),r=e.card||(await ze(e.url,{auth:String(e.auth||"")})).card,s=e.cancel?await Ho({card:r,id:String(e.id||""),auth:String(e.auth||"")}):await Go({card:r,id:String(e.id||""),auth:String(e.auth||"")});return a(o,200,{ok:!0,...s})}return a(o,404,{error:{message:`no such a2a route: ${i}`,type:"invalid_request"}})}catch(e){const r=e instanceof Ot||e?.name==="A2AClientError"?e.code:"ERROR";return a(o,e instanceof Ot&&e.code==="UNREACHABLE"?502:400,{error:{message:e.message,type:"a2a_error",code:r}})}}if(n.method==="POST"&&(i==="/agent-defs/export"||i==="/agent-defs/export-plan"))return z(n)?pe(n,o,t,i,{method:"POST",timeoutMs:15e3}):a(o,403,{error:{message:"exporting an agent: extension origin or gateway token required",type:"forbidden"}});if(n.method==="GET"&&/^\/skills\/[^/]+$/.test(i)){const e=decodeURIComponent(i.slice(8));return!e||e==="."||e===".."||e.includes("/")||e.includes("\\")?a(o,400,{error:{message:"not a skill id",type:"invalid_request"}}):pe(n,o,t,`/skills/${encodeURIComponent(e)}${Oe(f,t)}`,{pick:r=>({skill:r?.skill||null})})}if(i==="/channels"||/^\/channels\/(connect|pair|unpair|settings|disconnect)$/.test(i)){if(!z(n))return a(o,403,{error:{message:"channels: extension origin or gateway token required",type:"forbidden"}});if(!(i==="/channels"&&n.method==="GET"||i!=="/channels"&&n.method==="POST"))return a(o,405,{error:{message:"method not allowed",type:"invalid_request"}});const e=await $e(t);if(!e)return a(o,503,{error:{message:"no bridge is configured",type:"no_bridge"}});const r=Pe(t.bridge?.token);try{const s=n.method==="POST"?(await v(n,t.maxBodyBytes)).toString("utf8"):"",l=await fetch(`${e}${i}`,{method:n.method,headers:{Accept:"application/json",...n.method==="POST"?{"content-type":"application/json"}:{},...r?{Authorization:`Bearer ${r}`}:{}},...n.method==="POST"?{body:s||"{}"}:{},signal:AbortSignal.timeout(15e3)}),u=await l.json().catch(()=>({}));return a(o,l.status,u)}catch(s){return a(o,502,{error:{message:`bridge unreachable: ${s.message}`,type:"bridge_unreachable"}})}}if(n.method==="GET"&&/^\/skills\/[^/]+\/file\/.+/.test(i)){const e=/^\/skills\/([^/]+)\/file\/(.+)$/.exec(i),r=decodeURIComponent(e[1]),s=e[2];return!r||r==="."||r===".."||r.includes("/")||r.includes("\\")||/(^|\/)\.\.(\/|$)/.test(decodeURIComponent(s))?a(o,400,{error:{message:"not a skill file",type:"invalid_request"}}):pe(n,o,t,`/skills/${encodeURIComponent(r)}/file/${s}${Oe(f,t)}`)}if(n.method==="GET"&&/\/models$/.test(i)){const e=await J(),r=e.sig!==void 0&&e.sig!==y;return y=e.sig,a(o,200,await Jn(t,{serviceHealth:async()=>e,fresh:r}))}if(ha.some(e=>i===e||i.startsWith(`${e}/`)))return a(o,404,{error:{message:`this gateway (${Z}) has no ${i} — update it to use this feature`,type:"unknown_endpoint"}});const V=ra(i,n.headers,t);let H;try{H=await v(n,t.maxBodyBytes)}catch(e){a(o,e.code===413?413:400,{error:e.code===413?"payload too large":"bad request"}),n.destroy();return}let U=null,S=null,ne=H,Me=0,ke=0,ft=0,ge=!1,ve=!0;const Y=t.logRequests&&V.redactable&&n.method==="POST"?oa(oe):null;if(V.redactable&&n.method==="POST"&&H.length){try{S=JSON.parse(H.toString("utf8"))}catch{S=null}if(S&&na(S,V.kind))ne=H;else if(S){const e=t.tools||{};if(e.autoNarrow!==!1&&Array.isArray(S.tools)&&S.tools.length){const T=Number(e.maxPerTurn)>0?Number(e.maxPerTurn):Kn,p=e.narrowAll?null:_=>!Qn.test(eo(_)),O=S.tools.length;S.tools=So(S.tools,Xn(S,V.kind),{cap:T,keep:p,name:eo,description:Yn}),ft=O-S.tools.length}ve=await we(t.pro?.entitlementToken);const r=Mn(t,ve);if(!r.allowed)return a(o,402,{error:{message:`ChatPanel Gateway free trial used up (${r.cap} redactions). Add a ChatPanel Pro entitlement token to unlock unlimited full-tier redaction (names/orgs).`,type:"free_limit_reached"}});ge=String(n.headers["x-chatpanel-redaction"]||"").trim().toLowerCase()==="off"&&z(n),ge||await Ge(t);const s=ge?[]:V.adapter.collectSegments(S,t.redaction),l=new AbortController;o.on("close",()=>{o.writableFinished||l.abort()});const u=Y?Y.clock():0,{vault:k,count:h,sanitized:x}=ge?{vault:null,count:0,sanitized:0}:await Ie(s,t.redaction,{signal:l.signal,isPro:ve,onEgress:T=>ct.push(Yt({ts:Date.now(),client:"redaction",tool:`detect:${T.backend}@${T.host||"local"}`,ok:T.ok,ms:T.ms,error:T.error}))});if(Y&&Y.lap("redact",u),U=k,Me=h,ke=x||0,h>0&&o.setHeader("x-chatpanel-redacted",String(h)),!ve&&h>0){Dn(t,ve);try{me(t,se())}catch{}}if(!ge&&Array.isArray(S.tools)&&S.tools.length&&typeof V.adapter.injectSystemNote=="function"){const T=st(S?.model,t,V.kind,{destination:String(n.headers["x-chatpanel-destination"]||S?.chatpanel?.destination||"").trim(),down:O=>!!O.service&&P.fn(O.id)==="down"}),p=!(T&&T.type==="api");V.adapter.injectSystemNote(S,xo({toolData:t.tools?.toolData,ownTools:p}))}else!ge&&h>0&&typeof V.adapter.injectSystemNote=="function"&&V.adapter.injectSystemNote(S,Oo());ne=Buffer.from(JSON.stringify(S),"utf8")}}const gt=To({vault:U,toolData:t.tools?.toolData}),De=S&&typeof S.chatpanel=="object"&&S.chatpanel||null;if(De&&(delete S.chatpanel,ne=Buffer.from(JSON.stringify(S),"utf8")),typeof S?.model=="string"&&S.model.startsWith("fusion:")){const e=Rr(S.model,t,await J());if(e?.error)return Y?.commit(),a(o,400,{error:{message:e.error,type:"fusion"}});e&&(S.model=e.model,ne=Buffer.from(JSON.stringify(S),"utf8"),o.setHeader("x-chatpanel-fusion",`${e.fusion.id} -> ${e.model}`))}const ae={destination:String(n.headers["x-chatpanel-destination"]||De?.destination||"").trim(),reach:String(n.headers["x-chatpanel-reach"]||De?.reach||"").trim(),run:co(n.headers["x-chatpanel-run"],De?.run)},Qe=await J(),wt=e=>!!e.service&&Qe(e.id)==="down";let D=st(S?.model,t,V.kind,{destination:ae.destination,down:wt});if(D?.type==="agent"&&S?.model&&!ae.destination&&!Hn(D,S.model)&&(await Gn(t,{serviceHealth:async()=>Qe}),D=st(S?.model,t,V.kind,{destination:ae.destination,down:wt})),D?.service&&Qe(D.id)==="down")return Y?.commit(),a(o,503,{error:{message:`${D.id} is not running — the model ${JSON.stringify(S?.model||"")} is served by an engine the Runtime has stopped; start it under Settings › Runtime`,type:"engine_down",service:D.service}});if(ae.destination&&(!D||D.id!==ae.destination))return Y?.commit(),a(o,404,{error:{message:`no destination "${ae.destination}" is configured on this gateway`,type:"unknown_destination",known:zn(t).map(e=>e.id)}});Y&&(Y.meta={t:Date.now(),model:S?.model||null,dest:D?D.id:null,type:D?D.type:null,redacted:Me,sanitized:ke,narrowed:ft,detail:no(U,t.logDetail),redaction:ge?"off":t.redaction.tier||"basic"});const Ce=Co();if(Ce&&D){const e=D.type==="api"?xt(Ce,{model:S?.model||"",endpoint:D.baseUrl||""}):Io(Ce,D.agent||D.id)?xt(Ce,{model:S?.model||""}):{ok:!1,reason:`agent "${D.agent||D.id}" is not allowed by your organisation’s policy`};if(!e.ok)return Y?.commit(),a(o,403,{error:{message:e.reason,type:"policy",code:"org_policy"}})}if(D&&D.type==="api")return D.baseUrl?aa(D.baseUrl,t)?(Y?.commit(),a(o,508,{error:{message:`destination "${D.id}" points back at the gateway (${D.baseUrl}) — refusing to forward (would loop).`,type:"loop_detected"}})):ya(n,o,{...V,pathname:i,search:f.search,base:D.baseUrl,destKey:D.apiKey,destProtocol:D.protocol,harness:gt,trace:Y},ne,U):(Y?.commit(),a(o,502,{error:`destination "${D.id}" has no baseUrl`}));const Ye=Le(n),bt=Ye==="local"&&t.bridge?.openAgentLane?"token":Ye;if(bt==="local")return Y?.commit(),a(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 kt=Math.max(0,Math.min(8,Number(n.headers["x-chatpanel-ask-depth"])||0)),uo=new Set(["thread","ephemeral","workingDir"]);if(Ye==="token"&&n.headers["x-chatpanel-link-device"]&&!(ae.run&&Object.keys(ae.run).some(e=>!uo.has(e)))){const e=co(null,ir(sr(q.get("agentTools").agentTools?.value,D?.agent||S?.model)));e&&(ae.run={...e,...ae.run||{}})}const Re=Eo({...ae.run||{},...ae.reach?{reach:ae.reach}:{},...kt?{askDepth:kt}:{}},bt);return Re.reach&&o.setHeader("x-chatpanel-reach-used",Re.reach),ca(n,o,{...V,pathname:i,agentOverride:D?.agent,harness:gt,trace:Y,run:Object.keys(Re).length?Re:null},S,U,t,ve)});return ce.on("close",()=>{g?.stop("closed"),Fr(),d.close(),c?.stop()}),ce.on("upgrade",(n,o,f)=>{o.on("error",()=>{});const i=String(n.url||"").split("?")[0];if(c&&i.startsWith(an)){c.acceptTunnel(n,o,f).catch(()=>{try{o.destroy()}catch{}});return}try{o.end(`HTTP/1.1 404 Not Found\r
53
+ `);try{const l=await Zo({card:r,message:e.message||{messageId:`cp_${Date.now().toString(36)}`,role:"ROLE_USER",parts:[{text:String(e.text||"")}]},auth:String(e.auth||""),contextId:String(e.contextId||""),taskId:String(e.taskId||""),onEvent:d=>s(d.kind,{kind:d.kind,task:d.task,message:d.message})});s("done",l)}catch(l){s("error",{code:l.code||"ERROR",message:l.message})}return o.end()}if(n.method==="POST"&&i==="/a2a/task"){const e=JSON.parse((await S(n,t.maxBodyBytes)).toString("utf8")||"{}"),r=e.card||(await Ue(e.url,{auth:String(e.auth||"")})).card,s=e.cancel?await er({card:r,id:String(e.id||""),auth:String(e.auth||"")}):await qo({card:r,id:String(e.id||""),auth:String(e.auth||"")});return a(o,200,{ok:!0,...s})}return a(o,404,{error:{message:`no such a2a route: ${i}`,type:"invalid_request"}})}catch(e){const r=e instanceof Nt||e?.name==="A2AClientError"?e.code:"ERROR";return a(o,e instanceof Nt&&e.code==="UNREACHABLE"?502:400,{error:{message:e.message,type:"a2a_error",code:r}})}}if(n.method==="POST"&&(i==="/agent-defs/export"||i==="/agent-defs/export-plan"))return G(n)?me(n,o,t,i,{method:"POST",timeoutMs:15e3}):a(o,403,{error:{message:"exporting an agent: extension origin or gateway token required",type:"forbidden"}});if(n.method==="GET"&&/^\/skills\/[^/]+$/.test(i)){const e=decodeURIComponent(i.slice(8));return!e||e==="."||e===".."||e.includes("/")||e.includes("\\")?a(o,400,{error:{message:"not a skill id",type:"invalid_request"}}):me(n,o,t,`/skills/${encodeURIComponent(e)}${Ee(f,t)}`,{pick:r=>({skill:r?.skill||null})})}if(i==="/channels"||/^\/channels\/(connect|pair|unpair|settings|disconnect)$/.test(i)){if(!G(n))return a(o,403,{error:{message:"channels: extension origin or gateway token required",type:"forbidden"}});if(!(i==="/channels"&&n.method==="GET"||i!=="/channels"&&n.method==="POST"))return a(o,405,{error:{message:"method not allowed",type:"invalid_request"}});const e=await Be(t);if(!e)return a(o,503,{error:{message:"no bridge is configured",type:"no_bridge"}});const r=Me(t.bridge?.token);try{const s=n.method==="POST"?(await S(n,t.maxBodyBytes)).toString("utf8"):"",l=await fetch(`${e}${i}`,{method:n.method,headers:{Accept:"application/json",...n.method==="POST"?{"content-type":"application/json"}:{},...r?{Authorization:`Bearer ${r}`}:{}},...n.method==="POST"?{body:s||"{}"}:{},signal:AbortSignal.timeout(15e3)}),d=await l.json().catch(()=>({}));return a(o,l.status,d)}catch(s){return a(o,502,{error:{message:`bridge unreachable: ${s.message}`,type:"bridge_unreachable"}})}}if(n.method==="GET"&&/^\/skills\/[^/]+\/file\/.+/.test(i)){const e=/^\/skills\/([^/]+)\/file\/(.+)$/.exec(i),r=decodeURIComponent(e[1]),s=e[2];return!r||r==="."||r===".."||r.includes("/")||r.includes("\\")||/(^|\/)\.\.(\/|$)/.test(decodeURIComponent(s))?a(o,400,{error:{message:"not a skill file",type:"invalid_request"}}):me(n,o,t,`/skills/${encodeURIComponent(r)}/file/${s}${Ee(f,t)}`)}if(n.method==="GET"&&/\/models$/.test(i)){const e=await J(),r=e.sig!==void 0&&e.sig!==v;return v=e.sig,a(o,200,await Zn(t,{serviceHealth:async()=>e,fresh:r,engineAt:c.engineAt}))}if(_a.some(e=>i===e||i.startsWith(`${e}/`)))return a(o,404,{error:{message:`this gateway (${X}) has no ${i} — update it to use this feature`,type:"unknown_endpoint"}});const z=ya(i,n.headers,t);let K;try{K=await S(n,t.maxBodyBytes)}catch(e){a(o,e.code===413?413:400,{error:e.code===413?"payload too large":"bad request"}),n.destroy();return}let V=null,O=null,ye=K,gt=0,wt=0,bt=0,we=!1,Te=!1,kt="",xe=!0;const q=t.logRequests&&z.redactable&&n.method==="POST"?ha(ge):null;if(z.redactable&&n.method==="POST"&&K.length){try{O=JSON.parse(K.toString("utf8"))}catch{O=null}if(O&&fa(O,z.kind))ye=K;else if(O){const e=t.tools||{};if(e.autoNarrow!==!1&&Array.isArray(O.tools)&&O.tools.length){const w=Number(e.maxPerTurn)>0?Number(e.maxPerTurn):sa,b=e.narrowAll?null:x=>!ia.test(io(x)),E=O.tools.length;O.tools=Ao(O.tools,da(O,z.kind),{cap:w,keep:b,name:io,description:la}),bt=E-O.tools.length}xe=await ke(t.pro?.entitlementToken);const r=Vn(t,xe);if(!r.allowed)return a(o,402,{error:{message:`ChatPanel Gateway free trial used up (${r.cap} redactions). Add a ChatPanel Pro entitlement token to unlock unlimited full-tier redaction (names/orgs).`,type:"free_limit_reached"}});if(we=String(n.headers["x-chatpanel-redaction"]||"").trim().toLowerCase()==="off"&&G(n),!we){const w=Qe(O?.model,t,z.kind,{destination:String(n.headers["x-chatpanel-destination"]||O?.chatpanel?.destination||"").trim(),down:()=>!1}),b=w?.type==="api"?await c.decide(w,O?.model).catch(()=>null):null;Te=b?.redact===!1,kt=Te?b.engine||"declared":""}!we&&!Te&&await He(t);const s=we?[]:z.adapter.collectSegments(O,t.redaction),l=new AbortController;o.on("close",()=>{o.writableFinished||l.abort()});const d=q?q.clock():0,{vault:h,count:p,sanitized:T}=we?{vault:null,count:0,sanitized:0}:await ze(s,t.redaction,{signal:l.signal,isPro:xe,sanitizeOnly:Te,onEgress:w=>ut.push(ro({ts:Date.now(),client:"redaction",tool:`detect:${w.backend}@${w.host||"local"}`,ok:w.ok,ms:w.ms,error:w.error}))});if(q&&q.lap("redact",d),V=h,gt=p,wt=T||0,p>0&&o.setHeader("x-chatpanel-redacted",String(p)),!xe&&p>0){Fn(t,xe);try{ue(t,ae())}catch{}}if(!we&&!Te&&Array.isArray(O.tools)&&O.tools.length&&typeof z.adapter.injectSystemNote=="function"){const w=Qe(O?.model,t,z.kind,{destination:String(n.headers["x-chatpanel-destination"]||O?.chatpanel?.destination||"").trim(),down:E=>!!E.service&&M.fn(E.id)==="down"}),b=!(w&&w.type==="api");z.adapter.injectSystemNote(O,Bo({toolData:t.tools?.toolData,ownTools:b}))}else!we&&p>0&&typeof z.adapter.injectSystemNote=="function"&&z.adapter.injectSystemNote(O,Mo());ye=Buffer.from(JSON.stringify(O),"utf8")}}const vt=No({vault:V,toolData:t.tools?.toolData}),Ie=O&&typeof O.chatpanel=="object"&&O.chatpanel||null;if(Ie&&(delete O.chatpanel,ye=Buffer.from(JSON.stringify(O),"utf8")),typeof O?.model=="string"&&O.model.startsWith("fusion:")){const e=Fr(O.model,t,await J());if(e?.error)return q?.commit(),a(o,400,{error:{message:e.error,type:"fusion"}});e&&(O.model=e.model,ye=Buffer.from(JSON.stringify(O),"utf8"),o.setHeader("x-chatpanel-fusion",`${e.fusion.id} -> ${e.model}`))}const ne={destination:String(n.headers["x-chatpanel-destination"]||Ie?.destination||"").trim(),reach:String(n.headers["x-chatpanel-reach"]||Ie?.reach||"").trim(),run:wo(n.headers["x-chatpanel-run"],Ie?.run)},je=await J(),St=e=>!!e.service&&je(e.id)==="down";let D=Qe(O?.model,t,z.kind,{destination:ne.destination,down:St});D?.type==="agent"&&O?.model&&!ne.destination&&!ta(D,O.model)&&(await ea(t,{serviceHealth:async()=>je,engineAt:c.engineAt}),D=Qe(O?.model,t,z.kind,{destination:ne.destination,down:St}));const Tt=D?.service&&je(D.id)==="down"?await A().revive(D.service).catch(()=>null):null;if(Tt?.ok&&(M.at=0),D?.service&&je(D.id)==="down"&&!Tt?.ok)return q?.commit(),a(o,503,{error:{message:`${D.id} is not running — the model ${JSON.stringify(O?.model||"")} is served by an engine the Runtime has stopped; start it under Settings › Runtime`,type:"engine_down",service:D.service}});if(ne.destination&&(!D||D.id!==ne.destination))return q?.commit(),a(o,404,{error:{message:`no destination "${ne.destination}" is configured on this gateway`,type:"unknown_destination",known:qn(t).map(e=>e.id)}});q&&(q.meta={t:Date.now(),model:O?.model||null,dest:D?D.id:null,type:D?D.type:null,redacted:gt,sanitized:wt,narrowed:bt,detail:mo(V,t.logDetail),redaction:we?"off":Te?`on-device (${kt})`:t.redaction.tier||"basic"});const Le=Fo();if(Le&&D){const e=D.type==="api"?At(Le,{model:O?.model||"",endpoint:D.baseUrl||""}):Ko(Le,D.agent||D.id)?At(Le,{model:O?.model||""}):{ok:!1,reason:`agent "${D.agent||D.id}" is not allowed by your organisation’s policy`};if(!e.ok)return q?.commit(),a(o,403,{error:{message:e.reason,type:"policy",code:"org_policy"}})}if(D&&D.type==="api")return D.baseUrl?ga(D.baseUrl,t)?(q?.commit(),a(o,508,{error:{message:`destination "${D.id}" points back at the gateway (${D.baseUrl}) — refusing to forward (would loop).`,type:"loop_detected"}})):Ea(n,o,{...z,pathname:i,search:f.search,base:D.baseUrl,destKey:D.apiKey,destProtocol:D.protocol,harness:vt,trace:q},ye,V):(q?.commit(),a(o,502,{error:`destination "${D.id}" has no baseUrl`}));const Ze=Ae(n),xt=Ze==="local"&&t.bridge?.openAgentLane?"token":Ze;if(xt==="local")return q?.commit(),a(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 Ot=Math.max(0,Math.min(8,Number(n.headers["x-chatpanel-ask-depth"])||0)),bo=new Set(["thread","ephemeral","workingDir"]);if(Ze==="token"&&n.headers["x-chatpanel-link-device"]&&!(ne.run&&Object.keys(ne.run).some(e=>!bo.has(e)))){const e=wo(null,gr(fr(te.get("agentTools").agentTools?.value,D?.agent||O?.model)));e&&(ne.run={...e,...ne.run||{}})}const Je=Co({...ne.run||{},...ne.reach?{reach:ne.reach}:{},...Ot?{askDepth:Ot}:{}},xt);return Je.reach&&o.setHeader("x-chatpanel-reach-used",Je.reach),Sa(n,o,{...z,pathname:i,agentOverride:D?.agent,harness:vt,trace:q,run:Object.keys(Je).length?Je:null},O,V,t,xe)});return de.on("close",()=>{B?.stop("closed"),on(),m.close(),g?.stop()}),de.on("upgrade",(n,o,f)=>{o.on("error",()=>{});const i=String(n.url||"").split("?")[0];if(g&&i.startsWith(gn)){g.acceptTunnel(n,o,f).catch(()=>{try{o.destroy()}catch{}});return}try{o.end(`HTTP/1.1 404 Not Found\r
49
54
  connection: close\r
50
55
  content-length: 0\r
51
56
  \r
52
- `)}catch{}}),ce.once("listening",()=>{M()}),ce.linkHost=c,ce}function co(t,d){let c=d&&typeof d=="object"?d:null;if(!c&&t)try{c=JSON.parse(decodeURIComponent(String(t)))}catch{c=null}if(!c||typeof c!="object")return null;const m={};if(Array.isArray(c.grants)&&(m.grants=c.grants.map(g=>String(g).slice(0,80)).slice(0,32)),c.workspace&&typeof c.workspace=="object"&&c.workspace.repo){const g=c.workspace;m.workspace={repo:String(g.repo).slice(0,400),projectId:String(g.projectId||"").slice(0,120),jobId:String(g.jobId||"").slice(0,120),...g.base?{base:String(g.base).slice(0,120)}:{}}}if(c.connectionId&&(m.connectionId=String(c.connectionId).slice(0,64)),typeof c.workingDir=="string"&&c.workingDir.trim()&&/^([A-Za-z]:[\\/]|\/)/.test(c.workingDir.trim())&&(m.workingDir=c.workingDir.trim().slice(0,1024)),jn.includes(c.permissionMode)&&c.permissionMode!=="default"&&(m.permissionMode=c.permissionMode),c.sandbox&&typeof c.sandbox=="object"){const g=(Array.isArray(c.sandbox.hosts)?c.sandbox.hosts:String(c.sandbox.hosts||"").split(/[\s,;]+/)).map(y=>String(y).trim().toLowerCase().slice(0,253)).filter(Boolean).slice(0,64),E=(Array.isArray(c.sandbox.write)?c.sandbox.write:[]).map(y=>String(y).slice(0,1024)).filter(Boolean).slice(0,32),P=c.sandbox.outside===!0;(g.length||E.length||P)&&(m.sandbox={...g.length?{hosts:g}:{},...E.length?{write:E}:{},...P?{outside:!0}:{}})}const w=lr(c.thread);return w&&(m.thread=w),c.ephemeral===!0&&(m.ephemeral=!0),Object.keys(m).length?m:null}let Be=null,Ke=null;async function Us(t=vt()){tr();let d=null;try{d=await Do()}catch(y){throw y instanceof Ro&&(console.error(`[chatpanel-gateway] org policy: ${y.message}`),process.exit(78)),y}const c=d?.policy||null;c&&(Tt(t,c),console.log(`[chatpanel-gateway] ${d.label} — ${d.signed?"signed":"unsigned"} policy from ${d.source}`)),Bo(globalThis,{allow:c?.egress?(y,{local:J})=>jo(c,y,{local:J}):null}),Se();const m=fa(t),w=Zo(t),g=yo(t);let E=!1;m.on("error",y=>{if(y&&y.code==="EADDRINUSE"){const J=We(t.host)?"127.0.0.1":t.host;fetch(`http://${J}:${t.port}/health`,{signal:AbortSignal.timeout(1500)}).then(b=>b.ok?b.json():null).catch(()=>null).then(b=>{const M=!!(b?.version&&typeof b.tier=="string"),j=dr({name:"gateway",self:Z,holder:M?{ours:M,version:b.version}:null,managedBy:cr(process.env),port:t.port});if(j.action==="standby"||E&&!b){if(!E)for(const L of j.lines)console.error(L);E=!0,setTimeout(()=>m.listen(t.port,t.host),ur);return}if(M){const L=b.managedBy?` (run by ${b.managedBy})`:"";for(const[de,re]of j.lines.entries())console.error(de===0?re.replace(` on ${t.port}`,` at http://${J}:${t.port}${L}`):re)}else{const L=Or(t.port);console.error(`Port ${t.port} is held by ${L||"another program"}, which is not a ChatPanel gateway.`),console.error(`Fix: stop that program, or set a different port — edit "port" in ${se()} (or the extension's Gateway tab) and restart. The extension must point at the same port.`)}process.exit(1)});return}console.error(`Gateway server error: ${y?.message||y}`),process.exit(1)}),m.listen(t.port,t.host,()=>{E&&console.log(" standby : the other gateway is gone — this copy has the port now"),E=!1,console.log(`ChatPanel Privacy Gateway v${Z} on http://${t.host}:${t.port}`),m.linkHost?.start().catch(y=>console.log(` link : not started (${y?.message||y})`)),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"),Ke={mode:"starting",version:null,pid:null,restarts:0,why:"deciding: adopt the bridge that answers, or start ours"},xr(t,{childEnv:()=>({...Ln(t),...In(t)})}).then(y=>{Be=y}).catch(y=>{Ke={mode:"off",version:null,pid:null,restarts:0,why:`not supervised (${y?.message||y})`},console.log(` bridge : not supervised (${y?.message||y})`)}),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…)":"")),We(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.`)}),At()&&rt(B,et()).then(y=>{y?.ok&&(console.log(` warm : seeded ${y.ingested} records from ${y.file}`),y.whole&&Ne())}).catch(()=>{});const P=()=>{w?.stop(),g.stop(),Be?.stop(),Wn(m)};return process.on("SIGINT",P),process.on("SIGTERM",P),m}export{sa as RECORDS_MAX_BYTES,Ws as VERSION,fa as createGateway,ua as joinUpstream,ut as parseAgentModel,Us as start};
57
+ `)}catch{}}),de.once("listening",()=>{A()}),de.linkHost=g,de.runtimeDefaults=()=>A().ensureDefaults(),de}function wo(t,c){let u=c&&typeof c=="object"?c:null;if(!u&&t)try{u=JSON.parse(decodeURIComponent(String(t)))}catch{u=null}if(!u||typeof u!="object")return null;const m={};if(Array.isArray(u.grants)&&(m.grants=u.grants.map(k=>String(k).slice(0,80)).slice(0,32)),u.workspace&&typeof u.workspace=="object"&&u.workspace.repo){const k=u.workspace;m.workspace={repo:String(k.repo).slice(0,400),projectId:String(k.projectId||"").slice(0,120),jobId:String(k.jobId||"").slice(0,120),...k.base?{base:String(k.base).slice(0,120)}:{}}}if(u.connectionId&&(m.connectionId=String(u.connectionId).slice(0,64)),typeof u.workingDir=="string"&&u.workingDir.trim()&&/^([A-Za-z]:[\\/]|\/)/.test(u.workingDir.trim())&&(m.workingDir=u.workingDir.trim().slice(0,1024)),Yn.includes(u.permissionMode)&&u.permissionMode!=="default"&&(m.permissionMode=u.permissionMode),u.sandbox&&typeof u.sandbox=="object"){const k=(Array.isArray(u.sandbox.hosts)?u.sandbox.hosts:String(u.sandbox.hosts||"").split(/[\s,;]+/)).map(y=>String(y).trim().toLowerCase().slice(0,253)).filter(Boolean).slice(0,64),_=(Array.isArray(u.sandbox.write)?u.sandbox.write:[]).map(y=>String(y).slice(0,1024)).filter(Boolean).slice(0,32),B=u.sandbox.outside===!0;(k.length||_.length||B)&&(m.sandbox={...k.length?{hosts:k}:{},..._.length?{write:_}:{},...B?{outside:!0}:{}})}const g=wr(u.thread);return g&&(m.thread=g),u.ephemeral===!0&&(m.ephemeral=!0),Object.keys(m).length?m:null}let Re=null,Xe=null;async function si(t=_t()){ur();let c=null;try{c=await Vo()}catch(y){throw y instanceof Wo&&(console.error(`[chatpanel-gateway] org policy: ${y.message}`),process.exit(78)),y}const u=c?.policy||null;u&&(Pt(t,u),console.log(`[chatpanel-gateway] ${c.label} — ${c.signed?"signed":"unsigned"} policy from ${c.source}`)),Uo(globalThis,{allow:u?.egress?(y,{local:M})=>Qo(u,y,{local:M}):null}),ve();const m=$a(t),g=lr(t),k=To(t);let _=!1;m.on("error",y=>{if(y&&y.code==="EADDRINUSE"){const M=Ye(t.host)?"127.0.0.1":t.host;fetch(`http://${M}:${t.port}/health`,{signal:AbortSignal.timeout(1500)}).then(v=>v.ok?v.json():null).catch(()=>null).then(v=>{const J=!!(v?.version&&typeof v.tier=="string"),L=br({name:"gateway",self:X,holder:J?{ours:J,version:v.version}:null,managedBy:kr(process.env),port:t.port});if(L.action==="standby"||_&&!v){if(!_)for(const A of L.lines)console.error(A);_=!0,setTimeout(()=>m.listen(t.port,t.host),vr);return}if(J){const A=v.managedBy?` (run by ${v.managedBy})`:"";for(const[ie,re]of L.lines.entries())console.error(ie===0?re.replace(` on ${t.port}`,` at http://${M}:${t.port}${A}`):re)}else{const A=Cr(t.port);console.error(`Port ${t.port} is held by ${A||"another program"}, which is not a ChatPanel gateway.`),console.error(`Fix: stop that program, or set a different port — edit "port" in ${ae()} (or the extension's Gateway tab) and restart. The extension must point at the same port.`)}process.exit(1)});return}console.error(`Gateway server error: ${y?.message||y}`),process.exit(1)}),m.listen(t.port,t.host,()=>{_&&console.log(" standby : the other gateway is gone — this copy has the port now"),_=!1,console.log(`ChatPanel Privacy Gateway v${X} on http://${t.host}:${t.port}`),m.linkHost?.start().catch(y=>console.log(` link : not started (${y?.message||y})`)),m.runtimeDefaults?.().then(y=>{for(const M of y||[])console.log(` ${M.label.toLowerCase().padEnd(9).slice(0,9)}: ${M.ok?M.already?"running":M.adopted?"already running — adopted":"started":`not started (${M.skipped})`}`)}).catch(y=>console.log(` runtime : defaults not started (${y?.message||y})`)),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"),Xe={mode:"starting",version:null,pid:null,restarts:0,why:"deciding: adopt the bridge that answers, or start ours"},Dr(t,{childEnv:()=>({...Xn(t),...Qn(t)})}).then(y=>{Re=y}).catch(y=>{Xe={mode:"off",version:null,pid:null,restarts:0,why:`not supervised (${y?.message||y})`},console.log(` bridge : not supervised (${y?.message||y})`)}),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…)":"")),Ye(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.`)}),It()&&at(R,ot()).then(y=>{y?.ok&&(console.log(` warm : seeded ${y.ingested} records from ${y.file}`),y.whole&&Ce())}).catch(()=>{});const B=()=>{g?.stop(),k.stop(),Re?.stop(),aa(m)};return process.on("SIGINT",B),process.on("SIGTERM",B),m}export{wa as RECORDS_MAX_BYTES,di as VERSION,$a as createGateway,Ta as joinUpstream,mt as parseAgentModel,si as start};