@chatpanel/gateway 0.85.5 → 0.87.0

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