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