@chatpanel/gateway 0.168.0 → 0.168.1

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@chatpanel/gateway",
3
- "version": "0.168.0",
3
+ "version": "0.168.1",
4
4
  "description": "Local privacy gateway — redacts PII out of OpenAI/Anthropic API traffic before it reaches a model, then restores it in the reply. Point opencode, codex, aider, Claude Code, etc. at it.",
5
5
  "type": "module",
6
6
  "bin": {
@@ -24,7 +24,7 @@
24
24
  "dependencies": {
25
25
  "@anthropic-ai/sandbox-runtime": "^0.0.77",
26
26
  "@chatpanel/bridge": "^0.53.0",
27
- "@chatpanel/events": "^0.520.0",
27
+ "@chatpanel/events": "^0.521.0",
28
28
  "@chatpanel/pii": "^0.15.6",
29
29
  "@huggingface/transformers": "^4.2.0",
30
30
  "defuddle": "^0.19.4",
package/src/server.js CHANGED
@@ -1,4 +1,4 @@
1
- import{createServer as _r}from"node:http";import{loadConfig as co}from"./config.js";import{startEntitlementRefresh as Or,maybeRevalidate as Er}from"./entitlement-refresh.js";import{redactSegments as qe,segment as ht,rememberAnswer as uo}from"./redact.js";import{pipeRestoredStream as Pr,pipeRestoredOpenAIStream as $r,makeTokenRestorer as mo,restoreDeep as Ar}from"./stream.js";import{restoreText as Nr,gatedDictionary as Br,narrowSpecs as Mr,makeToolHarness as Dr,placeholderToolNote as Cr,placeholderNote as Ir,assertEndpointUrl as Rr,capRunOptions as Jr,isPaired as po}from"@chatpanel/pii";import{ensureGatewayToken as Pe,currentGatewayToken as Re,isAdminAuthorized as J,callerTrustOf as et,setPinnedExtensionIds as Lr,issuePairingCode as jr,claimPairingCode as Gr}from"./gateway-token.js";import{createPairAsk as zr,nativeConfirm as Ur}from"./pair-prompt.js";import{createEngineProbe as Hr}from"./local-engine-probe.js";import{randomUUID as Vr}from"node:crypto";import{installEgressLedger as Fr,egressAudit as Wr}from"./egress.js";import{trustSystemCertificates as Kr,systemCaWanted as ho,systemCaState as Qr}from"./system-ca.js";import{initPolicy as Yr,activePolicy as yt,applyPolicyToConfig as yo,managedSummary as tt,PolicyLoadError as Xr}from"./policy.js";import{routeAllowed as fo,agentAllowed as Zr,egressAllowed as qr}from"@chatpanel/events/policy.js";import{resolveBridgeUrl as ot}from"./bridge.js";import{secureFetch as Ve}from"./secure-fetch.js";import{fetchCard as ft,forgetCard as en,sendMessage as tn,streamMessage as on,getTask as rn,cancelTask as nn,knownAgents as an,A2AError as go}from"./a2a.js";import{streamBridgeChat as wo,readBridgeToken as rt,openBridgeChat as sn,acceptedBridgeToken as bo}from"./bridge.js";import{createRelaySession as ln,getRelaySession as ko,endRelaySession as nt,pumpBridgeStream as dn,deliverToolResult as vo,toolsToSpecs as cn,wantsApprovals as un,parseToolCallId as So,touchRelaySession as gt}from"./toolrelay.js";import{shaperFor as At}from"./shape.js";import{startNer as mn,ensureNer as wt,unionForThisMachine as pn,skippedCompanions as hn}from"./ner.js";import{recommendDetector as To}from"@chatpanel/pii/detector-router.js";import{installTimestampedConsole as yn}from"./log.js";import{saveBackupSecret as fn,clearBackupSecret as gn,loadBackupSecret as Nt,hasBackupSecret as xo}from"./history-store.js";import{createContextsApi as wn,handleContexts as bn}from"./contexts-api.js";let _o=null;import{createMemoryStore as kn}from"./memory-store.js";import{createPrefsStore as vn}from"./prefs-store.js";import{agentCardFor as Oo,runHintFor as Eo}from"@chatpanel/events/agent-run-hint.js";import{normalizeThread as Sn}from"@chatpanel/events/agent-thread.js";import{cleanRecordId as Po}from"@chatpanel/events/history-search.js";import{portClashPlan as Tn,serviceManagerOf as xn,STANDBY_POLL_MS as _n}from"@chatpanel/events/service-standby.js";import{threadTarget as On,frameQuestion as En,wireMessages as Pn,appendExchange as $n,MAX_MESSAGE as $o}from"@chatpanel/events/thread-send.js";import{researchStore as An,researchResponse as Nn}from"./research.js";import{createTeamStore as Bn,loadOrCreateKey as Bt}from"./team-store.js";import{createScorecardStore as Mn}from"./scorecard-store.js";import{createEngineLedgerStore as Dn}from"./engine-ledger-store.js";import{createProjectStore as Cn}from"./project-store.js";import{applicationsFor as In,recruitPass as Rn}from"./recruiting.js";import{ensureBridge as Jn,holderOf as Ln}from"./bridge-supervisor.js";import{checkForUpdate as jn,updateStatus as Gn,startUpdate as zn,updateJob as Un,installKind as Hn}from"./update.js";import{confinedStatus as at,confinedLine as Vn}from"./confine.js";import{appleHelperWanted as Fn,findAppleHelper as Mt}from"./apple-helper-fetch.js";import{createHistoryStore as Wn}from"./sqlite-store.js";import{createEventStore as Kn}from"./event-store.js";import{createGatewayEvents as Qn}from"./gateway-events.js";import{createPrincipals as Yn,presentedToken as Ao,LOCAL_AGENT_ID as No}from"./principals.js";import{createOidc as Xn,looksLikeJwt as Zn,normalizeOidc as Bo}from"./oidc.js";import{createLinkActivity as qn,linkSurface as ea,sseUsageTap as ta,usageOfBody as oa,GATEWAY_HOST as Mo}from"./link-activity.js";import{ingestCloudEvents as ra,cursorOf as Do}from"./event-sync.js";import{eventStats as na,projectYear as aa}from"./event-stats.js";import{toCloudEvent as Dt,ceHostOf as sa}from"./cloudevents.js";import{fusionsDocument as ia,resolveFusionModel as la}from"./fusions.js";import{ingestBackups as Ct}from"./backup-ingest.js";import{toSearchRecord as Co}from"@chatpanel/events/library.js";import{deriveBackupKey as da,openRecord as ca,keyCache as ua,nodeCodec as ma}from"@chatpanel/events/backup-envelope.js";import pa from"node:zlib";import*as z from"./ner-engine.js";import It from"node:os";import{capabilitiesDocument as ha,handleDetect as ya}from"./capabilities.js";import{createExtractService as fa}from"./extract/service.js";import{workerSandbox as ga,disposeWorkerSandbox as wa}from"./worker-sandbox.js";import{createRuntime as ba,SERVICES as ka,BUILTIN_IDS as va}from"./runtime.js";import{saveOwnManifest as Sa,removeOwnManifest as Ta}from"./engine-plugins.js";import{createCapabilityProxy as xa}from"./capability-proxy.js";import{createEmbeddedCapabilities as _a}from"./capability-embedded.js";import{EMBEDDED_MODELS as Oa,EMBEDDED_IDS as Ea}from"./embedded-models.js";import{handleExtract as Pa,handleExtractContext as $a}from"./extract/handler.js";import{createKbStore as Aa}from"./kb-store.js";import{createKbService as Na}from"./kb.js";import{createViewKey as Ba}from"./kb-view-key.js";import{MAX_DOCUMENT_BYTES as bt}from"./extract-capability.js";import{createReader as Ma}from"./retrieval/read.js";import{createBrowserRelayHost as Da}from"./browser-relay.js";import{createLinkHost as Ca}from"./link-host.js";import{checkLinkRoute as Io,tunnelHeader as Ia,LINK_TUNNEL_ROOM_PATH as Ra}from"@chatpanel/events/link-routes.js";import{createTailscale as Ja}from"./tailscale.js";import{linkCallerOf as Me,linkDestinationAllowed as La,linkVia as ja,partnerRunHint as Ga,PARTNER_APPROVAL_DECISIONS as Ro,partnerFilePath as za}from"@chatpanel/events/link-scopes.js";import{listPartnerFiles as Ua,readPartnerFile as Ha,writePartnerFile as Va,removePartnerFile as Fa}from"./link-files.js";import{handleFileWrite as Wa}from"./file-write.js";import{handleFileRead as Ka}from"./file-read.js";import{handleAppleNotes as Qa}from"./apple-notes.js";import{handlePickFolder as Ya}from"./folder-picker.js";import{createContextService as Xa}from"./context.js";import{createBucketSync as Za}from"./kb-bucket-sync.js";import{createCloudProfiles as qa}from"./cloud-profiles.js";import{revealPath as es}from"./reveal.js";import{apiEnginesFrom as ts}from"@chatpanel/events/search-api.js";import{CONTEXT_FEDERATED_HEADER as os}from"@chatpanel/events/context-api.js";import{WRITE_MAX_BYTES as rs}from"@chatpanel/events/file-write.js";import{isPermissionTool as Jo}from"@chatpanel/events/agent-permission.js";import{createApprovalInbox as ns}from"./link-approvals.js";import{createSearcher as as,toJinaSearch as ss,SEARCH_DEFAULTS as is}from"./retrieval/search.js";import{createSearxng as ls}from"./retrieval/search-searxng.js";import{searchEngines as ds}from"./retrieval/search-apis.js";import{toJinaText as cs}from"./read-document.js";import*as A from"./stt-engine.js";import*as P from"./diarize-engine.js";import*as Je from"./translate-engine.js";import*as us from"./indictrans-engine.js";import*as Rt from"./aec-engine.js";import{speechCoverage as ms}from"@chatpanel/events/speech-language.js";import*as ps from"./segment-engine.js";import{DIARIZE_MODEL_CATALOG as hs,DEFAULT_DIARIZE_MODEL as ys,isKnownDiarizeModel as Lo,diarizeModelEntry as fs}from"./diarize-models.js";import{providerOf as Jt}from"./providers.js";import{createRemoteTranscriber as jo}from"./stt-remote.js";import{parseMultipart as gs,decodeAudioFile as ws}from"./audio-file.js";import{MODEL_CATALOG as Go,isKnownModel as zo,isValidCustomModelId as Uo,recommendFor as bs}from"./models.js";import{STT_MODEL_CATALOG as ks,isKnownSttModel as vs,isValidCustomSttId as Ss,DEFAULT_STT_MODEL as Fe,STT_DTYPES as Ts,isValidDtype as xs,sttModel as kt,sttModelUnavailable as Ho,licenseAcceptance as Vo}from"./stt-models.js";import*as L from"./tts-engine.js";import{TTS_MODEL_CATALOG as Fo,TTS_VOICES as _s,isKnownTtsModel as Os,isValidCustomTtsId as Es,isKnownVoice as Wo,isValidVoiceId as Ko,DEFAULT_TTS_MODEL as Qo,DEFAULT_TTS_VOICE as De,TTS_DTYPES as Ps,isValidTtsDtype as $s,MAX_TTS_CHARS as Yo,ttsModelHasCustomVoices as As,resolveDefaultModel as Xo,POCKET_VOICES as Ns,DEFAULT_POCKET_VOICE as vt,isPocketVoice as St,ttsModelEngine as Tt}from"./tts-models.js";import{ttsDestination as Bs,synthesizeRemote as Ms,isValidRemoteVoice as Ds}from"./tts-remote.js";import{rawOrtAvailable as Lt}from"./ort.js";import*as ce from"./tts-voices.js";import{resolveTtsVoice as Cs}from"./tts-voice-resolve.js";import{resolvePro as xe,checkQuota as Is,consume as Rs,usage as Js}from"./freegate.js";import{publicConfig as Zo,applyConfigPatch as xt,isSelfDestination as Ls,registryChildEnv as js,applyNerModelSelection as qo,persistConfig as ue,configPath as Z,bridgeAgentOptions as er,PERMISSION_MODES as Gs,sandboxEnvFor as zs,sandboxProblems as Us}from"./configstore.js";import{createDestinationsService as Hs}from"./destinations-service.js";import{freeLimitProblem as Vs}from"./capability-config.js";import Le from"node:path";import{resolveDestination as _t,aggregateModelsAsync as Fs,listDestinations as Ws,ensureModelCatalog as Ks,agentOwnsModel as Qs}from"./router.js";import{makeAccessEvent as tr}from"./observability.js";import{createPersistentAccessLog as Ys}from"./access-log-store.js";import{planQueries as Xs,multiSearch as Zs}from"./rrf.js";import*as jt from"./openai.js";import*as or from"./responses.js";import*as Gt from"./anthropic.js";import{closeAndExit as qs}from"./shutdown.js";import{VERSION as le}from"./version.js";import{VERSION as Cd}from"./version.js";const G=await Wn(),$e=new Set;function We({ids:t=[]}={}){const c=G.lossless;if(!c||!$e.size)return;const u={newest:c.newest,rev:c.rev,size:c.size,at:Date.now()},h=JSON.stringify({...u,ids:t.slice(0,50)}),w=JSON.stringify(u);for(const v of $e)try{v.write(`event: records
1
+ import{createServer as _r}from"node:http";import{loadConfig as co}from"./config.js";import{startEntitlementRefresh as Or,maybeRevalidate as Er}from"./entitlement-refresh.js";import{redactSegments as qe,segment as ht,rememberAnswer as uo}from"./redact.js";import{pipeRestoredStream as Pr,pipeRestoredOpenAIStream as $r,makeTokenRestorer as mo,restoreDeep as Ar}from"./stream.js";import{restoreText as Nr,gatedDictionary as Br,narrowSpecs as Mr,makeToolHarness as Dr,placeholderToolNote as Cr,placeholderNote as Ir,assertEndpointUrl as Rr,capRunOptions as Jr,isPaired as po}from"@chatpanel/pii";import{ensureGatewayToken as Pe,currentGatewayToken as Re,isAdminAuthorized as J,callerTrustOf as et,setPinnedExtensionIds as Lr,issuePairingCode as jr,claimPairingCode as Gr}from"./gateway-token.js";import{createPairAsk as zr,nativeConfirm as Ur}from"./pair-prompt.js";import{createEngineProbe as Hr}from"./local-engine-probe.js";import{randomUUID as Vr}from"node:crypto";import{installEgressLedger as Fr,egressAudit as Wr}from"./egress.js";import{trustSystemCertificates as Kr,systemCaWanted as ho,systemCaState as Qr}from"./system-ca.js";import{initPolicy as Yr,activePolicy as yt,applyPolicyToConfig as yo,managedSummary as tt,PolicyLoadError as Xr}from"./policy.js";import{routeAllowed as fo,agentAllowed as Zr,egressAllowed as qr}from"@chatpanel/events/policy.js";import{resolveBridgeUrl as ot}from"./bridge.js";import{secureFetch as Ve}from"./secure-fetch.js";import{fetchCard as ft,forgetCard as en,sendMessage as tn,streamMessage as on,getTask as rn,cancelTask as nn,knownAgents as an,A2AError as go}from"./a2a.js";import{streamBridgeChat as wo,readBridgeToken as rt,openBridgeChat as sn,acceptedBridgeToken as bo}from"./bridge.js";import{createRelaySession as ln,getRelaySession as ko,endRelaySession as nt,pumpBridgeStream as dn,deliverToolResult as vo,toolsToSpecs as cn,wantsApprovals as un,parseToolCallId as So,touchRelaySession as gt}from"./toolrelay.js";import{shaperFor as At}from"./shape.js";import{startNer as mn,ensureNer as wt,unionForThisMachine as pn,skippedCompanions as hn}from"./ner.js";import{recommendDetector as To}from"@chatpanel/pii/detector-router.js";import{installTimestampedConsole as yn}from"./log.js";import{saveBackupSecret as fn,clearBackupSecret as gn,loadBackupSecret as Nt,hasBackupSecret as xo}from"./history-store.js";import{createContextsApi as wn,handleContexts as bn}from"./contexts-api.js";let _o=null;import{createMemoryStore as kn}from"./memory-store.js";import{createPrefsStore as vn}from"./prefs-store.js";import{agentCardFor as Oo,runHintFor as Eo}from"@chatpanel/events/agent-run-hint.js";import{normalizeThread as Sn}from"@chatpanel/events/agent-thread.js";import{cleanRecordId as Po}from"@chatpanel/events/history-search.js";import{portClashPlan as Tn,serviceManagerOf as xn,STANDBY_POLL_MS as _n}from"@chatpanel/events/service-standby.js";import{threadTarget as On,frameQuestion as En,wireMessages as Pn,appendExchange as $n,MAX_MESSAGE as $o}from"@chatpanel/events/thread-send.js";import{researchStore as An,researchResponse as Nn}from"./research.js";import{createTeamStore as Bn,loadOrCreateKey as Bt}from"./team-store.js";import{createScorecardStore as Mn}from"./scorecard-store.js";import{createEngineLedgerStore as Dn}from"./engine-ledger-store.js";import{createProjectStore as Cn}from"./project-store.js";import{applicationsFor as In,recruitPass as Rn}from"./recruiting.js";import{ensureBridge as Jn,holderOf as Ln}from"./bridge-supervisor.js";import{checkForUpdate as jn,updateStatus as Gn,startUpdate as zn,updateJob as Un,installKind as Hn}from"./update.js";import{confinedStatus as at,confinedLine as Vn}from"./confine.js";import{appleHelperWanted as Fn,findAppleHelper as Mt}from"./apple-helper-fetch.js";import{createHistoryStore as Wn}from"./sqlite-store.js";import{createEventStore as Kn}from"./event-store.js";import{createGatewayEvents as Qn}from"./gateway-events.js";import{createPrincipals as Yn,presentedToken as Ao,LOCAL_AGENT_ID as No}from"./principals.js";import{createOidc as Xn,looksLikeJwt as Zn,normalizeOidc as Bo}from"./oidc.js";import{createLinkActivity as qn,linkSurface as ea,sseUsageTap as ta,usageOfBody as oa,GATEWAY_HOST as Mo}from"./link-activity.js";import{ingestCloudEvents as ra,cursorOf as Do}from"./event-sync.js";import{eventStats as na,projectYear as aa}from"./event-stats.js";import{toCloudEvent as Dt,ceHostOf as sa}from"./cloudevents.js";import{fusionsDocument as ia,resolveFusionModel as la}from"./fusions.js";import{ingestBackups as Ct}from"./backup-ingest.js";import{toSearchRecord as Co}from"@chatpanel/events/library.js";import{deriveBackupKey as da,openRecord as ca,keyCache as ua,nodeCodec as ma}from"@chatpanel/events/backup-envelope.js";import pa from"node:zlib";import*as z from"./ner-engine.js";import It from"node:os";import{capabilitiesDocument as ha,handleDetect as ya}from"./capabilities.js";import{createExtractService as fa}from"./extract/service.js";import{workerSandbox as ga,disposeWorkerSandbox as wa}from"./worker-sandbox.js";import{createRuntime as ba,SERVICES as ka,BUILTIN_IDS as va}from"./runtime.js";import{saveOwnManifest as Sa,removeOwnManifest as Ta}from"./engine-plugins.js";import{createCapabilityProxy as xa}from"./capability-proxy.js";import{createEmbeddedCapabilities as _a}from"./capability-embedded.js";import{EMBEDDED_MODELS as Oa,EMBEDDED_IDS as Ea}from"./embedded-models.js";import{handleExtract as Pa,handleExtractContext as $a}from"./extract/handler.js";import{createKbStore as Aa}from"./kb-store.js";import{createKbService as Na}from"./kb.js";import{createViewKey as Ba}from"./kb-view-key.js";import{MAX_DOCUMENT_BYTES as bt}from"./extract-capability.js";import{createReader as Ma}from"./retrieval/read.js";import{createBrowserRelayHost as Da}from"./browser-relay.js";import{createLinkHost as Ca}from"./link-host.js";import{checkLinkRoute as Io,tunnelHeader as Ia,LINK_TUNNEL_ROOM_PATH as Ra,tailscaleRow as Ja}from"@chatpanel/events/link-routes.js";import{createTailscale as La}from"./tailscale.js";import{linkCallerOf as Me,linkDestinationAllowed as ja,linkVia as Ga,partnerRunHint as za,PARTNER_APPROVAL_DECISIONS as Ro,partnerFilePath as Ua}from"@chatpanel/events/link-scopes.js";import{listPartnerFiles as Ha,readPartnerFile as Va,writePartnerFile as Fa,removePartnerFile as Wa}from"./link-files.js";import{handleFileWrite as Ka}from"./file-write.js";import{handleFileRead as Qa}from"./file-read.js";import{handleAppleNotes as Ya}from"./apple-notes.js";import{handlePickFolder as Xa}from"./folder-picker.js";import{createContextService as Za}from"./context.js";import{createBucketSync as qa}from"./kb-bucket-sync.js";import{createCloudProfiles as es}from"./cloud-profiles.js";import{revealPath as ts}from"./reveal.js";import{apiEnginesFrom as os}from"@chatpanel/events/search-api.js";import{CONTEXT_FEDERATED_HEADER as rs}from"@chatpanel/events/context-api.js";import{WRITE_MAX_BYTES as ns}from"@chatpanel/events/file-write.js";import{isPermissionTool as Jo}from"@chatpanel/events/agent-permission.js";import{createApprovalInbox as as}from"./link-approvals.js";import{createSearcher as ss,toJinaSearch as is,SEARCH_DEFAULTS as ls}from"./retrieval/search.js";import{createSearxng as ds}from"./retrieval/search-searxng.js";import{searchEngines as cs}from"./retrieval/search-apis.js";import{toJinaText as us}from"./read-document.js";import*as A from"./stt-engine.js";import*as P from"./diarize-engine.js";import*as Je from"./translate-engine.js";import*as ms from"./indictrans-engine.js";import*as Rt from"./aec-engine.js";import{speechCoverage as ps}from"@chatpanel/events/speech-language.js";import*as hs from"./segment-engine.js";import{DIARIZE_MODEL_CATALOG as ys,DEFAULT_DIARIZE_MODEL as fs,isKnownDiarizeModel as Lo,diarizeModelEntry as gs}from"./diarize-models.js";import{providerOf as Jt}from"./providers.js";import{createRemoteTranscriber as jo}from"./stt-remote.js";import{parseMultipart as ws,decodeAudioFile as bs}from"./audio-file.js";import{MODEL_CATALOG as Go,isKnownModel as zo,isValidCustomModelId as Uo,recommendFor as ks}from"./models.js";import{STT_MODEL_CATALOG as vs,isKnownSttModel as Ss,isValidCustomSttId as Ts,DEFAULT_STT_MODEL as Fe,STT_DTYPES as xs,isValidDtype as _s,sttModel as kt,sttModelUnavailable as Ho,licenseAcceptance as Vo}from"./stt-models.js";import*as L from"./tts-engine.js";import{TTS_MODEL_CATALOG as Fo,TTS_VOICES as Os,isKnownTtsModel as Es,isValidCustomTtsId as Ps,isKnownVoice as Wo,isValidVoiceId as Ko,DEFAULT_TTS_MODEL as Qo,DEFAULT_TTS_VOICE as De,TTS_DTYPES as $s,isValidTtsDtype as As,MAX_TTS_CHARS as Yo,ttsModelHasCustomVoices as Ns,resolveDefaultModel as Xo,POCKET_VOICES as Bs,DEFAULT_POCKET_VOICE as vt,isPocketVoice as St,ttsModelEngine as Tt}from"./tts-models.js";import{ttsDestination as Ms,synthesizeRemote as Ds,isValidRemoteVoice as Cs}from"./tts-remote.js";import{rawOrtAvailable as Lt}from"./ort.js";import*as ce from"./tts-voices.js";import{resolveTtsVoice as Is}from"./tts-voice-resolve.js";import{resolvePro as xe,checkQuota as Rs,consume as Js,usage as Ls}from"./freegate.js";import{publicConfig as Zo,applyConfigPatch as xt,isSelfDestination as js,registryChildEnv as Gs,applyNerModelSelection as qo,persistConfig as ue,configPath as Z,bridgeAgentOptions as er,PERMISSION_MODES as zs,sandboxEnvFor as Us,sandboxProblems as Hs}from"./configstore.js";import{createDestinationsService as Vs}from"./destinations-service.js";import{freeLimitProblem as Fs}from"./capability-config.js";import Le from"node:path";import{resolveDestination as _t,aggregateModelsAsync as Ws,listDestinations as Ks,ensureModelCatalog as Qs,agentOwnsModel as Ys}from"./router.js";import{makeAccessEvent as tr}from"./observability.js";import{createPersistentAccessLog as Xs}from"./access-log-store.js";import{planQueries as Zs,multiSearch as qs}from"./rrf.js";import*as jt from"./openai.js";import*as or from"./responses.js";import*as Gt from"./anthropic.js";import{closeAndExit as ei}from"./shutdown.js";import{VERSION as le}from"./version.js";import{VERSION as Id}from"./version.js";const G=await Wn(),$e=new Set;function We({ids:t=[]}={}){const c=G.lossless;if(!c||!$e.size)return;const u={newest:c.newest,rev:c.rev,size:c.size,at:Date.now()},h=JSON.stringify({...u,ids:t.slice(0,50)}),w=JSON.stringify(u);for(const v of $e)try{v.write(`event: records
2
2
  data: ${v.chatpanelCredentialed?h:w}
3
3
 
4
4
  `)}catch{$e.delete(v)}}setInterval(()=>{for(const t of $e)try{t.write(`: ping
@@ -11,18 +11,18 @@ data: ${JSON.stringify(Dt(t))}
11
11
  `)}catch{Ce.delete(t)}},25e3).unref?.();const be=await kn(),me=vn(),Ke=Mn({key:Bt()}),Qe=Dn({key:Bt()}),ye=Cn({key:Bt()}),te=Bn({scorecards:Ke,engines:Qe}),Ut=new Set,rr=(t,c)=>{for(const h of Ut)try{h({applied:t,by:c,revision:me.revision})}catch{}const u=JSON.stringify({revision:me.revision,applied:(t||[]).slice(0,50),by:c||"",at:Date.now()});for(const h of $e)try{h.write(`event: prefs
12
12
  data: ${u}
13
13
 
14
- `)}catch{$e.delete(h)}},Ht=Ys(),nr=new Set(["codex","claude","opencode","pi","kiro","antigravity","hermes"]),ei=16,ti=/^mcp[_-]/i,ar=t=>t&&t.function&&t.function.name||t&&t.name||"",oi=t=>t&&t.function&&t.function.description||t&&t.description||"";function sr(t){return typeof t=="string"?t:Array.isArray(t)?t.map(c=>typeof c=="string"?c:c&&(c.text||c.content)||"").join(" "):""}function ri(t,c){if(!t)return"";if(c==="responses"){const h=t.input;return typeof h=="string"?h:Array.isArray(h)?h.map(w=>sr(w&&(w.content??w))).join(" "):""}const u=Array.isArray(t.messages)?t.messages:[];for(let h=u.length-1;h>=0;h--)if(u[h]&&u[h].role==="user")return sr(u[h].content);return""}const ir=new Set(["host","connection","content-length","transfer-encoding","accept-encoding","content-encoding","keep-alive"]);function Ot(t){if(!t)return!1;const c=t.replace(/:\d+$/,"").replace(/^\[|\]$/g,"");return c==="localhost"||c==="127.0.0.1"||c==="::1"}function ni(t,c){return!t||/^chrome-extension:\/\//.test(t)||/^moz-extension:\/\//.test(t)||/^http:\/\/(localhost|127\.0\.0\.1|\[::1\])(:\d+)?$/.test(t)?!0:Array.isArray(c.allowedOrigins)&&c.allowedOrigins.includes(t)}function ai(t,c){t.setHeader("Access-Control-Allow-Origin",c||"*"),t.setHeader("Access-Control-Allow-Methods","GET, POST, PUT, DELETE, OPTIONS"),t.setHeader("Access-Control-Allow-Headers","Content-Type, Authorization, X-ChatPanel-Token"),t.setHeader("Vary","Origin")}const lr=Date.now();function si(t){if(!t)return"";const c={redact:"redact",upstream:"model",stream:"stream",restore:"restore",total:"total"};return Object.keys(t).map(u=>`${c[u]||u} ${t[u]}ms`).join(" · ")}function ii(t){const c=/^(model|harness):([^/]+)(?:\/(.+))?$/.exec(String(t||""));return c?{kind:c[1],id:c[2],...c[3]?{model:c[3]}:{}}:null}function li(t){const c=performance.now(),u={};let h=!1;const w=(v,N)=>{u[v]=Math.round(N*10)/10};return{meta:{},timings:u,mark:w,lap(v,N){w(v,performance.now()-N)},clock(){return performance.now()},commit(){if(h)return;h=!0,w("total",performance.now()-c);const v={...this.meta,timings:u};setImmediate(()=>{t(v),console.log(`[gateway] model=${v.model||"-"} → ${v.dest?`${v.dest}(${v.type})`:"none"} · ${v.redaction==="off"?"redaction OFF (client request)":`redacted ${v.redacted||0}`}${v.sanitized?` · scrubbed ${v.sanitized} hidden`:""}${v.narrowed?` · narrowed -${v.narrowed}`:""} · ${si(u)}`)})}}}function dr(t,c){if(!t||!t.byToken||c!=="types"&&c!=="values")return;const u=[];for(const[h,w]of t.byToken){const v=/^\[\[([A-Z][A-Z0-9]*)_\d+\]\]$/.exec(h),N=v?v[1]:"PII",M=h.replace(/^\[\[|\]\]$/g,"");u.push(c==="values"?{token:M,type:N,value:w}:{token:M,type:N})}return u}function di(t,c,u){return Gt.matches(t)||"anthropic-version"in c?{kind:"anthropic",adapter:Gt,redactable:Gt.matches(t),base:u.upstreams?.anthropic?.baseUrl}:or.matches(t)?{kind:"responses",adapter:or,redactable:!0,base:u.upstreams?.openai?.baseUrl}:{kind:"openai",adapter:jt,redactable:jt.matches(t),base:u.upstreams?.openai?.baseUrl}}function Vt(t,c){const u=String(t||"");if(nr.has(u))return{agent:u,agentModel:""};const h=u.indexOf("/");if(h>0){const w=u.slice(0,h);if(nr.has(w))return{agent:w,agentModel:u.slice(h+1)}}return{agent:c.bridge.agent,agentModel:""}}function cr(t,c){return Vt(t,c).agent}function ci(t,c){if(c!=="openai"||!t)return!1;const u=jt.extractLatestToolResult(t);if(!u)return!1;const h=So(u.tool_call_id);return!!(h&&ko(h.gwId))}function ui(t,c){try{const u=new URL(t),h=u.hostname.replace(/^\[|\]$/g,""),w=h==="127.0.0.1"||h==="localhost"||h==="::1",v=u.port||(u.protocol==="https:"?"443":"80");return w&&String(v)===String(c.port)}catch{return!1}}const mi=25*1024*1024;async function b(t,c){const u=[];let h=0;for await(const w of t){if(h+=w.length,c&&h>c){const v=new Error("payload too large");throw v.code=413,v}u.push(w)}return Buffer.concat(u)}function a(t,c,u){t.writeHead(c,{"content-type":"application/json"}),t.end(JSON.stringify(u))}function ur(t){const c=t.redaction?.detection?.url;return!c||t.redaction?.detection?.backend==="off"?null:c}function Ft(t){const c=t?.redaction?.detection,u=t?.redaction?.tier==="full"?"full":"basic";if(c&&c.backend&&c.backend!=="off")return{source:"external",backend:c.backend,state:"external",model:c.model||null,ready:!0,tier:u,coverage:u==="full"?"names":"patterns"};const h=z.health(),w=h.ok&&u==="full";return{source:"bundled",state:h.state,model:h.model||t?.ner?.model||null,installed:z.modelOnDisk(t?.ner?.model||void 0),error:h.error||null,ready:w,tier:u,coverage:w?"names":"patterns"}}async function mr(t){if(z.state()!=="off"){const u=z.health();return{configured:u.configured,ok:u.ok,state:u.state,model:u.model,error:u.error||null,url:u.configured?`http://${t.host}:${t.port}/ner`:null,stats:u.stats,companions:u.companions}}const c=ur(t);if(!c)return{configured:!1,ok:!1,url:null,model:null};try{const u=await Ve(c.replace(/\/ner\/?$/,"")+"/health",{signal:AbortSignal.timeout(2e3)});if(!u.ok)return{configured:!0,ok:!1,url:c,model:null};const h=await u.json().catch(()=>({}));return{configured:!0,ok:!0,url:c,model:h.model||null}}catch{return{configured:!0,ok:!1,url:c,model:null}}}function pi(t,c){const u={};for(const[h,w]of Object.entries(t)){const v=h.toLowerCase();v.startsWith("x-chatpanel-")||ir.has(v)||(u[h]=w)}u["accept-encoding"]="identity";try{u.host=new URL(c).host}catch{}return u}async function pr(t,c,u,h){const w=mo(c.vault),v=Kt();t.on("close",()=>{t.writableFinished||nt(c.id)});const N=c.linkTurn||null,M=h?h.clock():0;let $=M,k=!0;const x=()=>{h&&k&&(h.lap("upstream",M),$=h.clock(),k=!1)};let C="";const E=()=>{c.redaction&&C&&uo(C,c.redaction),C=""};let F=null;const D={onText:H=>{x(),gt(c.id);const U=w.push(H);U&&(C+=U,t.write(u.sseDelta(U)))},onToolRequest:({name:H,restoredArgs:U,toolId:Y})=>{if(x(),gt(c.id),c.ownerApprovals&&Jo(H)){F=U;return}const oe=w.flush();oe&&(C+=oe,t.write(u.sseDelta(oe))),t.write(u.sseToolCalls([{id:Y,name:H,arguments:JSON.stringify(U)}])),t.write(u.sseToolFinish(v.value)),h&&h.lap("stream",$),t.end(),h?.commit(),E()},onDone:()=>{const H=w.flush();H&&(C+=H,t.write(u.sseDelta(H))),t.write(u.sseTail(v.value)),h&&h.lap("stream",$),t.end(),N?.end("ok"),nt(c.id),h?.commit(),E(),Wt(c)},onError:H=>{t.write(`data: ${JSON.stringify({error:{message:H.message,type:"bridge_error"}})}
14
+ `)}catch{$e.delete(h)}},Ht=Xs(),nr=new Set(["codex","claude","opencode","pi","kiro","antigravity","hermes"]),ti=16,oi=/^mcp[_-]/i,ar=t=>t&&t.function&&t.function.name||t&&t.name||"",ri=t=>t&&t.function&&t.function.description||t&&t.description||"";function sr(t){return typeof t=="string"?t:Array.isArray(t)?t.map(c=>typeof c=="string"?c:c&&(c.text||c.content)||"").join(" "):""}function ni(t,c){if(!t)return"";if(c==="responses"){const h=t.input;return typeof h=="string"?h:Array.isArray(h)?h.map(w=>sr(w&&(w.content??w))).join(" "):""}const u=Array.isArray(t.messages)?t.messages:[];for(let h=u.length-1;h>=0;h--)if(u[h]&&u[h].role==="user")return sr(u[h].content);return""}const ir=new Set(["host","connection","content-length","transfer-encoding","accept-encoding","content-encoding","keep-alive"]);function Ot(t){if(!t)return!1;const c=t.replace(/:\d+$/,"").replace(/^\[|\]$/g,"");return c==="localhost"||c==="127.0.0.1"||c==="::1"}function ai(t,c){return!t||/^chrome-extension:\/\//.test(t)||/^moz-extension:\/\//.test(t)||/^http:\/\/(localhost|127\.0\.0\.1|\[::1\])(:\d+)?$/.test(t)?!0:Array.isArray(c.allowedOrigins)&&c.allowedOrigins.includes(t)}function si(t,c){t.setHeader("Access-Control-Allow-Origin",c||"*"),t.setHeader("Access-Control-Allow-Methods","GET, POST, PUT, DELETE, OPTIONS"),t.setHeader("Access-Control-Allow-Headers","Content-Type, Authorization, X-ChatPanel-Token"),t.setHeader("Vary","Origin")}const lr=Date.now();function ii(t){if(!t)return"";const c={redact:"redact",upstream:"model",stream:"stream",restore:"restore",total:"total"};return Object.keys(t).map(u=>`${c[u]||u} ${t[u]}ms`).join(" · ")}function li(t){const c=/^(model|harness):([^/]+)(?:\/(.+))?$/.exec(String(t||""));return c?{kind:c[1],id:c[2],...c[3]?{model:c[3]}:{}}:null}function di(t){const c=performance.now(),u={};let h=!1;const w=(v,N)=>{u[v]=Math.round(N*10)/10};return{meta:{},timings:u,mark:w,lap(v,N){w(v,performance.now()-N)},clock(){return performance.now()},commit(){if(h)return;h=!0,w("total",performance.now()-c);const v={...this.meta,timings:u};setImmediate(()=>{t(v),console.log(`[gateway] model=${v.model||"-"} → ${v.dest?`${v.dest}(${v.type})`:"none"} · ${v.redaction==="off"?"redaction OFF (client request)":`redacted ${v.redacted||0}`}${v.sanitized?` · scrubbed ${v.sanitized} hidden`:""}${v.narrowed?` · narrowed -${v.narrowed}`:""} · ${ii(u)}`)})}}}function dr(t,c){if(!t||!t.byToken||c!=="types"&&c!=="values")return;const u=[];for(const[h,w]of t.byToken){const v=/^\[\[([A-Z][A-Z0-9]*)_\d+\]\]$/.exec(h),N=v?v[1]:"PII",M=h.replace(/^\[\[|\]\]$/g,"");u.push(c==="values"?{token:M,type:N,value:w}:{token:M,type:N})}return u}function ci(t,c,u){return Gt.matches(t)||"anthropic-version"in c?{kind:"anthropic",adapter:Gt,redactable:Gt.matches(t),base:u.upstreams?.anthropic?.baseUrl}:or.matches(t)?{kind:"responses",adapter:or,redactable:!0,base:u.upstreams?.openai?.baseUrl}:{kind:"openai",adapter:jt,redactable:jt.matches(t),base:u.upstreams?.openai?.baseUrl}}function Vt(t,c){const u=String(t||"");if(nr.has(u))return{agent:u,agentModel:""};const h=u.indexOf("/");if(h>0){const w=u.slice(0,h);if(nr.has(w))return{agent:w,agentModel:u.slice(h+1)}}return{agent:c.bridge.agent,agentModel:""}}function cr(t,c){return Vt(t,c).agent}function ui(t,c){if(c!=="openai"||!t)return!1;const u=jt.extractLatestToolResult(t);if(!u)return!1;const h=So(u.tool_call_id);return!!(h&&ko(h.gwId))}function mi(t,c){try{const u=new URL(t),h=u.hostname.replace(/^\[|\]$/g,""),w=h==="127.0.0.1"||h==="localhost"||h==="::1",v=u.port||(u.protocol==="https:"?"443":"80");return w&&String(v)===String(c.port)}catch{return!1}}const pi=25*1024*1024;async function b(t,c){const u=[];let h=0;for await(const w of t){if(h+=w.length,c&&h>c){const v=new Error("payload too large");throw v.code=413,v}u.push(w)}return Buffer.concat(u)}function a(t,c,u){t.writeHead(c,{"content-type":"application/json"}),t.end(JSON.stringify(u))}function ur(t){const c=t.redaction?.detection?.url;return!c||t.redaction?.detection?.backend==="off"?null:c}function Ft(t){const c=t?.redaction?.detection,u=t?.redaction?.tier==="full"?"full":"basic";if(c&&c.backend&&c.backend!=="off")return{source:"external",backend:c.backend,state:"external",model:c.model||null,ready:!0,tier:u,coverage:u==="full"?"names":"patterns"};const h=z.health(),w=h.ok&&u==="full";return{source:"bundled",state:h.state,model:h.model||t?.ner?.model||null,installed:z.modelOnDisk(t?.ner?.model||void 0),error:h.error||null,ready:w,tier:u,coverage:w?"names":"patterns"}}async function mr(t){if(z.state()!=="off"){const u=z.health();return{configured:u.configured,ok:u.ok,state:u.state,model:u.model,error:u.error||null,url:u.configured?`http://${t.host}:${t.port}/ner`:null,stats:u.stats,companions:u.companions}}const c=ur(t);if(!c)return{configured:!1,ok:!1,url:null,model:null};try{const u=await Ve(c.replace(/\/ner\/?$/,"")+"/health",{signal:AbortSignal.timeout(2e3)});if(!u.ok)return{configured:!0,ok:!1,url:c,model:null};const h=await u.json().catch(()=>({}));return{configured:!0,ok:!0,url:c,model:h.model||null}}catch{return{configured:!0,ok:!1,url:c,model:null}}}function hi(t,c){const u={};for(const[h,w]of Object.entries(t)){const v=h.toLowerCase();v.startsWith("x-chatpanel-")||ir.has(v)||(u[h]=w)}u["accept-encoding"]="identity";try{u.host=new URL(c).host}catch{}return u}async function pr(t,c,u,h){const w=mo(c.vault),v=Kt();t.on("close",()=>{t.writableFinished||nt(c.id)});const N=c.linkTurn||null,M=h?h.clock():0;let $=M,k=!0;const x=()=>{h&&k&&(h.lap("upstream",M),$=h.clock(),k=!1)};let C="";const E=()=>{c.redaction&&C&&uo(C,c.redaction),C=""};let F=null;const D={onText:H=>{x(),gt(c.id);const U=w.push(H);U&&(C+=U,t.write(u.sseDelta(U)))},onToolRequest:({name:H,restoredArgs:U,toolId:Y})=>{if(x(),gt(c.id),c.ownerApprovals&&Jo(H)){F=U;return}const oe=w.flush();oe&&(C+=oe,t.write(u.sseDelta(oe))),t.write(u.sseToolCalls([{id:Y,name:H,arguments:JSON.stringify(U)}])),t.write(u.sseToolFinish(v.value)),h&&h.lap("stream",$),t.end(),h?.commit(),E()},onDone:()=>{const H=w.flush();H&&(C+=H,t.write(u.sseDelta(H))),t.write(u.sseTail(v.value)),h&&h.lap("stream",$),t.end(),N?.end("ok"),nt(c.id),h?.commit(),E(),Wt(c)},onError:H=>{t.write(`data: ${JSON.stringify({error:{message:H.message,type:"bridge_error"}})}
15
15
 
16
16
  `),t.end(),N?.end("error",{code:"bridge_error"}),nt(c.id),h?.commit(),Wt(c)},onUsage:H=>{v.add(H),N?.add(H)}};for(;;){if(F=null,await dn(c,D)!=="parked"||!F)return;const U=c.ownerApprovals,Y=new AbortController,oe=()=>Y.abort();t.once("close",oe);const q=setInterval(()=>{gt(c.id),t.writableEnded||t.write(`: waiting for the owner’s approval
17
17
 
18
- `)},15e3);q.unref?.();let pe;try{pe=await U.inbox.ask(F,{partner:U.partner,device:U.device,conversation:U.conversation,signal:Y.signal})}finally{clearInterval(q),t.off("close",oe)}if(Y.signal.aborted||t.writableEnded){Wt(c);return}try{await vo(c,JSON.stringify(pe))}catch(I){D.onError(I);return}}}function Wt(t){t.ownerApprovals?.turnScoped&&t.ownerApprovals.inbox.forget(t.ownerApprovals.conversation)}async function hi(t,c,{kind:u,adapter:h,agent:w,run:v=null,owner:N=null,linkTurn:M=null},$,k,x,C,E,F=null,D=null){const{messages:H,system:U}=h.toTurn($),{agentModel:Y}=Vt($?.model,x),oe=er(x,{...Y?{model:Y}:{},...v||{}}),q=rt(x.bridge.token),pe=At(u,$?.model||w),I={tier:x.redaction.tier==="full"?"full":"basic",dictionary:Br(x.redaction,C),entities:[]},ge=await ot(x),j=ln({vault:k,redactOpts:I,bridgeUrl:ge,token:q,harness:F});N&&(j.ownerApprovals={...N,conversation:N.conversation||`partner.${N.device}.turn-${j.id}`,turnScoped:!N.conversation}),M&&(j.linkTurn=M,j.onEnd=()=>M.end("aborted")),k&&(j.redaction=x.redaction);let K;try{K=await sn({bridgeUrl:ge,agent:w,token:q,messages:H,system:U,specs:cn(E),options:oe,signal:void 0,approvals:!!N||un(E)})}catch(ve){return M?.end("error",{code:"bridge_error"}),nt(j.id),D?.commit(),a(c,502,{error:{message:`bridge: ${ve.message}`,type:"bridge_error"}})}return j.reader=K.body.getReader(),c.writeHead(200,{"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive"}),c.write(pe.sseHead()),pr(c,j,pe,D)}async function yi(t,c,u,h,w=null){gt(c.id),c.rounds=(c.rounds||0)+1;try{const N=w?w.clock():0;await vo(c,u),w&&w.lap("redact",N)}catch(N){return c.linkTurn?.end("error",{code:"tool_result"}),nt(c.id),w?.commit(),a(t,502,{error:{message:`tool-result: ${N.message}`,type:"bridge_error"}})}const v=At("openai",h||"codex");return t.writeHead(200,{"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive"}),t.write(v.sseHead()),pr(t,c,v,w)}function Kt(){let t=!1;const c={inputTokens:0,outputTokens:0,cacheReadTokens:0,cacheWriteTokens:0};return{add(u){t=!0;for(const h of Object.keys(c))c[h]+=Math.max(0,Number(u?.[h])||0)},get value(){return t?c:null}}}async function fi(t,c,{kind:u,adapter:h,redactable:w,pathname:v,agentOverride:N,harness:M,trace:$,run:k=null,owner:x=null,link:C=null},E,F,D,H){if(!w)return $?.commit(),a(c,404,{error:`endpoint ${v} not supported by the bridge backend`});if(u==="openai"){const ne=h.extractLatestToolResult(E);if(ne){const ae=So(ne.tool_call_id),he=ae&&ko(ae.gwId);if(he)return yi(c,he,ne.content,E?.model,$)}const we=h.extractTools(E);if((we.length||x)&&E?.stream===!0){const ae=N||cr(E?.model,D),he=C?zt.begin({...C,agentId:ae}):null;return hi(t,c,{kind:u,adapter:h,agent:ae,run:k,owner:x,linkTurn:he},E,F,D,H,we,M,$)}}const{messages:U,system:Y}=h.toTurn(E),oe=N||cr(E?.model,D),q=C?zt.begin({...C,agentId:oe}):null,pe=E?.stream===!0,I=At(u,E?.model||oe),ge=rt(D.bridge.token),j=new AbortController;c.on("close",()=>{c.writableFinished||j.abort()});const{agentModel:K}=Vt(E?.model,D),ve={bridgeUrl:await ot(D),agent:oe,token:ge,messages:U,system:Y,signal:j.signal,options:er(D,{...K?{model:K}:{},...k||{}})};if(!pe)try{let ne="";const we=Kt(),ae=$?$.clock():0;await wo(ve,Ne=>{ne+=Ne},null,Ne=>we.add(Ne)),$&&$.lap("upstream",ae);const he=$?$.clock():0,Xe=I.full(Nr(ne,F),we.value);return $&&$.lap("restore",he),c.writeHead(200,{"content-type":I.contentType}),c.end(Xe),q?.add(we.value),q?.end("ok"),$?.commit()}catch(ne){return q?.end(j.signal.aborted?"aborted":"error",{code:"bridge_error"}),$?.commit(),a(c,502,{error:{message:`bridge backend failed: ${ne.message}`,type:"bridge_error"}})}c.writeHead(200,{"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive"}),c.write(I.sseHead());const je=mo(F),_e=$?$.clock():0;let lt=_e;const Ge=Kt();let Ae="",ze=!1;try{let ne=!0;await wo(ve,ae=>{$&&ne&&($.lap("upstream",_e),lt=$.clock(),ne=!1);const he=je.push(ae);he&&(Ae+=he,c.write(I.sseDelta(he)))},I.sseActivity?ae=>{try{c.write(I.sseActivity(Ar(ae,F)))}catch{}}:null,ae=>Ge.add(ae));const we=je.flush();we&&(Ae+=we,c.write(I.sseDelta(we))),c.write(I.sseTail(Ge.value))}catch(ne){ze=!0,c.write(`data: ${JSON.stringify({error:{message:ne.message,type:"bridge_error"}})}
18
+ `)},15e3);q.unref?.();let pe;try{pe=await U.inbox.ask(F,{partner:U.partner,device:U.device,conversation:U.conversation,signal:Y.signal})}finally{clearInterval(q),t.off("close",oe)}if(Y.signal.aborted||t.writableEnded){Wt(c);return}try{await vo(c,JSON.stringify(pe))}catch(I){D.onError(I);return}}}function Wt(t){t.ownerApprovals?.turnScoped&&t.ownerApprovals.inbox.forget(t.ownerApprovals.conversation)}async function yi(t,c,{kind:u,adapter:h,agent:w,run:v=null,owner:N=null,linkTurn:M=null},$,k,x,C,E,F=null,D=null){const{messages:H,system:U}=h.toTurn($),{agentModel:Y}=Vt($?.model,x),oe=er(x,{...Y?{model:Y}:{},...v||{}}),q=rt(x.bridge.token),pe=At(u,$?.model||w),I={tier:x.redaction.tier==="full"?"full":"basic",dictionary:Br(x.redaction,C),entities:[]},ge=await ot(x),j=ln({vault:k,redactOpts:I,bridgeUrl:ge,token:q,harness:F});N&&(j.ownerApprovals={...N,conversation:N.conversation||`partner.${N.device}.turn-${j.id}`,turnScoped:!N.conversation}),M&&(j.linkTurn=M,j.onEnd=()=>M.end("aborted")),k&&(j.redaction=x.redaction);let K;try{K=await sn({bridgeUrl:ge,agent:w,token:q,messages:H,system:U,specs:cn(E),options:oe,signal:void 0,approvals:!!N||un(E)})}catch(ve){return M?.end("error",{code:"bridge_error"}),nt(j.id),D?.commit(),a(c,502,{error:{message:`bridge: ${ve.message}`,type:"bridge_error"}})}return j.reader=K.body.getReader(),c.writeHead(200,{"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive"}),c.write(pe.sseHead()),pr(c,j,pe,D)}async function fi(t,c,u,h,w=null){gt(c.id),c.rounds=(c.rounds||0)+1;try{const N=w?w.clock():0;await vo(c,u),w&&w.lap("redact",N)}catch(N){return c.linkTurn?.end("error",{code:"tool_result"}),nt(c.id),w?.commit(),a(t,502,{error:{message:`tool-result: ${N.message}`,type:"bridge_error"}})}const v=At("openai",h||"codex");return t.writeHead(200,{"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive"}),t.write(v.sseHead()),pr(t,c,v,w)}function Kt(){let t=!1;const c={inputTokens:0,outputTokens:0,cacheReadTokens:0,cacheWriteTokens:0};return{add(u){t=!0;for(const h of Object.keys(c))c[h]+=Math.max(0,Number(u?.[h])||0)},get value(){return t?c:null}}}async function gi(t,c,{kind:u,adapter:h,redactable:w,pathname:v,agentOverride:N,harness:M,trace:$,run:k=null,owner:x=null,link:C=null},E,F,D,H){if(!w)return $?.commit(),a(c,404,{error:`endpoint ${v} not supported by the bridge backend`});if(u==="openai"){const ne=h.extractLatestToolResult(E);if(ne){const ae=So(ne.tool_call_id),he=ae&&ko(ae.gwId);if(he)return fi(c,he,ne.content,E?.model,$)}const we=h.extractTools(E);if((we.length||x)&&E?.stream===!0){const ae=N||cr(E?.model,D),he=C?zt.begin({...C,agentId:ae}):null;return yi(t,c,{kind:u,adapter:h,agent:ae,run:k,owner:x,linkTurn:he},E,F,D,H,we,M,$)}}const{messages:U,system:Y}=h.toTurn(E),oe=N||cr(E?.model,D),q=C?zt.begin({...C,agentId:oe}):null,pe=E?.stream===!0,I=At(u,E?.model||oe),ge=rt(D.bridge.token),j=new AbortController;c.on("close",()=>{c.writableFinished||j.abort()});const{agentModel:K}=Vt(E?.model,D),ve={bridgeUrl:await ot(D),agent:oe,token:ge,messages:U,system:Y,signal:j.signal,options:er(D,{...K?{model:K}:{},...k||{}})};if(!pe)try{let ne="";const we=Kt(),ae=$?$.clock():0;await wo(ve,Ne=>{ne+=Ne},null,Ne=>we.add(Ne)),$&&$.lap("upstream",ae);const he=$?$.clock():0,Xe=I.full(Nr(ne,F),we.value);return $&&$.lap("restore",he),c.writeHead(200,{"content-type":I.contentType}),c.end(Xe),q?.add(we.value),q?.end("ok"),$?.commit()}catch(ne){return q?.end(j.signal.aborted?"aborted":"error",{code:"bridge_error"}),$?.commit(),a(c,502,{error:{message:`bridge backend failed: ${ne.message}`,type:"bridge_error"}})}c.writeHead(200,{"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive"}),c.write(I.sseHead());const je=mo(F),_e=$?$.clock():0;let lt=_e;const Ge=Kt();let Ae="",ze=!1;try{let ne=!0;await wo(ve,ae=>{$&&ne&&($.lap("upstream",_e),lt=$.clock(),ne=!1);const he=je.push(ae);he&&(Ae+=he,c.write(I.sseDelta(he)))},I.sseActivity?ae=>{try{c.write(I.sseActivity(Ar(ae,F)))}catch{}}:null,ae=>Ge.add(ae));const we=je.flush();we&&(Ae+=we,c.write(I.sseDelta(we))),c.write(I.sseTail(Ge.value))}catch(ne){ze=!0,c.write(`data: ${JSON.stringify({error:{message:ne.message,type:"bridge_error"}})}
19
19
 
20
- `)}$&&$.lap("stream",lt),c.end(),q&&(q.add(Ge.value),q.end(j.signal.aborted?"aborted":ze?"error":"ok",{code:"bridge_error"})),$?.commit(),F&&Ae&&uo(Ae,D.redaction)}function gi(t,c,u=""){const h=String(t||"").replace(/\/+$/,""),w=String(c||"").split("/")[1];return w&&h.endsWith(`/${w}`)?h.slice(0,-(w.length+1))+c+u:h+c+u}const hr=9e4,Qt=60,yr=Qt*16e3*4,wi=4e3;function bi(t,c,u){if(c===u)return t;const h=c/u,w=new Float32Array(Math.floor(t.length/h));for(let v=0;v<w.length;v++){const N=v*h,M=Math.floor(N),$=Math.min(t.length-1,M+1),k=N-M;w[v]=t[M]*(1-k)+t[$]*k}return w}const fr=new WeakMap,ki=["/tts","/stt","/ner","/diarize","/skills","/agent-defs","/agent-sessions","/a2a","/redact","/config","/logs","/status","/admin","/v1/browser","/v1/link","/v1/voice"];function gr(t,c){const u=kt(c)?.license;return u&&t.stt?.licenses?.[u.id]?.version===u.version?Vo(u):null}function Yt(t,{installing:c=!1}={}){return t.stt?.diarize===!1?"off":c&&t.stt?.allowDownload!==!1?"download":"ondisk"}async function Se(t,c,u,h,{method:w="GET",timeoutMs:v=8e3,pick:N=M=>M}={}){const M=await ot(u);if(!M)return a(c,503,{error:{message:"no bridge is configured",type:"no_bridge"}});const $=rt(u.bridge?.token),k=w!=="GET"&&w!=="DELETE";try{const x=k?(await b(t,u.maxBodyBytes)).toString("utf8"):"",C=await fetch(`${M}${h}`,{method:w,headers:{Accept:"application/json",...k?{"content-type":"application/json"}:{},...$?{Authorization:`Bearer ${$}`}:{}},...k?{body:x||"{}"}:{},signal:AbortSignal.timeout(v)}),E=await C.json().catch(()=>({}));return C.ok?a(c,200,N(E)):a(c,C.status,{error:{message:E?.error||`bridge ${C.status}`,type:"bridge_error"}})}catch(x){return a(c,502,{error:{message:`bridge unreachable: ${x.message}`,type:"bridge_unreachable"}})}}function Xt(t){return!t||t==="."||t===".."||t.includes("/")||t.includes("\\")}function Ye(t,c){const u=new URLSearchParams;for(const v of t.searchParams.getAll("dir"))v&&u.append("dir",v);const h=t.searchParams.get("workdir")||String(c?.bridge?.workingDir||"").trim();h&&u.set("workdir",h);const w=u.toString();return w?`?${w}`:""}async function vi(t,c,{adapter:u,kind:h,pathname:w,search:v,base:N,destKey:M,destProtocol:$,harness:k,trace:x,link:C=null},E,F){let D;const H=x?x.clock():0,U=C?zt.begin(C):null;let Y=!1;const oe=new AbortController;c.on("close",()=>{c.writableFinished||(Y=!0,oe.abort())});const q=(j,K)=>{U&&(U.add(K),U.end(Y?"aborted":j>=400?"error":"ok",{code:`http_${j}`}))};try{const j=pi(t.headers,N);M&&($==="anthropic"?(j["x-api-key"]=M,delete j.authorization):j.authorization=`Bearer ${M}`);const K=Rr(gi(N,w,v)).toString();D=await fetch(K,{method:t.method,headers:j,body:["GET","HEAD"].includes(t.method)?void 0:E,signal:oe.signal})}catch(j){return Y?(q(499),x?.commit()):(U?.end("error",{code:"upstream_unreachable"}),x?.commit(),a(c,502,{error:`upstream fetch failed: ${j.message}`}))}const pe=D.headers.get("content-type")||"",I={};if(D.headers.forEach((j,K)=>{ir.has(K.toLowerCase())||(I[K]=j)}),pe.includes("text/event-stream")&&D.body){x&&x.lap("upstream",H);const j=x?x.clock():0;c.writeHead(D.status,I);const K=U?ta():null,ve=K?D.body.pipeThrough(K.stream):D.body,je=h==="openai"?$r(ve,c,F,k):Pr(ve,c,F);return Promise.resolve(je).catch(_e=>{if(!Y)throw _e}).finally(()=>{x&&x.lap("stream",j),q(D.status,K?.usage()),x?.commit()})}let ge;try{ge=Buffer.from(await D.arrayBuffer())}catch(j){if(Y)return q(499),x?.commit();throw j}if(x&&x.lap("upstream",H),U&&q(D.status,pe.includes("json")?oa(ge.toString("utf8")):null),F&&pe.includes("application/json"))try{const j=x?x.clock():0,K=u.restoreResponse(JSON.parse(ge.toString("utf8")),F,k);return x&&x.lap("restore",j),c.writeHead(D.status,{...I,"content-type":"application/json"}),c.end(Buffer.from(JSON.stringify(K),"utf8")),x?.commit()}catch{}c.writeHead(D.status,I),c.end(ge),x?.commit()}function Si(t=co()){const c=Yn();try{c.ensureLocalAgentToken()}catch(r){console.log(`[gateway] could not write the agent token: ${r.message}`)}const u=Xn({getConfig:()=>t.identity?.oidc}),h=r=>{if(J(r))return{kind:"owner"};const o=c.verify(Ao(r.headers));return o?o.kind==="agent"?{kind:"agent",id:o.id,local:o.id===No,name:String(o.id===No?r.headers["x-chatpanel-agent"]||"local":o.name).trim().toLowerCase().slice(0,80)}:{kind:"person",id:o.id,name:o.name,groups:o.groups}:r.chatpanelOidc||null},w=()=>t.security?.personalReads==="open"?"open":"credential",v=(r,o)=>!!r&&(r.kind!=="person"||o.startsWith("/v1/contexts")),N=r=>(/^\/v1\/(history|memory|kb|context)(\/|$|s\b)/.test(r)||r==="/v1/research")&&r!=="/v1/history/stream",M=Hr({first:async r=>{const o=Number(new URL(r).port),y=ka.find(i=>i.port===o&&(i.provides||[]).includes("chat"));return y&&(await q())(y.id)==="up"?{engine:y.id,label:y.label,models:null}:null}}),$=zr({confirm:r=>typeof t.pairing?.confirm=="function"?t.pairing.confirm(r):Ur(r),newId:()=>Vr()}),k=Da({version:le}),x=ns({log:r=>console.log(` ${r}`)}),C=Ja({port:Number(t.port)||4320}),E=t.link?.enabled===!1?null:Ca({settings:t.link||{},port:t.port,...t.link?.path?{path:t.link.path}:{},dispatch:({method:r,path:o,headers:y,body:i,device:ee,signal:W})=>fetch(`http://127.0.0.1:${Be.address()?.port||t.port}${o}`,{method:r,body:i,...W?{signal:W}:{},headers:{...y,"x-chatpanel-token":Re()||Pe(),"x-chatpanel-link-device":String(ee||"")}}),ownerIsPro:()=>xe(t.pro?.entitlementToken),log:r=>console.log(` ${r}`)});t.stt?.diarizeModel&&t.stt.diarizeModel!==P.activeModel()&&(Lo(t.stt.diarizeModel)?P.setModel(t.stt.diarizeModel,{log:r=>console.log(r)}):console.warn(`[diarize] config names an unknown speaker model (${t.stt.diarizeModel}) — using ${ys}`));let F=null;const D=()=>{if(!F){const r=t.read||{};F=Ma({remote:r.remote?.url?{url:r.remote.url,key:r.remote.key||""}:null,defaultProvider:r.provider||"defuddle"})}return F};let H=null;const U=()=>(H||(H=fa({wrap:(r,o,y,i)=>ga().wrap(r,o,y,i),onLog:r=>console.warn(`[extract worker] ${r}`)})),H);let Y={at:0,fn:()=>"unknown"},oe=null;async function q(){if(Date.now()-Y.at<1e4)return Y.fn;let r=new Map;try{const i=await I().health();for(const[ee,W]of Object.entries(i)){const Te=(t.destinations||[]).filter(fe=>fe?.service===ee).flatMap(fe=>[fe.id,...fe.models||[]]);for(const fe of[ee,...Te])r.set(fe,W)}}catch{r=new Map}const o=i=>r.get(i)||"unknown",y=new Map((t.destinations||[]).filter(i=>i?.service).map(i=>[i.id,i.service]));return o.window=i=>{try{return I().contextWindow(y.get(i)||i)}catch{return null}},o.why=i=>{try{return I().whyDown(y.get(i)||i)}catch{return""}},o.card=i=>{try{return I().modelCard(y.get(i)||i)}catch{return null}},o.sig=JSON.stringify([...r.entries()].sort()),Y={at:Date.now(),fn:o},Y.fn}let pe=null;const I=()=>(pe||(pe=ba({cfg:t,bridgeHealth:async()=>{const r=await ot(t);if(!r)return null;const o=rt(t.bridge?.token),y=await fetch(`${r}/health`,{headers:{Accept:"application/json",...o?{Authorization:`Bearer ${o}`}:{}},signal:AbortSignal.timeout(4e3)});return y.ok?y.json():null},persist:()=>{try{ue(t,Z())}catch(r){console.warn(`[runtime] could not persist config: ${r.message}`)}},stateDir:Le.join(Le.dirname(Z()),"runtime"),workers:()=>{const r=H?.status();return r?.running?[{id:"extract",kind:"worker",engine:"extract",command:"extract worker",label:"document extractor",pid:r.pid,sandbox:r.sandbox,refused:[]}]:[]},log:r=>console.log(r)})),pe),ge=Number(t.runtime?.idleMinutes),j=_a({warmMs:(Number.isFinite(ge)&&ge>=0?ge:10)*6e4,log:r=>console.log(r)}),K=xa({cfg:t,wake:(r,o)=>I().wake(r,o),embedded:j,asleep:r=>I().isAsleep(r)});let ve=null;const je=Ba(()=>Re()||Pe()),_e=()=>(ve||(ve=Na({viewKey:je,store:Aa({log:r=>console.warn(`[kb] ${r}`)}),extract:U,embedded:j,cfg:t,rerank:async(r,o)=>{const y=await K.call("rerank",{query:r,documents:o.map(ee=>String(ee).slice(0,2e3))});if(y.status!==200)return null;const i=new Array(o.length).fill(0);for(const ee of y.body.results||[])i[ee.index]=ee.relevance_score;return i},read:()=>D(),completer:r=>async(o,{maxTokens:y=160}={})=>{const i=new AbortController,ee=setTimeout(()=>i.abort(),3e4);try{const W=Re()||Pe(),Te=await fetch(`http://127.0.0.1:${t.port}/v1/chat/completions`,{method:"POST",signal:i.signal,headers:{"content-type":"application/json",...W?{Authorization:`Bearer ${W}`}:{},"X-ChatPanel-Client":"kb"},body:JSON.stringify({model:r,messages:[{role:"user",content:o}],stream:!1,max_tokens:y,temperature:0})}),fe=await Te.json().catch(()=>({}));return Te.ok?String(fe?.choices?.[0]?.message?.content||""):""}finally{clearTimeout(ee)}},log:r=>console.warn(r),team:r=>ze().teamOf(r),remoteCards:()=>we().remoteCards(),reveal:(r,o)=>es(r,o),confined:()=>!!at({stateDir:Le.dirname(Z())}).on})),ve);let lt=null;const Ge=()=>lt||=qa();let Ae=null;const ze=()=>(Ae||(Ae=Za({store:_e().store,kb:()=>_e(),profiles:Ge(),entries:()=>Array.isArray(t.context?.providers)?t.context.providers:[],fetchFn:(r,o)=>Ve(r,{...o,maxRedirects:0}),version:le,log:r=>console.log(r)})),Ae);let ne=null;const we=()=>(ne||(ne=Xa({cfg:t,kb:()=>_e(),buckets:ze(),profiles:Ge(),search:async(r,{limit:o=8}={})=>{ae();const y=await Xe().search({q:r,limit:o,read:0});if(y.status!==200)throw new Error(y.body?.error?.message||`search ${y.status}`);return y.body},apiEngines:()=>t.search?.provider==="searxng"?[]:ts(t.search?.apis).filter(r=>r.enabled!==!1),redact:async r=>{let o=r;return await qe([ht(()=>o,y=>{o=y})],{...t.redaction,tier:"basic"},{isPro:!0}),o.replace(/\[\[[A-Z][A-Z0-9_]*_\d+\]\]/g," ").replace(/\s+/g," ").trim()},rerank:async(r,o)=>{const y=await K.call("rerank",{query:r,documents:o.map(ee=>String(ee).slice(0,2e3))});if(y.status!==200)return null;const i=new Array(o.length).fill(0);for(const ee of y.body.results||[])i[ee.index]=ee.relevance_score;return i},fetchFn:(r,o)=>Ve(r,o),persist:()=>ue(t,Z()),log:r=>console.log(r)})),ne),ae=()=>{t.search?.searxng?.url&&I().wake("searxng").catch(()=>{})};let he=null;const Xe=()=>{if(!he){const r=t.search||{},o=r.searxng?.url?ls({url:r.searxng.url,token:r.searxng.token||"",engines:r.searxng.engines||"",safesearch:r.searxng.safesearch??null}):null;he=as({reader:D(),searxng:o,engines:()=>ds(t),wakeSearxng:()=>I().wake("searxng"),defaultProvider:r.provider||"auto",redact:async y=>{let i=y;return await qe([ht(()=>i,ee=>{i=ee})],{...t.redaction,tier:"basic"},{isPro:!0}),i}})}return he};Lr(t.allowedExtensionIds||[]);const Ne=[],wr=r=>{Ne.push(r),Ne.length>50&&Ne.shift()},Be=_r(async(r,o)=>{const y=new URL(r.url,"http://127.0.0.1");let i=y.pathname;if(!Ot(r.headers.host))return a(o,403,{error:"loopback only"});if(!ni(r.headers.origin,t))return a(o,403,{error:"origin not allowed"});if(Ot(t.host)&&Ia(r.headers))return a(o,403,{error:{message:"this gateway answers a tunnel only on its Link path (/v1/link)",type:"forbidden"}});if(r.headers.origin&&ai(o,r.headers.origin),r.method==="OPTIONS")return o.writeHead(204),o.end();if(r.chatpanelOidc=null,u.configured()){const e=Ao(r.headers);Zn(e)&&(r.chatpanelOidc=await u.verify(e))}if(r.chatpanelViewOnly=!1,w()==="credential"&&N(i)&&!v(h(r),i)&&r.method==="GET"&&/^\/v1\/kb\/[^/]+\/view$/.test(i)&&y.searchParams.get("k"))r.chatpanelViewOnly=!0;else if(w()==="credential"&&N(i)&&!v(h(r),i))return r.method==="GET"&&/^\/v1\/kb\/[^/]+\/view$/.test(i)?a(o,403,{error:{message:"this citation link has no viewer key (links made before gateway 0.163.0 have none) — ask Chap again, or open the passage from the chat, and the new link opens here",type:"forbidden"}}):a(o,403,{error:{message:"the person's data — the gateway token, the ChatPanel extension, or an agent connected with `chatpanel-gateway connect` is required",type:"forbidden"}});if(i==="/admin/principals"||i.startsWith("/admin/principals/")){if(!J(r))return a(o,403,{error:{message:"principals: the gateway token or the ChatPanel extension is required",type:"forbidden"}});try{if(i==="/admin/principals"&&r.method==="GET")return a(o,200,{ok:!0,principals:c.list()});if(i==="/admin/principals"&&r.method==="POST"){const n=JSON.parse((await b(r,65536)).toString("utf8")||"{}"),s=Number(n.expiresInDays)||0,l=c.issue({kind:n.kind,name:n.name,groups:n.groups,expiresAt:s>0?Date.now()+s*864e5:0});return st("access.changed",{resource:l.principal.id,actor:{kind:"user",id:"owner"},fields:["issued"]}),a(o,200,{ok:!0,...l})}const e=decodeURIComponent(i.slice(18));return r.method==="DELETE"?c.revoke(e)?(st("access.changed",{resource:e,actor:{kind:"user",id:"owner"},fields:["revoked"]}),a(o,200,{ok:!0})):a(o,404,{error:{message:"no such principal",type:"not_found"}}):a(o,405,{error:{message:"method not allowed",type:"method_not_allowed"}})}catch(e){return a(o,400,{error:{message:`principals: ${e.message}`,type:"invalid_request_error"}})}}if(i==="/admin/identity"||i==="/admin/identity/test"){if(!J(r))return a(o,403,{error:{message:"identity: the gateway token or the ChatPanel extension is required",type:"forbidden"}});if(i==="/admin/identity/test"&&r.method==="POST")return a(o,200,await u.test());if(i==="/admin/identity"&&r.method==="GET")return a(o,200,{ok:!0,oidc:Bo(t.identity?.oidc)});if(i==="/admin/identity"&&r.method==="POST"){let e;try{e=JSON.parse((await b(r,16*1024)).toString("utf8")||"{}")}catch{e=null}if(!e||typeof e!="object"||!("oidc"in e))return a(o,400,{error:{message:"identity: { oidc: { issuer, audience, … } } or { oidc: null }",type:"invalid_request_error"}});try{xt(t,{identity:{oidc:e.oidc}})}catch(n){return a(o,400,{error:{message:n.message,type:"invalid_request_error"}})}try{ue(t,Z())}catch(n){return a(o,500,{error:{message:`could not persist config: ${n.message}`,type:"server_error"}})}return st("access.changed",{resource:"identity:oidc",actor:{kind:"user",id:"owner"},fields:[t.identity?.oidc?"oidc":"oidc-off"]}),a(o,200,{ok:!0,oidc:Bo(t.identity?.oidc)})}return a(o,405,{error:{message:"method not allowed",type:"method_not_allowed"}})}if(i==="/admin/token"&&r.method==="POST")return J(r)?a(o,200,{token:Pe()}):a(o,403,{error:"admin: extension origin or gateway token required"});if(i==="/pair/code"&&r.method==="POST"){if(!J(r))return a(o,403,{error:"pair/code: extension origin or gateway token required"});const e=jr();return console.log("[gateway] pairing code issued — valid for 5 minutes, one use"),a(o,200,{ok:!0,...e})}if(i==="/pair"&&r.method==="POST"){let e=null;try{e=JSON.parse((await b(r,t.maxBodyBytes)).toString("utf8"))}catch{e=null}const n=Gr(e?.code);if(!n.ok)return console.log(`[gateway] pairing refused (${n.reason}) from ${et(r)} caller`),a(o,403,{error:n.reason});console.log(`[gateway] paired a ${et(r)} client${r.headers.origin?` (${r.headers.origin})`:""}`);const{token:s,refused:l}=await bo(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:Re()||Pe(),...s?{bridgeToken:s}:{},...l?{bridgeRefused:l}:{}})}if(i==="/pair/ask"&&r.method==="POST"){const e=et(r);if(t.pairing?.prompt===!1)return a(o,403,{error:"pairing by confirmation is switched off on this gateway — use a pairing code",type:"disabled"});if(po(e))return a(o,409,{error:"this client is already trusted by the gateway",type:"already"});if(e!=="unpaired")return a(o,403,{error:"pair/ask: only a browser extension may ask to be paired",type:"forbidden"});let n=null;try{n=JSON.parse((await b(r,t.maxBodyBytes)).toString("utf8")||"{}")}catch{n=null}const s=$.ask({browser:n?.browser,who:r.headers.origin||""});if(!s.ok){const l=s.reason==="busy"?"a pairing question is already on screen — answer it, or wait a minute":"too many pairing questions — wait a few minutes, or use a pairing code";return a(o,429,{error:l,type:s.reason})}return console.log(`[gateway] pairing: an unrecognised extension (${r.headers.origin}) asked — the question is on screen`),a(o,202,{ok:!0,id:s.id,number:s.number,expiresAt:s.expiresAt})}if(i==="/pair/ask/result"&&r.method==="POST"){let e=null;try{e=JSON.parse((await b(r,t.maxBodyBytes)).toString("utf8")||"{}")}catch{e=null}const{status:n}=$.result(e?.id,{who:r.headers.origin||""});if(n!=="allowed")return a(o,200,{ok:!0,status:n});console.log(`[gateway] paired ${r.headers.origin} — allowed in the dialog on this computer`);const{token:s,refused:l}=await bo(t);return a(o,200,{ok:!0,status:n,token:Re()||Pe(),...s?{bridgeToken:s}:{},...l?{bridgeRefused:l}:{}})}if(i==="/whoami"&&r.method==="POST"){const e=et(r);return a(o,200,{ok:!0,trust:e,paired:po(e),version:le})}if(i==="/audit"&&r.method==="GET")return J(r)?a(o,200,Wr(t,{version:le,startedAt:lr,managed:tt(),certificates:{...Qr(),wanted:ho(t)},linkPartners:E?E.status().devices.filter(e=>e.kind==="partner"):[],confined:at({stateDir:Le.dirname(Z())}),readers:{personalReads:w(),principals:c.list(),...u.status()?{oidc:u.status()}:{}},identity:u.status()})):a(o,403,{error:"audit: extension origin or gateway token required"});if((i==="/config"||i==="/logs"||i==="/update"&&r.method!=="GET")&&!J(r))return a(o,403,{error:"admin route: extension origin or gateway token required"});if(i==="/update"&&r.method==="GET"){const e=await jn(le,{force:y.searchParams.get("force")==="1"}).catch(n=>({current:le,updateAvailable:!1,error:String(n?.message||n)}));return a(o,200,{ok:!0,update:e,job:Un()})}if(i==="/update"&&r.method==="POST"){const e=zn(le);return a(o,e.already?409:202,{ok:!0,job:e})}if((i==="/v1/history/key"||i==="/v1/history/ingest-backup")&&r.method==="POST"&&!J(r))return a(o,403,{error:{message:"history key route: extension origin or gateway token required",type:"forbidden"}});if(i==="/v1/history/records"&&r.method==="PUT"&&!J(r))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")&&r.method==="POST"&&!J(r))return a(o,403,{error:{message:"history write — extension origin or gateway token required",type:"forbidden"}});if(i.startsWith("/v1/contexts")&&!h(r))return a(o,403,{error:{message:"contexts — the gateway token, the ChatPanel extension or a credential the owner issued is required",type:"forbidden"}});if((i==="/v1/memory/remember"||i==="/v1/memory/forget"||i==="/v1/memory/sync"||i==="/v1/memory/clear")&&r.method==="POST"&&!J(r))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"))&&!J(r))return a(o,403,{error:{message:"prefs: extension origin or gateway token required",type:"forbidden"}});if((i==="/v1/browser"||i.startsWith("/v1/browser/"))&&!J(r))return a(o,403,{error:{message:"browser: extension origin or gateway token required",type:"forbidden"}});if((i==="/v1/link"||i.startsWith("/v1/link/"))&&!J(r))return a(o,403,{error:{message:"link: extension origin or gateway token required",type:"forbidden"}});if((i==="/v1/events"||i.startsWith("/v1/events/"))&&!J(r))return a(o,403,{error:{message:"events: extension origin or gateway token required",type:"forbidden"}});if(i.startsWith("/v1/observability")&&!J(r))return a(o,403,{error:{message:"observability: extension origin or gateway token required",type:"forbidden"}});if(r.method==="GET"&&i==="/")return o.writeHead(200,{"content-type":"text/plain; charset=utf-8","cache-control":"no-store"}),o.end(`ChatPanel Privacy Gateway v${le} is running.
20
+ `)}$&&$.lap("stream",lt),c.end(),q&&(q.add(Ge.value),q.end(j.signal.aborted?"aborted":ze?"error":"ok",{code:"bridge_error"})),$?.commit(),F&&Ae&&uo(Ae,D.redaction)}function wi(t,c,u=""){const h=String(t||"").replace(/\/+$/,""),w=String(c||"").split("/")[1];return w&&h.endsWith(`/${w}`)?h.slice(0,-(w.length+1))+c+u:h+c+u}const hr=9e4,Qt=60,yr=Qt*16e3*4,bi=4e3;function ki(t,c,u){if(c===u)return t;const h=c/u,w=new Float32Array(Math.floor(t.length/h));for(let v=0;v<w.length;v++){const N=v*h,M=Math.floor(N),$=Math.min(t.length-1,M+1),k=N-M;w[v]=t[M]*(1-k)+t[$]*k}return w}const fr=new WeakMap,vi=["/tts","/stt","/ner","/diarize","/skills","/agent-defs","/agent-sessions","/a2a","/redact","/config","/logs","/status","/admin","/v1/browser","/v1/link","/v1/voice"];function gr(t,c){const u=kt(c)?.license;return u&&t.stt?.licenses?.[u.id]?.version===u.version?Vo(u):null}function Yt(t,{installing:c=!1}={}){return t.stt?.diarize===!1?"off":c&&t.stt?.allowDownload!==!1?"download":"ondisk"}async function Se(t,c,u,h,{method:w="GET",timeoutMs:v=8e3,pick:N=M=>M}={}){const M=await ot(u);if(!M)return a(c,503,{error:{message:"no bridge is configured",type:"no_bridge"}});const $=rt(u.bridge?.token),k=w!=="GET"&&w!=="DELETE";try{const x=k?(await b(t,u.maxBodyBytes)).toString("utf8"):"",C=await fetch(`${M}${h}`,{method:w,headers:{Accept:"application/json",...k?{"content-type":"application/json"}:{},...$?{Authorization:`Bearer ${$}`}:{}},...k?{body:x||"{}"}:{},signal:AbortSignal.timeout(v)}),E=await C.json().catch(()=>({}));return C.ok?a(c,200,N(E)):a(c,C.status,{error:{message:E?.error||`bridge ${C.status}`,type:"bridge_error"}})}catch(x){return a(c,502,{error:{message:`bridge unreachable: ${x.message}`,type:"bridge_unreachable"}})}}function Xt(t){return!t||t==="."||t===".."||t.includes("/")||t.includes("\\")}function Ye(t,c){const u=new URLSearchParams;for(const v of t.searchParams.getAll("dir"))v&&u.append("dir",v);const h=t.searchParams.get("workdir")||String(c?.bridge?.workingDir||"").trim();h&&u.set("workdir",h);const w=u.toString();return w?`?${w}`:""}async function Si(t,c,{adapter:u,kind:h,pathname:w,search:v,base:N,destKey:M,destProtocol:$,harness:k,trace:x,link:C=null},E,F){let D;const H=x?x.clock():0,U=C?zt.begin(C):null;let Y=!1;const oe=new AbortController;c.on("close",()=>{c.writableFinished||(Y=!0,oe.abort())});const q=(j,K)=>{U&&(U.add(K),U.end(Y?"aborted":j>=400?"error":"ok",{code:`http_${j}`}))};try{const j=hi(t.headers,N);M&&($==="anthropic"?(j["x-api-key"]=M,delete j.authorization):j.authorization=`Bearer ${M}`);const K=Rr(wi(N,w,v)).toString();D=await fetch(K,{method:t.method,headers:j,body:["GET","HEAD"].includes(t.method)?void 0:E,signal:oe.signal})}catch(j){return Y?(q(499),x?.commit()):(U?.end("error",{code:"upstream_unreachable"}),x?.commit(),a(c,502,{error:`upstream fetch failed: ${j.message}`}))}const pe=D.headers.get("content-type")||"",I={};if(D.headers.forEach((j,K)=>{ir.has(K.toLowerCase())||(I[K]=j)}),pe.includes("text/event-stream")&&D.body){x&&x.lap("upstream",H);const j=x?x.clock():0;c.writeHead(D.status,I);const K=U?ta():null,ve=K?D.body.pipeThrough(K.stream):D.body,je=h==="openai"?$r(ve,c,F,k):Pr(ve,c,F);return Promise.resolve(je).catch(_e=>{if(!Y)throw _e}).finally(()=>{x&&x.lap("stream",j),q(D.status,K?.usage()),x?.commit()})}let ge;try{ge=Buffer.from(await D.arrayBuffer())}catch(j){if(Y)return q(499),x?.commit();throw j}if(x&&x.lap("upstream",H),U&&q(D.status,pe.includes("json")?oa(ge.toString("utf8")):null),F&&pe.includes("application/json"))try{const j=x?x.clock():0,K=u.restoreResponse(JSON.parse(ge.toString("utf8")),F,k);return x&&x.lap("restore",j),c.writeHead(D.status,{...I,"content-type":"application/json"}),c.end(Buffer.from(JSON.stringify(K),"utf8")),x?.commit()}catch{}c.writeHead(D.status,I),c.end(ge),x?.commit()}function Ti(t=co()){const c=Yn();try{c.ensureLocalAgentToken()}catch(r){console.log(`[gateway] could not write the agent token: ${r.message}`)}const u=Xn({getConfig:()=>t.identity?.oidc}),h=r=>{if(J(r))return{kind:"owner"};const o=c.verify(Ao(r.headers));return o?o.kind==="agent"?{kind:"agent",id:o.id,local:o.id===No,name:String(o.id===No?r.headers["x-chatpanel-agent"]||"local":o.name).trim().toLowerCase().slice(0,80)}:{kind:"person",id:o.id,name:o.name,groups:o.groups}:r.chatpanelOidc||null},w=()=>t.security?.personalReads==="open"?"open":"credential",v=(r,o)=>!!r&&(r.kind!=="person"||o.startsWith("/v1/contexts")),N=r=>(/^\/v1\/(history|memory|kb|context)(\/|$|s\b)/.test(r)||r==="/v1/research")&&r!=="/v1/history/stream",M=Hr({first:async r=>{const o=Number(new URL(r).port),y=ka.find(i=>i.port===o&&(i.provides||[]).includes("chat"));return y&&(await q())(y.id)==="up"?{engine:y.id,label:y.label,models:null}:null}}),$=zr({confirm:r=>typeof t.pairing?.confirm=="function"?t.pairing.confirm(r):Ur(r),newId:()=>Vr()}),k=Da({version:le}),x=as({log:r=>console.log(` ${r}`)}),C=La({port:Number(t.port)||4320}),E=t.link?.enabled===!1?null:Ca({settings:t.link||{},port:t.port,...t.link?.path?{path:t.link.path}:{},dispatch:({method:r,path:o,headers:y,body:i,device:ee,signal:W})=>fetch(`http://127.0.0.1:${Be.address()?.port||t.port}${o}`,{method:r,body:i,...W?{signal:W}:{},headers:{...y,"x-chatpanel-token":Re()||Pe(),"x-chatpanel-link-device":String(ee||"")}}),ownerIsPro:()=>xe(t.pro?.entitlementToken),log:r=>console.log(` ${r}`)});t.stt?.diarizeModel&&t.stt.diarizeModel!==P.activeModel()&&(Lo(t.stt.diarizeModel)?P.setModel(t.stt.diarizeModel,{log:r=>console.log(r)}):console.warn(`[diarize] config names an unknown speaker model (${t.stt.diarizeModel}) — using ${fs}`));let F=null;const D=()=>{if(!F){const r=t.read||{};F=Ma({remote:r.remote?.url?{url:r.remote.url,key:r.remote.key||""}:null,defaultProvider:r.provider||"defuddle"})}return F};let H=null;const U=()=>(H||(H=fa({wrap:(r,o,y,i)=>ga().wrap(r,o,y,i),onLog:r=>console.warn(`[extract worker] ${r}`)})),H);let Y={at:0,fn:()=>"unknown"},oe=null;async function q(){if(Date.now()-Y.at<1e4)return Y.fn;let r=new Map;try{const i=await I().health();for(const[ee,W]of Object.entries(i)){const Te=(t.destinations||[]).filter(fe=>fe?.service===ee).flatMap(fe=>[fe.id,...fe.models||[]]);for(const fe of[ee,...Te])r.set(fe,W)}}catch{r=new Map}const o=i=>r.get(i)||"unknown",y=new Map((t.destinations||[]).filter(i=>i?.service).map(i=>[i.id,i.service]));return o.window=i=>{try{return I().contextWindow(y.get(i)||i)}catch{return null}},o.why=i=>{try{return I().whyDown(y.get(i)||i)}catch{return""}},o.card=i=>{try{return I().modelCard(y.get(i)||i)}catch{return null}},o.sig=JSON.stringify([...r.entries()].sort()),Y={at:Date.now(),fn:o},Y.fn}let pe=null;const I=()=>(pe||(pe=ba({cfg:t,bridgeHealth:async()=>{const r=await ot(t);if(!r)return null;const o=rt(t.bridge?.token),y=await fetch(`${r}/health`,{headers:{Accept:"application/json",...o?{Authorization:`Bearer ${o}`}:{}},signal:AbortSignal.timeout(4e3)});return y.ok?y.json():null},persist:()=>{try{ue(t,Z())}catch(r){console.warn(`[runtime] could not persist config: ${r.message}`)}},stateDir:Le.join(Le.dirname(Z()),"runtime"),workers:()=>{const r=H?.status();return r?.running?[{id:"extract",kind:"worker",engine:"extract",command:"extract worker",label:"document extractor",pid:r.pid,sandbox:r.sandbox,refused:[]}]:[]},log:r=>console.log(r)})),pe),ge=Number(t.runtime?.idleMinutes),j=_a({warmMs:(Number.isFinite(ge)&&ge>=0?ge:10)*6e4,log:r=>console.log(r)}),K=xa({cfg:t,wake:(r,o)=>I().wake(r,o),embedded:j,asleep:r=>I().isAsleep(r)});let ve=null;const je=Ba(()=>Re()||Pe()),_e=()=>(ve||(ve=Na({viewKey:je,store:Aa({log:r=>console.warn(`[kb] ${r}`)}),extract:U,embedded:j,cfg:t,rerank:async(r,o)=>{const y=await K.call("rerank",{query:r,documents:o.map(ee=>String(ee).slice(0,2e3))});if(y.status!==200)return null;const i=new Array(o.length).fill(0);for(const ee of y.body.results||[])i[ee.index]=ee.relevance_score;return i},read:()=>D(),completer:r=>async(o,{maxTokens:y=160}={})=>{const i=new AbortController,ee=setTimeout(()=>i.abort(),3e4);try{const W=Re()||Pe(),Te=await fetch(`http://127.0.0.1:${t.port}/v1/chat/completions`,{method:"POST",signal:i.signal,headers:{"content-type":"application/json",...W?{Authorization:`Bearer ${W}`}:{},"X-ChatPanel-Client":"kb"},body:JSON.stringify({model:r,messages:[{role:"user",content:o}],stream:!1,max_tokens:y,temperature:0})}),fe=await Te.json().catch(()=>({}));return Te.ok?String(fe?.choices?.[0]?.message?.content||""):""}finally{clearTimeout(ee)}},log:r=>console.warn(r),team:r=>ze().teamOf(r),remoteCards:()=>we().remoteCards(),reveal:(r,o)=>ts(r,o),confined:()=>!!at({stateDir:Le.dirname(Z())}).on})),ve);let lt=null;const Ge=()=>lt||=es();let Ae=null;const ze=()=>(Ae||(Ae=qa({store:_e().store,kb:()=>_e(),profiles:Ge(),entries:()=>Array.isArray(t.context?.providers)?t.context.providers:[],fetchFn:(r,o)=>Ve(r,{...o,maxRedirects:0}),version:le,log:r=>console.log(r)})),Ae);let ne=null;const we=()=>(ne||(ne=Za({cfg:t,kb:()=>_e(),buckets:ze(),profiles:Ge(),search:async(r,{limit:o=8}={})=>{ae();const y=await Xe().search({q:r,limit:o,read:0});if(y.status!==200)throw new Error(y.body?.error?.message||`search ${y.status}`);return y.body},apiEngines:()=>t.search?.provider==="searxng"?[]:os(t.search?.apis).filter(r=>r.enabled!==!1),redact:async r=>{let o=r;return await qe([ht(()=>o,y=>{o=y})],{...t.redaction,tier:"basic"},{isPro:!0}),o.replace(/\[\[[A-Z][A-Z0-9_]*_\d+\]\]/g," ").replace(/\s+/g," ").trim()},rerank:async(r,o)=>{const y=await K.call("rerank",{query:r,documents:o.map(ee=>String(ee).slice(0,2e3))});if(y.status!==200)return null;const i=new Array(o.length).fill(0);for(const ee of y.body.results||[])i[ee.index]=ee.relevance_score;return i},fetchFn:(r,o)=>Ve(r,o),persist:()=>ue(t,Z()),log:r=>console.log(r)})),ne),ae=()=>{t.search?.searxng?.url&&I().wake("searxng").catch(()=>{})};let he=null;const Xe=()=>{if(!he){const r=t.search||{},o=r.searxng?.url?ds({url:r.searxng.url,token:r.searxng.token||"",engines:r.searxng.engines||"",safesearch:r.searxng.safesearch??null}):null;he=ss({reader:D(),searxng:o,engines:()=>cs(t),wakeSearxng:()=>I().wake("searxng"),defaultProvider:r.provider||"auto",redact:async y=>{let i=y;return await qe([ht(()=>i,ee=>{i=ee})],{...t.redaction,tier:"basic"},{isPro:!0}),i}})}return he};Lr(t.allowedExtensionIds||[]);const Ne=[],wr=r=>{Ne.push(r),Ne.length>50&&Ne.shift()},Be=_r(async(r,o)=>{const y=new URL(r.url,"http://127.0.0.1");let i=y.pathname;if(!Ot(r.headers.host))return a(o,403,{error:"loopback only"});if(!ai(r.headers.origin,t))return a(o,403,{error:"origin not allowed"});if(Ot(t.host)&&Ia(r.headers))return a(o,403,{error:{message:"this gateway answers a tunnel only on its Link path (/v1/link)",type:"forbidden"}});if(r.headers.origin&&si(o,r.headers.origin),r.method==="OPTIONS")return o.writeHead(204),o.end();if(r.chatpanelOidc=null,u.configured()){const e=Ao(r.headers);Zn(e)&&(r.chatpanelOidc=await u.verify(e))}if(r.chatpanelViewOnly=!1,w()==="credential"&&N(i)&&!v(h(r),i)&&r.method==="GET"&&/^\/v1\/kb\/[^/]+\/view$/.test(i)&&y.searchParams.get("k"))r.chatpanelViewOnly=!0;else if(w()==="credential"&&N(i)&&!v(h(r),i))return r.method==="GET"&&/^\/v1\/kb\/[^/]+\/view$/.test(i)?a(o,403,{error:{message:"this citation link has no viewer key (links made before gateway 0.163.0 have none) — ask Chap again, or open the passage from the chat, and the new link opens here",type:"forbidden"}}):a(o,403,{error:{message:"the person's data — the gateway token, the ChatPanel extension, or an agent connected with `chatpanel-gateway connect` is required",type:"forbidden"}});if(i==="/admin/principals"||i.startsWith("/admin/principals/")){if(!J(r))return a(o,403,{error:{message:"principals: the gateway token or the ChatPanel extension is required",type:"forbidden"}});try{if(i==="/admin/principals"&&r.method==="GET")return a(o,200,{ok:!0,principals:c.list()});if(i==="/admin/principals"&&r.method==="POST"){const n=JSON.parse((await b(r,65536)).toString("utf8")||"{}"),s=Number(n.expiresInDays)||0,l=c.issue({kind:n.kind,name:n.name,groups:n.groups,expiresAt:s>0?Date.now()+s*864e5:0});return st("access.changed",{resource:l.principal.id,actor:{kind:"user",id:"owner"},fields:["issued"]}),a(o,200,{ok:!0,...l})}const e=decodeURIComponent(i.slice(18));return r.method==="DELETE"?c.revoke(e)?(st("access.changed",{resource:e,actor:{kind:"user",id:"owner"},fields:["revoked"]}),a(o,200,{ok:!0})):a(o,404,{error:{message:"no such principal",type:"not_found"}}):a(o,405,{error:{message:"method not allowed",type:"method_not_allowed"}})}catch(e){return a(o,400,{error:{message:`principals: ${e.message}`,type:"invalid_request_error"}})}}if(i==="/admin/identity"||i==="/admin/identity/test"){if(!J(r))return a(o,403,{error:{message:"identity: the gateway token or the ChatPanel extension is required",type:"forbidden"}});if(i==="/admin/identity/test"&&r.method==="POST")return a(o,200,await u.test());if(i==="/admin/identity"&&r.method==="GET")return a(o,200,{ok:!0,oidc:Bo(t.identity?.oidc)});if(i==="/admin/identity"&&r.method==="POST"){let e;try{e=JSON.parse((await b(r,16*1024)).toString("utf8")||"{}")}catch{e=null}if(!e||typeof e!="object"||!("oidc"in e))return a(o,400,{error:{message:"identity: { oidc: { issuer, audience, … } } or { oidc: null }",type:"invalid_request_error"}});try{xt(t,{identity:{oidc:e.oidc}})}catch(n){return a(o,400,{error:{message:n.message,type:"invalid_request_error"}})}try{ue(t,Z())}catch(n){return a(o,500,{error:{message:`could not persist config: ${n.message}`,type:"server_error"}})}return st("access.changed",{resource:"identity:oidc",actor:{kind:"user",id:"owner"},fields:[t.identity?.oidc?"oidc":"oidc-off"]}),a(o,200,{ok:!0,oidc:Bo(t.identity?.oidc)})}return a(o,405,{error:{message:"method not allowed",type:"method_not_allowed"}})}if(i==="/admin/token"&&r.method==="POST")return J(r)?a(o,200,{token:Pe()}):a(o,403,{error:"admin: extension origin or gateway token required"});if(i==="/pair/code"&&r.method==="POST"){if(!J(r))return a(o,403,{error:"pair/code: extension origin or gateway token required"});const e=jr();return console.log("[gateway] pairing code issued — valid for 5 minutes, one use"),a(o,200,{ok:!0,...e})}if(i==="/pair"&&r.method==="POST"){let e=null;try{e=JSON.parse((await b(r,t.maxBodyBytes)).toString("utf8"))}catch{e=null}const n=Gr(e?.code);if(!n.ok)return console.log(`[gateway] pairing refused (${n.reason}) from ${et(r)} caller`),a(o,403,{error:n.reason});console.log(`[gateway] paired a ${et(r)} client${r.headers.origin?` (${r.headers.origin})`:""}`);const{token:s,refused:l}=await bo(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:Re()||Pe(),...s?{bridgeToken:s}:{},...l?{bridgeRefused:l}:{}})}if(i==="/pair/ask"&&r.method==="POST"){const e=et(r);if(t.pairing?.prompt===!1)return a(o,403,{error:"pairing by confirmation is switched off on this gateway — use a pairing code",type:"disabled"});if(po(e))return a(o,409,{error:"this client is already trusted by the gateway",type:"already"});if(e!=="unpaired")return a(o,403,{error:"pair/ask: only a browser extension may ask to be paired",type:"forbidden"});let n=null;try{n=JSON.parse((await b(r,t.maxBodyBytes)).toString("utf8")||"{}")}catch{n=null}const s=$.ask({browser:n?.browser,who:r.headers.origin||""});if(!s.ok){const l=s.reason==="busy"?"a pairing question is already on screen — answer it, or wait a minute":"too many pairing questions — wait a few minutes, or use a pairing code";return a(o,429,{error:l,type:s.reason})}return console.log(`[gateway] pairing: an unrecognised extension (${r.headers.origin}) asked — the question is on screen`),a(o,202,{ok:!0,id:s.id,number:s.number,expiresAt:s.expiresAt})}if(i==="/pair/ask/result"&&r.method==="POST"){let e=null;try{e=JSON.parse((await b(r,t.maxBodyBytes)).toString("utf8")||"{}")}catch{e=null}const{status:n}=$.result(e?.id,{who:r.headers.origin||""});if(n!=="allowed")return a(o,200,{ok:!0,status:n});console.log(`[gateway] paired ${r.headers.origin} — allowed in the dialog on this computer`);const{token:s,refused:l}=await bo(t);return a(o,200,{ok:!0,status:n,token:Re()||Pe(),...s?{bridgeToken:s}:{},...l?{bridgeRefused:l}:{}})}if(i==="/whoami"&&r.method==="POST"){const e=et(r);return a(o,200,{ok:!0,trust:e,paired:po(e),version:le})}if(i==="/audit"&&r.method==="GET")return J(r)?a(o,200,Wr(t,{version:le,startedAt:lr,managed:tt(),certificates:{...Qr(),wanted:ho(t)},linkPartners:E?E.status().devices.filter(e=>e.kind==="partner"):[],confined:at({stateDir:Le.dirname(Z())}),readers:{personalReads:w(),principals:c.list(),...u.status()?{oidc:u.status()}:{}},identity:u.status()})):a(o,403,{error:"audit: extension origin or gateway token required"});if((i==="/config"||i==="/logs"||i==="/update"&&r.method!=="GET")&&!J(r))return a(o,403,{error:"admin route: extension origin or gateway token required"});if(i==="/update"&&r.method==="GET"){const e=await jn(le,{force:y.searchParams.get("force")==="1"}).catch(n=>({current:le,updateAvailable:!1,error:String(n?.message||n)}));return a(o,200,{ok:!0,update:e,job:Un()})}if(i==="/update"&&r.method==="POST"){const e=zn(le);return a(o,e.already?409:202,{ok:!0,job:e})}if((i==="/v1/history/key"||i==="/v1/history/ingest-backup")&&r.method==="POST"&&!J(r))return a(o,403,{error:{message:"history key route: extension origin or gateway token required",type:"forbidden"}});if(i==="/v1/history/records"&&r.method==="PUT"&&!J(r))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")&&r.method==="POST"&&!J(r))return a(o,403,{error:{message:"history write — extension origin or gateway token required",type:"forbidden"}});if(i.startsWith("/v1/contexts")&&!h(r))return a(o,403,{error:{message:"contexts — the gateway token, the ChatPanel extension or a credential the owner issued is required",type:"forbidden"}});if((i==="/v1/memory/remember"||i==="/v1/memory/forget"||i==="/v1/memory/sync"||i==="/v1/memory/clear")&&r.method==="POST"&&!J(r))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"))&&!J(r))return a(o,403,{error:{message:"prefs: extension origin or gateway token required",type:"forbidden"}});if((i==="/v1/browser"||i.startsWith("/v1/browser/"))&&!J(r))return a(o,403,{error:{message:"browser: extension origin or gateway token required",type:"forbidden"}});if((i==="/v1/link"||i.startsWith("/v1/link/"))&&!J(r))return a(o,403,{error:{message:"link: extension origin or gateway token required",type:"forbidden"}});if((i==="/v1/events"||i.startsWith("/v1/events/"))&&!J(r))return a(o,403,{error:{message:"events: extension origin or gateway token required",type:"forbidden"}});if(i.startsWith("/v1/observability")&&!J(r))return a(o,403,{error:{message:"observability: extension origin or gateway token required",type:"forbidden"}});if(r.method==="GET"&&i==="/")return o.writeHead(200,{"content-type":"text/plain; charset=utf-8","cache-control":"no-store"}),o.end(`ChatPanel Privacy Gateway v${le} is running.
21
21
 
22
22
  This address is for ChatPanel's apps, not a web page — there is nothing to open here.
23
23
  Use ChatPanel itself (the browser extension's Settings, or the desktop app).
24
24
  In a terminal, \`chatpanel-gateway --status\` shows what is running.
25
- `);if(r.method==="GET"&&i==="/health"){const e=A.health(),n=L.health();return a(o,200,{ok:!0,version:le,backend:t.backend,tier:t.redaction.tier,personalReads:w(),pairing:!0,pairPrompt:t.pairing?.prompt!==!1,...tt()?{managed:tt()}:{},...process.env.CHATPANEL_MANAGED_BY?{managedBy:String(process.env.CHATPANEL_MANAGED_BY).slice(0,32)}:{},install:Hn(),confined:at({stateDir:Le.dirname(Z())}),...Fn({release:It.release()})?{appleHelper:!!Mt()}:{},...it?{bridge:it.status()}:Et?{bridge:Et}:{},search:{provider:t.search?.provider||"auto",searxng:!!t.search?.searxng?.url},stt:{enabled:t.stt?.enabled!==!1,state:e.state,ready:e.ok,model:e.model||t.stt?.model||Fe,runtime:e.runtime,dtype:e.dtype},tts:{enabled:t.tts?.enabled!==!1,state:n.state,ready:n.ok,model:n.model||t.tts?.model||Qo,voice:t.tts?.voice||De,runtime:n.runtime,dtype:n.dtype},events:Q?{count:Q.count(),hosts:Q.hosts().length}:null,browser:k.health()})}if(i==="/status"&&r.method==="GET"){Er(t);const e=await xe(t.pro?.entitlementToken),n=await mr(t);return a(o,200,{ok:!0,version:le,backend:t.backend,tier:t.redaction.tier,search:{provider:t.search?.provider||"auto",searxng:!!t.search?.searxng?.url},...tt()?{managed:tt()}:{},...process.env.CHATPANEL_MANAGED_BY?{managedBy:String(process.env.CHATPANEL_MANAGED_BY).slice(0,32)}:{},ner:{autostart:!!t.ner?.autostart,configured:n.configured,ready:n.ok,model:n.model,url:n.url},detector:Ft(t),pro:{unlocked:e},usage:Js(t),uptimeSeconds:Math.floor((Date.now()-lr)/1e3),update:Gn(le)})}if(i==="/v1/history/ingest"&&r.method==="POST")try{const e=JSON.parse((await b(r,t.maxBodyBytes)).toString("utf8"))||{},n=G.bulk({upserts:Array.isArray(e.upserts)?e.upserts:[],removes:Array.isArray(e.removes)?e.removes:[]});return a(o,200,{ok:!0,size:n})}catch(e){return a(o,400,{error:{message:`ingest failed: ${e.message}`,type:"ingest_error"}})}if(i==="/v1/prefs"&&r.method==="GET"){const e=String(y.searchParams.get("section")||"");return y.searchParams.get("stamps")?a(o,200,{ok:!0,revision:me.revision,stamps:me.stamps()}):a(o,200,{ok:!0,revision:me.revision,sections:me.get(e)})}if(i==="/v1/prefs"&&(r.method==="POST"||r.method==="PUT"))try{const e=JSON.parse((await b(r,t.maxBodyBytes)).toString("utf8"))||{},n=me.put(e.sections||{},{by:e.by||""});return n.applied.length&&rr(n.applied,e.by||""),a(o,200,{ok:!0,...n})}catch(e){return a(o,400,{error:{message:`prefs write failed: ${e.message}`,type:"prefs_error"}})}if(i==="/v1/prefs"&&r.method==="DELETE"){const e=String(y.searchParams.get("section")||""),n=e?me.remove(e):!1;return n&&rr([e],""),a(o,200,{ok:!0,removed:n})}if(i==="/v1/prefs/events"&&r.method==="GET"){o.writeHead(200,{"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive"});const e=l=>o.write(`data: ${JSON.stringify(l)}
25
+ `);if(r.method==="GET"&&i==="/health"){const e=A.health(),n=L.health();return a(o,200,{ok:!0,version:le,backend:t.backend,tier:t.redaction.tier,personalReads:w(),pairing:!0,pairPrompt:t.pairing?.prompt!==!1,...tt()?{managed:tt()}:{},...process.env.CHATPANEL_MANAGED_BY?{managedBy:String(process.env.CHATPANEL_MANAGED_BY).slice(0,32)}:{},install:Hn(),confined:at({stateDir:Le.dirname(Z())}),...Fn({release:It.release()})?{appleHelper:!!Mt()}:{},...it?{bridge:it.status()}:Et?{bridge:Et}:{},search:{provider:t.search?.provider||"auto",searxng:!!t.search?.searxng?.url},stt:{enabled:t.stt?.enabled!==!1,state:e.state,ready:e.ok,model:e.model||t.stt?.model||Fe,runtime:e.runtime,dtype:e.dtype},tts:{enabled:t.tts?.enabled!==!1,state:n.state,ready:n.ok,model:n.model||t.tts?.model||Qo,voice:t.tts?.voice||De,runtime:n.runtime,dtype:n.dtype},events:Q?{count:Q.count(),hosts:Q.hosts().length}:null,browser:k.health()})}if(i==="/status"&&r.method==="GET"){Er(t);const e=await xe(t.pro?.entitlementToken),n=await mr(t);return a(o,200,{ok:!0,version:le,backend:t.backend,tier:t.redaction.tier,search:{provider:t.search?.provider||"auto",searxng:!!t.search?.searxng?.url},...tt()?{managed:tt()}:{},...process.env.CHATPANEL_MANAGED_BY?{managedBy:String(process.env.CHATPANEL_MANAGED_BY).slice(0,32)}:{},ner:{autostart:!!t.ner?.autostart,configured:n.configured,ready:n.ok,model:n.model,url:n.url},detector:Ft(t),pro:{unlocked:e},usage:Ls(t),uptimeSeconds:Math.floor((Date.now()-lr)/1e3),update:Gn(le)})}if(i==="/v1/history/ingest"&&r.method==="POST")try{const e=JSON.parse((await b(r,t.maxBodyBytes)).toString("utf8"))||{},n=G.bulk({upserts:Array.isArray(e.upserts)?e.upserts:[],removes:Array.isArray(e.removes)?e.removes:[]});return a(o,200,{ok:!0,size:n})}catch(e){return a(o,400,{error:{message:`ingest failed: ${e.message}`,type:"ingest_error"}})}if(i==="/v1/prefs"&&r.method==="GET"){const e=String(y.searchParams.get("section")||"");return y.searchParams.get("stamps")?a(o,200,{ok:!0,revision:me.revision,stamps:me.stamps()}):a(o,200,{ok:!0,revision:me.revision,sections:me.get(e)})}if(i==="/v1/prefs"&&(r.method==="POST"||r.method==="PUT"))try{const e=JSON.parse((await b(r,t.maxBodyBytes)).toString("utf8"))||{},n=me.put(e.sections||{},{by:e.by||""});return n.applied.length&&rr(n.applied,e.by||""),a(o,200,{ok:!0,...n})}catch(e){return a(o,400,{error:{message:`prefs write failed: ${e.message}`,type:"prefs_error"}})}if(i==="/v1/prefs"&&r.method==="DELETE"){const e=String(y.searchParams.get("section")||""),n=e?me.remove(e):!1;return n&&rr([e],""),a(o,200,{ok:!0,removed:n})}if(i==="/v1/prefs/events"&&r.method==="GET"){o.writeHead(200,{"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive"});const e=l=>o.write(`data: ${JSON.stringify(l)}
26
26
 
27
27
  `);e({type:"hello",revision:me.revision,stamps:me.stamps()});const n=l=>e({type:"changed",...l});Ut.add(n);const s=setInterval(()=>{try{o.write(`: keep-alive
28
28
 
@@ -30,7 +30,7 @@ In a terminal, \`chatpanel-gateway --status\` shows what is running.
30
30
 
31
31
  `);let f=y.searchParams.has("after")?Number(y.searchParams.get("after")):-1;p({seq:-1,type:"hello",at:Date.now(),payload:{project:ye.get(n),after:f}});const g=ye.watch(n,_=>{_.seq>f&&(f=_.seq,p(_))});for(const _ of ye.eventsSince(n,f))f=_.seq,p(_);const S=setInterval(()=>{try{o.write(`: keep
32
32
 
33
- `)}catch{}},25e3);r.on("close",()=>{clearInterval(S),g()});return}}}if(i==="/v1/agents/scorecards"&&r.method==="GET")return a(o,200,{ok:!0,agents:Ke.list()});{const e=/^\/v1\/agents\/([a-zA-Z0-9_.:@+-]{1,120})\/scorecard$/.exec(i);if(e){const n=decodeURIComponent(e[1]);if(r.method==="GET")return a(o,200,{ok:!0,...await Ke.get(n)});if(r.method==="POST")try{const s=JSON.parse((await b(r,t.maxBodyBytes)).toString("utf8"))||{},l=await Ke.append({agentId:n,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 Qe.fromRating(Ke.chains.get(n)||[],{...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"&&r.method==="GET")return a(o,200,ha(t,{version:le,reader:F,searcher:he,extract:U(),proxy:K}));if(i==="/v1/fusions"&&r.method==="GET"){const e={active:z.health().model||t.ner?.model||null,companions:z.companions()};let n=null;try{n=await I().status()}catch{n=null}return a(o,200,ia({cfg:t,ner:e,runtimeDoc:n}))}if(i==="/v1/runtime"&&r.method==="GET"){const e=Object.fromEntries(Ea.map(n=>{const s=Jt(t,n);return[n,{provider:s.kind,model:s.kind==="embedded"?s.model:null,models:Oa[n],threads:j.threads,...s.kind==="embedded"?j.health(n,s.model):{}}]}));return a(o,200,{...await I().status(),inProcess:e})}if(i==="/v1/runtime/plugins"&&r.method==="GET")return a(o,200,{ok:!0,...I().pluginList()});if(i==="/v1/runtime/plugins"&&r.method==="POST"||i.startsWith("/v1/runtime/plugins/")&&r.method==="DELETE"){if(!J(r)||Me(r.headers))return a(o,403,{error:{message:"engines: only the owner of this machine adds or removes one (the gateway token or its extension, from this machine)",type:"forbidden"}});if(at({stateDir:Le.dirname(Z())}).on)return a(o,403,{error:{message:"engines: this gateway runs confined and starts no new programs",type:"confined"}});if(r.method==="DELETE"){const s=Ta(decodeURIComponent(i.slice(20)));return s.ok?a(o,200,{ok:!0,...await I().reloadPlugins()}):a(o,404,{ok:!1,error:s.error})}let e;try{e=JSON.parse((await b(r,256*1024)).toString("utf8")||"{}")}catch{return a(o,400,{ok:!1,error:"engines: the body must be JSON"})}const n=Sa(e?.manifest??e,{builtins:[...va]});return n.ok?a(o,200,{ok:!0,manifest:n.manifest,...await I().reloadPlugins()}):a(o,400,{ok:!1,error:n.error})}if(i==="/v1/runtime/recipe"&&r.method==="GET"){if(!J(r))return a(o,403,{error:"runtime: extension origin or gateway token required"});const e=new URL(r.url,"http://x").searchParams,n=await I().recipe(String(e.get("service")||"llama"),e.get("model"));return a(o,n.ok?200:400,n)}if(i==="/v1/runtime/plan"&&r.method==="GET"){const e=new URL(r.url,"http://x").searchParams,n=await I().plan(String(e.get("service")||"mlx"),{model:e.get("model")||void 0,ctx:e.get("ctx"),needMB:e.get("need_mb")});return a(o,n.ok?200:400,n)}{const e=/^\/v1\/runtime\/(engines|services)\/([a-z0-9-]+)$/.exec(i);if(e&&r.method==="POST"){if(!J(r))return a(o,403,{error:"runtime: extension origin or gateway token required"});let n={};try{n=JSON.parse((await b(r,t.maxBodyBytes)).toString("utf8")||"{}")}catch{n={}}const s=String(n.action||"start"),l=I(),d=e[1]==="engines"?s==="start"?await l.startEngine(e[2]):{ok:!1,error:`unknown action ${s}`}:s==="start"?await l.startService(e[2],{force:n.force===!0}):s==="stop"?await l.stopService(e[2]):s==="model"?await l.setModel(e[2],n.model,{tunings:n.tunings||null}):s==="tune"?await l.setTunings(e[2],n.tunings):s==="profile"?await l.setProfile(e[2],n.profile):s==="pull"?await l.pullModel(e[2]):s==="install"?await l.installRunner(e[2]):s==="update"?await l.updateRunner(e[2]):s==="build"?await l.setBuild(e[2],String(n.build||"")):s==="cancel"?l.cancelJob(e[2]):s==="remove"?await l.removeService(e[2]):{ok:!1,error:`unknown action ${s}`};return a(o,d.ok?200:400,d)}}if(i==="/v1/embeddings"&&r.method==="POST"){let e;try{e=JSON.parse((await b(r,t.maxBodyBytes)).toString("utf8"))}catch{return a(o,400,{error:{message:"embed: body must be JSON",type:"invalid_request"}})}const n=await K.call("embed",e);return a(o,n.status,n.body)}if((i==="/v1/rerank"||i==="/v1/decide")&&r.method==="POST"){const e=i.slice(4);let n;try{n=JSON.parse((await b(r,t.maxBodyBytes)).toString("utf8"))}catch{return a(o,400,{error:{message:`${e}: body must be JSON`,type:"invalid_request"}})}const s=await K.call(e,n);return a(o,s.status,s.body)}if(i==="/v1/detect"&&r.method==="POST"){let e;try{e=JSON.parse((await b(r,t.maxBodyBytes)).toString("utf8"))}catch{return a(o,400,{error:{message:"detect: body must be JSON",type:"invalid_request"}})}try{const n=await ya(e,{ensure:()=>wt(t),model:z.health().model});return a(o,n.status,n.body)}catch(n){return a(o,500,{error:{message:`detect: ${n.message}`,type:"detector_error"}})}}if(i==="/v1/extract/context"&&r.method==="POST"){let e;try{e=JSON.parse((await b(r,Math.max(t.maxBodyBytes,Math.ceil(bt*4/3)+1024))).toString("utf8"))}catch{return a(o,400,{error:{message:"extract/context: body must be JSON",type:"invalid_request"}})}const n=await $a(e,{service:U()});return a(o,n.status,n.body)}if((i==="/v1/files/write"||i==="/v1/files/exists")&&r.method==="POST"){if(!J(r)||Me(r.headers))return a(o,403,{error:{message:"files: a client on this computer with the gateway token or the pinned extension only",type:"forbidden"}});let e;try{e=JSON.parse((await b(r,Math.max(t.maxBodyBytes,rs*6+4096))).toString("utf8"))}catch{return a(o,400,{error:{message:"files: body must be JSON",type:"invalid_request"}})}const n=await Wa(i.slice(10),e);return a(o,n.status,n.body)}if(i==="/v1/files/fs"&&r.method==="POST"){if(!J(r)||Me(r.headers))return a(o,403,{error:{message:"files: a client on this computer with the gateway token or the pinned extension only",type:"forbidden"}});let e;try{e=JSON.parse((await b(r,64*1024)).toString("utf8"))}catch{return a(o,400,{error:{message:"files: body must be JSON",type:"invalid_request"}})}const n=await Ka(e);return a(o,n.status,n.body)}if(i==="/v1/files/pick-folder"&&r.method==="POST"){if(!J(r)||Me(r.headers))return a(o,403,{error:{message:"files: a client on this computer with the gateway token or the pinned extension only",type:"forbidden"}});let e={};try{e=JSON.parse((await b(r,4*1024)).toString("utf8")||"{}")}catch{return a(o,400,{error:{message:"files: body must be JSON",type:"invalid_request"}})}const n=await Ya(e);return a(o,n.status,n.body)}if(i==="/v1/import/apple-notes"&&r.method==="POST"){if(!J(r)||Me(r.headers))return a(o,403,{error:{message:"apple-notes: a client on this computer with the gateway token or the pinned extension only",type:"forbidden"}});let e;try{e=JSON.parse((await b(r,t.maxBodyBytes)).toString("utf8"))}catch{return a(o,400,{error:{message:"apple-notes: body must be JSON",type:"invalid_request"}})}const n=await Qa(e);return a(o,n.status,n.body)}if(i==="/v1/extract"&&r.method==="POST"){let e;try{e=JSON.parse((await b(r,Math.max(t.maxBodyBytes,Math.ceil(bt*4/3)+1024))).toString("utf8"))}catch{return a(o,400,{error:{message:"extract: body must be JSON",type:"invalid_request"}})}const n=await Pa(e,{service:U()});return a(o,n.status,n.body)}if(i==="/v1/read"&&r.method==="POST"){let e;try{e=JSON.parse((await b(r,t.maxBodyBytes)).toString("utf8"))}catch{return a(o,400,{error:{message:"read: body must be JSON",type:"invalid_request"}})}const n=await D().read(e);return a(o,n.status,n.body)}if(i==="/v1/search"&&r.method==="POST"){let e;try{e=JSON.parse((await b(r,t.maxBodyBytes)).toString("utf8"))}catch{return a(o,400,{error:{message:"search: body must be JSON",type:"invalid_request"}})}ae();const n=await Xe().search(e);return a(o,n.status,n.body)}if(/^\/v1\/search\/./.test(i)&&r.method==="GET"){let e;try{e=decodeURIComponent(i.slice(11))}catch{e=i.slice(11)}const n=y.searchParams.has("read")?Math.max(0,Math.min(10,Number(y.searchParams.get("read"))||0)):is.aliasRead;ae();const s=await Xe().search({q:e,read:n,limit:Math.max(n,5)});return a(o,s.status,s.status===200?ss(s.body):s.body)}if(/^\/v1\/read\/./.test(i)&&r.method==="GET"){const e=String(r.url||"").slice(9),n=/^https?:\/\//i.test(e)?e:decodeURIComponent(e),s=/application\/json/i.test(r.headers.accept||""),l=/^text$/i.test(r.headers["x-return-format"]||"")?"text":"markdown",d=await D().read({url:n,format:l});return d.status!==200||s?a(o,d.status,d.status===200?{code:200,status:2e4,data:d.body}:d.body):(o.writeHead(200,{"content-type":"text/plain; charset=utf-8","x-chatpanel-provider":d.body.provider}),o.end(cs(d.body)))}if(i==="/v1/engines"&&r.method==="GET"){const e=Number(y.searchParams.get("minCalls"))||void 0;return a(o,200,{ok:!0,engines:Qe.list({minCalls:e})})}{const e=/^\/v1\/engines\/(.+)\/(card|entries)$/.exec(i);if(e){const n=decodeURIComponent(e[1]).slice(0,300);if(e[2]==="card"&&r.method==="GET"){const s=Number(y.searchParams.get("minCalls"))||void 0;return a(o,200,{ok:!0,...await Qe.get(n,{entries:y.searchParams.get("entries")==="1",minCalls:s})})}if(e[2]==="entries"&&r.method==="POST")try{const s=JSON.parse((await b(r,t.maxBodyBytes)).toString("utf8"))||{},l=s.engine||ii(n);if(!l)return a(o,400,{error:{message:"model-ledger: engine required",type:"model_ledger_error"}});const d=await Qe.append({...s,engine:l,kind:s.kind||"call"});return d.key!==n?a(o,400,{error:{message:`model-ledger: entry is for ${d.key}, not ${n}`,type:"model_ledger_error"}}):a(o,200,{ok:!0,entry:d})}catch(s){return a(o,400,{error:{message:`model-ledger: ${s.message}`,type:"model_ledger_error"}})}}}if(i==="/v1/teams/stream"&&r.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)}
33
+ `)}catch{}},25e3);r.on("close",()=>{clearInterval(S),g()});return}}}if(i==="/v1/agents/scorecards"&&r.method==="GET")return a(o,200,{ok:!0,agents:Ke.list()});{const e=/^\/v1\/agents\/([a-zA-Z0-9_.:@+-]{1,120})\/scorecard$/.exec(i);if(e){const n=decodeURIComponent(e[1]);if(r.method==="GET")return a(o,200,{ok:!0,...await Ke.get(n)});if(r.method==="POST")try{const s=JSON.parse((await b(r,t.maxBodyBytes)).toString("utf8"))||{},l=await Ke.append({agentId:n,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 Qe.fromRating(Ke.chains.get(n)||[],{...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"&&r.method==="GET")return a(o,200,ha(t,{version:le,reader:F,searcher:he,extract:U(),proxy:K}));if(i==="/v1/fusions"&&r.method==="GET"){const e={active:z.health().model||t.ner?.model||null,companions:z.companions()};let n=null;try{n=await I().status()}catch{n=null}return a(o,200,ia({cfg:t,ner:e,runtimeDoc:n}))}if(i==="/v1/runtime"&&r.method==="GET"){const e=Object.fromEntries(Ea.map(n=>{const s=Jt(t,n);return[n,{provider:s.kind,model:s.kind==="embedded"?s.model:null,models:Oa[n],threads:j.threads,...s.kind==="embedded"?j.health(n,s.model):{}}]}));return a(o,200,{...await I().status(),inProcess:e})}if(i==="/v1/runtime/plugins"&&r.method==="GET")return a(o,200,{ok:!0,...I().pluginList()});if(i==="/v1/runtime/plugins"&&r.method==="POST"||i.startsWith("/v1/runtime/plugins/")&&r.method==="DELETE"){if(!J(r)||Me(r.headers))return a(o,403,{error:{message:"engines: only the owner of this machine adds or removes one (the gateway token or its extension, from this machine)",type:"forbidden"}});if(at({stateDir:Le.dirname(Z())}).on)return a(o,403,{error:{message:"engines: this gateway runs confined and starts no new programs",type:"confined"}});if(r.method==="DELETE"){const s=Ta(decodeURIComponent(i.slice(20)));return s.ok?a(o,200,{ok:!0,...await I().reloadPlugins()}):a(o,404,{ok:!1,error:s.error})}let e;try{e=JSON.parse((await b(r,256*1024)).toString("utf8")||"{}")}catch{return a(o,400,{ok:!1,error:"engines: the body must be JSON"})}const n=Sa(e?.manifest??e,{builtins:[...va]});return n.ok?a(o,200,{ok:!0,manifest:n.manifest,...await I().reloadPlugins()}):a(o,400,{ok:!1,error:n.error})}if(i==="/v1/runtime/recipe"&&r.method==="GET"){if(!J(r))return a(o,403,{error:"runtime: extension origin or gateway token required"});const e=new URL(r.url,"http://x").searchParams,n=await I().recipe(String(e.get("service")||"llama"),e.get("model"));return a(o,n.ok?200:400,n)}if(i==="/v1/runtime/plan"&&r.method==="GET"){const e=new URL(r.url,"http://x").searchParams,n=await I().plan(String(e.get("service")||"mlx"),{model:e.get("model")||void 0,ctx:e.get("ctx"),needMB:e.get("need_mb")});return a(o,n.ok?200:400,n)}{const e=/^\/v1\/runtime\/(engines|services)\/([a-z0-9-]+)$/.exec(i);if(e&&r.method==="POST"){if(!J(r))return a(o,403,{error:"runtime: extension origin or gateway token required"});let n={};try{n=JSON.parse((await b(r,t.maxBodyBytes)).toString("utf8")||"{}")}catch{n={}}const s=String(n.action||"start"),l=I(),d=e[1]==="engines"?s==="start"?await l.startEngine(e[2]):{ok:!1,error:`unknown action ${s}`}:s==="start"?await l.startService(e[2],{force:n.force===!0}):s==="stop"?await l.stopService(e[2]):s==="model"?await l.setModel(e[2],n.model,{tunings:n.tunings||null}):s==="tune"?await l.setTunings(e[2],n.tunings):s==="profile"?await l.setProfile(e[2],n.profile):s==="pull"?await l.pullModel(e[2]):s==="install"?await l.installRunner(e[2]):s==="update"?await l.updateRunner(e[2]):s==="build"?await l.setBuild(e[2],String(n.build||"")):s==="cancel"?l.cancelJob(e[2]):s==="remove"?await l.removeService(e[2]):{ok:!1,error:`unknown action ${s}`};return a(o,d.ok?200:400,d)}}if(i==="/v1/embeddings"&&r.method==="POST"){let e;try{e=JSON.parse((await b(r,t.maxBodyBytes)).toString("utf8"))}catch{return a(o,400,{error:{message:"embed: body must be JSON",type:"invalid_request"}})}const n=await K.call("embed",e);return a(o,n.status,n.body)}if((i==="/v1/rerank"||i==="/v1/decide")&&r.method==="POST"){const e=i.slice(4);let n;try{n=JSON.parse((await b(r,t.maxBodyBytes)).toString("utf8"))}catch{return a(o,400,{error:{message:`${e}: body must be JSON`,type:"invalid_request"}})}const s=await K.call(e,n);return a(o,s.status,s.body)}if(i==="/v1/detect"&&r.method==="POST"){let e;try{e=JSON.parse((await b(r,t.maxBodyBytes)).toString("utf8"))}catch{return a(o,400,{error:{message:"detect: body must be JSON",type:"invalid_request"}})}try{const n=await ya(e,{ensure:()=>wt(t),model:z.health().model});return a(o,n.status,n.body)}catch(n){return a(o,500,{error:{message:`detect: ${n.message}`,type:"detector_error"}})}}if(i==="/v1/extract/context"&&r.method==="POST"){let e;try{e=JSON.parse((await b(r,Math.max(t.maxBodyBytes,Math.ceil(bt*4/3)+1024))).toString("utf8"))}catch{return a(o,400,{error:{message:"extract/context: body must be JSON",type:"invalid_request"}})}const n=await $a(e,{service:U()});return a(o,n.status,n.body)}if((i==="/v1/files/write"||i==="/v1/files/exists")&&r.method==="POST"){if(!J(r)||Me(r.headers))return a(o,403,{error:{message:"files: a client on this computer with the gateway token or the pinned extension only",type:"forbidden"}});let e;try{e=JSON.parse((await b(r,Math.max(t.maxBodyBytes,ns*6+4096))).toString("utf8"))}catch{return a(o,400,{error:{message:"files: body must be JSON",type:"invalid_request"}})}const n=await Ka(i.slice(10),e);return a(o,n.status,n.body)}if(i==="/v1/files/fs"&&r.method==="POST"){if(!J(r)||Me(r.headers))return a(o,403,{error:{message:"files: a client on this computer with the gateway token or the pinned extension only",type:"forbidden"}});let e;try{e=JSON.parse((await b(r,64*1024)).toString("utf8"))}catch{return a(o,400,{error:{message:"files: body must be JSON",type:"invalid_request"}})}const n=await Qa(e);return a(o,n.status,n.body)}if(i==="/v1/files/pick-folder"&&r.method==="POST"){if(!J(r)||Me(r.headers))return a(o,403,{error:{message:"files: a client on this computer with the gateway token or the pinned extension only",type:"forbidden"}});let e={};try{e=JSON.parse((await b(r,4*1024)).toString("utf8")||"{}")}catch{return a(o,400,{error:{message:"files: body must be JSON",type:"invalid_request"}})}const n=await Xa(e);return a(o,n.status,n.body)}if(i==="/v1/import/apple-notes"&&r.method==="POST"){if(!J(r)||Me(r.headers))return a(o,403,{error:{message:"apple-notes: a client on this computer with the gateway token or the pinned extension only",type:"forbidden"}});let e;try{e=JSON.parse((await b(r,t.maxBodyBytes)).toString("utf8"))}catch{return a(o,400,{error:{message:"apple-notes: body must be JSON",type:"invalid_request"}})}const n=await Ya(e);return a(o,n.status,n.body)}if(i==="/v1/extract"&&r.method==="POST"){let e;try{e=JSON.parse((await b(r,Math.max(t.maxBodyBytes,Math.ceil(bt*4/3)+1024))).toString("utf8"))}catch{return a(o,400,{error:{message:"extract: body must be JSON",type:"invalid_request"}})}const n=await Pa(e,{service:U()});return a(o,n.status,n.body)}if(i==="/v1/read"&&r.method==="POST"){let e;try{e=JSON.parse((await b(r,t.maxBodyBytes)).toString("utf8"))}catch{return a(o,400,{error:{message:"read: body must be JSON",type:"invalid_request"}})}const n=await D().read(e);return a(o,n.status,n.body)}if(i==="/v1/search"&&r.method==="POST"){let e;try{e=JSON.parse((await b(r,t.maxBodyBytes)).toString("utf8"))}catch{return a(o,400,{error:{message:"search: body must be JSON",type:"invalid_request"}})}ae();const n=await Xe().search(e);return a(o,n.status,n.body)}if(/^\/v1\/search\/./.test(i)&&r.method==="GET"){let e;try{e=decodeURIComponent(i.slice(11))}catch{e=i.slice(11)}const n=y.searchParams.has("read")?Math.max(0,Math.min(10,Number(y.searchParams.get("read"))||0)):ls.aliasRead;ae();const s=await Xe().search({q:e,read:n,limit:Math.max(n,5)});return a(o,s.status,s.status===200?is(s.body):s.body)}if(/^\/v1\/read\/./.test(i)&&r.method==="GET"){const e=String(r.url||"").slice(9),n=/^https?:\/\//i.test(e)?e:decodeURIComponent(e),s=/application\/json/i.test(r.headers.accept||""),l=/^text$/i.test(r.headers["x-return-format"]||"")?"text":"markdown",d=await D().read({url:n,format:l});return d.status!==200||s?a(o,d.status,d.status===200?{code:200,status:2e4,data:d.body}:d.body):(o.writeHead(200,{"content-type":"text/plain; charset=utf-8","x-chatpanel-provider":d.body.provider}),o.end(us(d.body)))}if(i==="/v1/engines"&&r.method==="GET"){const e=Number(y.searchParams.get("minCalls"))||void 0;return a(o,200,{ok:!0,engines:Qe.list({minCalls:e})})}{const e=/^\/v1\/engines\/(.+)\/(card|entries)$/.exec(i);if(e){const n=decodeURIComponent(e[1]).slice(0,300);if(e[2]==="card"&&r.method==="GET"){const s=Number(y.searchParams.get("minCalls"))||void 0;return a(o,200,{ok:!0,...await Qe.get(n,{entries:y.searchParams.get("entries")==="1",minCalls:s})})}if(e[2]==="entries"&&r.method==="POST")try{const s=JSON.parse((await b(r,t.maxBodyBytes)).toString("utf8"))||{},l=s.engine||li(n);if(!l)return a(o,400,{error:{message:"model-ledger: engine required",type:"model_ledger_error"}});const d=await Qe.append({...s,engine:l,kind:s.kind||"call"});return d.key!==n?a(o,400,{error:{message:`model-ledger: entry is for ${d.key}, not ${n}`,type:"model_ledger_error"}}):a(o,200,{ok:!0,entry:d})}catch(s){return a(o,400,{error:{message:`model-ledger: ${s.message}`,type:"model_ledger_error"}})}}}if(i==="/v1/teams/stream"&&r.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)}
34
34
 
35
35
  `)}catch{}};e({type:"hello",at:Date.now()});const n=te.watchAll(l=>e({type:"run",id:l.id,removed:!!l.removed})),s=setInterval(()=>{try{o.write(`: keep-alive
36
36
 
@@ -38,7 +38,7 @@ In a terminal, \`chatpanel-gateway --status\` shows what is running.
38
38
 
39
39
  `),d=y.searchParams.has("after")?Number(y.searchParams.get("after")):NaN;let m=Number.isFinite(d)?d:-1;l({seq:-1,type:"hello",at:Date.now(),payload:{run:te.get(n),after:m}});const p=te.watch(n,g=>{g.seq==null?l(g):g.seq>m&&(m=g.seq,l(g))});for(const g of te.eventsSince(n,m))m=g.seq,l(g);const f=setInterval(()=>{try{o.write(`: keep-alive
40
40
 
41
- `)}catch{}},25e3);o.on("close",()=>{p(),clearInterval(f)});return}}}if(i.startsWith("/v1/contexts")){const e=G.lossless;if(!e)return a(o,501,{error:{message:"contexts need the SQLite warm store",type:"unavailable"}});_o||=wn({store:e,notify:We,audit:st});const n=async l=>{const d=(await b(l,262144)).toString("utf8");return d?JSON.parse(d):{}},s=h(r);if(await bn(r,o,{pathname:i,api:_o,readJson:n,sendJson:a,principal:s}))return}if(i==="/v1/memory/list"&&r.method==="GET")return a(o,200,{ok:!0,size:be.size,memories:be.list()});if(i==="/v1/memory/recall"&&r.method==="POST")try{const e=JSON.parse((await b(r,t.maxBodyBytes)).toString("utf8"))||{},n=be.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:be.size,...n})}catch(e){return a(o,400,{error:{message:`recall failed: ${e.message}`,type:"memory_error"}})}if(i==="/v1/memory/remember"&&r.method==="POST")try{const e=JSON.parse((await b(r,t.maxBodyBytes)).toString("utf8"))||{},n=be.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:n.action,record:n.record,replaced:n.replaces||null,size:be.size})}catch(e){return a(o,400,{error:{message:e.message,type:"memory_error"}})}if(i==="/v1/memory/forget"&&r.method==="POST")try{const e=JSON.parse((await b(r,t.maxBodyBytes)).toString("utf8"))||{},{removed:n}=be.forget(String(e.query||""));return a(o,200,{ok:!0,removed:n,size:be.size})}catch(e){return a(o,400,{error:{message:e.message,type:"memory_error"}})}if(i==="/v1/memory/sync"&&r.method==="POST")try{const e=JSON.parse((await b(r,t.maxBodyBytes)).toString("utf8"))||{},n=be.bulk({upserts:Array.isArray(e.upserts)?e.upserts:[],removes:Array.isArray(e.removes)?e.removes:[]});return a(o,200,{ok:!0,...n,memories:be.list()})}catch(e){return a(o,400,{error:{message:`memory sync failed: ${e.message}`,type:"memory_error"}})}if(i==="/v1/memory/clear"&&r.method==="POST")return a(o,200,{ok:!0,dropped:be.clear(),size:be.size});if(i==="/v1/history/clear"&&r.method==="POST"){const e=G.clear();return a(o,200,{ok:!0,dropped:e,size:G.size})}if(i==="/v1/history/search"&&r.method==="POST")try{const e=JSON.parse((await b(r,t.maxBodyBytes)).toString("utf8"))||{},n=G.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:G.size,newest:G.newest,results:n})}catch(e){return a(o,400,{error:{message:`search failed: ${e.message}`,type:"search_error"}})}if(i==="/v1/history/smart-search"&&r.method==="POST")try{const e=JSON.parse((await b(r,t.maxBodyBytes)).toString("utf8"))||{},n=String(e.question||e.query||""),s=Xs(n,{extra:Array.isArray(e.queries)?e.queries.map(String):[],max:Math.min(6,Math.max(1,Number(e.maxQueries)||4))}),l={type:e.type?String(e.type):null,since:e.since!=null?Number(e.since):null,before:e.before!=null?Number(e.before):null},d=Math.min(30,Math.max(5,Number(e.limit)||10)*2),m=await Zs(s,f=>G.search(f,{limit:d,...l}),{limit:Math.min(50,Math.max(1,Number(e.limit)||10))}),p=l.type?m:[...m.filter(f=>f.type==="brief"),...m.filter(f=>f.type!=="brief")];return a(o,200,{ok:!0,size:G.size,newest:G.newest,queries:s,results:p})}catch(e){return a(o,400,{error:{message:`smart search failed: ${e.message}`,type:"search_error"}})}if(i==="/v1/research"&&r.method==="POST"){let e;try{e=JSON.parse((await b(r,t.maxBodyBytes)).toString("utf8")||"{}")||{}}catch{return a(o,400,{error:{message:"research: the body must be JSON",type:"invalid_request_error"}})}const n=String(e.question||"").trim();if(!n)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&&!J(r))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:${r.socket.localPort}`,d=s?async(g,{maxTokens:S=220}={})=>{const _=new AbortController,T=setTimeout(()=>_.abort(),3e4);try{const R=Re()||Pe(),X=await fetch(`${l}/v1/chat/completions`,{method:"POST",signal:_.signal,headers:{"content-type":"application/json",...R?{Authorization:`Bearer ${R}`}:{},"X-ChatPanel-Client":"research"},body:JSON.stringify({model:s,messages:[{role:"user",content:g}],stream:!1,max_tokens:S,temperature:.2})}),ke=await X.json().catch(()=>({}));return X.ok?String(ke?.choices?.[0]?.message?.content||""):""}finally{clearTimeout(T)}}:null,m=me.get("identity")?.identity?.value||{},p=e.previous&&typeof e.previous=="object"&&e.previous.plan&&typeof e.previous.plan=="object"?{plan:e.previous.plan,top:typeof e.previous.top=="string"?e.previous.top:null,answer:String(e.previous.answer||"").slice(0,4e3)}:null,f=await An(n,{store:G,memories:be.list(),complete:d,previous:p,self:String(m.selfName||"").trim(),excludeId:typeof e.excludeId=="string"?e.excludeId:null,ids:Array.isArray(e.ids)?e.ids.filter(g=>typeof g=="string"&&/^(chat|note|meeting|brief):[^\s]{1,200}$/.test(g)).slice(0,2e3):null,parallel:3});return a(o,200,Nn(n,f,{size:G.size,newest:G.newest}))}if(i==="/v1/context"||i.startsWith("/v1/context/")){let e=null;if(r.method==="POST"){const s=/\/upload$/.test(i)?Math.ceil(bt*4/3)+1024:t.maxBodyBytes;try{const l=(await b(r,Math.max(t.maxBodyBytes,s))).toString("utf8");e=l?JSON.parse(l):{}}catch{return a(o,400,{error:{message:"context: body must be JSON",type:"invalid_request"}})}}const n=await we().handle({method:r.method,pathname:i,body:e,admin:J(r),agent:String(r.headers["x-chatpanel-agent"]||""),federated:!!r.headers[os]});return a(o,n.status,n.body)}if(i==="/v1/destinations"||i.startsWith("/v1/destinations/")){let e=null;if(r.method==="POST"||r.method==="PUT")try{const l=(await b(r,t.maxBodyBytes)).toString("utf8");e=l?JSON.parse(l):{}}catch{return a(o,400,{error:{message:"destinations: body must be JSON",type:"invalid_request"}})}const s=Hs({cfg:t,apply:xt,persist:()=>ue(t,Z()),isSelf:l=>Ls(l,t)}).handle({method:r.method,pathname:i,body:e,admin:J(r)});return a(o,s.status,s.body)}if(i==="/v1/kb"||i.startsWith("/v1/kb/")){let e=null;if(r.method==="POST"||r.method==="PUT")try{const s=(await b(r,Math.max(t.maxBodyBytes,Math.ceil(bt*4/3)+1024))).toString("utf8");e=s?JSON.parse(s):{}}catch{return a(o,400,{error:{message:"kb: body must be JSON",type:"invalid_request"}})}const n=await _e().handle({method:r.method,pathname:i,query:y.searchParams,body:e,admin:!r.chatpanelViewOnly&&J(r),agent:r.chatpanelViewOnly?"":String(r.headers["x-chatpanel-agent"]||""),local:!Me(r.headers),viewOnly:!!r.chatpanelViewOnly});return n.text!=null?(o.writeHead(n.status,{"content-type":n.contentType||"text/plain; charset=utf-8",...n.headers||{}}),o.end(n.text)):a(o,n.status,n.body)}if(i==="/v1/history/related"&&r.method==="GET"){const e=String(y.searchParams.get("id")||""),n=Math.min(30,Math.max(1,Number(y.searchParams.get("limit"))||5));return a(o,200,{ok:!0,results:G.related(e,{limit:n})})}if(i==="/v1/history/status"&&r.method==="GET")return a(o,200,{ok:!0,size:G.size,newest:G.newest,bytes:G.bytes,lossless:G.lossless?{records:G.lossless.size,newest:G.lossless.newest}:null});if(i==="/v1/observability"&&r.method==="GET"){const e=Math.min(500,Math.max(1,Number(y.searchParams.get("limit"))||200));return a(o,200,{ok:!0,storage:{warm:{records:G.size,bytes:G.bytes,newest:G.newest}},access:Ht.snapshot(e)})}if(i==="/v1/observability/access"&&r.method==="POST")try{const e=JSON.parse((await b(r,t.maxBodyBytes)).toString("utf8"))||{},n=Ht.push(tr({ts:Date.now(),...e}));return a(o,200,{ok:!0,event:n})}catch(e){return a(o,400,{error:{message:`access log failed: ${e.message}`,type:"observability_error"}})}if(i==="/v1/history/records"&&r.method==="PUT"){const e=G.lossless;if(!e)return a(o,501,{error:{message:"lossless records need the SQLite warm store",type:"unavailable"}});try{const n=JSON.parse((await b(r,Math.max(t.maxBodyBytes||0,mi))).toString("utf8"))||{},s=String(n.host||"").slice(0,80),l=Number(n.at)||Date.now(),d=[];let m=0,p={},f=[],g=[];const S={upserts:[],removes:[]},_=T=>{if(!T||T.deletedAt){T?.id&&S.removes.push(T.id);return}try{const R=Co(T);R&&S.upserts.push(R)}catch{}};if(Array.isArray(n.records)){const T=e.write(n.records,{host:s,at:l,merge:n.merge===!0});d.push(...T.written),p=T.revs,f=T.conflicts,g=T.merged;for(const R of T.written)_(e.get(R))}if(Array.isArray(n.entries)){const T=Nt(),R=T?ua((re,Ee)=>da(T,{salt:re,iterations:Ee})):null,X=async re=>{if(!R||!re.blob)return null;const Ee=await R(re.blob),V=re.blob.compression&&re.blob.compression!=="none"?ma(pa,re.blob.compression):null;return ca(re.blob,Ee,{codec:V})},ke=await e.upsertEntries(n.entries,{open:X});d.push(...ke.written),m+=ke.sealed;for(const re of ke.written)_(e.get(re))}return(S.upserts.length||S.removes.length)&&G.bulk(S),d.length&&We({ids:d}),a(o,200,{ok:!0,written:d.length,ids:d,revs:p,conflicts:f,merged:g,sealed:m,size:e.size,rev:e.rev})}catch(n){return a(o,400,{error:{message:`records failed: ${n.message}`,type:"ingest_error"}})}}if(i==="/v1/events"&&r.method==="DELETE"){if(!Q)return a(o,501,{error:{message:"the event log needs SQLite",type:"unavailable"}});const e=m=>/^(1|true|yes)$/i.test(y.searchParams.get(m)||""),n=y.searchParams.get("host"),s=e("all");if((n===null||n==="")==!s)return a(o,400,{error:{message:"events: name one host (?host=<id>) or the whole log (?all=1) — exactly one",type:"invalid_request_error"}});if(n!==null&&n.length>200)return a(o,400,{error:{message:"events: host is at most 200 characters",type:"invalid_request_error"}});const l=s?null:n;if(!e("force")){const m=Q.countOf(l);return a(o,409,{ok:!1,wouldDelete:m,...s?{all:!0}:{host:n},error:{message:`events: add force=1 to delete ${m} event(s) ${s?"in the whole log":`for host "${n}"`} — nothing was deleted`,type:"confirm_required",code:"confirm_required"}})}const d=Q.deleteOf(l);for(const m of Ce)try{m.write(`event: deleted
41
+ `)}catch{}},25e3);o.on("close",()=>{p(),clearInterval(f)});return}}}if(i.startsWith("/v1/contexts")){const e=G.lossless;if(!e)return a(o,501,{error:{message:"contexts need the SQLite warm store",type:"unavailable"}});_o||=wn({store:e,notify:We,audit:st});const n=async l=>{const d=(await b(l,262144)).toString("utf8");return d?JSON.parse(d):{}},s=h(r);if(await bn(r,o,{pathname:i,api:_o,readJson:n,sendJson:a,principal:s}))return}if(i==="/v1/memory/list"&&r.method==="GET")return a(o,200,{ok:!0,size:be.size,memories:be.list()});if(i==="/v1/memory/recall"&&r.method==="POST")try{const e=JSON.parse((await b(r,t.maxBodyBytes)).toString("utf8"))||{},n=be.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:be.size,...n})}catch(e){return a(o,400,{error:{message:`recall failed: ${e.message}`,type:"memory_error"}})}if(i==="/v1/memory/remember"&&r.method==="POST")try{const e=JSON.parse((await b(r,t.maxBodyBytes)).toString("utf8"))||{},n=be.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:n.action,record:n.record,replaced:n.replaces||null,size:be.size})}catch(e){return a(o,400,{error:{message:e.message,type:"memory_error"}})}if(i==="/v1/memory/forget"&&r.method==="POST")try{const e=JSON.parse((await b(r,t.maxBodyBytes)).toString("utf8"))||{},{removed:n}=be.forget(String(e.query||""));return a(o,200,{ok:!0,removed:n,size:be.size})}catch(e){return a(o,400,{error:{message:e.message,type:"memory_error"}})}if(i==="/v1/memory/sync"&&r.method==="POST")try{const e=JSON.parse((await b(r,t.maxBodyBytes)).toString("utf8"))||{},n=be.bulk({upserts:Array.isArray(e.upserts)?e.upserts:[],removes:Array.isArray(e.removes)?e.removes:[]});return a(o,200,{ok:!0,...n,memories:be.list()})}catch(e){return a(o,400,{error:{message:`memory sync failed: ${e.message}`,type:"memory_error"}})}if(i==="/v1/memory/clear"&&r.method==="POST")return a(o,200,{ok:!0,dropped:be.clear(),size:be.size});if(i==="/v1/history/clear"&&r.method==="POST"){const e=G.clear();return a(o,200,{ok:!0,dropped:e,size:G.size})}if(i==="/v1/history/search"&&r.method==="POST")try{const e=JSON.parse((await b(r,t.maxBodyBytes)).toString("utf8"))||{},n=G.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:G.size,newest:G.newest,results:n})}catch(e){return a(o,400,{error:{message:`search failed: ${e.message}`,type:"search_error"}})}if(i==="/v1/history/smart-search"&&r.method==="POST")try{const e=JSON.parse((await b(r,t.maxBodyBytes)).toString("utf8"))||{},n=String(e.question||e.query||""),s=Zs(n,{extra:Array.isArray(e.queries)?e.queries.map(String):[],max:Math.min(6,Math.max(1,Number(e.maxQueries)||4))}),l={type:e.type?String(e.type):null,since:e.since!=null?Number(e.since):null,before:e.before!=null?Number(e.before):null},d=Math.min(30,Math.max(5,Number(e.limit)||10)*2),m=await qs(s,f=>G.search(f,{limit:d,...l}),{limit:Math.min(50,Math.max(1,Number(e.limit)||10))}),p=l.type?m:[...m.filter(f=>f.type==="brief"),...m.filter(f=>f.type!=="brief")];return a(o,200,{ok:!0,size:G.size,newest:G.newest,queries:s,results:p})}catch(e){return a(o,400,{error:{message:`smart search failed: ${e.message}`,type:"search_error"}})}if(i==="/v1/research"&&r.method==="POST"){let e;try{e=JSON.parse((await b(r,t.maxBodyBytes)).toString("utf8")||"{}")||{}}catch{return a(o,400,{error:{message:"research: the body must be JSON",type:"invalid_request_error"}})}const n=String(e.question||"").trim();if(!n)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&&!J(r))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:${r.socket.localPort}`,d=s?async(g,{maxTokens:S=220}={})=>{const _=new AbortController,T=setTimeout(()=>_.abort(),3e4);try{const R=Re()||Pe(),X=await fetch(`${l}/v1/chat/completions`,{method:"POST",signal:_.signal,headers:{"content-type":"application/json",...R?{Authorization:`Bearer ${R}`}:{},"X-ChatPanel-Client":"research"},body:JSON.stringify({model:s,messages:[{role:"user",content:g}],stream:!1,max_tokens:S,temperature:.2})}),ke=await X.json().catch(()=>({}));return X.ok?String(ke?.choices?.[0]?.message?.content||""):""}finally{clearTimeout(T)}}:null,m=me.get("identity")?.identity?.value||{},p=e.previous&&typeof e.previous=="object"&&e.previous.plan&&typeof e.previous.plan=="object"?{plan:e.previous.plan,top:typeof e.previous.top=="string"?e.previous.top:null,answer:String(e.previous.answer||"").slice(0,4e3)}:null,f=await An(n,{store:G,memories:be.list(),complete:d,previous:p,self:String(m.selfName||"").trim(),excludeId:typeof e.excludeId=="string"?e.excludeId:null,ids:Array.isArray(e.ids)?e.ids.filter(g=>typeof g=="string"&&/^(chat|note|meeting|brief):[^\s]{1,200}$/.test(g)).slice(0,2e3):null,parallel:3});return a(o,200,Nn(n,f,{size:G.size,newest:G.newest}))}if(i==="/v1/context"||i.startsWith("/v1/context/")){let e=null;if(r.method==="POST"){const s=/\/upload$/.test(i)?Math.ceil(bt*4/3)+1024:t.maxBodyBytes;try{const l=(await b(r,Math.max(t.maxBodyBytes,s))).toString("utf8");e=l?JSON.parse(l):{}}catch{return a(o,400,{error:{message:"context: body must be JSON",type:"invalid_request"}})}}const n=await we().handle({method:r.method,pathname:i,body:e,admin:J(r),agent:String(r.headers["x-chatpanel-agent"]||""),federated:!!r.headers[rs]});return a(o,n.status,n.body)}if(i==="/v1/destinations"||i.startsWith("/v1/destinations/")){let e=null;if(r.method==="POST"||r.method==="PUT")try{const l=(await b(r,t.maxBodyBytes)).toString("utf8");e=l?JSON.parse(l):{}}catch{return a(o,400,{error:{message:"destinations: body must be JSON",type:"invalid_request"}})}const s=Vs({cfg:t,apply:xt,persist:()=>ue(t,Z()),isSelf:l=>js(l,t)}).handle({method:r.method,pathname:i,body:e,admin:J(r)});return a(o,s.status,s.body)}if(i==="/v1/kb"||i.startsWith("/v1/kb/")){let e=null;if(r.method==="POST"||r.method==="PUT")try{const s=(await b(r,Math.max(t.maxBodyBytes,Math.ceil(bt*4/3)+1024))).toString("utf8");e=s?JSON.parse(s):{}}catch{return a(o,400,{error:{message:"kb: body must be JSON",type:"invalid_request"}})}const n=await _e().handle({method:r.method,pathname:i,query:y.searchParams,body:e,admin:!r.chatpanelViewOnly&&J(r),agent:r.chatpanelViewOnly?"":String(r.headers["x-chatpanel-agent"]||""),local:!Me(r.headers),viewOnly:!!r.chatpanelViewOnly});return n.text!=null?(o.writeHead(n.status,{"content-type":n.contentType||"text/plain; charset=utf-8",...n.headers||{}}),o.end(n.text)):a(o,n.status,n.body)}if(i==="/v1/history/related"&&r.method==="GET"){const e=String(y.searchParams.get("id")||""),n=Math.min(30,Math.max(1,Number(y.searchParams.get("limit"))||5));return a(o,200,{ok:!0,results:G.related(e,{limit:n})})}if(i==="/v1/history/status"&&r.method==="GET")return a(o,200,{ok:!0,size:G.size,newest:G.newest,bytes:G.bytes,lossless:G.lossless?{records:G.lossless.size,newest:G.lossless.newest}:null});if(i==="/v1/observability"&&r.method==="GET"){const e=Math.min(500,Math.max(1,Number(y.searchParams.get("limit"))||200));return a(o,200,{ok:!0,storage:{warm:{records:G.size,bytes:G.bytes,newest:G.newest}},access:Ht.snapshot(e)})}if(i==="/v1/observability/access"&&r.method==="POST")try{const e=JSON.parse((await b(r,t.maxBodyBytes)).toString("utf8"))||{},n=Ht.push(tr({ts:Date.now(),...e}));return a(o,200,{ok:!0,event:n})}catch(e){return a(o,400,{error:{message:`access log failed: ${e.message}`,type:"observability_error"}})}if(i==="/v1/history/records"&&r.method==="PUT"){const e=G.lossless;if(!e)return a(o,501,{error:{message:"lossless records need the SQLite warm store",type:"unavailable"}});try{const n=JSON.parse((await b(r,Math.max(t.maxBodyBytes||0,pi))).toString("utf8"))||{},s=String(n.host||"").slice(0,80),l=Number(n.at)||Date.now(),d=[];let m=0,p={},f=[],g=[];const S={upserts:[],removes:[]},_=T=>{if(!T||T.deletedAt){T?.id&&S.removes.push(T.id);return}try{const R=Co(T);R&&S.upserts.push(R)}catch{}};if(Array.isArray(n.records)){const T=e.write(n.records,{host:s,at:l,merge:n.merge===!0});d.push(...T.written),p=T.revs,f=T.conflicts,g=T.merged;for(const R of T.written)_(e.get(R))}if(Array.isArray(n.entries)){const T=Nt(),R=T?ua((re,Ee)=>da(T,{salt:re,iterations:Ee})):null,X=async re=>{if(!R||!re.blob)return null;const Ee=await R(re.blob),V=re.blob.compression&&re.blob.compression!=="none"?ma(pa,re.blob.compression):null;return ca(re.blob,Ee,{codec:V})},ke=await e.upsertEntries(n.entries,{open:X});d.push(...ke.written),m+=ke.sealed;for(const re of ke.written)_(e.get(re))}return(S.upserts.length||S.removes.length)&&G.bulk(S),d.length&&We({ids:d}),a(o,200,{ok:!0,written:d.length,ids:d,revs:p,conflicts:f,merged:g,sealed:m,size:e.size,rev:e.rev})}catch(n){return a(o,400,{error:{message:`records failed: ${n.message}`,type:"ingest_error"}})}}if(i==="/v1/events"&&r.method==="DELETE"){if(!Q)return a(o,501,{error:{message:"the event log needs SQLite",type:"unavailable"}});const e=m=>/^(1|true|yes)$/i.test(y.searchParams.get(m)||""),n=y.searchParams.get("host"),s=e("all");if((n===null||n==="")==!s)return a(o,400,{error:{message:"events: name one host (?host=<id>) or the whole log (?all=1) — exactly one",type:"invalid_request_error"}});if(n!==null&&n.length>200)return a(o,400,{error:{message:"events: host is at most 200 characters",type:"invalid_request_error"}});const l=s?null:n;if(!e("force")){const m=Q.countOf(l);return a(o,409,{ok:!1,wouldDelete:m,...s?{all:!0}:{host:n},error:{message:`events: add force=1 to delete ${m} event(s) ${s?"in the whole log":`for host "${n}"`} — nothing was deleted`,type:"confirm_required",code:"confirm_required"}})}const d=Q.deleteOf(l);for(const m of Ce)try{m.write(`event: deleted
42
42
  data: ${JSON.stringify({...s?{all:!0}:{host:n},deleted:d})}
43
43
 
44
44
  `)}catch{}return a(o,200,{ok:!0,deleted:d,...s?{all:!0}:{host:n},cursor:Q.cursor()})}if(i==="/v1/events"&&r.method==="POST"){if(!Q)return a(o,501,{error:{message:"the event log needs SQLite",type:"unavailable"}});try{const e=JSON.parse((await b(r,t.maxBodyBytes)).toString("utf8"))||{},n=Array.isArray(e)?e:e.events;if(!Array.isArray(n))return a(o,400,{error:{message:"events: an array of CloudEvents (or { events: [...] }) required",type:"invalid_request_error"}});if(n.length>2e3)return a(o,413,{error:{message:"events: at most 2000 per batch",type:"invalid_request_error"}});const s=m=>(typeof m?.host=="string"&&m.host?m.host:sa(m?.source))===Mo,l=n.filter(s).map(m=>({id:m?.id??null,code:"RESERVED_HOST",message:`host "${Mo}" is this gateway's own log`})),d=ra(Q,l.length?n.filter(m=>!s(m)):n);return a(o,200,{ok:!0,appended:d.appended,duplicates:d.duplicates,rejected:[...l,...d.rejected],cursor:Q.cursor()})}catch(e){return a(o,400,{error:{message:`events: ${e?.message||e}`,type:"invalid_request_error"}})}}if(i==="/v1/events/cursor"&&r.method==="GET")return Q?a(o,200,{ok:!0,cursor:Q.cursor(),count:Q.count()}):a(o,501,{error:{message:"the event log needs SQLite",type:"unavailable"}});if(i==="/v1/events/stats"&&r.method==="GET"){if(!Q)return a(o,501,{error:{message:"the event log needs SQLite",type:"unavailable"}});const e=na(Q.all());return a(o,200,{ok:!0,stats:e,year:aa(e)})}if(i==="/v1/events"&&r.method==="GET"){if(!Q)return a(o,501,{error:{message:"the event log needs SQLite",type:"unavailable"}});let e={};try{e=Do(JSON.parse(y.searchParams.get("cursor")||"{}"))}catch{return a(o,400,{error:{message:"events: cursor must be JSON { host: seq }",type:"invalid_request_error"}})}const n=Q.since(e,{limit:Number(y.searchParams.get("limit"))||void 0,host:y.searchParams.get("host")||null});return a(o,200,{ok:!0,events:n.events.map(s=>Dt(s)),cursor:n.cursor,more:n.more})}if(i==="/v1/events/stream"&&r.method==="GET"){if(!Q)return a(o,501,{error:{message:"the event log needs SQLite",type:"unavailable"}});let e=null;if(y.searchParams.has("cursor"))try{e=Do(JSON.parse(y.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
@@ -47,7 +47,7 @@ data: ${JSON.stringify({cursor:Q.cursor(),count:Q.count(),version:le})}
47
47
  `),Ce.add(o),r.on("close",()=>Ce.delete(o)),e){let n={cursor:e,more:!0};for(;n.more;){n=Q.since(n.cursor);for(const s of n.events)o.write(`event: cloudevent
48
48
  data: ${JSON.stringify(Dt(s))}
49
49
 
50
- `)}}return}if(i==="/v1/link"&&r.method==="GET")return a(o,200,{...E?{enabled:!0,...E.status()}:{enabled:!1,devices:[],pairing:null},agentSessions:t.link?.agentSessions!==!1});if(i==="/v1/link/settings"&&r.method==="POST"){if(r.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 b(r,t.maxBodyBytes)).toString("utf8")||"{}")||{}}catch{e={}}if(typeof e.agentSessions!="boolean")return a(o,400,{error:{message:"link settings: { agentSessions: true|false }",type:"invalid_request"}});t.link={...t.link||{},agentSessions:e.agentSessions};try{ue(t,Z())}catch(n){console.warn(`[link] could not persist the settings: ${n.message}`)}return a(o,200,{ok:!0,agentSessions:t.link.agentSessions})}if(i==="/v1/link/pair"&&r.method==="POST"){if(!E)return a(o,409,{error:{message:"link is off (link.enabled: false)",type:"disabled"}});if(r.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 b(r,t.maxBodyBytes)).toString("utf8")||"{}")||{}}catch{e={}}if(e?.kind==="partner"){const n={partner:e.partner?.name,scopes:e.scopes,route:e.route||null,relay:String(e.relay||""),folder:typeof e.folder=="string"?e.folder:""};let s;try{s=E.previewPartner(n)}catch(l){return a(o,400,{error:{message:l?.message||String(l),type:"invalid_request",code:l?.code||"bad_partner"}})}if(e.confirm!==!0)return a(o,200,{confirmed:!1,preview:s});try{return a(o,200,{confirmed:!0,...await E.pairPartner(n)})}catch(l){return a(o,l?.code==="bad_partner"?400:502,{error:{message:l?.message||String(l),type:l?.code==="bad_partner"?"invalid_request":"relay"}})}}if(e?.kind&&e.kind!=="phone")return a(o,400,{error:{message:"link pair: kind is phone or partner",type:"invalid_request"}});try{return a(o,200,await E.pair({name:String(e?.name||"").slice(0,60)||void 0}))}catch(n){return a(o,502,{error:{message:n?.message||String(n),type:"relay"}})}}if(i==="/v1/link/tailscale"){if(r.headers["x-chatpanel-link-device"])return a(o,403,{error:{message:"a paired phone cannot change the route",type:"forbidden"}});if(r.method==="GET")return a(o,200,await C.detect());if(r.method!=="POST")return a(o,405,{error:{message:"method not allowed",type:"method_not_allowed"}});if(!E)return a(o,409,{error:{message:"link is off (link.enabled: false)",type:"disabled"}});let e={};try{e=JSON.parse((await b(r,t.maxBodyBytes)).toString("utf8")||"{}")||{}}catch{e={}}if(e.action==="remove"){const d=t.link?.tailscaleServed?await C.unserve():{ok:!0},m={...t.link||{},tailscaleServed:!d.ok};m.route==="tailscale"&&(m.route="link",delete m.tunnelUrl),t.link=m;try{ue(t,Z())}catch(p){console.warn(`[link] could not persist the route: ${p.message}`)}return a(o,d.ok?200:502,{enabled:!0,...await E.applySettings(m),tailscale:await C.detect(),...d.ok?{}:{error:{message:d.error,type:"tailscale"}}})}if(e.action!=="setup")return a(o,400,{error:{message:"link tailscale: action is setup or remove",type:"invalid_request"}});const n=await C.serve();if(!n.ok)return a(o,409,{error:{message:n.error,type:"tailscale"},tailscale:n.state});let s;try{s=Io({id:"tailscale",url:n.state.address})}catch(d){return a(o,400,{error:{message:d.message,type:"bad_route"},tailscale:n.state})}const l={...t.link||{},route:"tailscale",tunnelUrl:s.url,fallback:e.fallback!==!1,tailscaleServed:!0};t.link=l;try{ue(t,Z())}catch(d){console.warn(`[link] could not persist the route: ${d.message}`)}return a(o,200,{enabled:!0,...await E.applySettings(l),tailscale:n.state})}if(i==="/v1/link/route"&&r.method==="POST"){if(!E)return a(o,409,{error:{message:"link is off (link.enabled: false)",type:"disabled"}});if(r.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 b(r,t.maxBodyBytes)).toString("utf8")||"{}")||{}}catch{e={}}let n;try{n=Io({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:n.id,fallback:e.fallback!==!1};n.id!=="tailscale"&&t.link?.tailscaleServed&&(s.tailscaleServed=!(await C.unserve()).ok),n.id==="relay"?s.relayUrl=n.url:n.id==="link"&&delete s.relayUrl,(n.id==="tailscale"||n.id==="cloudflare")&&(s.tunnelUrl=n.url),t.link=s;try{ue(t,Z())}catch(l){console.warn(`[link] could not persist the route: ${l.message}`)}return a(o,200,{enabled:!0,...await E.applySettings(s)})}if(i.startsWith("/v1/link/devices/")&&r.method==="DELETE"){if(!E)return a(o,404,{error:{message:"link is off",type:"disabled"}});const e=decodeURIComponent(i.slice(17));return await E.remove(e)?(x.cancelDevice(e),a(o,200,{ok:!0})):a(o,404,{error:{message:"no such device",type:"not_found"}})}if(i==="/v1/link/files"||i.startsWith("/v1/link/files/")){const e=Me(r.headers);if(e?.kind!=="partner"||!e.scopes.includes("files"))return a(o,403,{error:{message:"link files: a partner’s own folder, for a partner granted files",type:"forbidden",code:"link_scope"}});const n=E?.partnerFolderOf(e.device);if(!n)return a(o,403,{error:{message:"link files: this partner has no folder on this computer — pair it again with agents and files",type:"forbidden",code:"link_scope"}});const s=i.slice(14).replace(/^\//,"");let l=s;try{l=decodeURIComponent(s)}catch{}const d=r.method==="GET"&&(!s||/^(data|\.claude\/skills|\.claude\/agents|\.agents\/skills)\/?$/.test(l));let m;try{m=za(s,{listing:d})}catch(p){return a(o,400,{error:{message:p.message,type:"invalid_request",code:"bad_path"}})}try{if(r.method==="GET"&&d)return a(o,200,{folder:"its own",files:Ua(n,m.replace(/\/$/,""))});if(r.method==="GET"){const p=Ha(n,m);o.writeHead(200,{"content-type":"application/octet-stream","content-length":String(p.size)}),p.stream.pipe(o);return}return r.method==="PUT"?a(o,200,Va(n,m,await b(r,t.maxBodyBytes))):r.method==="DELETE"?Fa(n,m)?a(o,200,{ok:!0}):a(o,404,{error:{message:`${m}: no such file`,type:"not_found"}}):a(o,405,{error:{message:"link files: GET, PUT or DELETE",type:"invalid_request"}})}catch(p){const f=p?.status||(p?.code===413?413:p?.code==="bad_partner"?400:500);return a(o,f,{error:{message:p?.message||String(p),type:f===404?"not_found":f===413?"too_large":"invalid_request"}})}}if(i==="/v1/link/approvals"||i.startsWith("/v1/link/approvals/")){if(r.headers["x-chatpanel-link-device"])return a(o,403,{error:{message:"an agent’s approval is the owner’s to give, on this computer",type:"forbidden"}});if(i==="/v1/link/approvals"&&r.method==="GET")return a(o,200,{pending:x.list()});if(i==="/v1/link/approvals/stream"&&r.method==="GET"){o.writeHead(200,{"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive"});const n=d=>o.write(`event: approvals
50
+ `)}}return}if(i==="/v1/link"&&r.method==="GET")return a(o,200,{...E?{enabled:!0,...E.status()}:{enabled:!1,devices:[],pairing:null},agentSessions:t.link?.agentSessions!==!1});if(i==="/v1/link/settings"&&r.method==="POST"){if(r.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 b(r,t.maxBodyBytes)).toString("utf8")||"{}")||{}}catch{e={}}if(typeof e.agentSessions!="boolean")return a(o,400,{error:{message:"link settings: { agentSessions: true|false }",type:"invalid_request"}});t.link={...t.link||{},agentSessions:e.agentSessions};try{ue(t,Z())}catch(n){console.warn(`[link] could not persist the settings: ${n.message}`)}return a(o,200,{ok:!0,agentSessions:t.link.agentSessions})}if(i==="/v1/link/pair"&&r.method==="POST"){if(!E)return a(o,409,{error:{message:"link is off (link.enabled: false)",type:"disabled"}});if(r.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 b(r,t.maxBodyBytes)).toString("utf8")||"{}")||{}}catch{e={}}if(e?.kind==="partner"){const n={partner:e.partner?.name,scopes:e.scopes,route:e.route||null,relay:String(e.relay||""),folder:typeof e.folder=="string"?e.folder:""};let s;try{s=E.previewPartner(n)}catch(l){return a(o,400,{error:{message:l?.message||String(l),type:"invalid_request",code:l?.code||"bad_partner"}})}if(e.confirm!==!0)return a(o,200,{confirmed:!1,preview:s});try{return a(o,200,{confirmed:!0,...await E.pairPartner(n)})}catch(l){return a(o,l?.code==="bad_partner"?400:502,{error:{message:l?.message||String(l),type:l?.code==="bad_partner"?"invalid_request":"relay"}})}}if(e?.kind&&e.kind!=="phone")return a(o,400,{error:{message:"link pair: kind is phone or partner",type:"invalid_request"}});try{return a(o,200,await E.pair({name:String(e?.name||"").slice(0,60)||void 0}))}catch(n){return a(o,502,{error:{message:n?.message||String(n),type:"relay"}})}}if(i==="/v1/link/tailscale"){const e=m=>m&&{...m,row:Ja(m,{route:t.link?.route||"link"})};if(r.headers["x-chatpanel-link-device"])return a(o,403,{error:{message:"a paired phone cannot change the route",type:"forbidden"}});if(r.method==="GET")return a(o,200,e(await C.detect()));if(r.method!=="POST")return a(o,405,{error:{message:"method not allowed",type:"method_not_allowed"}});if(!E)return a(o,409,{error:{message:"link is off (link.enabled: false)",type:"disabled"}});let n={};try{n=JSON.parse((await b(r,t.maxBodyBytes)).toString("utf8")||"{}")||{}}catch{n={}}if(n.action==="remove"){const m=t.link?.tailscaleServed?await C.unserve():{ok:!0},p={...t.link||{},tailscaleServed:!m.ok};p.route==="tailscale"&&(p.route="link",delete p.tunnelUrl),t.link=p;try{ue(t,Z())}catch(f){console.warn(`[link] could not persist the route: ${f.message}`)}return a(o,m.ok?200:502,{enabled:!0,...await E.applySettings(p),tailscale:e(await C.detect()),...m.ok?{}:{error:{message:m.error,type:"tailscale"}}})}if(n.action!=="setup")return a(o,400,{error:{message:"link tailscale: action is setup or remove",type:"invalid_request"}});const s=await C.serve();if(!s.ok)return a(o,409,{error:{message:s.error,type:"tailscale"},tailscale:e(s.state)});let l;try{l=Io({id:"tailscale",url:s.state.address})}catch(m){return a(o,400,{error:{message:m.message,type:"bad_route"},tailscale:s.state})}const d={...t.link||{},route:"tailscale",tunnelUrl:l.url,fallback:n.fallback!==!1,tailscaleServed:!0};t.link=d;try{ue(t,Z())}catch(m){console.warn(`[link] could not persist the route: ${m.message}`)}return a(o,200,{enabled:!0,...await E.applySettings(d),tailscale:e(s.state)})}if(i==="/v1/link/route"&&r.method==="POST"){if(!E)return a(o,409,{error:{message:"link is off (link.enabled: false)",type:"disabled"}});if(r.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 b(r,t.maxBodyBytes)).toString("utf8")||"{}")||{}}catch{e={}}let n;try{n=Io({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:n.id,fallback:e.fallback!==!1};n.id!=="tailscale"&&t.link?.tailscaleServed&&(s.tailscaleServed=!(await C.unserve()).ok),n.id==="relay"?s.relayUrl=n.url:n.id==="link"&&delete s.relayUrl,(n.id==="tailscale"||n.id==="cloudflare")&&(s.tunnelUrl=n.url),t.link=s;try{ue(t,Z())}catch(l){console.warn(`[link] could not persist the route: ${l.message}`)}return a(o,200,{enabled:!0,...await E.applySettings(s)})}if(i.startsWith("/v1/link/devices/")&&r.method==="DELETE"){if(!E)return a(o,404,{error:{message:"link is off",type:"disabled"}});const e=decodeURIComponent(i.slice(17));return await E.remove(e)?(x.cancelDevice(e),a(o,200,{ok:!0})):a(o,404,{error:{message:"no such device",type:"not_found"}})}if(i==="/v1/link/files"||i.startsWith("/v1/link/files/")){const e=Me(r.headers);if(e?.kind!=="partner"||!e.scopes.includes("files"))return a(o,403,{error:{message:"link files: a partner’s own folder, for a partner granted files",type:"forbidden",code:"link_scope"}});const n=E?.partnerFolderOf(e.device);if(!n)return a(o,403,{error:{message:"link files: this partner has no folder on this computer — pair it again with agents and files",type:"forbidden",code:"link_scope"}});const s=i.slice(14).replace(/^\//,"");let l=s;try{l=decodeURIComponent(s)}catch{}const d=r.method==="GET"&&(!s||/^(data|\.claude\/skills|\.claude\/agents|\.agents\/skills)\/?$/.test(l));let m;try{m=Ua(s,{listing:d})}catch(p){return a(o,400,{error:{message:p.message,type:"invalid_request",code:"bad_path"}})}try{if(r.method==="GET"&&d)return a(o,200,{folder:"its own",files:Ha(n,m.replace(/\/$/,""))});if(r.method==="GET"){const p=Va(n,m);o.writeHead(200,{"content-type":"application/octet-stream","content-length":String(p.size)}),p.stream.pipe(o);return}return r.method==="PUT"?a(o,200,Fa(n,m,await b(r,t.maxBodyBytes))):r.method==="DELETE"?Wa(n,m)?a(o,200,{ok:!0}):a(o,404,{error:{message:`${m}: no such file`,type:"not_found"}}):a(o,405,{error:{message:"link files: GET, PUT or DELETE",type:"invalid_request"}})}catch(p){const f=p?.status||(p?.code===413?413:p?.code==="bad_partner"?400:500);return a(o,f,{error:{message:p?.message||String(p),type:f===404?"not_found":f===413?"too_large":"invalid_request"}})}}if(i==="/v1/link/approvals"||i.startsWith("/v1/link/approvals/")){if(r.headers["x-chatpanel-link-device"])return a(o,403,{error:{message:"an agent’s approval is the owner’s to give, on this computer",type:"forbidden"}});if(i==="/v1/link/approvals"&&r.method==="GET")return a(o,200,{pending:x.list()});if(i==="/v1/link/approvals/stream"&&r.method==="GET"){o.writeHead(200,{"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive"});const n=d=>o.write(`event: approvals
51
51
  data: ${JSON.stringify({pending:d})}
52
52
 
53
53
  `);n(x.list());const s=x.subscribe(n),l=setInterval(()=>o.write(`:
@@ -55,13 +55,13 @@ data: ${JSON.stringify({pending:d})}
55
55
  `),25e3);l.unref?.(),o.on("close",()=>{s(),clearInterval(l)});return}const e=/^\/v1\/link\/approvals\/([A-Za-z0-9_-]{1,40})$/.exec(i);if(e&&r.method==="POST"){let n={};try{n=JSON.parse((await b(r,t.maxBodyBytes)).toString("utf8")||"{}")||{}}catch{n={}}return Ro.some(s=>s.id===n.decision)?x.answer(e[1],n.decision)?a(o,200,{ok:!0}):a(o,404,{error:{message:"nothing is waiting under that id — answered, withdrawn or expired",type:"not_found"}}):a(o,400,{error:{message:`link approvals: { decision: ${Ro.map(s=>s.id).join(" | ")} }`,type:"invalid_request"}})}}if(i==="/v1/browser"&&r.method==="GET")return a(o,200,k.status());if(i==="/v1/browser/stream"&&r.method==="GET"){k.stream(r,o);return}if((i==="/v1/browser/call"||i==="/v1/browser/announce"||i==="/v1/browser/result")&&r.method==="POST"){let e;try{e=JSON.parse((await b(r,t.maxBodyBytes)).toString("utf8"))}catch{return a(o,400,{error:{message:"browser: body must be JSON",type:"invalid_request"}})}const n=i==="/v1/browser/call"?await k.call(e,r):i==="/v1/browser/announce"?k.announce(e):k.result(e);return a(o,n.status,n.body)}if(i==="/v1/history/stream"&&r.method==="GET"){const e=G.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
56
56
  data: ${JSON.stringify({newest:e.newest,rev:e.rev,size:e.size,version:le,prefsRevision:me.revision})}
57
57
 
58
- `),o.chatpanelCredentialed=!!h(r),$e.add(o),r.on("close",()=>$e.delete(o));return}if(i==="/v1/history/records"&&r.method==="GET"){const e=G.lossless;if(!e)return a(o,501,{error:{message:"lossless records need the SQLite warm store",type:"unavailable"}});const n=e.since({since:Number(y.searchParams.get("since"))||0,cursor:y.searchParams.get("cursor")||"",limit:Number(y.searchParams.get("limit"))||200,kind:y.searchParams.get("kind")||null,bytes:Number(y.searchParams.get("bytes"))||0,afterRev:y.searchParams.has("after_rev")?Number(y.searchParams.get("after_rev"))||0:null});return a(o,200,{ok:!0,...n,size:e.size,newest:e.newest})}if(i==="/v1/history/list"&&r.method==="GET"){const e=Math.min(500,Math.max(1,Number(y.searchParams.get("limit"))||50)),n=Math.max(0,Number(y.searchParams.get("offset"))||0),s=y.searchParams.get("type")||null;return a(o,200,{ok:!0,...G.list({limit:e,offset:n,type:s})})}if(i==="/v1/history/get"&&r.method==="GET"){const e=y.searchParams.get("maxChars")!=null?Math.max(1,Number(y.searchParams.get("maxChars"))||0):null,n=Math.max(0,Number(y.searchParams.get("offset"))||0),s=String(y.searchParams.get("id")||""),l=G.get(s,{maxChars:e,offset:n})||(Po(s)!==s?G.get(Po(s),{maxChars:e,offset:n}):null);return l?a(o,200,{ok:!0,record:l}):a(o,404,{error:{message:"no such record",type:"not_found"}})}if(i==="/v1/history/key"&&r.method==="GET")return a(o,200,{ok:!0,hasKey:xo()});if(i==="/v1/history/key"&&r.method==="POST")try{const e=JSON.parse((await b(r,t.maxBodyBytes)).toString("utf8"))||{};e.passphrase?fn(String(e.passphrase)):gn();const n=e.passphrase?await Ct(G,String(e.passphrase)):{ok:!0,ingested:0};return n.ok&&n.whole&&We(),a(o,200,{ok:!0,hasKey:!!e.passphrase,...n})}catch(e){return a(o,400,{error:{message:`key handoff failed: ${e.message}`,type:"key_error"}})}if(i==="/v1/history/ingest-backup"&&r.method==="POST")try{const e=await Ct(G,Nt());return e.ok&&e.whole&&We(),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(r.method==="GET"){const e=await mr(t);return a(o,e.ok?200:503,e)}if(r.method==="POST"){if(await wt(t),z.state()!=="off"){if(!z.isReady()){const n=z.health();return a(o,503,{error:{message:n.state==="error"?`NER model failed to load: ${n.error||"unknown error"}`:`NER model is ${n.state} — not ready yet`,type:n.state==="error"?"ner_error":"ner_loading"},state:n.state,model:n.model})}try{const n=await b(r,t.maxBodyBytes);let s="",l=!1;try{const m=JSON.parse(n.toString("utf8"));s=m?.text||"",l=m?.strict===!0}catch{}const d=await z.detect(s,{strict:l});return a(o,200,{entities:d})}catch(n){return a(o,500,{error:{message:`NER error: ${n.message}`,type:"ner_error"}})}}const e=ur(t);if(!e){const n=z.modelOnDisk(t.ner?.model||void 0);return a(o,503,{error:{message:n?"the bundled detector could not start — deterministic-only redaction":"no entity detector is installed — deterministic-only redaction (install one from Gateway settings)",type:n?"ner_error":"ner_not_installed"},state:z.state(),model:t.ner?.model||null})}try{const n=await b(r,t.maxBodyBytes),s=await Ve(e,{method:"POST",headers:{"content-type":"application/json"},body:n,signal:AbortSignal.timeout(8e3)}),l=await s.text();return o.writeHead(s.status,{"content-type":"application/json"}),o.end(l)}catch(n){return a(o,502,{error:{message:`NER unreachable: ${n.message}`,type:"ner_unreachable"}})}}}if(i==="/redact"&&r.method==="POST"){let e="";try{e=String(JSON.parse((await b(r,t.maxBodyBytes)).toString("utf8"))?.text||"")}catch{e=""}if(!e)return a(o,200,{text:"",count:0,sanitized:0,entities:[],detector:Ft(t)});try{let n=e;const s=await xe(t.pro?.entitlementToken);await wt(t);const l=await qe([ht(()=>n,d=>{n=d})],t.redaction,{isPro:s});return a(o,200,{text:n,count:l.count||0,sanitized:l.sanitized||0,tier:t.redaction?.tier==="full"?"full":"basic",entities:dr(l.vault,"types")||[],detector:Ft(t)})}catch(n){return a(o,500,{error:{message:`redaction preview failed: ${n.message}`,type:"redact_error"}})}}if(i==="/ner/models"){if(r.method==="GET"){const e=z.health().model||t.ner?.model||null,n=Math.round(It.totalmem()/1048576),s=bs(Go,{totalRamMB:n}).map(l=>({...l,installed:z.modelOnDisk(l.id)}));for(const l of[e,...z.modelsOnDisk()])!l||s.some(d=>d.id===l)||s.push({id:l,label:l,lang:"—",custom:!0,installed:z.modelOnDisk(l),note:"Custom model (from Hugging Face)."});return a(o,200,{active:e,companions:z.companions(),union:Array.isArray(t.ner?.union)?t.ner.union:[],machine:{totalRamMB:n},skipped:hn(),recommendation:To(s,{totalRamMB:n},[]),state:z.state(),progress:z.progress(),available:s})}if(r.method==="POST"){let e=null;try{e=JSON.parse((await b(r,t.maxBodyBytes)).toString("utf8"))}catch{e=null}if(e&&e.recommended===!0){const s=Math.round(It.totalmem()/1048576),l=To(Go.map(d=>({...d,installed:z.modelOnDisk(d.id)})),{totalRamMB:s},[]);e={id:l.primary,union:l.union}}const n=e&&typeof e.id=="string"?e.id.trim():null;if(e&&Array.isArray(e.union)){const s=[...new Set(e.union.map(d=>String(d||"").trim()).filter(Boolean))];for(const d of s)if(!(zo(d)||Uo(d)))return a(o,400,{error:{message:`unknown or invalid model id in union: ${d}`,type:"bad_model"}});const l=n||t.ner?.model||z.health().model;t.ner=t.ner||{allowDownload:!0,enableFullTier:!0},t.ner.union=s.filter(d=>d!==l),n&&qo(t,n);try{ue(t,Z())}catch{}return(async()=>{n&&await z.setModel(n,{onLog:m=>console.log(m)});const d=pn(t.ner,{log:m=>console.log(m)});for(const m of z.companions())d.includes(m.model)||await z.removeCompanion(m.model);for(const m of d)await z.addCompanion(m,{onLog:p=>console.log(p),allowDownload:t.ner.allowDownload!==!1});z.setUnionOrder(d)})().catch(d=>console.log(`[ner] union update failed: ${d.message}`)),a(o,202,{accepted:!0,active:l,union:t.ner.union,companions:z.companions(),state:z.state()})}if(!n||!(zo(n)||Uo(n)))return a(o,400,{error:{message:"unknown or invalid model id",type:"bad_model"}});qo(t,n);try{ue(t,Z())}catch{}return z.setModel(n,{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:n,state:z.state(),progress:z.progress()})}}if(i==="/stt/models"){if(r.method==="GET"){const e=A.health().model||t.stt?.model||Fe,n={platform:process.platform,arch:process.arch,helper:!!Mt()},s=ks.map(l=>{const d=Ho(l,n);return{...l,installed:A.modelOnDisk(l.id),...d?{unavailable:d}:{}}});return e&&!s.some(l=>l.id===e)&&s.push({id:e,label:e,lang:"—",tier:"custom",custom:!0,installed:A.modelOnDisk(e),note:"Custom model (from Hugging Face)."}),a(o,200,{active:e,state:A.state(),progress:A.progress(),available:s,dtype:t.stt?.dtype||"auto",loadedDtype:A.health().dtype,runtime:A.health().runtime,dtypes:Ts,licenses:t.stt?.licenses||{}})}if(r.method==="POST"){let e=null;try{e=JSON.parse((await b(r,t.maxBodyBytes)).toString("utf8"))}catch{e=null}const n=e&&typeof e.id=="string"?e.id.trim():null;if(!n||!(vs(n)||Ss(n)))return a(o,400,{error:{message:"unknown or invalid model id",type:"bad_model"}});const s=Ho(kt(n),{platform:process.platform,arch:process.arch,helper:!!Mt()});if(s)return a(o,400,{error:{message:s,type:"bad_model"}});const l=kt(n)?.license||null;if(l){const m=Vo(l),p=t.stt?.licenses?.[l.id]?.version===l.version;if(!p&&e.acceptLicense!==m)return a(o,409,{error:{message:`Accept the ${l.name} to use this model`,type:"license_required"},license:{...l,accept:m}});p||(t.stt||={enabled:!0,allowDownload:!0},t.stt.licenses={...t.stt.licenses||{},[l.id]:{version:l.version,acceptedAt:new Date().toISOString()}})}const d=typeof e.dtype=="string"&&xs(e.dtype)?e.dtype:void 0;t.stt?t.stt.model=n:t.stt={enabled:!0,model:n,allowDownload:!0},d&&(t.stt.dtype=d==="auto"?null:d);try{ue(t,Z())}catch{}return A.setModel(n,{onLog:m=>console.log(m),dtype:d||t.stt.dtype||"auto",warmMs:t.stt.warmMs,allowDownload:t.stt?.allowDownload!==!1,segment:t.stt?.segment,speaker:Yt(t,{installing:!0}),licenseAccepted:gr(t,n)}),a(o,202,{accepted:!0,active:n,dtype:t.stt.dtype||"auto",state:A.state(),progress:A.progress(),speaker:{id:P.activeModel(),state:P.state(),installed:P.modelOnDisk()}})}}if(i==="/diarize/model"){if(r.method==="GET"){const e=P.activeModel(),n=hs.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(),segment:ps.health(),translate:Je.health(),indictrans:us.health(),aec:Rt.health(),progress:P.progress(),available:n})}if(r.method==="POST"){let e=null;try{e=JSON.parse((await b(r,t.maxBodyBytes)).toString("utf8")||"{}")}catch{e=null}const n=e&&typeof e.id=="string"?e.id.trim():null;if(n){if(!Lo(n))return a(o,400,{error:{message:"unknown speaker model id",type:"bad_model"}});if(!await P.setModel(n,{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=n:t.stt={enabled:!0,diarize:!0,diarizeModel:n};try{ue(t,Z())}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(r.method==="GET"){const e=L.health().model||t.tts?.model||Xo(Lt()),n=Lt(),s=Fo.find(d=>d.id===e)||null,l=Fo.map(d=>({...d,installed:L.modelOnDisk(d.id),unavailable:d.requiresNative&&!n?"needs the npm gateway — the standalone binary cannot load this engine":void 0}));return e&&!l.some(d=>d.id===e)&&l.push({id:e,label:e,lang:"—",tier:"custom",custom:!0,installed:L.modelOnDisk(e),note:"Custom model (from Hugging Face)."}),a(o,200,{active:e,state:L.state(),progress:L.progress(),available:l,voice:t.tts?.voice||(Tt(e)==="pocket-tts"?vt:De),arch:L.arch(),supportsVoices:L.arch()?L.supportsVoices():s?s.arch==="style-tts2"&&!!s.voices:!0,supportsCustomVoices:L.arch()?L.supportsCustomVoices():!!s?.customVoices,sampleRate:L.sampleRate(),voices:L.isPocket()||!L.arch()&&Tt(e)==="pocket-tts"?(L.builtinVoices().length?L.builtinVoices():Ns).map(d=>({id:d,label:d[0].toUpperCase()+d.slice(1),lang:"en",installed:L.builtinVoices().includes(d)})):L.arch()&&L.arch()!=="style-tts2"?[]:_s.map(d=>({...d,installed:L.voiceOnDisk(d.id,e)})),dtype:t.tts?.dtype||"auto",loadedDtype:L.health().dtype,runtime:L.health().runtime,dtypes:Ps})}if(r.method==="POST"){let e=null;try{e=JSON.parse((await b(r,t.maxBodyBytes)).toString("utf8"))}catch{e=null}const n=e&&typeof e.id=="string"?e.id.trim():null;if(n&&!(Os(n)||Es(n)))return a(o,400,{error:{message:"unknown or invalid model id",type:"bad_model"}});const s=e&&typeof e.voice=="string"?e.voice.trim():null;if(s){const d=ce.parseCustomVoice(s);if(!(d?!!ce.getVoice(d):St(s)||Wo(s)&&Ko(s)))return a(o,400,{error:{message:"unknown or invalid voice",type:"bad_voice"}})}const l=e&&typeof e.dtype=="string"&&$s(e.dtype)?e.dtype:void 0;if(t.tts||(t.tts={enabled:!0,model:Qo,voice:De,allowDownload:!0}),n&&(t.tts.model=n),s&&(t.tts.voice=s),n&&!s){const d=As(n),m=ce.parseCustomVoice(t.tts.voice||""),p=!!(m&&ce.getVoice(m));if(d&&!p)if(Tt(n)==="pocket-tts")t.tts.voice=vt;else{const g=ce.listVoices();t.tts.voice=g.length?`custom:${g[0].id}`:""}else!d&&p&&(t.tts.voice=De);const f=Tt(n)==="pocket-tts";f&&!ce.parseCustomVoice(t.tts.voice||"")&&!St(t.tts.voice)&&(t.tts.voice=vt),!f&&St(t.tts.voice)&&(t.tts.voice=De)}l&&(t.tts.dtype=l==="auto"?null:l);try{ue(t,Z())}catch{}return n&&L.setModel(n,{onLog:d=>console.log(d),dtype:l||t.tts.dtype||"auto"}),a(o,202,{accepted:!0,active:t.tts.model,voice:t.tts.voice,dtype:t.tts.dtype||"auto",state:L.state(),progress:L.progress()})}}if(i==="/tts/voices"){if(r.method==="GET")return a(o,200,{voices:ce.listVoices(),usable:L.supportsCustomVoices(),embedder:P.activeModel(),embedderReady:P.isReady()});if(r.method==="POST"){let e=null;try{e=JSON.parse((await b(r,t.maxBodyBytes)).toString("utf8"))}catch{e=null}const n=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(!ce.getVoice(l))return a(o,404,{error:{message:"no such saved voice",type:"bad_voice"}});if(!s){if(!n)return a(o,400,{error:{message:"a name is required",type:"bad_request"}});try{return a(o,200,{...ce.renameVoice(l,n),usable:L.supportsCustomVoices()})}catch(d){return a(o,400,{error:{message:d.message,type:"rename_failed"}})}}if(s.length<16e3)return a(o,400,{error:{message:"need at least 1 second of 16 kHz mono audio",type:"sample_too_short"}})}else if(!n)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{const d=fs(P.activeModel())?.dim===ce.EMBED_DIM;if(d&&!P.isReady()){const _=P.download({onLog:X=>console.log(X)}),T=Symbol("timeout"),R=await Promise.race([_.then(()=>null).catch(X=>X),new Promise(X=>setTimeout(()=>X(T),hr))]);if(R===T||!P.isReady())return a(o,503,{error:{message:R===T?"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 m=Float32Array.from(s),p=d?await P.embed(m):null;let f=null;try{const _=await L.pocketForEncoding({allowDownload:t.tts?.allowDownload!==!1,log:T=>console.log(T)});_&&(f=await _.encodeVoice(bi(m,16e3,24e3)))}catch(_){console.log(`[tts] pocket conditioning unavailable for this voice (${_.message})`)}const g=l?ce.replaceVoice(l,{vec:p,pocket:f}):ce.saveVoice({name:n,vec:p,pocket:f}),S=l&&n&&n!==g.name?ce.renameVoice(l,n):g;return console.log(`[tts] ${l?"re-recorded":"saved"} custom voice "${S.name}" (${(g.kinds||[]).join(" + ")}, sample discarded)`),a(o,l?200:201,{...g,...S,usable:L.supportsCustomVoices()})}catch(d){return a(o,400,{error:{message:d.message,type:"save_failed"}})}}if(r.method==="DELETE"){const e=y.searchParams.get("id")||"",n=ce.deleteVoice(e);if(n&&t.tts?.voice===`custom:${e}`){const s=ce.listVoices();t.tts.voice=s.length?`custom:${s[0].id}`:De;try{ue(t,Z())}catch{}}return a(o,200,{deleted:n,voice:t.tts?.voice})}}if((i==="/tts"||i==="/v1/audio/speech")&&r.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 b(r,t.maxBodyBytes)).toString("utf8"))}catch{e=null}const n=e&&typeof(e.input??e.text)=="string"?String(e.input??e.text).trim():"";if(!n)return a(o,400,{error:{message:"text is required",type:"bad_request"}});if(n.length>Yo)return a(o,413,{error:{message:`text too long (max ${Yo} chars)`,type:"too_long"}});const s=Number.isFinite(e.speed)?Math.min(2,Math.max(.5,e.speed)):1,l=Bs(t),d=e&&typeof e.voice=="string"&&e.voice.trim()?e.voice.trim():null,m=d||(l?l.voice:t.tts?.voice||De);if(l&&!Ds(m))return a(o,400,{error:{message:"unknown or invalid voice",type:"bad_voice"}});const p=e&&typeof e.response_format=="string"?e.response_format.toLowerCase():"wav";if(p!=="wav"&&p!=="pcm")return a(o,400,{error:{message:`unsupported response_format "${p}" — this gateway synthesizes wav`,type:"bad_format"}});try{if(l){const{audio:re,contentType:Ee,redacted:V}=await Ms({dest:l,text:n,voice:m,speed:s,auth:r.headers.authorization||r.headers["xi-api-key"]||"",redaction:t.redaction,isPro:await xe(t.pro?.entitlementToken),format:p});return o.writeHead(200,{"Content-Type":Ee,"Content-Length":String(re.length),"Cache-Control":"no-store","X-Tts-Provider":l.kind,"X-Tts-Redacted":String(V)}),o.end(re)}if(!await L.ready({onLog:re=>console.log(re),allowDownload:t.tts?.allowDownload!==!1,model:t.tts?.model||Xo(Lt()),dtype:t.tts?.dtype||"auto"}))return a(o,503,{error:{message:L.health().error||"tts model not ready",type:"tts_unavailable"}});const g=Cs({requested:d,configured:m,engine:L,voices:ce,isPocketVoice:St,isKnownVoice:Wo,isValidVoiceId:Ko,defaultVoice:De,defaultPocketVoice:vt});if(!g.ok)return a(o,g.status,{error:{message:g.message,type:g.type}});const{voice:S,customId:_,speakerEmbedding:T}=g,R=await L.synth(n,{voice:S,speed:s,speakerEmbedding:T}),X=L.sampleRate(),ke=p==="pcm"?Buffer.from(new Float32Array(R).buffer):L.toWav(R,X);return o.writeHead(200,{"Content-Type":p==="pcm"?"application/octet-stream":"audio/wav","Content-Length":String(ke.length),"Cache-Control":"no-store","X-Tts-Sample-Rate":String(X),..._||L.isPocket()||L.supportsVoices()?{"X-Tts-Voice":S}:{}}),o.end(ke)}catch(f){return a(o,500,{error:{message:f.message,type:"tts_failed"}})}}if(i==="/v1/audio/transcriptions"&&r.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=gs(await b(r,Math.max(t.maxBodyBytes||0,64*1024*1024)),r.headers["content-type"])}catch(S){return a(o,S.code===413?413:415,{error:{message:S.message,type:"bad_request"}})}const n=S=>e.find(_=>_.name===S&&!_.filename)?.data.toString("utf8").trim()||"",s=e.find(S=>S.name==="file"&&S.filename)||e.find(S=>S.filename);if(!s?.data?.length)return a(o,400,{error:{message:"a `file` part is required",type:"bad_request"}});let l;try{l=await ws(s.data)}catch(S){return a(o,S.code===415?415:500,{error:{message:S.message,type:"unsupported_media"}})}const d=["json","text","verbose_json"].includes(n("response_format"))?n("response_format"):"json",m=Jt(t,"stt");let p=null;if(m.kind==="remote"||m.kind==="container")try{p=jo(m,{fetchImpl:Ve})}catch(S){return a(o,500,{error:{message:`stt provider: ${S.message}`,type:"bad_provider"}})}if(!p&&!A.isReady()&&await A.init({model:t.stt?.model||Fe,allowDownload:t.stt?.allowDownload!==!1,dtype:t.stt?.dtype||void 0,warmMs:t.stt?.warmMs,segment:t.stt?.segment,speaker:Yt(t),onLog:S=>console.log(S)}),!p&&!A.isReady())return a(o,503,{error:{message:`speech model not ready: ${A.health().error||A.state()}`,type:"stt_not_ready"}});const f=n("diarize")==="true"&&t.stt?.diarize!==!1;f&&!P.isReady()&&await P.init({allowDownload:t.stt?.allowDownload!==!1,warmMs:t.stt?.warmMs,onLog:S=>console.log(S)});const g=Date.now();try{const{id:S}=A.createSession({lang:n("language")||void 0,diarize:f,interims:!1,remote:p}),_=[],T=[];let R=null;A.subscribe(S,V=>{V.type==="final"&&V.text?_.push(V):V.type==="language"?R=V.lang:V.type==="error"&&T.push(V.message||V.code)});const X=16e3*5;for(let V=0;V<l.pcm.length;V+=X)A.pushAudio(S,l.pcm.subarray(V,Math.min(l.pcm.length,V+X))),await A.decodeNow(S);if(await A.endSession(S),!_.length&&T.length)return a(o,500,{error:{message:T[0],type:"decode_failed"}});let ke=0;const re=_.map((V,Tr)=>{const lo=typeof V.startMs=="number"?V.startMs/1e3:ke,xr=(V.durationMs||0)/1e3;return ke=lo+xr,{id:Tr,start:Math.round(lo*100)/100,end:Math.round(ke*100)/100,text:V.text,...V.speaker?{speaker:V.speaker}:{},...V.turns?{turns:V.turns.map(pt=>({start:Math.round(pt.startMs/10)/100,end:Math.round((pt.startMs+pt.durationMs)/10)/100,speaker:pt.speaker}))}:{}}}),Ee=re.map(V=>V.text).join(" ").replace(/\s+/g," ").trim();return d==="text"?(o.writeHead(200,{"content-type":"text/plain; charset=utf-8"}),o.end(Ee)):d==="verbose_json"?a(o,200,{task:"transcribe",language:R||n("language")||null,duration:Math.round(l.seconds*100)/100,text:Ee,segments:re,provider:m.kind,took_ms:Date.now()-g}):a(o,200,{text:Ee})}catch(S){return a(o,S.code==="too_many_sessions"?429:500,{error:{message:S.message,type:S.code||"stt_error"}})}}if(i==="/v1/voice/embed"&&r.method==="POST"){if(t.stt?.enabled===!1)return a(o,403,{error:{message:"STT disabled in gateway config",type:"stt_disabled"}});if(t.stt?.diarize===!1)return a(o,403,{error:{message:"the speaker model is switched off in the gateway config (stt.diarize)",type:"speaker_disabled"}});const e=String(r.headers["content-type"]||"").split(";")[0].trim().toLowerCase();if(e&&e!=="audio/pcm"&&e!=="application/octet-stream")return a(o,415,{error:{message:"send raw 16 kHz mono Float32 little-endian samples as audio/pcm or application/octet-stream",type:"unsupported_media"}});if(Number(r.headers["content-length"])>yr)return a(o,413,{error:{message:`at most ${Qt} s of audio`,type:"too_large"}});let n;try{n=await b(r,yr)}catch(d){return a(o,d.code===413?413:400,{error:{message:d.code===413?`at most ${Qt} s of audio`:d.message,type:d.code===413?"too_large":"bad_request"}})}const s=A.toFloat32(n);if(s.length<wi)return a(o,400,{error:{message:"too little audio to fingerprint (at least a quarter of a second)",type:"sample_too_short"}});if(!P.isReady()){const d=P.init({allowDownload:t.stt?.allowDownload!==!1,warmMs:t.stt?.warmMs,onLog:f=>console.log(f)}),m=Symbol("timeout"),p=await Promise.race([d.then(()=>null,()=>null),new Promise(f=>{setTimeout(()=>f(m),hr).unref?.()})]);if(!P.isReady())return a(o,503,{error:{message:p===m?"the speaker model is still downloading — try again shortly":`the speaker model is not available: ${P.health().error||P.state()}`,type:"speaker_not_ready"},...P.progress()?{progress:P.progress()}:{}})}const l=await P.embed(s);return l?a(o,200,{vec:P.plainVector(l),seconds:Math.round(s.length/16e3*100)/100,model:P.activeModel()}):a(o,500,{error:{message:"the speaker model gave no fingerprint for this audio",type:"embed_failed"}})}if(i.startsWith("/v1/stt/sessions")&&(i=i.slice(3)),i==="/stt/sessions"&&r.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 b(r,t.maxBodyBytes)).toString("utf8")||"{}")}catch{e=null}const n=Jt(t,"stt");let s=null;if(n.kind==="remote"||n.kind==="container")try{s=jo(n,{fetchImpl:Ve})}catch(_){return a(o,500,{error:{message:`stt provider: ${_.message}`,type:"bad_provider"}})}!s&&!A.isReady()&&A.init({model:t.stt?.model||Fe,allowDownload:t.stt?.allowDownload!==!1,dtype:t.stt?.dtype||void 0,warmMs:t.stt?.warmMs,segment:t.stt?.segment,speaker:Yt(t),licenseAccepted:gr(t,t.stt?.model||Fe),onLog:_=>console.log(_)});const l=e?.diarize===!0&&t.stt?.diarize!==!1;l&&!P.isReady()&&P.init({allowDownload:t.stt?.allowDownload!==!1,warmMs:t.stt?.warmMs,onLog:_=>console.log(_)});const d=typeof e?.translateTo=="string"&&t.stt?.translate!==!1?e.translateTo:null,m=d?{allowDownload:t.stt?.allowDownload!==!1,warmMs:t.stt?.warmMs,onLog:_=>console.log(_)}:null,p=e?.echo&&typeof e.echo=="object"&&typeof e.echo.group=="string"&&["mic","reference"].includes(e.echo.role)&&t.stt?.aec!==!1&&!s?{group:e.echo.group,role:e.echo.role}:null;p&&Rt.state()==="off"&&Rt.init({allowDownload:t.stt?.allowDownload!==!1,warmMs:t.stt?.warmMs,onLog:_=>console.log(_)});const f=Array.isArray(e?.langs)?e.langs.slice(0,12):null,g=t.stt?.model||Fe,S=f&&!s?ms(f,{engine:kt(g)?.engine||"",englishOnly:/\.en$/.test(g)}).missing:[];try{const _=e?.poll===!0,T=e?.format==="pcm16"?"pcm16":"f32",R=l&&e?.vectors===!0,{id:X}=A.createSession({lang:e?.lang,langs:f,translateTo:d,translateLoad:m,echo:p,redact:e?.redact===!0,diarize:l,vectors:R,speakerLabel:e?.speakerLabel,endSilenceMs:e?.endSilenceMs,interims:e?.interims!==!1,remote:s,poll:_,format:T});return a(o,201,{id:X,state:A.state(),format:T,..._?{poll:!0}:{},...R?{vectors:!0}:{},...S.length?{languagesMissing:S}:{},...d?{translate:Je.state()}:{}})}catch(_){return a(o,_.code==="too_many_sessions"?429:500,{error:{message:_.message,type:_.code||"stt_error"}})}}{const e=i.match(/^\/stt\/sessions\/([0-9a-f-]{36})(\/audio|\/events)?$/);if(e){const n=e[1],s=async(d,m,p)=>{if(m.type!=="final"&&m.type!=="translation"||!d.redact||!m.text)return m;try{let f=m.text;return await qe([ht(()=>f,g=>{f=g})],t.redaction,{isPro:p}),{...m,text:f}}catch{return m}},l=async d=>{const m=A.drainEvents(n);if(!m)return null;const p=[];if(d&&!d.closed){const g=d.remote?"ready":A.state();g==="downloading"||g==="loading"?p.push({type:"progress",state:g,...A.progress()||{}}):g==="error"?p.push({type:"error",code:"model_failed",message:A.health().error||"model failed to load",fatal:!0}):d.diarize&&["downloading","loading"].includes(P.state())?p.push({type:"diarize-progress",state:P.state(),...P.progress()||{}}):d.translateTo&&["downloading","loading"].includes(Je.state())?p.push({type:"translate-progress",state:Je.state(),...Je.progress()||{}}):fr.get(d)!==g&&(fr.set(d,g),p.push({type:"state",state:g}))}const f=d?.redact?await xe(t.pro?.entitlementToken):!0;for(const g of m)d?p.push(await s(d,g,f)):g.type!=="final"&&g.type!=="interim"&&g.type!=="translation"&&p.push(g);return p};if(e[2]==="/audio"&&r.method==="POST"){const d=A.getSession(n)||A.endedSession(n);try{const m=await b(r,t.maxBodyBytes);A.pushAudio(n,A.toFloat32(m,d?.format));const p=await l(d);return a(o,200,{ok:!0,state:A.state(),...p?{events:p}:{}})}catch(m){const p=m.code==="no_session"?await l(d).catch(()=>null):null;return a(o,m.code==="no_session"?404:400,{error:{message:m.message,type:m.code||"stt_error"},...p?{events:p}:{}})}}if(e[2]==="/events"&&r.method==="GET"){const d=A.getSession(n);if(!d)return a(o,404,{error:{message:"no such session",type:"no_session"}});o.writeHead(200,{"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive"});const m=T=>o.write(`data: ${JSON.stringify(T)}
58
+ `),o.chatpanelCredentialed=!!h(r),$e.add(o),r.on("close",()=>$e.delete(o));return}if(i==="/v1/history/records"&&r.method==="GET"){const e=G.lossless;if(!e)return a(o,501,{error:{message:"lossless records need the SQLite warm store",type:"unavailable"}});const n=e.since({since:Number(y.searchParams.get("since"))||0,cursor:y.searchParams.get("cursor")||"",limit:Number(y.searchParams.get("limit"))||200,kind:y.searchParams.get("kind")||null,bytes:Number(y.searchParams.get("bytes"))||0,afterRev:y.searchParams.has("after_rev")?Number(y.searchParams.get("after_rev"))||0:null});return a(o,200,{ok:!0,...n,size:e.size,newest:e.newest})}if(i==="/v1/history/list"&&r.method==="GET"){const e=Math.min(500,Math.max(1,Number(y.searchParams.get("limit"))||50)),n=Math.max(0,Number(y.searchParams.get("offset"))||0),s=y.searchParams.get("type")||null;return a(o,200,{ok:!0,...G.list({limit:e,offset:n,type:s})})}if(i==="/v1/history/get"&&r.method==="GET"){const e=y.searchParams.get("maxChars")!=null?Math.max(1,Number(y.searchParams.get("maxChars"))||0):null,n=Math.max(0,Number(y.searchParams.get("offset"))||0),s=String(y.searchParams.get("id")||""),l=G.get(s,{maxChars:e,offset:n})||(Po(s)!==s?G.get(Po(s),{maxChars:e,offset:n}):null);return l?a(o,200,{ok:!0,record:l}):a(o,404,{error:{message:"no such record",type:"not_found"}})}if(i==="/v1/history/key"&&r.method==="GET")return a(o,200,{ok:!0,hasKey:xo()});if(i==="/v1/history/key"&&r.method==="POST")try{const e=JSON.parse((await b(r,t.maxBodyBytes)).toString("utf8"))||{};e.passphrase?fn(String(e.passphrase)):gn();const n=e.passphrase?await Ct(G,String(e.passphrase)):{ok:!0,ingested:0};return n.ok&&n.whole&&We(),a(o,200,{ok:!0,hasKey:!!e.passphrase,...n})}catch(e){return a(o,400,{error:{message:`key handoff failed: ${e.message}`,type:"key_error"}})}if(i==="/v1/history/ingest-backup"&&r.method==="POST")try{const e=await Ct(G,Nt());return e.ok&&e.whole&&We(),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(r.method==="GET"){const e=await mr(t);return a(o,e.ok?200:503,e)}if(r.method==="POST"){if(await wt(t),z.state()!=="off"){if(!z.isReady()){const n=z.health();return a(o,503,{error:{message:n.state==="error"?`NER model failed to load: ${n.error||"unknown error"}`:`NER model is ${n.state} — not ready yet`,type:n.state==="error"?"ner_error":"ner_loading"},state:n.state,model:n.model})}try{const n=await b(r,t.maxBodyBytes);let s="",l=!1;try{const m=JSON.parse(n.toString("utf8"));s=m?.text||"",l=m?.strict===!0}catch{}const d=await z.detect(s,{strict:l});return a(o,200,{entities:d})}catch(n){return a(o,500,{error:{message:`NER error: ${n.message}`,type:"ner_error"}})}}const e=ur(t);if(!e){const n=z.modelOnDisk(t.ner?.model||void 0);return a(o,503,{error:{message:n?"the bundled detector could not start — deterministic-only redaction":"no entity detector is installed — deterministic-only redaction (install one from Gateway settings)",type:n?"ner_error":"ner_not_installed"},state:z.state(),model:t.ner?.model||null})}try{const n=await b(r,t.maxBodyBytes),s=await Ve(e,{method:"POST",headers:{"content-type":"application/json"},body:n,signal:AbortSignal.timeout(8e3)}),l=await s.text();return o.writeHead(s.status,{"content-type":"application/json"}),o.end(l)}catch(n){return a(o,502,{error:{message:`NER unreachable: ${n.message}`,type:"ner_unreachable"}})}}}if(i==="/redact"&&r.method==="POST"){let e="";try{e=String(JSON.parse((await b(r,t.maxBodyBytes)).toString("utf8"))?.text||"")}catch{e=""}if(!e)return a(o,200,{text:"",count:0,sanitized:0,entities:[],detector:Ft(t)});try{let n=e;const s=await xe(t.pro?.entitlementToken);await wt(t);const l=await qe([ht(()=>n,d=>{n=d})],t.redaction,{isPro:s});return a(o,200,{text:n,count:l.count||0,sanitized:l.sanitized||0,tier:t.redaction?.tier==="full"?"full":"basic",entities:dr(l.vault,"types")||[],detector:Ft(t)})}catch(n){return a(o,500,{error:{message:`redaction preview failed: ${n.message}`,type:"redact_error"}})}}if(i==="/ner/models"){if(r.method==="GET"){const e=z.health().model||t.ner?.model||null,n=Math.round(It.totalmem()/1048576),s=ks(Go,{totalRamMB:n}).map(l=>({...l,installed:z.modelOnDisk(l.id)}));for(const l of[e,...z.modelsOnDisk()])!l||s.some(d=>d.id===l)||s.push({id:l,label:l,lang:"—",custom:!0,installed:z.modelOnDisk(l),note:"Custom model (from Hugging Face)."});return a(o,200,{active:e,companions:z.companions(),union:Array.isArray(t.ner?.union)?t.ner.union:[],machine:{totalRamMB:n},skipped:hn(),recommendation:To(s,{totalRamMB:n},[]),state:z.state(),progress:z.progress(),available:s})}if(r.method==="POST"){let e=null;try{e=JSON.parse((await b(r,t.maxBodyBytes)).toString("utf8"))}catch{e=null}if(e&&e.recommended===!0){const s=Math.round(It.totalmem()/1048576),l=To(Go.map(d=>({...d,installed:z.modelOnDisk(d.id)})),{totalRamMB:s},[]);e={id:l.primary,union:l.union}}const n=e&&typeof e.id=="string"?e.id.trim():null;if(e&&Array.isArray(e.union)){const s=[...new Set(e.union.map(d=>String(d||"").trim()).filter(Boolean))];for(const d of s)if(!(zo(d)||Uo(d)))return a(o,400,{error:{message:`unknown or invalid model id in union: ${d}`,type:"bad_model"}});const l=n||t.ner?.model||z.health().model;t.ner=t.ner||{allowDownload:!0,enableFullTier:!0},t.ner.union=s.filter(d=>d!==l),n&&qo(t,n);try{ue(t,Z())}catch{}return(async()=>{n&&await z.setModel(n,{onLog:m=>console.log(m)});const d=pn(t.ner,{log:m=>console.log(m)});for(const m of z.companions())d.includes(m.model)||await z.removeCompanion(m.model);for(const m of d)await z.addCompanion(m,{onLog:p=>console.log(p),allowDownload:t.ner.allowDownload!==!1});z.setUnionOrder(d)})().catch(d=>console.log(`[ner] union update failed: ${d.message}`)),a(o,202,{accepted:!0,active:l,union:t.ner.union,companions:z.companions(),state:z.state()})}if(!n||!(zo(n)||Uo(n)))return a(o,400,{error:{message:"unknown or invalid model id",type:"bad_model"}});qo(t,n);try{ue(t,Z())}catch{}return z.setModel(n,{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:n,state:z.state(),progress:z.progress()})}}if(i==="/stt/models"){if(r.method==="GET"){const e=A.health().model||t.stt?.model||Fe,n={platform:process.platform,arch:process.arch,helper:!!Mt()},s=vs.map(l=>{const d=Ho(l,n);return{...l,installed:A.modelOnDisk(l.id),...d?{unavailable:d}:{}}});return e&&!s.some(l=>l.id===e)&&s.push({id:e,label:e,lang:"—",tier:"custom",custom:!0,installed:A.modelOnDisk(e),note:"Custom model (from Hugging Face)."}),a(o,200,{active:e,state:A.state(),progress:A.progress(),available:s,dtype:t.stt?.dtype||"auto",loadedDtype:A.health().dtype,runtime:A.health().runtime,dtypes:xs,licenses:t.stt?.licenses||{}})}if(r.method==="POST"){let e=null;try{e=JSON.parse((await b(r,t.maxBodyBytes)).toString("utf8"))}catch{e=null}const n=e&&typeof e.id=="string"?e.id.trim():null;if(!n||!(Ss(n)||Ts(n)))return a(o,400,{error:{message:"unknown or invalid model id",type:"bad_model"}});const s=Ho(kt(n),{platform:process.platform,arch:process.arch,helper:!!Mt()});if(s)return a(o,400,{error:{message:s,type:"bad_model"}});const l=kt(n)?.license||null;if(l){const m=Vo(l),p=t.stt?.licenses?.[l.id]?.version===l.version;if(!p&&e.acceptLicense!==m)return a(o,409,{error:{message:`Accept the ${l.name} to use this model`,type:"license_required"},license:{...l,accept:m}});p||(t.stt||={enabled:!0,allowDownload:!0},t.stt.licenses={...t.stt.licenses||{},[l.id]:{version:l.version,acceptedAt:new Date().toISOString()}})}const d=typeof e.dtype=="string"&&_s(e.dtype)?e.dtype:void 0;t.stt?t.stt.model=n:t.stt={enabled:!0,model:n,allowDownload:!0},d&&(t.stt.dtype=d==="auto"?null:d);try{ue(t,Z())}catch{}return A.setModel(n,{onLog:m=>console.log(m),dtype:d||t.stt.dtype||"auto",warmMs:t.stt.warmMs,allowDownload:t.stt?.allowDownload!==!1,segment:t.stt?.segment,speaker:Yt(t,{installing:!0}),licenseAccepted:gr(t,n)}),a(o,202,{accepted:!0,active:n,dtype:t.stt.dtype||"auto",state:A.state(),progress:A.progress(),speaker:{id:P.activeModel(),state:P.state(),installed:P.modelOnDisk()}})}}if(i==="/diarize/model"){if(r.method==="GET"){const e=P.activeModel(),n=ys.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(),segment:hs.health(),translate:Je.health(),indictrans:ms.health(),aec:Rt.health(),progress:P.progress(),available:n})}if(r.method==="POST"){let e=null;try{e=JSON.parse((await b(r,t.maxBodyBytes)).toString("utf8")||"{}")}catch{e=null}const n=e&&typeof e.id=="string"?e.id.trim():null;if(n){if(!Lo(n))return a(o,400,{error:{message:"unknown speaker model id",type:"bad_model"}});if(!await P.setModel(n,{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=n:t.stt={enabled:!0,diarize:!0,diarizeModel:n};try{ue(t,Z())}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(r.method==="GET"){const e=L.health().model||t.tts?.model||Xo(Lt()),n=Lt(),s=Fo.find(d=>d.id===e)||null,l=Fo.map(d=>({...d,installed:L.modelOnDisk(d.id),unavailable:d.requiresNative&&!n?"needs the npm gateway — the standalone binary cannot load this engine":void 0}));return e&&!l.some(d=>d.id===e)&&l.push({id:e,label:e,lang:"—",tier:"custom",custom:!0,installed:L.modelOnDisk(e),note:"Custom model (from Hugging Face)."}),a(o,200,{active:e,state:L.state(),progress:L.progress(),available:l,voice:t.tts?.voice||(Tt(e)==="pocket-tts"?vt:De),arch:L.arch(),supportsVoices:L.arch()?L.supportsVoices():s?s.arch==="style-tts2"&&!!s.voices:!0,supportsCustomVoices:L.arch()?L.supportsCustomVoices():!!s?.customVoices,sampleRate:L.sampleRate(),voices:L.isPocket()||!L.arch()&&Tt(e)==="pocket-tts"?(L.builtinVoices().length?L.builtinVoices():Bs).map(d=>({id:d,label:d[0].toUpperCase()+d.slice(1),lang:"en",installed:L.builtinVoices().includes(d)})):L.arch()&&L.arch()!=="style-tts2"?[]:Os.map(d=>({...d,installed:L.voiceOnDisk(d.id,e)})),dtype:t.tts?.dtype||"auto",loadedDtype:L.health().dtype,runtime:L.health().runtime,dtypes:$s})}if(r.method==="POST"){let e=null;try{e=JSON.parse((await b(r,t.maxBodyBytes)).toString("utf8"))}catch{e=null}const n=e&&typeof e.id=="string"?e.id.trim():null;if(n&&!(Es(n)||Ps(n)))return a(o,400,{error:{message:"unknown or invalid model id",type:"bad_model"}});const s=e&&typeof e.voice=="string"?e.voice.trim():null;if(s){const d=ce.parseCustomVoice(s);if(!(d?!!ce.getVoice(d):St(s)||Wo(s)&&Ko(s)))return a(o,400,{error:{message:"unknown or invalid voice",type:"bad_voice"}})}const l=e&&typeof e.dtype=="string"&&As(e.dtype)?e.dtype:void 0;if(t.tts||(t.tts={enabled:!0,model:Qo,voice:De,allowDownload:!0}),n&&(t.tts.model=n),s&&(t.tts.voice=s),n&&!s){const d=Ns(n),m=ce.parseCustomVoice(t.tts.voice||""),p=!!(m&&ce.getVoice(m));if(d&&!p)if(Tt(n)==="pocket-tts")t.tts.voice=vt;else{const g=ce.listVoices();t.tts.voice=g.length?`custom:${g[0].id}`:""}else!d&&p&&(t.tts.voice=De);const f=Tt(n)==="pocket-tts";f&&!ce.parseCustomVoice(t.tts.voice||"")&&!St(t.tts.voice)&&(t.tts.voice=vt),!f&&St(t.tts.voice)&&(t.tts.voice=De)}l&&(t.tts.dtype=l==="auto"?null:l);try{ue(t,Z())}catch{}return n&&L.setModel(n,{onLog:d=>console.log(d),dtype:l||t.tts.dtype||"auto"}),a(o,202,{accepted:!0,active:t.tts.model,voice:t.tts.voice,dtype:t.tts.dtype||"auto",state:L.state(),progress:L.progress()})}}if(i==="/tts/voices"){if(r.method==="GET")return a(o,200,{voices:ce.listVoices(),usable:L.supportsCustomVoices(),embedder:P.activeModel(),embedderReady:P.isReady()});if(r.method==="POST"){let e=null;try{e=JSON.parse((await b(r,t.maxBodyBytes)).toString("utf8"))}catch{e=null}const n=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(!ce.getVoice(l))return a(o,404,{error:{message:"no such saved voice",type:"bad_voice"}});if(!s){if(!n)return a(o,400,{error:{message:"a name is required",type:"bad_request"}});try{return a(o,200,{...ce.renameVoice(l,n),usable:L.supportsCustomVoices()})}catch(d){return a(o,400,{error:{message:d.message,type:"rename_failed"}})}}if(s.length<16e3)return a(o,400,{error:{message:"need at least 1 second of 16 kHz mono audio",type:"sample_too_short"}})}else if(!n)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{const d=gs(P.activeModel())?.dim===ce.EMBED_DIM;if(d&&!P.isReady()){const _=P.download({onLog:X=>console.log(X)}),T=Symbol("timeout"),R=await Promise.race([_.then(()=>null).catch(X=>X),new Promise(X=>setTimeout(()=>X(T),hr))]);if(R===T||!P.isReady())return a(o,503,{error:{message:R===T?"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 m=Float32Array.from(s),p=d?await P.embed(m):null;let f=null;try{const _=await L.pocketForEncoding({allowDownload:t.tts?.allowDownload!==!1,log:T=>console.log(T)});_&&(f=await _.encodeVoice(ki(m,16e3,24e3)))}catch(_){console.log(`[tts] pocket conditioning unavailable for this voice (${_.message})`)}const g=l?ce.replaceVoice(l,{vec:p,pocket:f}):ce.saveVoice({name:n,vec:p,pocket:f}),S=l&&n&&n!==g.name?ce.renameVoice(l,n):g;return console.log(`[tts] ${l?"re-recorded":"saved"} custom voice "${S.name}" (${(g.kinds||[]).join(" + ")}, sample discarded)`),a(o,l?200:201,{...g,...S,usable:L.supportsCustomVoices()})}catch(d){return a(o,400,{error:{message:d.message,type:"save_failed"}})}}if(r.method==="DELETE"){const e=y.searchParams.get("id")||"",n=ce.deleteVoice(e);if(n&&t.tts?.voice===`custom:${e}`){const s=ce.listVoices();t.tts.voice=s.length?`custom:${s[0].id}`:De;try{ue(t,Z())}catch{}}return a(o,200,{deleted:n,voice:t.tts?.voice})}}if((i==="/tts"||i==="/v1/audio/speech")&&r.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 b(r,t.maxBodyBytes)).toString("utf8"))}catch{e=null}const n=e&&typeof(e.input??e.text)=="string"?String(e.input??e.text).trim():"";if(!n)return a(o,400,{error:{message:"text is required",type:"bad_request"}});if(n.length>Yo)return a(o,413,{error:{message:`text too long (max ${Yo} chars)`,type:"too_long"}});const s=Number.isFinite(e.speed)?Math.min(2,Math.max(.5,e.speed)):1,l=Ms(t),d=e&&typeof e.voice=="string"&&e.voice.trim()?e.voice.trim():null,m=d||(l?l.voice:t.tts?.voice||De);if(l&&!Cs(m))return a(o,400,{error:{message:"unknown or invalid voice",type:"bad_voice"}});const p=e&&typeof e.response_format=="string"?e.response_format.toLowerCase():"wav";if(p!=="wav"&&p!=="pcm")return a(o,400,{error:{message:`unsupported response_format "${p}" — this gateway synthesizes wav`,type:"bad_format"}});try{if(l){const{audio:re,contentType:Ee,redacted:V}=await Ds({dest:l,text:n,voice:m,speed:s,auth:r.headers.authorization||r.headers["xi-api-key"]||"",redaction:t.redaction,isPro:await xe(t.pro?.entitlementToken),format:p});return o.writeHead(200,{"Content-Type":Ee,"Content-Length":String(re.length),"Cache-Control":"no-store","X-Tts-Provider":l.kind,"X-Tts-Redacted":String(V)}),o.end(re)}if(!await L.ready({onLog:re=>console.log(re),allowDownload:t.tts?.allowDownload!==!1,model:t.tts?.model||Xo(Lt()),dtype:t.tts?.dtype||"auto"}))return a(o,503,{error:{message:L.health().error||"tts model not ready",type:"tts_unavailable"}});const g=Is({requested:d,configured:m,engine:L,voices:ce,isPocketVoice:St,isKnownVoice:Wo,isValidVoiceId:Ko,defaultVoice:De,defaultPocketVoice:vt});if(!g.ok)return a(o,g.status,{error:{message:g.message,type:g.type}});const{voice:S,customId:_,speakerEmbedding:T}=g,R=await L.synth(n,{voice:S,speed:s,speakerEmbedding:T}),X=L.sampleRate(),ke=p==="pcm"?Buffer.from(new Float32Array(R).buffer):L.toWav(R,X);return o.writeHead(200,{"Content-Type":p==="pcm"?"application/octet-stream":"audio/wav","Content-Length":String(ke.length),"Cache-Control":"no-store","X-Tts-Sample-Rate":String(X),..._||L.isPocket()||L.supportsVoices()?{"X-Tts-Voice":S}:{}}),o.end(ke)}catch(f){return a(o,500,{error:{message:f.message,type:"tts_failed"}})}}if(i==="/v1/audio/transcriptions"&&r.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=ws(await b(r,Math.max(t.maxBodyBytes||0,64*1024*1024)),r.headers["content-type"])}catch(S){return a(o,S.code===413?413:415,{error:{message:S.message,type:"bad_request"}})}const n=S=>e.find(_=>_.name===S&&!_.filename)?.data.toString("utf8").trim()||"",s=e.find(S=>S.name==="file"&&S.filename)||e.find(S=>S.filename);if(!s?.data?.length)return a(o,400,{error:{message:"a `file` part is required",type:"bad_request"}});let l;try{l=await bs(s.data)}catch(S){return a(o,S.code===415?415:500,{error:{message:S.message,type:"unsupported_media"}})}const d=["json","text","verbose_json"].includes(n("response_format"))?n("response_format"):"json",m=Jt(t,"stt");let p=null;if(m.kind==="remote"||m.kind==="container")try{p=jo(m,{fetchImpl:Ve})}catch(S){return a(o,500,{error:{message:`stt provider: ${S.message}`,type:"bad_provider"}})}if(!p&&!A.isReady()&&await A.init({model:t.stt?.model||Fe,allowDownload:t.stt?.allowDownload!==!1,dtype:t.stt?.dtype||void 0,warmMs:t.stt?.warmMs,segment:t.stt?.segment,speaker:Yt(t),onLog:S=>console.log(S)}),!p&&!A.isReady())return a(o,503,{error:{message:`speech model not ready: ${A.health().error||A.state()}`,type:"stt_not_ready"}});const f=n("diarize")==="true"&&t.stt?.diarize!==!1;f&&!P.isReady()&&await P.init({allowDownload:t.stt?.allowDownload!==!1,warmMs:t.stt?.warmMs,onLog:S=>console.log(S)});const g=Date.now();try{const{id:S}=A.createSession({lang:n("language")||void 0,diarize:f,interims:!1,remote:p}),_=[],T=[];let R=null;A.subscribe(S,V=>{V.type==="final"&&V.text?_.push(V):V.type==="language"?R=V.lang:V.type==="error"&&T.push(V.message||V.code)});const X=16e3*5;for(let V=0;V<l.pcm.length;V+=X)A.pushAudio(S,l.pcm.subarray(V,Math.min(l.pcm.length,V+X))),await A.decodeNow(S);if(await A.endSession(S),!_.length&&T.length)return a(o,500,{error:{message:T[0],type:"decode_failed"}});let ke=0;const re=_.map((V,Tr)=>{const lo=typeof V.startMs=="number"?V.startMs/1e3:ke,xr=(V.durationMs||0)/1e3;return ke=lo+xr,{id:Tr,start:Math.round(lo*100)/100,end:Math.round(ke*100)/100,text:V.text,...V.speaker?{speaker:V.speaker}:{},...V.turns?{turns:V.turns.map(pt=>({start:Math.round(pt.startMs/10)/100,end:Math.round((pt.startMs+pt.durationMs)/10)/100,speaker:pt.speaker}))}:{}}}),Ee=re.map(V=>V.text).join(" ").replace(/\s+/g," ").trim();return d==="text"?(o.writeHead(200,{"content-type":"text/plain; charset=utf-8"}),o.end(Ee)):d==="verbose_json"?a(o,200,{task:"transcribe",language:R||n("language")||null,duration:Math.round(l.seconds*100)/100,text:Ee,segments:re,provider:m.kind,took_ms:Date.now()-g}):a(o,200,{text:Ee})}catch(S){return a(o,S.code==="too_many_sessions"?429:500,{error:{message:S.message,type:S.code||"stt_error"}})}}if(i==="/v1/voice/embed"&&r.method==="POST"){if(t.stt?.enabled===!1)return a(o,403,{error:{message:"STT disabled in gateway config",type:"stt_disabled"}});if(t.stt?.diarize===!1)return a(o,403,{error:{message:"the speaker model is switched off in the gateway config (stt.diarize)",type:"speaker_disabled"}});const e=String(r.headers["content-type"]||"").split(";")[0].trim().toLowerCase();if(e&&e!=="audio/pcm"&&e!=="application/octet-stream")return a(o,415,{error:{message:"send raw 16 kHz mono Float32 little-endian samples as audio/pcm or application/octet-stream",type:"unsupported_media"}});if(Number(r.headers["content-length"])>yr)return a(o,413,{error:{message:`at most ${Qt} s of audio`,type:"too_large"}});let n;try{n=await b(r,yr)}catch(d){return a(o,d.code===413?413:400,{error:{message:d.code===413?`at most ${Qt} s of audio`:d.message,type:d.code===413?"too_large":"bad_request"}})}const s=A.toFloat32(n);if(s.length<bi)return a(o,400,{error:{message:"too little audio to fingerprint (at least a quarter of a second)",type:"sample_too_short"}});if(!P.isReady()){const d=P.init({allowDownload:t.stt?.allowDownload!==!1,warmMs:t.stt?.warmMs,onLog:f=>console.log(f)}),m=Symbol("timeout"),p=await Promise.race([d.then(()=>null,()=>null),new Promise(f=>{setTimeout(()=>f(m),hr).unref?.()})]);if(!P.isReady())return a(o,503,{error:{message:p===m?"the speaker model is still downloading — try again shortly":`the speaker model is not available: ${P.health().error||P.state()}`,type:"speaker_not_ready"},...P.progress()?{progress:P.progress()}:{}})}const l=await P.embed(s);return l?a(o,200,{vec:P.plainVector(l),seconds:Math.round(s.length/16e3*100)/100,model:P.activeModel()}):a(o,500,{error:{message:"the speaker model gave no fingerprint for this audio",type:"embed_failed"}})}if(i.startsWith("/v1/stt/sessions")&&(i=i.slice(3)),i==="/stt/sessions"&&r.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 b(r,t.maxBodyBytes)).toString("utf8")||"{}")}catch{e=null}const n=Jt(t,"stt");let s=null;if(n.kind==="remote"||n.kind==="container")try{s=jo(n,{fetchImpl:Ve})}catch(_){return a(o,500,{error:{message:`stt provider: ${_.message}`,type:"bad_provider"}})}!s&&!A.isReady()&&A.init({model:t.stt?.model||Fe,allowDownload:t.stt?.allowDownload!==!1,dtype:t.stt?.dtype||void 0,warmMs:t.stt?.warmMs,segment:t.stt?.segment,speaker:Yt(t),licenseAccepted:gr(t,t.stt?.model||Fe),onLog:_=>console.log(_)});const l=e?.diarize===!0&&t.stt?.diarize!==!1;l&&!P.isReady()&&P.init({allowDownload:t.stt?.allowDownload!==!1,warmMs:t.stt?.warmMs,onLog:_=>console.log(_)});const d=typeof e?.translateTo=="string"&&t.stt?.translate!==!1?e.translateTo:null,m=d?{allowDownload:t.stt?.allowDownload!==!1,warmMs:t.stt?.warmMs,onLog:_=>console.log(_)}:null,p=e?.echo&&typeof e.echo=="object"&&typeof e.echo.group=="string"&&["mic","reference"].includes(e.echo.role)&&t.stt?.aec!==!1&&!s?{group:e.echo.group,role:e.echo.role}:null;p&&Rt.state()==="off"&&Rt.init({allowDownload:t.stt?.allowDownload!==!1,warmMs:t.stt?.warmMs,onLog:_=>console.log(_)});const f=Array.isArray(e?.langs)?e.langs.slice(0,12):null,g=t.stt?.model||Fe,S=f&&!s?ps(f,{engine:kt(g)?.engine||"",englishOnly:/\.en$/.test(g)}).missing:[];try{const _=e?.poll===!0,T=e?.format==="pcm16"?"pcm16":"f32",R=l&&e?.vectors===!0,{id:X}=A.createSession({lang:e?.lang,langs:f,translateTo:d,translateLoad:m,echo:p,redact:e?.redact===!0,diarize:l,vectors:R,speakerLabel:e?.speakerLabel,endSilenceMs:e?.endSilenceMs,interims:e?.interims!==!1,remote:s,poll:_,format:T});return a(o,201,{id:X,state:A.state(),format:T,..._?{poll:!0}:{},...R?{vectors:!0}:{},...S.length?{languagesMissing:S}:{},...d?{translate:Je.state()}:{}})}catch(_){return a(o,_.code==="too_many_sessions"?429:500,{error:{message:_.message,type:_.code||"stt_error"}})}}{const e=i.match(/^\/stt\/sessions\/([0-9a-f-]{36})(\/audio|\/events)?$/);if(e){const n=e[1],s=async(d,m,p)=>{if(m.type!=="final"&&m.type!=="translation"||!d.redact||!m.text)return m;try{let f=m.text;return await qe([ht(()=>f,g=>{f=g})],t.redaction,{isPro:p}),{...m,text:f}}catch{return m}},l=async d=>{const m=A.drainEvents(n);if(!m)return null;const p=[];if(d&&!d.closed){const g=d.remote?"ready":A.state();g==="downloading"||g==="loading"?p.push({type:"progress",state:g,...A.progress()||{}}):g==="error"?p.push({type:"error",code:"model_failed",message:A.health().error||"model failed to load",fatal:!0}):d.diarize&&["downloading","loading"].includes(P.state())?p.push({type:"diarize-progress",state:P.state(),...P.progress()||{}}):d.translateTo&&["downloading","loading"].includes(Je.state())?p.push({type:"translate-progress",state:Je.state(),...Je.progress()||{}}):fr.get(d)!==g&&(fr.set(d,g),p.push({type:"state",state:g}))}const f=d?.redact?await xe(t.pro?.entitlementToken):!0;for(const g of m)d?p.push(await s(d,g,f)):g.type!=="final"&&g.type!=="interim"&&g.type!=="translation"&&p.push(g);return p};if(e[2]==="/audio"&&r.method==="POST"){const d=A.getSession(n)||A.endedSession(n);try{const m=await b(r,t.maxBodyBytes);A.pushAudio(n,A.toFloat32(m,d?.format));const p=await l(d);return a(o,200,{ok:!0,state:A.state(),...p?{events:p}:{}})}catch(m){const p=m.code==="no_session"?await l(d).catch(()=>null):null;return a(o,m.code==="no_session"?404:400,{error:{message:m.message,type:m.code||"stt_error"},...p?{events:p}:{}})}}if(e[2]==="/events"&&r.method==="GET"){const d=A.getSession(n);if(!d)return a(o,404,{error:{message:"no such session",type:"no_session"}});o.writeHead(200,{"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive"});const m=T=>o.write(`data: ${JSON.stringify(T)}
59
59
 
60
- `),p=d.redact?await xe(t.pro?.entitlementToken):!0,f=T=>s(d,T,p);m({type:"state",state:d.remote?"ready":A.state()});const g=setInterval(()=>{const T=d.remote?"ready":A.state();if(T==="downloading"||T==="loading"){m({type:"progress",state:T,...A.progress()||{}});return}if(T==="error"){m({type:"error",code:"model_failed",message:A.health().error||"model failed to load",fatal:!0}),clearInterval(g);return}if(d.diarize){const R=P.state();if(R==="downloading"||R==="loading"){m({type:"diarize-progress",state:R,...P.progress()||{}});return}}if(d.translateTo){const R=Je.state();if(R==="downloading"||R==="loading"){m({type:"translate-progress",state:R,...Je.progress()||{}});return}}m({type:"state",state:T}),clearInterval(g)},500);g.unref?.();let S=Promise.resolve();const _=A.subscribe(n,T=>{S=S.then(async()=>{m(await f(T)),T.type==="end"&&(clearInterval(g),o.end())}).catch(()=>{})});r.on("close",()=>{clearInterval(g),_?.()});return}if(!e[2]&&r.method==="DELETE"){const d=A.getSession(n);await A.endSession(n);const m=d?.poll?await l(d).catch(()=>null):null;return a(o,200,{ok:!0,...m?{events:m}:{}})}}}if(i==="/logs"&&r.method==="GET")return a(o,200,{entries:[...Ne].reverse()});if(i==="/config"&&r.method==="GET"){const e=await xe(t.pro?.entitlementToken);return a(o,200,Zo(t,{proUnlocked:e,policy:yt()}))}if(i==="/config"&&r.method==="POST"){let e=null;try{e=JSON.parse((await b(r,t.maxBodyBytes)).toString("utf8"))}catch{e=null}if(!e||typeof e!="object")return a(o,400,{error:"invalid config patch"});const n=JSON.stringify(t.sandbox||null);if(e.capabilities&&typeof e.capabilities=="object"){const p=JSON.parse(JSON.stringify({capabilities:t.capabilities||{},redaction:t.redaction||{}}));try{xt(p,{capabilities:e.capabilities})}catch(g){if(g?.code==="SHAPE")return a(o,400,{error:g.message});throw g}const f=Object.keys(e.capabilities).map(g=>Vs(g,t.capabilities?.[g],p.capabilities?.[g])).find(Boolean);if(f&&!await xe(t.pro?.entitlementToken))return a(o,403,{error:f,needs:"pro"})}try{xt(t,e)}catch(p){if(p?.code==="SHAPE")return a(o,400,{error:p.message});throw p}yo(t),JSON.stringify(t.sandbox||null)!==n&&it?.restart("sandbox settings changed");try{ue(t,Z())}catch(p){return a(o,500,{error:`could not persist config: ${p.message}`})}const s=t.redaction?.detection,l=!s||!s.backend||s.backend==="off",d=z.state();t.ner?.autostart&&l&&d!=="ready"&&d!=="loading"&&d!=="downloading"&&z.setModel(t.ner.model,{onLog:p=>console.log(p)}).then(p=>{p&&t.ner?.enableFullTier&&t.redaction.tier!=="full"&&(t.redaction.tier="full")});const m=await xe(t.pro?.entitlementToken);return a(o,200,Zo(t,{proUnlocked:m,policy:yt()}))}if(r.method==="GET"&&i==="/skills")return Se(r,o,t,`/skills${Ye(y,t)}`,{pick:e=>({skills:Array.isArray(e?.skills)?e.skills:[]})});if(r.method==="POST"&&i==="/v1/threads/send"){if(!J(r))return a(o,403,{error:{message:"asking another chat: extension origin or gateway token required",type:"forbidden"}});if(r.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=G.lossless;if(!e)return a(o,501,{error:{message:"asking another chat needs the SQLite warm store",type:"unavailable"}});let n={};try{n=JSON.parse((await b(r,t.maxBodyBytes)).toString("utf8")||"{}")||{}}catch{return a(o,400,{error:{message:"threads/send: body must be JSON",type:"invalid_request"}})}const s=String(n.to||""),l=String(n.message||"").trim();if(!l||l.length>$o)return a(o,400,{error:{message:`threads/send: a message of 1–${$o} characters`,type:"invalid_request"}});const d=n.from&&typeof n.from=="object"?{id:String(n.from.id||"").slice(0,200),title:String(n.from.title||"").slice(0,200)}:null,m=e.get(s);if(!m||m.deletedAt)return a(o,404,{error:{message:"no such chat on this computer — it may not have synced here yet",type:"not_found"}});const p=On(m,{cards:me.get("agentTools").agentTools?.value?.agents||[]});if(p.error)return a(o,409,{error:{message:p.error,type:"no_model"}});if(n.dryRun===!0)return a(o,200,{ok:!0,title:m.title,model:p.model});const f=En({fromTitle:d?.title,message:l}),g={thread:{id:p.thread,...m.title?{title:m.title}:{}},...p.workingDir?{workingDir:p.workingDir}:{}};let S="";try{const T=await fetch(`http://127.0.0.1:${r.socket.localPort}/v1/chat/completions`,{method:"POST",headers:{"content-type":"application/json","x-chatpanel-token":Re()||Pe(),"x-chatpanel-run":encodeURIComponent(JSON.stringify(g))},body:JSON.stringify({model:p.model,messages:[...Pn(m),{role:"user",content:f}],stream:!1}),signal:AbortSignal.timeout(6e5)}),R=await T.json().catch(()=>null);if(!T.ok)return a(o,502,{error:{message:`that chat's ${p.model} did not answer: ${R?.error?.message||`HTTP ${T.status}`}`,type:"upstream"}});S=String(R?.choices?.[0]?.message?.content||"")}catch(T){return a(o,502,{error:{message:`that chat's ${p.model} did not answer: ${T?.message||T}`,type:"upstream"}})}const _=$n(e.get(s)||m,{question:f,reply:S,model:p.model,from:d});e.write([_],{host:"gateway",at:Date.now()});try{const T=Co(e.get(s));T&&G.bulk({upserts:[T],removes:[]})}catch{}return We({ids:[s]}),a(o,200,{ok:!0,title:m.title,model:p.model,reply:S})}const ee=/^(?:\/v1)?(\/agent-sessions(?:\/read|\/adopt|\/catchup)?)$/.exec(i)?.[1];if(r.method==="POST"&&ee)return J(r)?r.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 › Link › Phones",type:"forbidden"}}):Se(r,o,t,ee,{method:"POST",timeoutMs:3e4}):a(o,403,{error:{message:"the agents' own sessions: extension origin or gateway token required",type:"forbidden"}});if(r.method==="GET"&&i==="/skills-quarantined")return Se(r,o,t,`/skills-quarantined${Ye(y,t)}`,{pick:e=>({quarantined:Array.isArray(e?.quarantined)?e.quarantined:[]})});if(i==="/skills"&&r.method==="POST")return J(r)?Se(r,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)&&r.method==="DELETE"){const e=decodeURIComponent(i.slice(8));return Xt(e)?a(o,400,{error:{message:"not a skill id",type:"invalid_request"}}):J(r)?Se(r,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)&&r.method==="PUT"){const e=/^\/skills\/([^/]+)\/file\/(.+)$/.exec(i),n=decodeURIComponent(e[1]);return Xt(n)||/(^|\/)\.\.(\/|$)/.test(decodeURIComponent(e[2]))?a(o,400,{error:{message:"not a skill file",type:"invalid_request"}}):J(r)?Se(r,o,t,`/skills/${encodeURIComponent(n)}/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(r.method==="GET"&&i==="/agent-defs")return Se(r,o,t,`/agent-defs${Ye(y,t)}`,{pick:e=>({agents:Array.isArray(e?.agents)?e.agents:[],...e?.quarantined?{quarantined:e.quarantined}:{},...e?.problems?{problems:e.problems}:{}})});if(r.method==="GET"&&/^\/agent-defs\/[^/]+$/.test(i)){const e=decodeURIComponent(i.slice(12));return Xt(e)?a(o,400,{error:{message:"not an agent id",type:"invalid_request"}}):Se(r,o,t,`/agent-defs/${encodeURIComponent(e)}${Ye(y,t)}`)}if(i.startsWith("/a2a/")){if(!J(r))return a(o,403,{error:{message:"a2a: extension origin or gateway token required",type:"forbidden"}});try{if(r.method==="GET"&&i==="/a2a/agents")return a(o,200,{agents:an()});if(r.method==="POST"&&i==="/a2a/card"){const e=JSON.parse((await b(r,t.maxBodyBytes)).toString("utf8")||"{}");e.forget&&en(e.url||"");const n=await ft(e.url,{force:!!e.force,auth:String(e.auth||"")});return a(o,200,{ok:!0,card:n.card,fingerprint:n.fingerprint,fresh:n.fresh,changed:!!n.changed,url:n.url})}if(r.method==="POST"&&i==="/a2a/message"){const e=JSON.parse((await b(r,t.maxBodyBytes)).toString("utf8")||"{}"),n=e.card||(await ft(e.url,{auth:String(e.auth||"")})).card,s=await tn({card:n,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(r.method==="POST"&&i==="/a2a/message/stream"){const e=JSON.parse((await b(r,t.maxBodyBytes)).toString("utf8")||"{}"),n=e.card||(await ft(e.url,{auth:String(e.auth||"")})).card;o.writeHead(200,{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"});const s=(l,d)=>o.write(`event: ${l}
60
+ `),p=d.redact?await xe(t.pro?.entitlementToken):!0,f=T=>s(d,T,p);m({type:"state",state:d.remote?"ready":A.state()});const g=setInterval(()=>{const T=d.remote?"ready":A.state();if(T==="downloading"||T==="loading"){m({type:"progress",state:T,...A.progress()||{}});return}if(T==="error"){m({type:"error",code:"model_failed",message:A.health().error||"model failed to load",fatal:!0}),clearInterval(g);return}if(d.diarize){const R=P.state();if(R==="downloading"||R==="loading"){m({type:"diarize-progress",state:R,...P.progress()||{}});return}}if(d.translateTo){const R=Je.state();if(R==="downloading"||R==="loading"){m({type:"translate-progress",state:R,...Je.progress()||{}});return}}m({type:"state",state:T}),clearInterval(g)},500);g.unref?.();let S=Promise.resolve();const _=A.subscribe(n,T=>{S=S.then(async()=>{m(await f(T)),T.type==="end"&&(clearInterval(g),o.end())}).catch(()=>{})});r.on("close",()=>{clearInterval(g),_?.()});return}if(!e[2]&&r.method==="DELETE"){const d=A.getSession(n);await A.endSession(n);const m=d?.poll?await l(d).catch(()=>null):null;return a(o,200,{ok:!0,...m?{events:m}:{}})}}}if(i==="/logs"&&r.method==="GET")return a(o,200,{entries:[...Ne].reverse()});if(i==="/config"&&r.method==="GET"){const e=await xe(t.pro?.entitlementToken);return a(o,200,Zo(t,{proUnlocked:e,policy:yt()}))}if(i==="/config"&&r.method==="POST"){let e=null;try{e=JSON.parse((await b(r,t.maxBodyBytes)).toString("utf8"))}catch{e=null}if(!e||typeof e!="object")return a(o,400,{error:"invalid config patch"});const n=JSON.stringify(t.sandbox||null);if(e.capabilities&&typeof e.capabilities=="object"){const p=JSON.parse(JSON.stringify({capabilities:t.capabilities||{},redaction:t.redaction||{}}));try{xt(p,{capabilities:e.capabilities})}catch(g){if(g?.code==="SHAPE")return a(o,400,{error:g.message});throw g}const f=Object.keys(e.capabilities).map(g=>Fs(g,t.capabilities?.[g],p.capabilities?.[g])).find(Boolean);if(f&&!await xe(t.pro?.entitlementToken))return a(o,403,{error:f,needs:"pro"})}try{xt(t,e)}catch(p){if(p?.code==="SHAPE")return a(o,400,{error:p.message});throw p}yo(t),JSON.stringify(t.sandbox||null)!==n&&it?.restart("sandbox settings changed");try{ue(t,Z())}catch(p){return a(o,500,{error:`could not persist config: ${p.message}`})}const s=t.redaction?.detection,l=!s||!s.backend||s.backend==="off",d=z.state();t.ner?.autostart&&l&&d!=="ready"&&d!=="loading"&&d!=="downloading"&&z.setModel(t.ner.model,{onLog:p=>console.log(p)}).then(p=>{p&&t.ner?.enableFullTier&&t.redaction.tier!=="full"&&(t.redaction.tier="full")});const m=await xe(t.pro?.entitlementToken);return a(o,200,Zo(t,{proUnlocked:m,policy:yt()}))}if(r.method==="GET"&&i==="/skills")return Se(r,o,t,`/skills${Ye(y,t)}`,{pick:e=>({skills:Array.isArray(e?.skills)?e.skills:[]})});if(r.method==="POST"&&i==="/v1/threads/send"){if(!J(r))return a(o,403,{error:{message:"asking another chat: extension origin or gateway token required",type:"forbidden"}});if(r.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=G.lossless;if(!e)return a(o,501,{error:{message:"asking another chat needs the SQLite warm store",type:"unavailable"}});let n={};try{n=JSON.parse((await b(r,t.maxBodyBytes)).toString("utf8")||"{}")||{}}catch{return a(o,400,{error:{message:"threads/send: body must be JSON",type:"invalid_request"}})}const s=String(n.to||""),l=String(n.message||"").trim();if(!l||l.length>$o)return a(o,400,{error:{message:`threads/send: a message of 1–${$o} characters`,type:"invalid_request"}});const d=n.from&&typeof n.from=="object"?{id:String(n.from.id||"").slice(0,200),title:String(n.from.title||"").slice(0,200)}:null,m=e.get(s);if(!m||m.deletedAt)return a(o,404,{error:{message:"no such chat on this computer — it may not have synced here yet",type:"not_found"}});const p=On(m,{cards:me.get("agentTools").agentTools?.value?.agents||[]});if(p.error)return a(o,409,{error:{message:p.error,type:"no_model"}});if(n.dryRun===!0)return a(o,200,{ok:!0,title:m.title,model:p.model});const f=En({fromTitle:d?.title,message:l}),g={thread:{id:p.thread,...m.title?{title:m.title}:{}},...p.workingDir?{workingDir:p.workingDir}:{}};let S="";try{const T=await fetch(`http://127.0.0.1:${r.socket.localPort}/v1/chat/completions`,{method:"POST",headers:{"content-type":"application/json","x-chatpanel-token":Re()||Pe(),"x-chatpanel-run":encodeURIComponent(JSON.stringify(g))},body:JSON.stringify({model:p.model,messages:[...Pn(m),{role:"user",content:f}],stream:!1}),signal:AbortSignal.timeout(6e5)}),R=await T.json().catch(()=>null);if(!T.ok)return a(o,502,{error:{message:`that chat's ${p.model} did not answer: ${R?.error?.message||`HTTP ${T.status}`}`,type:"upstream"}});S=String(R?.choices?.[0]?.message?.content||"")}catch(T){return a(o,502,{error:{message:`that chat's ${p.model} did not answer: ${T?.message||T}`,type:"upstream"}})}const _=$n(e.get(s)||m,{question:f,reply:S,model:p.model,from:d});e.write([_],{host:"gateway",at:Date.now()});try{const T=Co(e.get(s));T&&G.bulk({upserts:[T],removes:[]})}catch{}return We({ids:[s]}),a(o,200,{ok:!0,title:m.title,model:p.model,reply:S})}const ee=/^(?:\/v1)?(\/agent-sessions(?:\/read|\/adopt|\/catchup)?)$/.exec(i)?.[1];if(r.method==="POST"&&ee)return J(r)?r.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 › Link › Phones",type:"forbidden"}}):Se(r,o,t,ee,{method:"POST",timeoutMs:3e4}):a(o,403,{error:{message:"the agents' own sessions: extension origin or gateway token required",type:"forbidden"}});if(r.method==="GET"&&i==="/skills-quarantined")return Se(r,o,t,`/skills-quarantined${Ye(y,t)}`,{pick:e=>({quarantined:Array.isArray(e?.quarantined)?e.quarantined:[]})});if(i==="/skills"&&r.method==="POST")return J(r)?Se(r,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)&&r.method==="DELETE"){const e=decodeURIComponent(i.slice(8));return Xt(e)?a(o,400,{error:{message:"not a skill id",type:"invalid_request"}}):J(r)?Se(r,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)&&r.method==="PUT"){const e=/^\/skills\/([^/]+)\/file\/(.+)$/.exec(i),n=decodeURIComponent(e[1]);return Xt(n)||/(^|\/)\.\.(\/|$)/.test(decodeURIComponent(e[2]))?a(o,400,{error:{message:"not a skill file",type:"invalid_request"}}):J(r)?Se(r,o,t,`/skills/${encodeURIComponent(n)}/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(r.method==="GET"&&i==="/agent-defs")return Se(r,o,t,`/agent-defs${Ye(y,t)}`,{pick:e=>({agents:Array.isArray(e?.agents)?e.agents:[],...e?.quarantined?{quarantined:e.quarantined}:{},...e?.problems?{problems:e.problems}:{}})});if(r.method==="GET"&&/^\/agent-defs\/[^/]+$/.test(i)){const e=decodeURIComponent(i.slice(12));return Xt(e)?a(o,400,{error:{message:"not an agent id",type:"invalid_request"}}):Se(r,o,t,`/agent-defs/${encodeURIComponent(e)}${Ye(y,t)}`)}if(i.startsWith("/a2a/")){if(!J(r))return a(o,403,{error:{message:"a2a: extension origin or gateway token required",type:"forbidden"}});try{if(r.method==="GET"&&i==="/a2a/agents")return a(o,200,{agents:an()});if(r.method==="POST"&&i==="/a2a/card"){const e=JSON.parse((await b(r,t.maxBodyBytes)).toString("utf8")||"{}");e.forget&&en(e.url||"");const n=await ft(e.url,{force:!!e.force,auth:String(e.auth||"")});return a(o,200,{ok:!0,card:n.card,fingerprint:n.fingerprint,fresh:n.fresh,changed:!!n.changed,url:n.url})}if(r.method==="POST"&&i==="/a2a/message"){const e=JSON.parse((await b(r,t.maxBodyBytes)).toString("utf8")||"{}"),n=e.card||(await ft(e.url,{auth:String(e.auth||"")})).card,s=await tn({card:n,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(r.method==="POST"&&i==="/a2a/message/stream"){const e=JSON.parse((await b(r,t.maxBodyBytes)).toString("utf8")||"{}"),n=e.card||(await ft(e.url,{auth:String(e.auth||"")})).card;o.writeHead(200,{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"});const s=(l,d)=>o.write(`event: ${l}
61
61
  data: ${JSON.stringify(d)}
62
62
 
63
- `);try{const l=await on({card:n,message:e.message||{messageId:`cp_${Date.now().toString(36)}`,role:"ROLE_USER",parts:[{text:String(e.text||"")}]},auth:String(e.auth||""),contextId:String(e.contextId||""),taskId:String(e.taskId||""),onEvent:d=>s(d.kind,{kind:d.kind,task:d.task,message:d.message})});s("done",l)}catch(l){s("error",{code:l.code||"ERROR",message:l.message})}return o.end()}if(r.method==="POST"&&i==="/a2a/task"){const e=JSON.parse((await b(r,t.maxBodyBytes)).toString("utf8")||"{}"),n=e.card||(await ft(e.url,{auth:String(e.auth||"")})).card,s=e.cancel?await nn({card:n,id:String(e.id||""),auth:String(e.auth||"")}):await rn({card:n,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 n=e instanceof go||e?.name==="A2AClientError"?e.code:"ERROR";return a(o,e instanceof go&&e.code==="UNREACHABLE"?502:400,{error:{message:e.message,type:"a2a_error",code:n}})}}if(r.method==="POST"&&(i==="/agent-defs/export"||i==="/agent-defs/export-plan"))return J(r)?Se(r,o,t,i,{method:"POST",timeoutMs:15e3}):a(o,403,{error:{message:"exporting an agent: extension origin or gateway token required",type:"forbidden"}});if(r.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"}}):Se(r,o,t,`/skills/${encodeURIComponent(e)}${Ye(y,t)}`,{pick:n=>({skill:n?.skill||null})})}if(i==="/channels"||/^\/channels\/(connect|pair|unpair|settings|disconnect)$/.test(i)){if(!J(r))return a(o,403,{error:{message:"channels: extension origin or gateway token required",type:"forbidden"}});if(!(i==="/channels"&&r.method==="GET"||i!=="/channels"&&r.method==="POST"))return a(o,405,{error:{message:"method not allowed",type:"invalid_request"}});const e=await ot(t);if(!e)return a(o,503,{error:{message:"no bridge is configured",type:"no_bridge"}});const n=rt(t.bridge?.token);try{const s=r.method==="POST"?(await b(r,t.maxBodyBytes)).toString("utf8"):"",l=await fetch(`${e}${i}`,{method:r.method,headers:{Accept:"application/json",...r.method==="POST"?{"content-type":"application/json"}:{},...n?{Authorization:`Bearer ${n}`}:{}},...r.method==="POST"?{body:s||"{}"}:{},signal:AbortSignal.timeout(15e3)}),d=await l.json().catch(()=>({}));return a(o,l.status,d)}catch(s){return a(o,502,{error:{message:`bridge unreachable: ${s.message}`,type:"bridge_unreachable"}})}}if(r.method==="GET"&&/^\/skills\/[^/]+\/file\/.+/.test(i)){const e=/^\/skills\/([^/]+)\/file\/(.+)$/.exec(i),n=decodeURIComponent(e[1]),s=e[2];return!n||n==="."||n===".."||n.includes("/")||n.includes("\\")||/(^|\/)\.\.(\/|$)/.test(decodeURIComponent(s))?a(o,400,{error:{message:"not a skill file",type:"invalid_request"}}):Se(r,o,t,`/skills/${encodeURIComponent(n)}/file/${s}${Ye(y,t)}`)}if(r.method==="GET"&&/\/models$/.test(i)){const e=await q(),n=e.sig!==void 0&&e.sig!==oe;return oe=e.sig,a(o,200,await Fs(t,{serviceHealth:async()=>e,fresh:n,engineAt:M.engineAt}))}if(ki.some(e=>i===e||i.startsWith(`${e}/`)))return a(o,404,{error:{message:`this gateway (${le}) has no ${i} — update it to use this feature`,type:"unknown_endpoint"}});const W=di(i,r.headers,t);let Te;try{Te=await b(r,t.maxBodyBytes)}catch(e){a(o,e.code===413?413:400,{error:e.code===413?"payload too large":"bad request"}),r.destroy();return}let fe=null,O=null,Ze=Te,qt=0,eo=0,to=0,Oe=!1,Ie=!1,oo="",Ue=!0;const se=t.logRequests&&W.redactable&&r.method==="POST"?li(wr):null,br=Date.now();if(W.redactable&&r.method==="POST"&&Te.length){try{O=JSON.parse(Te.toString("utf8"))}catch{O=null}if(O&&ci(O,W.kind))Ze=Te;else if(O){const e=t.tools||{};if(e.autoNarrow!==!1&&Array.isArray(O.tools)&&O.tools.length){const f=Number(e.maxPerTurn)>0?Number(e.maxPerTurn):ei,g=e.narrowAll?null:_=>!ti.test(ar(_)),S=O.tools.length;O.tools=Mr(O.tools,ri(O,W.kind),{cap:f,keep:g,name:ar,description:oi}),to=S-O.tools.length}if(Ue=await xe(t.pro?.entitlementToken),Oe=String(r.headers["x-chatpanel-redaction"]||"").trim().toLowerCase()==="off"&&J(r),!Oe){const f=_t(O?.model,t,W.kind,{destination:String(r.headers["x-chatpanel-destination"]||O?.chatpanel?.destination||"").trim(),down:()=>!1}),g=f?.type==="api"?await M.decide(f,O?.model).catch(()=>null):null;Ie=g?.redact===!1,oo=Ie?g.engine||"declared":""}if(!Oe&&!Ie){const f=Is(t,Ue);if(!f.allowed)return a(o,402,{error:{message:`ChatPanel Gateway free trial used up (${f.cap} redactions). If you have ChatPanel Pro, open Chap (the browser extension or the desktop app) and it hands this gateway its plan — or paste an entitlement token in Settings › Gateway › Pro.`,type:"free_limit_reached"}})}!Oe&&!Ie&&await wt(t);const n=Oe?[]:W.adapter.collectSegments(O,t.redaction,{skipPublic:J(r)}),s=new AbortController;o.on("close",()=>{o.writableFinished||s.abort()});const l=se?se.clock():0,{vault:d,count:m,sanitized:p}=Oe?{vault:null,count:0,sanitized:0}:await qe(n,t.redaction,{signal:s.signal,isPro:Ue,sanitizeOnly:Ie,onEgress:f=>Ht.push(tr({ts:Date.now(),client:"redaction",tool:`detect:${f.backend}@${f.host||"local"}`,ok:f.ok,ms:f.ms,error:f.error}))});if(se&&se.lap("redact",l),W.adapter.joinTextParts?.(O),fe=d,qt=m,eo=p||0,m>0&&o.setHeader("x-chatpanel-redacted",String(m)),!Ue&&m>0){Rs(t,Ue);try{ue(t,Z())}catch{}}if(!Oe&&!Ie&&Array.isArray(O.tools)&&O.tools.length&&typeof W.adapter.injectSystemNote=="function"){const f=_t(O?.model,t,W.kind,{destination:String(r.headers["x-chatpanel-destination"]||O?.chatpanel?.destination||"").trim(),down:S=>!!S.service&&Y.fn(S.id)==="down"}),g=!(f&&f.type==="api");W.adapter.injectSystemNote(O,Cr({toolData:t.tools?.toolData,ownTools:g}))}else!Oe&&m>0&&typeof W.adapter.injectSystemNote=="function"&&W.adapter.injectSystemNote(O,Ir());Ze=Buffer.from(JSON.stringify(O),"utf8")}}const ro=Dr({vault:fe,toolData:t.tools?.toolData}),dt=O&&typeof O.chatpanel=="object"&&O.chatpanel||null;if(dt&&(delete O.chatpanel,Ze=Buffer.from(JSON.stringify(O),"utf8")),typeof O?.model=="string"&&O.model.startsWith("fusion:")){const e=la(O.model,t,await q());if(e?.error)return se?.commit(),a(o,400,{error:{message:e.error,type:"fusion"}});e&&(O.model=e.model,Ze=Buffer.from(JSON.stringify(O),"utf8"),o.setHeader("x-chatpanel-fusion",`${e.fusion.id} -> ${e.model}`))}const ie={destination:String(r.headers["x-chatpanel-destination"]||dt?.destination||"").trim(),reach:String(r.headers["x-chatpanel-reach"]||dt?.reach||"").trim(),run:Zt(r.headers["x-chatpanel-run"],dt?.run)},ct=await q(),no=e=>!!e.service&&ct(e.id)==="down";let B=_t(O?.model,t,W.kind,{destination:ie.destination,down:no});B?.type==="agent"&&O?.model&&!ie.destination&&!Qs(B,O.model)&&(await Ks(t,{serviceHealth:async()=>ct,engineAt:M.engineAt}),B=_t(O?.model,t,W.kind,{destination:ie.destination,down:no}));const ao=B?.service&&ct(B.id)==="down"?await I().revive(B.service).catch(()=>null):null;if(ao?.ok&&(Y.at=0),B?.service&&ct(B.id)==="down"&&!ao?.ok)return se?.commit(),a(o,503,{error:{message:`${B.id} is not running — the model ${JSON.stringify(O?.model||"")} is served by an engine the Runtime has stopped; start it under Settings › Runtime`,type:"engine_down",service:B.service}});if(ie.destination&&(!B||B.id!==ie.destination))return se?.commit(),a(o,404,{error:{message:`no destination "${ie.destination}" is configured on this gateway`,type:"unknown_destination",known:Ws(t).map(e=>e.id)}});const de=Me(r.headers);if(de&&!La(de,B?.type==="api"?"api":"agent"))return se?.commit(),a(o,403,{error:{message:`link: partner "${de.partner}" may not use ${B?.type==="api"?"this model":"this computer’s coding agents"} — its scopes are ${de.scopes.join(", ")||"none"}; the owner grants agents at pairing`,type:"forbidden",code:"link_scope"}});const ut=de&&W.redactable&&r.method==="POST"&&O?{caller:de,surface:ea(de,de.kind==="partner"?"":E?.deviceNameOf(de.device)),model:O.model||null,startedAt:br}:null;se&&(se.meta={t:Date.now(),model:O?.model||null,dest:B?B.id:null,type:B?B.type:null,redacted:qt,sanitized:eo,narrowed:to,detail:dr(fe,t.logDetail),redaction:Oe?"off":Ie?`on-device (${oo})`:t.redaction.tier||"basic",...de?.kind==="partner"?{via:ja(de)}:{}});const mt=yt();if(mt&&B){const e=B.type==="api"?fo(mt,{model:O?.model||"",endpoint:B.baseUrl||""}):Zr(mt,B.agent||B.id)?fo(mt,{model:O?.model||""}):{ok:!1,reason:`agent "${B.agent||B.id}" is not allowed by your organisation’s policy`};if(!e.ok)return se?.commit(),a(o,403,{error:{message:e.reason,type:"policy",code:"org_policy"}})}if(B&&B.type==="api")return B.baseUrl?ui(B.baseUrl,t)?(se?.commit(),a(o,508,{error:{message:`destination "${B.id}" points back at the gateway (${B.baseUrl}) — refusing to forward (would loop).`,type:"loop_detected"}})):vi(r,o,{...W,pathname:i,search:y.search,base:B.baseUrl,destKey:B.apiKey,destProtocol:B.protocol,harness:ro,trace:se,link:ut&&{...ut,agentId:B.id,dest:{type:"api",id:B.id}}},Ze,fe):(se?.commit(),a(o,502,{error:`destination "${B.id}" has no baseUrl`}));const Pt=et(r),so=Pt==="local"&&t.bridge?.openAgentLane?"token":Pt;if(so==="local")return se?.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 io=Math.max(0,Math.min(8,Number(r.headers["x-chatpanel-ask-depth"])||0)),kr=new Set(["thread","ephemeral","workingDir","worker"]),$t=de?.kind==="partner";if(Pt==="token"&&r.headers["x-chatpanel-link-device"]&&!$t&&!(ie.run&&Object.keys(ie.run).some(e=>!kr.has(e)))){const e=Zt(null,Eo(Oo(me.get("agentTools").agentTools?.value,B?.agent||O?.model)));e&&(ie.run={...e,...ie.run||{}})}if($t){const e=Zt(null,Eo(Oo(me.get("agentTools").agentTools?.value,B?.agent||O?.model)));ie.run={...e||{},...Ga(ie.run,de.device)};const n=E?.partnerFolderOf(de.device);if(!n)return se?.commit(),a(o,403,{error:{message:"link: this partner has no folder on this computer — pair it again with agents",type:"forbidden",code:"link_scope"}});ie.run.workingDir=n,ie.reach="",Array.isArray(O?.tools)&&(O.tools=O.tools.filter(s=>!Jo(s?.function?.name??s?.name)))}const He=Jr({...ie.run||{},...ie.reach?{reach:ie.reach}:{},...io?{askDepth:io}:{}},so);He.reach&&o.setHeader("x-chatpanel-reach-used",He.reach);const vr=$t?{inbox:x,partner:de.partner,device:de.device,conversation:He.thread?.id||null}:null,Sr=ut&&{...ut,dest:{type:"agent",id:B?.id||"bridge"},threadId:He.thread?.id||null};return fi(r,o,{...W,pathname:i,agentOverride:B?.agent,harness:ro,trace:se,run:Object.keys(He).length?He:null,owner:vr,link:Sr},O,fe,t,Ue)});return Be.on("close",()=>{H?.stop("closed"),wa(),k.close(),E?.stop(),x.stop()}),Be.on("upgrade",(r,o,y)=>{o.on("error",()=>{});const i=String(r.url||"").split("?")[0];if(E&&i.startsWith(Ra)){E.acceptTunnel(r,o,y).catch(()=>{try{o.destroy()}catch{}});return}try{o.end(`HTTP/1.1 404 Not Found\r
63
+ `);try{const l=await on({card:n,message:e.message||{messageId:`cp_${Date.now().toString(36)}`,role:"ROLE_USER",parts:[{text:String(e.text||"")}]},auth:String(e.auth||""),contextId:String(e.contextId||""),taskId:String(e.taskId||""),onEvent:d=>s(d.kind,{kind:d.kind,task:d.task,message:d.message})});s("done",l)}catch(l){s("error",{code:l.code||"ERROR",message:l.message})}return o.end()}if(r.method==="POST"&&i==="/a2a/task"){const e=JSON.parse((await b(r,t.maxBodyBytes)).toString("utf8")||"{}"),n=e.card||(await ft(e.url,{auth:String(e.auth||"")})).card,s=e.cancel?await nn({card:n,id:String(e.id||""),auth:String(e.auth||"")}):await rn({card:n,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 n=e instanceof go||e?.name==="A2AClientError"?e.code:"ERROR";return a(o,e instanceof go&&e.code==="UNREACHABLE"?502:400,{error:{message:e.message,type:"a2a_error",code:n}})}}if(r.method==="POST"&&(i==="/agent-defs/export"||i==="/agent-defs/export-plan"))return J(r)?Se(r,o,t,i,{method:"POST",timeoutMs:15e3}):a(o,403,{error:{message:"exporting an agent: extension origin or gateway token required",type:"forbidden"}});if(r.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"}}):Se(r,o,t,`/skills/${encodeURIComponent(e)}${Ye(y,t)}`,{pick:n=>({skill:n?.skill||null})})}if(i==="/channels"||/^\/channels\/(connect|pair|unpair|settings|disconnect)$/.test(i)){if(!J(r))return a(o,403,{error:{message:"channels: extension origin or gateway token required",type:"forbidden"}});if(!(i==="/channels"&&r.method==="GET"||i!=="/channels"&&r.method==="POST"))return a(o,405,{error:{message:"method not allowed",type:"invalid_request"}});const e=await ot(t);if(!e)return a(o,503,{error:{message:"no bridge is configured",type:"no_bridge"}});const n=rt(t.bridge?.token);try{const s=r.method==="POST"?(await b(r,t.maxBodyBytes)).toString("utf8"):"",l=await fetch(`${e}${i}`,{method:r.method,headers:{Accept:"application/json",...r.method==="POST"?{"content-type":"application/json"}:{},...n?{Authorization:`Bearer ${n}`}:{}},...r.method==="POST"?{body:s||"{}"}:{},signal:AbortSignal.timeout(15e3)}),d=await l.json().catch(()=>({}));return a(o,l.status,d)}catch(s){return a(o,502,{error:{message:`bridge unreachable: ${s.message}`,type:"bridge_unreachable"}})}}if(r.method==="GET"&&/^\/skills\/[^/]+\/file\/.+/.test(i)){const e=/^\/skills\/([^/]+)\/file\/(.+)$/.exec(i),n=decodeURIComponent(e[1]),s=e[2];return!n||n==="."||n===".."||n.includes("/")||n.includes("\\")||/(^|\/)\.\.(\/|$)/.test(decodeURIComponent(s))?a(o,400,{error:{message:"not a skill file",type:"invalid_request"}}):Se(r,o,t,`/skills/${encodeURIComponent(n)}/file/${s}${Ye(y,t)}`)}if(r.method==="GET"&&/\/models$/.test(i)){const e=await q(),n=e.sig!==void 0&&e.sig!==oe;return oe=e.sig,a(o,200,await Ws(t,{serviceHealth:async()=>e,fresh:n,engineAt:M.engineAt}))}if(vi.some(e=>i===e||i.startsWith(`${e}/`)))return a(o,404,{error:{message:`this gateway (${le}) has no ${i} — update it to use this feature`,type:"unknown_endpoint"}});const W=ci(i,r.headers,t);let Te;try{Te=await b(r,t.maxBodyBytes)}catch(e){a(o,e.code===413?413:400,{error:e.code===413?"payload too large":"bad request"}),r.destroy();return}let fe=null,O=null,Ze=Te,qt=0,eo=0,to=0,Oe=!1,Ie=!1,oo="",Ue=!0;const se=t.logRequests&&W.redactable&&r.method==="POST"?di(wr):null,br=Date.now();if(W.redactable&&r.method==="POST"&&Te.length){try{O=JSON.parse(Te.toString("utf8"))}catch{O=null}if(O&&ui(O,W.kind))Ze=Te;else if(O){const e=t.tools||{};if(e.autoNarrow!==!1&&Array.isArray(O.tools)&&O.tools.length){const f=Number(e.maxPerTurn)>0?Number(e.maxPerTurn):ti,g=e.narrowAll?null:_=>!oi.test(ar(_)),S=O.tools.length;O.tools=Mr(O.tools,ni(O,W.kind),{cap:f,keep:g,name:ar,description:ri}),to=S-O.tools.length}if(Ue=await xe(t.pro?.entitlementToken),Oe=String(r.headers["x-chatpanel-redaction"]||"").trim().toLowerCase()==="off"&&J(r),!Oe){const f=_t(O?.model,t,W.kind,{destination:String(r.headers["x-chatpanel-destination"]||O?.chatpanel?.destination||"").trim(),down:()=>!1}),g=f?.type==="api"?await M.decide(f,O?.model).catch(()=>null):null;Ie=g?.redact===!1,oo=Ie?g.engine||"declared":""}if(!Oe&&!Ie){const f=Rs(t,Ue);if(!f.allowed)return a(o,402,{error:{message:`ChatPanel Gateway free trial used up (${f.cap} redactions). If you have ChatPanel Pro, open Chap (the browser extension or the desktop app) and it hands this gateway its plan — or paste an entitlement token in Settings › Gateway › Pro.`,type:"free_limit_reached"}})}!Oe&&!Ie&&await wt(t);const n=Oe?[]:W.adapter.collectSegments(O,t.redaction,{skipPublic:J(r)}),s=new AbortController;o.on("close",()=>{o.writableFinished||s.abort()});const l=se?se.clock():0,{vault:d,count:m,sanitized:p}=Oe?{vault:null,count:0,sanitized:0}:await qe(n,t.redaction,{signal:s.signal,isPro:Ue,sanitizeOnly:Ie,onEgress:f=>Ht.push(tr({ts:Date.now(),client:"redaction",tool:`detect:${f.backend}@${f.host||"local"}`,ok:f.ok,ms:f.ms,error:f.error}))});if(se&&se.lap("redact",l),W.adapter.joinTextParts?.(O),fe=d,qt=m,eo=p||0,m>0&&o.setHeader("x-chatpanel-redacted",String(m)),!Ue&&m>0){Js(t,Ue);try{ue(t,Z())}catch{}}if(!Oe&&!Ie&&Array.isArray(O.tools)&&O.tools.length&&typeof W.adapter.injectSystemNote=="function"){const f=_t(O?.model,t,W.kind,{destination:String(r.headers["x-chatpanel-destination"]||O?.chatpanel?.destination||"").trim(),down:S=>!!S.service&&Y.fn(S.id)==="down"}),g=!(f&&f.type==="api");W.adapter.injectSystemNote(O,Cr({toolData:t.tools?.toolData,ownTools:g}))}else!Oe&&m>0&&typeof W.adapter.injectSystemNote=="function"&&W.adapter.injectSystemNote(O,Ir());Ze=Buffer.from(JSON.stringify(O),"utf8")}}const ro=Dr({vault:fe,toolData:t.tools?.toolData}),dt=O&&typeof O.chatpanel=="object"&&O.chatpanel||null;if(dt&&(delete O.chatpanel,Ze=Buffer.from(JSON.stringify(O),"utf8")),typeof O?.model=="string"&&O.model.startsWith("fusion:")){const e=la(O.model,t,await q());if(e?.error)return se?.commit(),a(o,400,{error:{message:e.error,type:"fusion"}});e&&(O.model=e.model,Ze=Buffer.from(JSON.stringify(O),"utf8"),o.setHeader("x-chatpanel-fusion",`${e.fusion.id} -> ${e.model}`))}const ie={destination:String(r.headers["x-chatpanel-destination"]||dt?.destination||"").trim(),reach:String(r.headers["x-chatpanel-reach"]||dt?.reach||"").trim(),run:Zt(r.headers["x-chatpanel-run"],dt?.run)},ct=await q(),no=e=>!!e.service&&ct(e.id)==="down";let B=_t(O?.model,t,W.kind,{destination:ie.destination,down:no});B?.type==="agent"&&O?.model&&!ie.destination&&!Ys(B,O.model)&&(await Qs(t,{serviceHealth:async()=>ct,engineAt:M.engineAt}),B=_t(O?.model,t,W.kind,{destination:ie.destination,down:no}));const ao=B?.service&&ct(B.id)==="down"?await I().revive(B.service).catch(()=>null):null;if(ao?.ok&&(Y.at=0),B?.service&&ct(B.id)==="down"&&!ao?.ok)return se?.commit(),a(o,503,{error:{message:`${B.id} is not running — the model ${JSON.stringify(O?.model||"")} is served by an engine the Runtime has stopped; start it under Settings › Runtime`,type:"engine_down",service:B.service}});if(ie.destination&&(!B||B.id!==ie.destination))return se?.commit(),a(o,404,{error:{message:`no destination "${ie.destination}" is configured on this gateway`,type:"unknown_destination",known:Ks(t).map(e=>e.id)}});const de=Me(r.headers);if(de&&!ja(de,B?.type==="api"?"api":"agent"))return se?.commit(),a(o,403,{error:{message:`link: partner "${de.partner}" may not use ${B?.type==="api"?"this model":"this computer’s coding agents"} — its scopes are ${de.scopes.join(", ")||"none"}; the owner grants agents at pairing`,type:"forbidden",code:"link_scope"}});const ut=de&&W.redactable&&r.method==="POST"&&O?{caller:de,surface:ea(de,de.kind==="partner"?"":E?.deviceNameOf(de.device)),model:O.model||null,startedAt:br}:null;se&&(se.meta={t:Date.now(),model:O?.model||null,dest:B?B.id:null,type:B?B.type:null,redacted:qt,sanitized:eo,narrowed:to,detail:dr(fe,t.logDetail),redaction:Oe?"off":Ie?`on-device (${oo})`:t.redaction.tier||"basic",...de?.kind==="partner"?{via:Ga(de)}:{}});const mt=yt();if(mt&&B){const e=B.type==="api"?fo(mt,{model:O?.model||"",endpoint:B.baseUrl||""}):Zr(mt,B.agent||B.id)?fo(mt,{model:O?.model||""}):{ok:!1,reason:`agent "${B.agent||B.id}" is not allowed by your organisation’s policy`};if(!e.ok)return se?.commit(),a(o,403,{error:{message:e.reason,type:"policy",code:"org_policy"}})}if(B&&B.type==="api")return B.baseUrl?mi(B.baseUrl,t)?(se?.commit(),a(o,508,{error:{message:`destination "${B.id}" points back at the gateway (${B.baseUrl}) — refusing to forward (would loop).`,type:"loop_detected"}})):Si(r,o,{...W,pathname:i,search:y.search,base:B.baseUrl,destKey:B.apiKey,destProtocol:B.protocol,harness:ro,trace:se,link:ut&&{...ut,agentId:B.id,dest:{type:"api",id:B.id}}},Ze,fe):(se?.commit(),a(o,502,{error:`destination "${B.id}" has no baseUrl`}));const Pt=et(r),so=Pt==="local"&&t.bridge?.openAgentLane?"token":Pt;if(so==="local")return se?.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 io=Math.max(0,Math.min(8,Number(r.headers["x-chatpanel-ask-depth"])||0)),kr=new Set(["thread","ephemeral","workingDir","worker"]),$t=de?.kind==="partner";if(Pt==="token"&&r.headers["x-chatpanel-link-device"]&&!$t&&!(ie.run&&Object.keys(ie.run).some(e=>!kr.has(e)))){const e=Zt(null,Eo(Oo(me.get("agentTools").agentTools?.value,B?.agent||O?.model)));e&&(ie.run={...e,...ie.run||{}})}if($t){const e=Zt(null,Eo(Oo(me.get("agentTools").agentTools?.value,B?.agent||O?.model)));ie.run={...e||{},...za(ie.run,de.device)};const n=E?.partnerFolderOf(de.device);if(!n)return se?.commit(),a(o,403,{error:{message:"link: this partner has no folder on this computer — pair it again with agents",type:"forbidden",code:"link_scope"}});ie.run.workingDir=n,ie.reach="",Array.isArray(O?.tools)&&(O.tools=O.tools.filter(s=>!Jo(s?.function?.name??s?.name)))}const He=Jr({...ie.run||{},...ie.reach?{reach:ie.reach}:{},...io?{askDepth:io}:{}},so);He.reach&&o.setHeader("x-chatpanel-reach-used",He.reach);const vr=$t?{inbox:x,partner:de.partner,device:de.device,conversation:He.thread?.id||null}:null,Sr=ut&&{...ut,dest:{type:"agent",id:B?.id||"bridge"},threadId:He.thread?.id||null};return gi(r,o,{...W,pathname:i,agentOverride:B?.agent,harness:ro,trace:se,run:Object.keys(He).length?He:null,owner:vr,link:Sr},O,fe,t,Ue)});return Be.on("close",()=>{H?.stop("closed"),wa(),k.close(),E?.stop(),x.stop()}),Be.on("upgrade",(r,o,y)=>{o.on("error",()=>{});const i=String(r.url||"").split("?")[0];if(E&&i.startsWith(Ra)){E.acceptTunnel(r,o,y).catch(()=>{try{o.destroy()}catch{}});return}try{o.end(`HTTP/1.1 404 Not Found\r
64
64
  connection: close\r
65
65
  content-length: 0\r
66
66
  \r
67
- `)}catch{}}),Be.once("listening",()=>{I()}),Be.linkHost=E,Be.teamBuckets=ze,Be.runtimeDefaults=()=>I().ensureDefaults(),Be}function Zt(t,c){let u=c&&typeof c=="object"?c:null;if(!u&&t)try{u=JSON.parse(decodeURIComponent(String(t)))}catch{u=null}if(!u||typeof u!="object")return null;const h={};if(Array.isArray(u.grants)&&(h.grants=u.grants.map(v=>String(v).slice(0,80)).slice(0,32)),u.workspace&&typeof u.workspace=="object"&&u.workspace.repo){const v=u.workspace;h.workspace={repo:String(v.repo).slice(0,400),projectId:String(v.projectId||"").slice(0,120),jobId:String(v.jobId||"").slice(0,120),...v.base?{base:String(v.base).slice(0,120)}:{}}}if(u.connectionId&&(h.connectionId=String(u.connectionId).slice(0,64)),typeof u.workingDir=="string"&&u.workingDir.trim()&&/^([A-Za-z]:[\\/]|\/)/.test(u.workingDir.trim())&&(h.workingDir=u.workingDir.trim().slice(0,1024)),Gs.includes(u.permissionMode)&&u.permissionMode!=="default"&&(h.permissionMode=u.permissionMode),u.sandbox&&typeof u.sandbox=="object"){const v=(Array.isArray(u.sandbox.hosts)?u.sandbox.hosts:String(u.sandbox.hosts||"").split(/[\s,;]+/)).map(k=>String(k).trim().toLowerCase().slice(0,253)).filter(Boolean).slice(0,64),N=(Array.isArray(u.sandbox.write)?u.sandbox.write:[]).map(k=>String(k).slice(0,1024)).filter(Boolean).slice(0,32),M=u.sandbox.outside===!0,$=(Array.isArray(u.sandbox.signIn)?u.sandbox.signIn:[]).map(k=>String(k).trim().toLowerCase().slice(0,32)).filter(Boolean).slice(0,8);(v.length||N.length||M||$.length)&&(h.sandbox={...v.length?{hosts:v}:{},...N.length?{write:N}:{},...M?{outside:!0}:{},...$.length?{signIn:$}:{}})}const w=Sn(u.thread);return w&&(h.thread=w),u.ephemeral===!0&&(h.ephemeral=!0),u.worker===!0&&(h.worker=!0,h.ephemeral=!0),u.lean===!0&&(h.lean=!0,h.ephemeral=!0),Object.keys(h).length?h:null}let it=null,Et=null;async function Bd(t=co()){yn();let c=null;try{c=await Yr()}catch(k){throw k instanceof Xr&&(console.error(`[chatpanel-gateway] org policy: ${k.message}`),process.exit(78)),k}const u=c?.policy||null;u&&(yo(t,u),console.log(`[chatpanel-gateway] ${c.label} — ${c.signed?"signed":"unsigned"} policy from ${c.source}`));const h=Kr({enabled:ho(t)});console.log(`[chatpanel-gateway] certificates: ${h.on?`this computer's list is trusted too (${h.added} added to the runtime's own)`:`the runtime's own list only — ${h.why}`}`),Fr(globalThis,{allow:u?.egress?(k,{local:x})=>qr(u,k,{local:x}):null}),Pe();const w=Si(t),v=mn(t),N=Or(t);let M=!1;w.on("error",k=>{if(k&&k.code==="EADDRINUSE"){const x=Ot(t.host)?"127.0.0.1":t.host;fetch(`http://${x}:${t.port}/health`,{signal:AbortSignal.timeout(1500)}).then(C=>C.ok?C.json():null).catch(()=>null).then(C=>{const E=!!(C?.version&&typeof C.tier=="string"),F=Tn({name:"gateway",self:le,holder:E?{ours:E,version:C.version}:null,managedBy:xn(process.env),port:t.port});if(F.action==="standby"||M&&!C){if(!M)for(const D of F.lines)console.error(D);M=!0,setTimeout(()=>w.listen(t.port,t.host),_n);return}if(E){const D=C.managedBy?` (run by ${C.managedBy})`:"";for(const[H,U]of F.lines.entries())console.error(H===0?U.replace(` on ${t.port}`,` at http://${x}:${t.port}${D}`):U)}else{const D=Ln(t.port);console.error(`Port ${t.port} is held by ${D||"another program"}, which is not a ChatPanel gateway.`),console.error(`Fix: stop that program, or set a different port — edit "port" in ${Z()} (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: ${k?.message||k}`),process.exit(1)}),w.listen(t.port,t.host,()=>{if(M&&console.log(" standby : the other gateway is gone — this copy has the port now"),M=!1,console.log(`ChatPanel Privacy Gateway v${le} on http://${t.host}:${t.port}`),w.linkHost?.start().catch(k=>console.log(` link : not started (${k?.message||k})`)),(t.context?.providers||[]).some(k=>k?.kind==="bucket"&&k.enabled!==!1))try{w.teamBuckets?.().start()}catch(k){console.log(` team : not started (${k?.message||k})`)}w.runtimeDefaults?.().then(k=>{for(const x of k||[])console.log(` ${x.label.toLowerCase().padEnd(9).slice(0,9)}: ${x.ok?x.already?"running":x.adopted?"already running — adopted":"started":`not started (${x.skipped})`}`)}).catch(k=>console.log(` runtime : defaults not started (${k?.message||k})`)),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");for(const k of Us(t))console.log(` ⚠ sandbox : ${k}`);console.log(` confined : ${Vn(at({stateDir:Le.dirname(Z())}))}`),Et={mode:"starting",version:null,pid:null,restarts:0,why:"deciding: adopt the bridge that answers, or start ours"},Jn(t,{childEnv:()=>({...zs(t,process.env,yt()),...js(t)})}).then(k=>{it=k}).catch(k=>{Et={mode:"off",version:null,pid:null,restarts:0,why:`not supervised (${k?.message||k})`},console.log(` bridge : not supervised (${k?.message||k})`)}),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…)":"")),Ot(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.`)}),xo()&&Ct(G,Nt()).then(k=>{k?.ok&&(console.log(` warm : seeded ${k.ingested} records from ${k.file}`),k.whole&&We())}).catch(()=>{});const $=()=>{v?.stop(),N.stop(),it?.stop(),qs(w)};return process.on("SIGINT",$),process.on("SIGTERM",$),w}export{mi as RECORDS_MAX_BYTES,Cd as VERSION,Si as createGateway,gi as joinUpstream,Vt as parseAgentModel,Bd as start};
67
+ `)}catch{}}),Be.once("listening",()=>{I()}),Be.linkHost=E,Be.teamBuckets=ze,Be.runtimeDefaults=()=>I().ensureDefaults(),Be}function Zt(t,c){let u=c&&typeof c=="object"?c:null;if(!u&&t)try{u=JSON.parse(decodeURIComponent(String(t)))}catch{u=null}if(!u||typeof u!="object")return null;const h={};if(Array.isArray(u.grants)&&(h.grants=u.grants.map(v=>String(v).slice(0,80)).slice(0,32)),u.workspace&&typeof u.workspace=="object"&&u.workspace.repo){const v=u.workspace;h.workspace={repo:String(v.repo).slice(0,400),projectId:String(v.projectId||"").slice(0,120),jobId:String(v.jobId||"").slice(0,120),...v.base?{base:String(v.base).slice(0,120)}:{}}}if(u.connectionId&&(h.connectionId=String(u.connectionId).slice(0,64)),typeof u.workingDir=="string"&&u.workingDir.trim()&&/^([A-Za-z]:[\\/]|\/)/.test(u.workingDir.trim())&&(h.workingDir=u.workingDir.trim().slice(0,1024)),zs.includes(u.permissionMode)&&u.permissionMode!=="default"&&(h.permissionMode=u.permissionMode),u.sandbox&&typeof u.sandbox=="object"){const v=(Array.isArray(u.sandbox.hosts)?u.sandbox.hosts:String(u.sandbox.hosts||"").split(/[\s,;]+/)).map(k=>String(k).trim().toLowerCase().slice(0,253)).filter(Boolean).slice(0,64),N=(Array.isArray(u.sandbox.write)?u.sandbox.write:[]).map(k=>String(k).slice(0,1024)).filter(Boolean).slice(0,32),M=u.sandbox.outside===!0,$=(Array.isArray(u.sandbox.signIn)?u.sandbox.signIn:[]).map(k=>String(k).trim().toLowerCase().slice(0,32)).filter(Boolean).slice(0,8);(v.length||N.length||M||$.length)&&(h.sandbox={...v.length?{hosts:v}:{},...N.length?{write:N}:{},...M?{outside:!0}:{},...$.length?{signIn:$}:{}})}const w=Sn(u.thread);return w&&(h.thread=w),u.ephemeral===!0&&(h.ephemeral=!0),u.worker===!0&&(h.worker=!0,h.ephemeral=!0),u.lean===!0&&(h.lean=!0,h.ephemeral=!0),Object.keys(h).length?h:null}let it=null,Et=null;async function Md(t=co()){yn();let c=null;try{c=await Yr()}catch(k){throw k instanceof Xr&&(console.error(`[chatpanel-gateway] org policy: ${k.message}`),process.exit(78)),k}const u=c?.policy||null;u&&(yo(t,u),console.log(`[chatpanel-gateway] ${c.label} — ${c.signed?"signed":"unsigned"} policy from ${c.source}`));const h=Kr({enabled:ho(t)});console.log(`[chatpanel-gateway] certificates: ${h.on?`this computer's list is trusted too (${h.added} added to the runtime's own)`:`the runtime's own list only — ${h.why}`}`),Fr(globalThis,{allow:u?.egress?(k,{local:x})=>qr(u,k,{local:x}):null}),Pe();const w=Ti(t),v=mn(t),N=Or(t);let M=!1;w.on("error",k=>{if(k&&k.code==="EADDRINUSE"){const x=Ot(t.host)?"127.0.0.1":t.host;fetch(`http://${x}:${t.port}/health`,{signal:AbortSignal.timeout(1500)}).then(C=>C.ok?C.json():null).catch(()=>null).then(C=>{const E=!!(C?.version&&typeof C.tier=="string"),F=Tn({name:"gateway",self:le,holder:E?{ours:E,version:C.version}:null,managedBy:xn(process.env),port:t.port});if(F.action==="standby"||M&&!C){if(!M)for(const D of F.lines)console.error(D);M=!0,setTimeout(()=>w.listen(t.port,t.host),_n);return}if(E){const D=C.managedBy?` (run by ${C.managedBy})`:"";for(const[H,U]of F.lines.entries())console.error(H===0?U.replace(` on ${t.port}`,` at http://${x}:${t.port}${D}`):U)}else{const D=Ln(t.port);console.error(`Port ${t.port} is held by ${D||"another program"}, which is not a ChatPanel gateway.`),console.error(`Fix: stop that program, or set a different port — edit "port" in ${Z()} (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: ${k?.message||k}`),process.exit(1)}),w.listen(t.port,t.host,()=>{if(M&&console.log(" standby : the other gateway is gone — this copy has the port now"),M=!1,console.log(`ChatPanel Privacy Gateway v${le} on http://${t.host}:${t.port}`),w.linkHost?.start().catch(k=>console.log(` link : not started (${k?.message||k})`)),(t.context?.providers||[]).some(k=>k?.kind==="bucket"&&k.enabled!==!1))try{w.teamBuckets?.().start()}catch(k){console.log(` team : not started (${k?.message||k})`)}w.runtimeDefaults?.().then(k=>{for(const x of k||[])console.log(` ${x.label.toLowerCase().padEnd(9).slice(0,9)}: ${x.ok?x.already?"running":x.adopted?"already running — adopted":"started":`not started (${x.skipped})`}`)}).catch(k=>console.log(` runtime : defaults not started (${k?.message||k})`)),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");for(const k of Hs(t))console.log(` ⚠ sandbox : ${k}`);console.log(` confined : ${Vn(at({stateDir:Le.dirname(Z())}))}`),Et={mode:"starting",version:null,pid:null,restarts:0,why:"deciding: adopt the bridge that answers, or start ours"},Jn(t,{childEnv:()=>({...Us(t,process.env,yt()),...Gs(t)})}).then(k=>{it=k}).catch(k=>{Et={mode:"off",version:null,pid:null,restarts:0,why:`not supervised (${k?.message||k})`},console.log(` bridge : not supervised (${k?.message||k})`)}),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…)":"")),Ot(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.`)}),xo()&&Ct(G,Nt()).then(k=>{k?.ok&&(console.log(` warm : seeded ${k.ingested} records from ${k.file}`),k.whole&&We())}).catch(()=>{});const $=()=>{v?.stop(),N.stop(),it?.stop(),ei(w)};return process.on("SIGINT",$),process.on("SIGTERM",$),w}export{pi as RECORDS_MAX_BYTES,Id as VERSION,Ti as createGateway,wi as joinUpstream,Vt as parseAgentModel,Md as start};
package/src/version.js CHANGED
@@ -1 +1 @@
1
- const o="0.168.0";export{o as VERSION};
1
+ const o="0.168.1";export{o as VERSION};