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