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