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