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