@chatpanel/gateway 0.52.3 → 0.53.0

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