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