@chatpanel/gateway 0.104.0 → 0.105.1

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.104.0",
3
+ "version": "0.105.1",
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": {
@@ -24,7 +24,7 @@
24
24
  "dependencies": {
25
25
  "@anthropic-ai/sandbox-runtime": "^0.0.77",
26
26
  "@chatpanel/bridge": "^0.47.0",
27
- "@chatpanel/events": "^0.372.0",
27
+ "@chatpanel/events": "^0.374.0",
28
28
  "@chatpanel/pii": "^0.15.0",
29
29
  "@huggingface/transformers": "^4.2.0",
30
30
  "defuddle": "^0.19.4",
@@ -1,4 +1,4 @@
1
- import{join as T}from"node:path";import{mkdirSync as O,chmodSync as A,existsSync as L}from"node:fs";import f from"node:os";import{openDb as S}from"./sqlite-store.js";import{validateEvent as C,EventError as M}from"./event.js";const p=T(f.homedir(),".chatpanel"),m=process.env.CHATPANEL_EVENTS_DB||T(p,"events.db"),I=25e3,d=2e4,y=250,b=16e3,a=1e3,D=`
1
+ import{join as T}from"node:path";import{mkdirSync as N,chmodSync as L,existsSync as f}from"node:fs";import A from"node:os";import{openDb as S}from"./sqlite-store.js";import{validateEvent as C,EventError as M}from"./event.js";const u=T(A.homedir(),".chatpanel"),b=process.env.CHATPANEL_EVENTS_DB||T(u,"events.db"),m=25e3,R=2e4,I=250,D=16e3,r=1e3,y=`
2
2
  CREATE TABLE IF NOT EXISTS events (
3
3
  id TEXT PRIMARY KEY,
4
4
  host TEXT NOT NULL,
@@ -12,4 +12,4 @@ CREATE TABLE IF NOT EXISTS events (
12
12
  );
13
13
  CREATE INDEX IF NOT EXISTS events_at ON events (at, host, seq);
14
14
  CREATE INDEX IF NOT EXISTS events_type ON events (type, at);
15
- `;class _{constructor({path:t=m,now:s=()=>Date.now()}={}){this.path=t,this.now=s,this.db=null,this._sinceCheck=0,this._watchers=new Set}async init(){if(this.path!==":memory:"){O(p,{recursive:!0,mode:448});const t=!L(this.path);if(this.db=await S(this.path),t)try{A(this.path,384)}catch{}}else this.db=await S(this.path);return this.db.exec("PRAGMA journal_mode = WAL"),this.db.exec(D),this}append(t){if(C(t),this.db.get("SELECT 1 AS x FROM events WHERE id = ?",[t.id]))return{appended:!1,event:t};const s=this.db.get("SELECT MAX(seq) AS seq FROM events WHERE host = ?",[t.host])?.seq;if(Number.isFinite(s)&&s!==null&&t.seq<=s)throw new M("SEQ",`seq ${t.seq} <= ${s} already seen for host ${t.host}`,t.host);let e=JSON.stringify(t.payload);e.length>b&&(e=JSON.stringify({_clipped:!0,_chars:e.length,...q(t.payload)})),this.db.run("INSERT INTO events (id, host, seq, at, type, causes, payload, v) VALUES (?, ?, ?, ?, ?, ?, ?, ?)",[t.id,t.host,t.seq,t.at,t.type,JSON.stringify(t.causes),e,t.v]),this._sinceCheck+=1,this._sinceCheck>=y&&(this._sinceCheck=0,this.prune());for(const h of this._watchers)try{h(t)}catch{}return{appended:!0,event:t}}cursor(){const t={};for(const s of this.db.all("SELECT host, MAX(seq) AS seq FROM events GROUP BY host ORDER BY host"))t[s.host]=s.seq;return t}since(t={},{limit:s=a,host:e=null}={}){const h=Math.max(1,Math.min(a,Number(s)||a)),u=e?[e]:this.db.all("SELECT DISTINCT host FROM events ORDER BY host").map(n=>n.host),r=[];let i=!1;for(const n of u){if(r.length>=h){i=!0;break}const R=Number.isInteger(t?.[n])?t[n]:-1,c=this.db.all("SELECT * FROM events WHERE host = ? AND seq > ? ORDER BY seq ASC LIMIT ?",[n,R,h-r.length+1]);c.length>h-r.length&&(i=!0,c.length=h-r.length);for(const N of c)r.push(l(N))}const E={...t};for(const n of r)E[n.host]=Math.max(E[n.host]??-1,n.seq);return{events:r,cursor:E,more:i}}recent({limit:t=200,type:s=null}={}){const e=Math.max(1,Math.min(a,Number(t)||200));return(s?this.db.all("SELECT * FROM events WHERE type = ? ORDER BY at DESC, seq DESC LIMIT ?",[s,e]):this.db.all("SELECT * FROM events ORDER BY at DESC, host DESC, seq DESC LIMIT ?",[e])).map(l)}all(){return this.db.all("SELECT * FROM events ORDER BY at ASC, host ASC, seq ASC").map(l)}count(){return this.db.get("SELECT COUNT(*) AS n FROM events")?.n||0}hosts(){return this.db.all("SELECT host, COUNT(*) AS n, MAX(seq) AS seq, MAX(at) AS at FROM events GROUP BY host ORDER BY host")}prune(){const t=this.count();return t<=I?0:(this.db.run("DELETE FROM events WHERE id IN (SELECT id FROM events ORDER BY at ASC, host ASC, seq ASC LIMIT ?)",[t-d]),t-d)}watch(t){return this._watchers.add(t),()=>this._watchers.delete(t)}clear(){this.db.exec("DELETE FROM events")}}function l(o){return{v:o.v??1,id:o.id,host:o.host,seq:o.seq,at:o.at,type:o.type,causes:JSON.parse(o.causes||"[]"),payload:JSON.parse(o.payload)}}function q(o){const t={};for(const[s,e]of Object.entries(o||{}))t[s]=typeof e=="string"&&e.length>2e3?`${e.slice(0,2e3)}…`:e;return t}async function X(o={}){try{return await new _(o).init()}catch(t){return console.log(`[events] SQLite unavailable (${t.message}); the event log is off`),null}}export{_ as EventStore,I as MAX_EVENTS,a as PAGE_LIMIT,d as PRUNE_TO,X as createEventStore};
15
+ `;class _{constructor({path:t=b,now:s=()=>Date.now()}={}){this.path=t,this.now=s,this.db=null,this._sinceCheck=0,this._watchers=new Set}async init(){if(this.path!==":memory:"){N(u,{recursive:!0,mode:448});const t=!f(this.path);if(this.db=await S(this.path),t)try{L(this.path,384)}catch{}}else this.db=await S(this.path);return this.db.exec("PRAGMA journal_mode = WAL"),this.db.exec(y),this}append(t){if(C(t),this.db.get("SELECT 1 AS x FROM events WHERE id = ?",[t.id]))return{appended:!1,event:t};const s=this.db.get("SELECT MAX(seq) AS seq FROM events WHERE host = ?",[t.host])?.seq;if(Number.isFinite(s)&&s!==null&&t.seq<=s)throw new M("SEQ",`seq ${t.seq} <= ${s} already seen for host ${t.host}`,t.host);let e=JSON.stringify(t.payload);e.length>D&&(e=JSON.stringify({_clipped:!0,_chars:e.length,...q(t.payload)})),this.db.run("INSERT INTO events (id, host, seq, at, type, causes, payload, v) VALUES (?, ?, ?, ?, ?, ?, ?, ?)",[t.id,t.host,t.seq,t.at,t.type,JSON.stringify(t.causes),e,t.v]),this._sinceCheck+=1,this._sinceCheck>=I&&(this._sinceCheck=0,this.prune());for(const E of this._watchers)try{E(t)}catch{}return{appended:!0,event:t}}cursor(){const t={};for(const s of this.db.all("SELECT host, MAX(seq) AS seq FROM events GROUP BY host ORDER BY host"))t[s.host]=s.seq;return t}since(t={},{limit:s=r,host:e=null}={}){const E=Math.max(1,Math.min(r,Number(s)||r)),d=e?[e]:this.db.all("SELECT DISTINCT host FROM events ORDER BY host").map(o=>o.host),h=[];let i=!1;for(const o of d){if(h.length>=E){i=!0;break}const O=Number.isInteger(t?.[o])?t[o]:-1,c=this.db.all("SELECT * FROM events WHERE host = ? AND seq > ? ORDER BY seq ASC LIMIT ?",[o,O,E-h.length+1]);c.length>E-h.length&&(i=!0,c.length=E-h.length);for(const p of c)h.push(l(p))}const a={...t};for(const o of h)a[o.host]=Math.max(a[o.host]??-1,o.seq);return{events:h,cursor:a,more:i}}recent({limit:t=200,type:s=null}={}){const e=Math.max(1,Math.min(r,Number(t)||200));return(s?this.db.all("SELECT * FROM events WHERE type = ? ORDER BY at DESC, seq DESC LIMIT ?",[s,e]):this.db.all("SELECT * FROM events ORDER BY at DESC, host DESC, seq DESC LIMIT ?",[e])).map(l)}all(){return this.db.all("SELECT * FROM events ORDER BY at ASC, host ASC, seq ASC").map(l)}count(){return this.db.get("SELECT COUNT(*) AS n FROM events")?.n||0}hosts(){return this.db.all("SELECT host, COUNT(*) AS n, MAX(seq) AS seq, MAX(at) AS at FROM events GROUP BY host ORDER BY host")}prune(){const t=this.count();return t<=m?0:(this.db.run("DELETE FROM events WHERE id IN (SELECT id FROM events ORDER BY at ASC, host ASC, seq ASC LIMIT ?)",[t-R]),t-R)}watch(t){return this._watchers.add(t),()=>this._watchers.delete(t)}clear(){this.db.exec("DELETE FROM events")}countOf(t=null){return(t===null?this.db.get("SELECT COUNT(*) AS n FROM events"):this.db.get("SELECT COUNT(*) AS n FROM events WHERE host = ?",[t]))?.n||0}deleteOf(t=null){const s=this.countOf(t);return t===null?this.db.exec("DELETE FROM events"):this.db.run("DELETE FROM events WHERE host = ?",[t]),s}}function l(n){return{v:n.v??1,id:n.id,host:n.host,seq:n.seq,at:n.at,type:n.type,causes:JSON.parse(n.causes||"[]"),payload:JSON.parse(n.payload)}}function q(n){const t={};for(const[s,e]of Object.entries(n||{}))t[s]=typeof e=="string"&&e.length>2e3?`${e.slice(0,2e3)}…`:e;return t}async function X(n={}){try{return await new _(n).init()}catch(t){return console.log(`[events] SQLite unavailable (${t.message}); the event log is off`),null}}export{_ as EventStore,m as MAX_EVENTS,r as PAGE_LIMIT,R as PRUNE_TO,X as createEventStore};
package/src/server.js CHANGED
@@ -1,64 +1,67 @@
1
- import{createServer as Yo}from"node:http";import{loadConfig as Ut}from"./config.js";import{startEntitlementRefresh as Qo,maybeRevalidate as Xo}from"./entitlement-refresh.js";import{redactSegments as Qe,segment as ut,rememberAnswer as Vt}from"./redact.js";import{pipeRestoredStream as Zo,pipeRestoredOpenAIStream as qo,makeTokenRestorer as Ft,restoreDeep as er}from"./stream.js";import{restoreText as tr,gatedDictionary as or,narrowSpecs as rr,makeToolHarness as nr,placeholderToolNote as ar,placeholderNote as sr,assertEndpointUrl as ir,capRunOptions as lr,isPaired as Wt}from"@chatpanel/pii";import{ensureGatewayToken as _e,currentGatewayToken as Be,isAdminAuthorized as U,callerTrustOf as Ie,setPinnedExtensionIds as dr,issuePairingCode as cr,claimPairingCode as ur}from"./gateway-token.js";import{createPairAsk as mr,nativeConfirm as pr}from"./pair-prompt.js";import{createEngineProbe as hr}from"./local-engine-probe.js";import{randomUUID as yr}from"node:crypto";import{installEgressLedger as fr,egressAudit as gr}from"./egress.js";import{trustSystemCertificates as wr,systemCaWanted as Kt,systemCaState as br}from"./system-ca.js";import{initPolicy as kr,activePolicy as Xe,applyPolicyToConfig as Yt,managedSummary as Re,PolicyLoadError as vr}from"./policy.js";import{routeAllowed as Qt,agentAllowed as Sr,egressAllowed as Tr}from"@chatpanel/events/policy.js";import{resolveBridgeUrl as je}from"./bridge.js";import{secureFetch as Ze}from"./secure-fetch.js";import{fetchCard as qe,forgetCard as xr,sendMessage as _r,streamMessage as Or,getTask as Er,cancelTask as Pr,knownAgents as $r,A2AError as Xt}from"./a2a.js";import{streamBridgeChat as Zt,readBridgeToken as Je,openBridgeChat as Ar,acceptedBridgeToken as qt}from"./bridge.js";import{createRelaySession as Nr,getRelaySession as eo,endRelaySession as Le,pumpBridgeStream as Br,deliverToolResult as to,toolsToSpecs as Mr,wantsApprovals as Dr,parseToolCallId as oo,touchRelaySession as et}from"./toolrelay.js";import{shaperFor as mt}from"./shape.js";import{startNer as Cr,ensureNer as tt,unionForThisMachine as Ir,skippedCompanions as Rr}from"./ner.js";import{recommendDetector as ro}from"@chatpanel/pii/detector-router.js";import{installTimestampedConsole as jr}from"./log.js";import{saveBackupSecret as Jr,clearBackupSecret as Lr,loadBackupSecret as pt,hasBackupSecret as no}from"./history-store.js";import{createMemoryStore as zr}from"./memory-store.js";import{createPrefsStore as Gr}from"./prefs-store.js";import{agentCardFor as ao,runHintFor as so}from"@chatpanel/events/agent-run-hint.js";import{normalizeThread as Hr}from"@chatpanel/events/agent-thread.js";import{portClashPlan as Ur,serviceManagerOf as Vr,STANDBY_POLL_MS as Fr}from"@chatpanel/events/service-standby.js";import{threadTarget as Wr,frameQuestion as Kr,wireMessages as Yr,appendExchange as Qr,MAX_MESSAGE as io}from"@chatpanel/events/thread-send.js";import{researchStore as Xr,researchResponse as Zr}from"./research.js";import{createTeamStore as qr,loadOrCreateKey as ht}from"./team-store.js";import{createScorecardStore as en}from"./scorecard-store.js";import{createEngineLedgerStore as tn}from"./engine-ledger-store.js";import{createProjectStore as on}from"./project-store.js";import{applicationsFor as rn,recruitPass as nn}from"./recruiting.js";import{ensureBridge as an,holderOf as sn}from"./bridge-supervisor.js";import{checkForUpdate as ln,updateStatus as dn,startUpdate as cn,updateJob as un,installKind as mn}from"./update.js";import{confinedStatus as yt,confinedLine as pn}from"./confine.js";import{appleHelperWanted as hn,findAppleHelper as ft}from"./apple-helper-fetch.js";import{createHistoryStore as yn}from"./sqlite-store.js";import{createEventStore as fn}from"./event-store.js";import{createLinkActivity as gn,linkSurface as wn,sseUsageTap as bn,usageOfBody as kn,GATEWAY_HOST as lo}from"./link-activity.js";import{ingestCloudEvents as vn,cursorOf as co}from"./event-sync.js";import{eventStats as Sn,projectYear as Tn}from"./event-stats.js";import{toCloudEvent as gt,ceHostOf as xn}from"./cloudevents.js";import{fusionsDocument as _n,resolveFusionModel as On}from"./fusions.js";import{ingestBackups as wt}from"./backup-ingest.js";import{toSearchRecord as uo}from"@chatpanel/events/library.js";import{deriveBackupKey as En,openRecord as Pn,keyCache as $n,nodeCodec as An}from"@chatpanel/events/backup-envelope.js";import Nn from"node:zlib";import*as I from"./ner-engine.js";import bt from"node:os";import{capabilitiesDocument as Bn,handleDetect as Mn}from"./capabilities.js";import{createExtractService as Dn}from"./extract/service.js";import{workerSandbox as Cn,disposeWorkerSandbox as In}from"./worker-sandbox.js";import{createRuntime as Rn,SERVICES as jn}from"./runtime.js";import{createCapabilityProxy as Jn}from"./capability-proxy.js";import{createEmbeddedCapabilities as Ln}from"./capability-embedded.js";import{EMBEDDED_MODELS as zn,EMBEDDED_IDS as Gn}from"./embedded-models.js";import{handleExtract as Hn,handleExtractContext as Un}from"./extract/handler.js";import{createKbStore as Vn}from"./kb-store.js";import{createKbService as Fn}from"./kb.js";import{MAX_DOCUMENT_BYTES as kt}from"./extract-capability.js";import{createReader as Wn}from"./retrieval/read.js";import{createBrowserRelayHost as Kn}from"./browser-relay.js";import{createLinkHost as Yn}from"./link-host.js";import{checkLinkRoute as Qn,tunnelHeader as Xn,LINK_TUNNEL_ROOM_PATH as Zn}from"@chatpanel/events/link-routes.js";import{linkCallerOf as vt,linkDestinationAllowed as qn,linkVia as ea,partnerRunHint as ta,PARTNER_APPROVAL_DECISIONS as mo,partnerFilePath as oa}from"@chatpanel/events/link-scopes.js";import{listPartnerFiles as ra,readPartnerFile as na,writePartnerFile as aa,removePartnerFile as sa}from"./link-files.js";import{handleFileWrite as ia}from"./file-write.js";import{WRITE_MAX_BYTES as la}from"@chatpanel/events/file-write.js";import{isPermissionTool as po}from"@chatpanel/events/agent-permission.js";import{createApprovalInbox as da}from"./link-approvals.js";import{createSearcher as ca,toJinaSearch as ua,SEARCH_DEFAULTS as ma}from"./retrieval/search.js";import{createSearxng as pa}from"./retrieval/search-searxng.js";import{searchEngines as ha}from"./retrieval/search-apis.js";import{toJinaText as ya}from"./read-document.js";import*as $ from"./stt-engine.js";import*as M from"./diarize-engine.js";import*as fa from"./segment-engine.js";import{DIARIZE_MODEL_CATALOG as ga,DEFAULT_DIARIZE_MODEL as wa,isKnownDiarizeModel as ho}from"./diarize-models.js";import{providerOf as St}from"./providers.js";import{createRemoteTranscriber as yo}from"./stt-remote.js";import{parseMultipart as ba,decodeAudioFile as ka}from"./audio-file.js";import{MODEL_CATALOG as fo,isKnownModel as go,isValidCustomModelId as wo,recommendFor as va}from"./models.js";import{STT_MODEL_CATALOG as Sa,isKnownSttModel as Ta,isValidCustomSttId as xa,DEFAULT_STT_MODEL as ot,STT_DTYPES as _a,isValidDtype as Oa,sttModel as Ea,sttModelUnavailable as bo}from"./stt-models.js";import*as D from"./tts-engine.js";import{TTS_MODEL_CATALOG as ko,TTS_VOICES as Pa,isKnownTtsModel as $a,isValidCustomTtsId as Aa,isKnownVoice as vo,isValidVoiceId as So,DEFAULT_TTS_MODEL as To,DEFAULT_TTS_VOICE as Oe,TTS_DTYPES as Na,isValidTtsDtype as Ba,MAX_TTS_CHARS as xo,ttsModelHasCustomVoices as Ma,resolveDefaultModel as _o,POCKET_VOICES as Da,DEFAULT_POCKET_VOICE as rt,isPocketVoice as nt,ttsModelEngine as at}from"./tts-models.js";import{ttsDestination as Ca,synthesizeRemote as Ia,isValidRemoteVoice as Ra}from"./tts-remote.js";import{rawOrtAvailable as Tt}from"./ort.js";import*as pe from"./tts-voices.js";import{resolveTtsVoice as ja}from"./tts-voice-resolve.js";import{resolvePro as Te,checkQuota as Ja,consume as La,usage as za}from"./freegate.js";import{publicConfig as Oo,applyConfigPatch as Ga,registryChildEnv as Ha,applyNerModelSelection as Eo,persistConfig as we,configPath as le,bridgeAgentOptions as Po,PERMISSION_MODES as Ua,sandboxEnvFor as Va,sandboxProblems as Fa}from"./configstore.js";import ze from"node:path";import{resolveDestination as st,aggregateModelsAsync as Wa,listDestinations as Ka,ensureModelCatalog as Ya,agentOwnsModel as Qa}from"./router.js";import{makeAccessEvent as $o}from"./observability.js";import{createPersistentAccessLog as Xa}from"./access-log-store.js";import{planQueries as Za,multiSearch as qa}from"./rrf.js";import*as xt from"./openai.js";import*as Ao from"./responses.js";import*as _t from"./anthropic.js";import{closeAndExit as es}from"./shutdown.js";import{VERSION as de}from"./version.js";import{VERSION as fl}from"./version.js";const R=await yn(),xe=new Set;function Ge({ids:t=[]}={}){const c=R.lossless;if(!c||!xe.size)return;const u=JSON.stringify({newest:c.newest,rev:c.rev,size:c.size,ids:t.slice(0,50),at:Date.now()});for(const m of xe)try{m.write(`event: records
1
+ import{createServer as Qo}from"node:http";import{loadConfig as Ut}from"./config.js";import{startEntitlementRefresh as Yo,maybeRevalidate as Xo}from"./entitlement-refresh.js";import{redactSegments as Ye,segment as ut,rememberAnswer as Vt}from"./redact.js";import{pipeRestoredStream as Zo,pipeRestoredOpenAIStream as qo,makeTokenRestorer as Ft,restoreDeep as er}from"./stream.js";import{restoreText as tr,gatedDictionary as or,narrowSpecs as rr,makeToolHarness as nr,placeholderToolNote as ar,placeholderNote as sr,assertEndpointUrl as ir,capRunOptions as lr,isPaired as Wt}from"@chatpanel/pii";import{ensureGatewayToken as _e,currentGatewayToken as Be,isAdminAuthorized as U,callerTrustOf as Ie,setPinnedExtensionIds as dr,issuePairingCode as cr,claimPairingCode as ur}from"./gateway-token.js";import{createPairAsk as mr,nativeConfirm as pr}from"./pair-prompt.js";import{createEngineProbe as hr}from"./local-engine-probe.js";import{randomUUID as yr}from"node:crypto";import{installEgressLedger as fr,egressAudit as gr}from"./egress.js";import{trustSystemCertificates as wr,systemCaWanted as Kt,systemCaState as br}from"./system-ca.js";import{initPolicy as kr,activePolicy as Xe,applyPolicyToConfig as Qt,managedSummary as Re,PolicyLoadError as vr}from"./policy.js";import{routeAllowed as Yt,agentAllowed as Sr,egressAllowed as Tr}from"@chatpanel/events/policy.js";import{resolveBridgeUrl as je}from"./bridge.js";import{secureFetch as Ze}from"./secure-fetch.js";import{fetchCard as qe,forgetCard as xr,sendMessage as _r,streamMessage as Or,getTask as Er,cancelTask as Pr,knownAgents as $r,A2AError as Xt}from"./a2a.js";import{streamBridgeChat as Zt,readBridgeToken as Je,openBridgeChat as Ar,acceptedBridgeToken as qt}from"./bridge.js";import{createRelaySession as Nr,getRelaySession as eo,endRelaySession as Le,pumpBridgeStream as Br,deliverToolResult as to,toolsToSpecs as Mr,wantsApprovals as Dr,parseToolCallId as oo,touchRelaySession as et}from"./toolrelay.js";import{shaperFor as mt}from"./shape.js";import{startNer as Cr,ensureNer as tt,unionForThisMachine as Ir,skippedCompanions as Rr}from"./ner.js";import{recommendDetector as ro}from"@chatpanel/pii/detector-router.js";import{installTimestampedConsole as jr}from"./log.js";import{saveBackupSecret as Jr,clearBackupSecret as Lr,loadBackupSecret as pt,hasBackupSecret as no}from"./history-store.js";import{createMemoryStore as zr}from"./memory-store.js";import{createPrefsStore as Gr}from"./prefs-store.js";import{agentCardFor as ao,runHintFor as so}from"@chatpanel/events/agent-run-hint.js";import{normalizeThread as Hr}from"@chatpanel/events/agent-thread.js";import{portClashPlan as Ur,serviceManagerOf as Vr,STANDBY_POLL_MS as Fr}from"@chatpanel/events/service-standby.js";import{threadTarget as Wr,frameQuestion as Kr,wireMessages as Qr,appendExchange as Yr,MAX_MESSAGE as io}from"@chatpanel/events/thread-send.js";import{researchStore as Xr,researchResponse as Zr}from"./research.js";import{createTeamStore as qr,loadOrCreateKey as ht}from"./team-store.js";import{createScorecardStore as en}from"./scorecard-store.js";import{createEngineLedgerStore as tn}from"./engine-ledger-store.js";import{createProjectStore as on}from"./project-store.js";import{applicationsFor as rn,recruitPass as nn}from"./recruiting.js";import{ensureBridge as an,holderOf as sn}from"./bridge-supervisor.js";import{checkForUpdate as ln,updateStatus as dn,startUpdate as cn,updateJob as un,installKind as mn}from"./update.js";import{confinedStatus as yt,confinedLine as pn}from"./confine.js";import{appleHelperWanted as hn,findAppleHelper as ft}from"./apple-helper-fetch.js";import{createHistoryStore as yn}from"./sqlite-store.js";import{createEventStore as fn}from"./event-store.js";import{createLinkActivity as gn,linkSurface as wn,sseUsageTap as bn,usageOfBody as kn,GATEWAY_HOST as lo}from"./link-activity.js";import{ingestCloudEvents as vn,cursorOf as co}from"./event-sync.js";import{eventStats as Sn,projectYear as Tn}from"./event-stats.js";import{toCloudEvent as gt,ceHostOf as xn}from"./cloudevents.js";import{fusionsDocument as _n,resolveFusionModel as On}from"./fusions.js";import{ingestBackups as wt}from"./backup-ingest.js";import{toSearchRecord as uo}from"@chatpanel/events/library.js";import{deriveBackupKey as En,openRecord as Pn,keyCache as $n,nodeCodec as An}from"@chatpanel/events/backup-envelope.js";import Nn from"node:zlib";import*as R from"./ner-engine.js";import bt from"node:os";import{capabilitiesDocument as Bn,handleDetect as Mn}from"./capabilities.js";import{createExtractService as Dn}from"./extract/service.js";import{workerSandbox as Cn,disposeWorkerSandbox as In}from"./worker-sandbox.js";import{createRuntime as Rn,SERVICES as jn}from"./runtime.js";import{createCapabilityProxy as Jn}from"./capability-proxy.js";import{createEmbeddedCapabilities as Ln}from"./capability-embedded.js";import{EMBEDDED_MODELS as zn,EMBEDDED_IDS as Gn}from"./embedded-models.js";import{handleExtract as Hn,handleExtractContext as Un}from"./extract/handler.js";import{createKbStore as Vn}from"./kb-store.js";import{createKbService as Fn}from"./kb.js";import{MAX_DOCUMENT_BYTES as kt}from"./extract-capability.js";import{createReader as Wn}from"./retrieval/read.js";import{createBrowserRelayHost as Kn}from"./browser-relay.js";import{createLinkHost as Qn}from"./link-host.js";import{checkLinkRoute as Yn,tunnelHeader as Xn,LINK_TUNNEL_ROOM_PATH as Zn}from"@chatpanel/events/link-routes.js";import{linkCallerOf as vt,linkDestinationAllowed as qn,linkVia as ea,partnerRunHint as ta,PARTNER_APPROVAL_DECISIONS as mo,partnerFilePath as oa}from"@chatpanel/events/link-scopes.js";import{listPartnerFiles as ra,readPartnerFile as na,writePartnerFile as aa,removePartnerFile as sa}from"./link-files.js";import{handleFileWrite as ia}from"./file-write.js";import{WRITE_MAX_BYTES as la}from"@chatpanel/events/file-write.js";import{isPermissionTool as po}from"@chatpanel/events/agent-permission.js";import{createApprovalInbox as da}from"./link-approvals.js";import{createSearcher as ca,toJinaSearch as ua,SEARCH_DEFAULTS as ma}from"./retrieval/search.js";import{createSearxng as pa}from"./retrieval/search-searxng.js";import{searchEngines as ha}from"./retrieval/search-apis.js";import{toJinaText as ya}from"./read-document.js";import*as $ from"./stt-engine.js";import*as M from"./diarize-engine.js";import*as fa from"./segment-engine.js";import{DIARIZE_MODEL_CATALOG as ga,DEFAULT_DIARIZE_MODEL as wa,isKnownDiarizeModel as ho}from"./diarize-models.js";import{providerOf as St}from"./providers.js";import{createRemoteTranscriber as yo}from"./stt-remote.js";import{parseMultipart as ba,decodeAudioFile as ka}from"./audio-file.js";import{MODEL_CATALOG as fo,isKnownModel as go,isValidCustomModelId as wo,recommendFor as va}from"./models.js";import{STT_MODEL_CATALOG as Sa,isKnownSttModel as Ta,isValidCustomSttId as xa,DEFAULT_STT_MODEL as ot,STT_DTYPES as _a,isValidDtype as Oa,sttModel as Ea,sttModelUnavailable as bo}from"./stt-models.js";import*as D from"./tts-engine.js";import{TTS_MODEL_CATALOG as ko,TTS_VOICES as Pa,isKnownTtsModel as $a,isValidCustomTtsId as Aa,isKnownVoice as vo,isValidVoiceId as So,DEFAULT_TTS_MODEL as To,DEFAULT_TTS_VOICE as Oe,TTS_DTYPES as Na,isValidTtsDtype as Ba,MAX_TTS_CHARS as xo,ttsModelHasCustomVoices as Ma,resolveDefaultModel as _o,POCKET_VOICES as Da,DEFAULT_POCKET_VOICE as rt,isPocketVoice as nt,ttsModelEngine as at}from"./tts-models.js";import{ttsDestination as Ca,synthesizeRemote as Ia,isValidRemoteVoice as Ra}from"./tts-remote.js";import{rawOrtAvailable as Tt}from"./ort.js";import*as pe from"./tts-voices.js";import{resolveTtsVoice as ja}from"./tts-voice-resolve.js";import{resolvePro as Te,checkQuota as Ja,consume as La,usage as za}from"./freegate.js";import{publicConfig as Oo,applyConfigPatch as Ga,registryChildEnv as Ha,applyNerModelSelection as Eo,persistConfig as be,configPath as le,bridgeAgentOptions as Po,PERMISSION_MODES as Ua,sandboxEnvFor as Va,sandboxProblems as Fa}from"./configstore.js";import ze from"node:path";import{resolveDestination as st,aggregateModelsAsync as Wa,listDestinations as Ka,ensureModelCatalog as Qa,agentOwnsModel as Ya}from"./router.js";import{makeAccessEvent as $o}from"./observability.js";import{createPersistentAccessLog as Xa}from"./access-log-store.js";import{planQueries as Za,multiSearch as qa}from"./rrf.js";import*as xt from"./openai.js";import*as Ao from"./responses.js";import*as _t from"./anthropic.js";import{closeAndExit as es}from"./shutdown.js";import{VERSION as de}from"./version.js";import{VERSION as fl}from"./version.js";const j=await yn(),xe=new Set;function Ge({ids:t=[]}={}){const c=j.lossless;if(!c||!xe.size)return;const u=JSON.stringify({newest:c.newest,rev:c.rev,size:c.size,ids:t.slice(0,50),at:Date.now()});for(const p of xe)try{p.write(`event: records
2
2
  data: ${u}
3
3
 
4
- `)}catch{xe.delete(m)}}setInterval(()=>{for(const t of xe)try{t.write(`: ping
4
+ `)}catch{xe.delete(p)}}setInterval(()=>{for(const t of xe)try{t.write(`: ping
5
5
 
6
- `)}catch{xe.delete(t)}},25e3).unref?.();const q=await fn(),Ot=gn({store:q,log:t=>console.log(t)}),Pe=new Set;q?.watch(t=>{if(!Pe.size)return;const c=`event: cloudevent
6
+ `)}catch{xe.delete(t)}},25e3).unref?.();const Q=await fn(),Ot=gn({store:Q,log:t=>console.log(t)}),Ee=new Set;Q?.watch(t=>{if(!Ee.size)return;const c=`event: cloudevent
7
7
  data: ${JSON.stringify(gt(t))}
8
8
 
9
- `;for(const u of Pe)try{u.write(c)}catch{Pe.delete(u)}}),setInterval(()=>{for(const t of Pe)try{t.write(`: ping
9
+ `;for(const u of Ee)try{u.write(c)}catch{Ee.delete(u)}}),setInterval(()=>{for(const t of Ee)try{t.write(`: ping
10
10
 
11
- `)}catch{Pe.delete(t)}},25e3).unref?.();const fe=await zr(),ce=Gr(),Me=en({key:ht()}),De=tn({key:ht()}),he=on({key:ht()}),ee=qr({scorecards:Me,engines:De}),Et=new Set,No=(t,c)=>{for(const m of Et)try{m({applied:t,by:c,revision:ce.revision})}catch{}const u=JSON.stringify({revision:ce.revision,applied:(t||[]).slice(0,50),by:c||"",at:Date.now()});for(const m of xe)try{m.write(`event: prefs
11
+ `)}catch{Ee.delete(t)}},25e3).unref?.();const fe=await zr(),ce=Gr(),Me=en({key:ht()}),De=tn({key:ht()}),he=on({key:ht()}),oe=qr({scorecards:Me,engines:De}),Et=new Set,No=(t,c)=>{for(const p of Et)try{p({applied:t,by:c,revision:ce.revision})}catch{}const u=JSON.stringify({revision:ce.revision,applied:(t||[]).slice(0,50),by:c||"",at:Date.now()});for(const p of xe)try{p.write(`event: prefs
12
12
  data: ${u}
13
13
 
14
- `)}catch{xe.delete(m)}},Pt=Xa(),Bo=new Set(["codex","claude","opencode","pi","kiro","antigravity","hermes"]),ts=16,os=/^mcp[_-]/i,Mo=t=>t&&t.function&&t.function.name||t&&t.name||"",rs=t=>t&&t.function&&t.function.description||t&&t.description||"";function Do(t){return typeof t=="string"?t:Array.isArray(t)?t.map(c=>typeof c=="string"?c:c&&(c.text||c.content)||"").join(" "):""}function ns(t,c){if(!t)return"";if(c==="responses"){const m=t.input;return typeof m=="string"?m:Array.isArray(m)?m.map(g=>Do(g&&(g.content??g))).join(" "):""}const u=Array.isArray(t.messages)?t.messages:[];for(let m=u.length-1;m>=0;m--)if(u[m]&&u[m].role==="user")return Do(u[m].content);return""}const Co=new Set(["host","connection","content-length","transfer-encoding","accept-encoding","content-encoding","keep-alive"]);function it(t){if(!t)return!1;const c=t.replace(/:\d+$/,"").replace(/^\[|\]$/g,"");return c==="localhost"||c==="127.0.0.1"||c==="::1"}function as(t,c){return!t||/^chrome-extension:\/\//.test(t)||/^moz-extension:\/\//.test(t)||/^http:\/\/(localhost|127\.0\.0\.1|\[::1\])(:\d+)?$/.test(t)?!0:Array.isArray(c.allowedOrigins)&&c.allowedOrigins.includes(t)}function ss(t,c){t.setHeader("Access-Control-Allow-Origin",c||"*"),t.setHeader("Access-Control-Allow-Methods","GET, POST, PUT, DELETE, OPTIONS"),t.setHeader("Access-Control-Allow-Headers","Content-Type, Authorization, X-ChatPanel-Token"),t.setHeader("Vary","Origin")}const Io=Date.now();function is(t){if(!t)return"";const c={redact:"redact",upstream:"model",stream:"stream",restore:"restore",total:"total"};return Object.keys(t).map(u=>`${c[u]||u} ${t[u]}ms`).join(" · ")}function ls(t){const c=/^(model|harness):([^/]+)(?:\/(.+))?$/.exec(String(t||""));return c?{kind:c[1],id:c[2],...c[3]?{model:c[3]}:{}}:null}function ds(t){const c=performance.now(),u={};let m=!1;const g=(y,P)=>{u[y]=Math.round(P*10)/10};return{meta:{},timings:u,mark:g,lap(y,P){g(y,performance.now()-P)},clock(){return performance.now()},commit(){if(m)return;m=!0,g("total",performance.now()-c);const y={...this.meta,timings:u};setImmediate(()=>{t(y),console.log(`[gateway] model=${y.model||"-"} → ${y.dest?`${y.dest}(${y.type})`:"none"} · ${y.redaction==="off"?"redaction OFF (client request)":`redacted ${y.redacted||0}`}${y.sanitized?` · scrubbed ${y.sanitized} hidden`:""}${y.narrowed?` · narrowed -${y.narrowed}`:""} · ${is(u)}`)})}}}function Ro(t,c){if(!t||!t.byToken||c!=="types"&&c!=="values")return;const u=[];for(const[m,g]of t.byToken){const y=/^\[\[([A-Z][A-Z0-9]*)_\d+\]\]$/.exec(m),P=y?y[1]:"PII",N=m.replace(/^\[\[|\]\]$/g,"");u.push(c==="values"?{token:N,type:P,value:g}:{token:N,type:P})}return u}function cs(t,c,u){return _t.matches(t)||"anthropic-version"in c?{kind:"anthropic",adapter:_t,redactable:_t.matches(t),base:u.upstreams?.anthropic?.baseUrl}:Ao.matches(t)?{kind:"responses",adapter:Ao,redactable:!0,base:u.upstreams?.openai?.baseUrl}:{kind:"openai",adapter:xt,redactable:xt.matches(t),base:u.upstreams?.openai?.baseUrl}}function $t(t,c){const u=String(t||"");if(Bo.has(u))return{agent:u,agentModel:""};const m=u.indexOf("/");if(m>0){const g=u.slice(0,m);if(Bo.has(g))return{agent:g,agentModel:u.slice(m+1)}}return{agent:c.bridge.agent,agentModel:""}}function jo(t,c){return $t(t,c).agent}function us(t,c){if(c!=="openai"||!t)return!1;const u=xt.extractLatestToolResult(t);if(!u)return!1;const m=oo(u.tool_call_id);return!!(m&&eo(m.gwId))}function ms(t,c){try{const u=new URL(t),m=u.hostname.replace(/^\[|\]$/g,""),g=m==="127.0.0.1"||m==="localhost"||m==="::1",y=u.port||(u.protocol==="https:"?"443":"80");return g&&String(y)===String(c.port)}catch{return!1}}const ps=25*1024*1024;async function T(t,c){const u=[];let m=0;for await(const g of t){if(m+=g.length,c&&m>c){const y=new Error("payload too large");throw y.code=413,y}u.push(g)}return Buffer.concat(u)}function a(t,c,u){t.writeHead(c,{"content-type":"application/json"}),t.end(JSON.stringify(u))}function Jo(t){const c=t.redaction?.detection?.url;return!c||t.redaction?.detection?.backend==="off"?null:c}function At(t){const c=t?.redaction?.detection,u=t?.redaction?.tier==="full"?"full":"basic";if(c&&c.backend&&c.backend!=="off")return{source:"external",backend:c.backend,state:"external",model:c.model||null,ready:!0,tier:u,coverage:u==="full"?"names":"patterns"};const m=I.health(),g=m.ok&&u==="full";return{source:"bundled",state:m.state,model:m.model||t?.ner?.model||null,installed:I.modelOnDisk(t?.ner?.model||void 0),error:m.error||null,ready:g,tier:u,coverage:g?"names":"patterns"}}async function Lo(t){if(I.state()!=="off"){const u=I.health();return{configured:u.configured,ok:u.ok,state:u.state,model:u.model,error:u.error||null,url:u.configured?`http://${t.host}:${t.port}/ner`:null,stats:u.stats,companions:u.companions}}const c=Jo(t);if(!c)return{configured:!1,ok:!1,url:null,model:null};try{const u=await Ze(c.replace(/\/ner\/?$/,"")+"/health",{signal:AbortSignal.timeout(2e3)});if(!u.ok)return{configured:!0,ok:!1,url:c,model:null};const m=await u.json().catch(()=>({}));return{configured:!0,ok:!0,url:c,model:m.model||null}}catch{return{configured:!0,ok:!1,url:c,model:null}}}function hs(t,c){const u={};for(const[m,g]of Object.entries(t)){const y=m.toLowerCase();y.startsWith("x-chatpanel-")||Co.has(y)||(u[m]=g)}u["accept-encoding"]="identity";try{u.host=new URL(c).host}catch{}return u}async function zo(t,c,u,m){const g=Ft(c.vault),y=Bt();t.on("close",()=>{t.writableFinished||Le(c.id)});const P=c.linkTurn||null,N=m?m.clock():0;let O=N,S=!0;const x=()=>{m&&S&&(m.lap("upstream",N),O=m.clock(),S=!1)};let C="";const J=()=>{c.redaction&&C&&Vt(C,c.redaction),C=""};let V=null;const E={onText:H=>{x(),et(c.id);const L=g.push(H);L&&(C+=L,t.write(u.sseDelta(L)))},onToolRequest:({name:H,restoredArgs:L,toolId:te})=>{if(x(),et(c.id),c.ownerApprovals&&po(H)){V=L;return}const Z=g.flush();Z&&(C+=Z,t.write(u.sseDelta(Z))),t.write(u.sseToolCalls([{id:te,name:H,arguments:JSON.stringify(L)}])),t.write(u.sseToolFinish(y.value)),m&&m.lap("stream",O),t.end(),m?.commit(),J()},onDone:()=>{const H=g.flush();H&&(C+=H,t.write(u.sseDelta(H))),t.write(u.sseTail(y.value)),m&&m.lap("stream",O),t.end(),P?.end("ok"),Le(c.id),m?.commit(),J(),Nt(c)},onError:H=>{t.write(`data: ${JSON.stringify({error:{message:H.message,type:"bridge_error"}})}
14
+ `)}catch{xe.delete(p)}},Pt=Xa(),Bo=new Set(["codex","claude","opencode","pi","kiro","antigravity","hermes"]),ts=16,os=/^mcp[_-]/i,Mo=t=>t&&t.function&&t.function.name||t&&t.name||"",rs=t=>t&&t.function&&t.function.description||t&&t.description||"";function Do(t){return typeof t=="string"?t:Array.isArray(t)?t.map(c=>typeof c=="string"?c:c&&(c.text||c.content)||"").join(" "):""}function ns(t,c){if(!t)return"";if(c==="responses"){const p=t.input;return typeof p=="string"?p:Array.isArray(p)?p.map(g=>Do(g&&(g.content??g))).join(" "):""}const u=Array.isArray(t.messages)?t.messages:[];for(let p=u.length-1;p>=0;p--)if(u[p]&&u[p].role==="user")return Do(u[p].content);return""}const Co=new Set(["host","connection","content-length","transfer-encoding","accept-encoding","content-encoding","keep-alive"]);function it(t){if(!t)return!1;const c=t.replace(/:\d+$/,"").replace(/^\[|\]$/g,"");return c==="localhost"||c==="127.0.0.1"||c==="::1"}function as(t,c){return!t||/^chrome-extension:\/\//.test(t)||/^moz-extension:\/\//.test(t)||/^http:\/\/(localhost|127\.0\.0\.1|\[::1\])(:\d+)?$/.test(t)?!0:Array.isArray(c.allowedOrigins)&&c.allowedOrigins.includes(t)}function ss(t,c){t.setHeader("Access-Control-Allow-Origin",c||"*"),t.setHeader("Access-Control-Allow-Methods","GET, POST, PUT, DELETE, OPTIONS"),t.setHeader("Access-Control-Allow-Headers","Content-Type, Authorization, X-ChatPanel-Token"),t.setHeader("Vary","Origin")}const Io=Date.now();function is(t){if(!t)return"";const c={redact:"redact",upstream:"model",stream:"stream",restore:"restore",total:"total"};return Object.keys(t).map(u=>`${c[u]||u} ${t[u]}ms`).join(" · ")}function ls(t){const c=/^(model|harness):([^/]+)(?:\/(.+))?$/.exec(String(t||""));return c?{kind:c[1],id:c[2],...c[3]?{model:c[3]}:{}}:null}function ds(t){const c=performance.now(),u={};let p=!1;const g=(y,P)=>{u[y]=Math.round(P*10)/10};return{meta:{},timings:u,mark:g,lap(y,P){g(y,performance.now()-P)},clock(){return performance.now()},commit(){if(p)return;p=!0,g("total",performance.now()-c);const y={...this.meta,timings:u};setImmediate(()=>{t(y),console.log(`[gateway] model=${y.model||"-"} → ${y.dest?`${y.dest}(${y.type})`:"none"} · ${y.redaction==="off"?"redaction OFF (client request)":`redacted ${y.redacted||0}`}${y.sanitized?` · scrubbed ${y.sanitized} hidden`:""}${y.narrowed?` · narrowed -${y.narrowed}`:""} · ${is(u)}`)})}}}function Ro(t,c){if(!t||!t.byToken||c!=="types"&&c!=="values")return;const u=[];for(const[p,g]of t.byToken){const y=/^\[\[([A-Z][A-Z0-9]*)_\d+\]\]$/.exec(p),P=y?y[1]:"PII",N=p.replace(/^\[\[|\]\]$/g,"");u.push(c==="values"?{token:N,type:P,value:g}:{token:N,type:P})}return u}function cs(t,c,u){return _t.matches(t)||"anthropic-version"in c?{kind:"anthropic",adapter:_t,redactable:_t.matches(t),base:u.upstreams?.anthropic?.baseUrl}:Ao.matches(t)?{kind:"responses",adapter:Ao,redactable:!0,base:u.upstreams?.openai?.baseUrl}:{kind:"openai",adapter:xt,redactable:xt.matches(t),base:u.upstreams?.openai?.baseUrl}}function $t(t,c){const u=String(t||"");if(Bo.has(u))return{agent:u,agentModel:""};const p=u.indexOf("/");if(p>0){const g=u.slice(0,p);if(Bo.has(g))return{agent:g,agentModel:u.slice(p+1)}}return{agent:c.bridge.agent,agentModel:""}}function jo(t,c){return $t(t,c).agent}function us(t,c){if(c!=="openai"||!t)return!1;const u=xt.extractLatestToolResult(t);if(!u)return!1;const p=oo(u.tool_call_id);return!!(p&&eo(p.gwId))}function ms(t,c){try{const u=new URL(t),p=u.hostname.replace(/^\[|\]$/g,""),g=p==="127.0.0.1"||p==="localhost"||p==="::1",y=u.port||(u.protocol==="https:"?"443":"80");return g&&String(y)===String(c.port)}catch{return!1}}const ps=25*1024*1024;async function T(t,c){const u=[];let p=0;for await(const g of t){if(p+=g.length,c&&p>c){const y=new Error("payload too large");throw y.code=413,y}u.push(g)}return Buffer.concat(u)}function a(t,c,u){t.writeHead(c,{"content-type":"application/json"}),t.end(JSON.stringify(u))}function Jo(t){const c=t.redaction?.detection?.url;return!c||t.redaction?.detection?.backend==="off"?null:c}function At(t){const c=t?.redaction?.detection,u=t?.redaction?.tier==="full"?"full":"basic";if(c&&c.backend&&c.backend!=="off")return{source:"external",backend:c.backend,state:"external",model:c.model||null,ready:!0,tier:u,coverage:u==="full"?"names":"patterns"};const p=R.health(),g=p.ok&&u==="full";return{source:"bundled",state:p.state,model:p.model||t?.ner?.model||null,installed:R.modelOnDisk(t?.ner?.model||void 0),error:p.error||null,ready:g,tier:u,coverage:g?"names":"patterns"}}async function Lo(t){if(R.state()!=="off"){const u=R.health();return{configured:u.configured,ok:u.ok,state:u.state,model:u.model,error:u.error||null,url:u.configured?`http://${t.host}:${t.port}/ner`:null,stats:u.stats,companions:u.companions}}const c=Jo(t);if(!c)return{configured:!1,ok:!1,url:null,model:null};try{const u=await Ze(c.replace(/\/ner\/?$/,"")+"/health",{signal:AbortSignal.timeout(2e3)});if(!u.ok)return{configured:!0,ok:!1,url:c,model:null};const p=await u.json().catch(()=>({}));return{configured:!0,ok:!0,url:c,model:p.model||null}}catch{return{configured:!0,ok:!1,url:c,model:null}}}function hs(t,c){const u={};for(const[p,g]of Object.entries(t)){const y=p.toLowerCase();y.startsWith("x-chatpanel-")||Co.has(y)||(u[p]=g)}u["accept-encoding"]="identity";try{u.host=new URL(c).host}catch{}return u}async function zo(t,c,u,p){const g=Ft(c.vault),y=Bt();t.on("close",()=>{t.writableFinished||Le(c.id)});const P=c.linkTurn||null,N=p?p.clock():0;let O=N,S=!0;const x=()=>{p&&S&&(p.lap("upstream",N),O=p.clock(),S=!1)};let I="";const L=()=>{c.redaction&&I&&Vt(I,c.redaction),I=""};let V=null;const E={onText:H=>{x(),et(c.id);const z=g.push(H);z&&(I+=z,t.write(u.sseDelta(z)))},onToolRequest:({name:H,restoredArgs:z,toolId:X})=>{if(x(),et(c.id),c.ownerApprovals&&po(H)){V=z;return}const ee=g.flush();ee&&(I+=ee,t.write(u.sseDelta(ee))),t.write(u.sseToolCalls([{id:X,name:H,arguments:JSON.stringify(z)}])),t.write(u.sseToolFinish(y.value)),p&&p.lap("stream",O),t.end(),p?.commit(),L()},onDone:()=>{const H=g.flush();H&&(I+=H,t.write(u.sseDelta(H))),t.write(u.sseTail(y.value)),p&&p.lap("stream",O),t.end(),P?.end("ok"),Le(c.id),p?.commit(),L(),Nt(c)},onError:H=>{t.write(`data: ${JSON.stringify({error:{message:H.message,type:"bridge_error"}})}
15
15
 
16
- `),t.end(),P?.end("error",{code:"bridge_error"}),Le(c.id),m?.commit(),Nt(c)},onUsage:H=>{y.add(H),P?.add(H)}};for(;;){if(V=null,await Br(c,E)!=="parked"||!V)return;const L=c.ownerApprovals,te=new AbortController,Z=()=>te.abort();t.once("close",Z);const oe=setInterval(()=>{et(c.id),t.writableEnded||t.write(`: waiting for the owner’s approval
16
+ `),t.end(),P?.end("error",{code:"bridge_error"}),Le(c.id),p?.commit(),Nt(c)},onUsage:H=>{y.add(H),P?.add(H)}};for(;;){if(V=null,await Br(c,E)!=="parked"||!V)return;const z=c.ownerApprovals,X=new AbortController,ee=()=>X.abort();t.once("close",ee);const te=setInterval(()=>{et(c.id),t.writableEnded||t.write(`: waiting for the owner’s approval
17
17
 
18
- `)},15e3);oe.unref?.();let ue;try{ue=await L.inbox.ask(V,{partner:L.partner,device:L.device,conversation:L.conversation,signal:te.signal})}finally{clearInterval(oe),t.off("close",Z)}if(te.signal.aborted||t.writableEnded){Nt(c);return}try{await to(c,JSON.stringify(ue))}catch(Q){E.onError(Q);return}}}function Nt(t){t.ownerApprovals?.turnScoped&&t.ownerApprovals.inbox.forget(t.ownerApprovals.conversation)}async function ys(t,c,{kind:u,adapter:m,agent:g,run:y=null,owner:P=null,linkTurn:N=null},O,S,x,C,J,V=null,E=null){const{messages:H,system:L}=m.toTurn(O),{agentModel:te}=$t(O?.model,x),Z=Po(x,{...te?{model:te}:{},...y||{}}),oe=Je(x.bridge.token),ue=mt(u,O?.model||g),Q={tier:x.redaction.tier==="full"?"full":"basic",dictionary:or(x.redaction,C),entities:[]},Y=await je(x),z=Nr({vault:S,redactOpts:Q,bridgeUrl:Y,token:oe,harness:V});P&&(z.ownerApprovals={...P,conversation:P.conversation||`partner.${P.device}.turn-${z.id}`,turnScoped:!P.conversation}),N&&(z.linkTurn=N,z.onEnd=()=>N.end("aborted")),S&&(z.redaction=x.redaction);let ke;try{ke=await Ar({bridgeUrl:Y,agent:g,token:oe,messages:H,system:L,specs:Mr(J),options:Z,signal:void 0,approvals:!!P||Dr(J)})}catch(ye){return N?.end("error",{code:"bridge_error"}),Le(z.id),E?.commit(),a(c,502,{error:{message:`bridge: ${ye.message}`,type:"bridge_error"}})}return z.reader=ke.body.getReader(),c.writeHead(200,{"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive"}),c.write(ue.sseHead()),zo(c,z,ue,E)}async function fs(t,c,u,m,g=null){et(c.id),c.rounds=(c.rounds||0)+1;try{const P=g?g.clock():0;await to(c,u),g&&g.lap("redact",P)}catch(P){return c.linkTurn?.end("error",{code:"tool_result"}),Le(c.id),g?.commit(),a(t,502,{error:{message:`tool-result: ${P.message}`,type:"bridge_error"}})}const y=mt("openai",m||"codex");return t.writeHead(200,{"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive"}),t.write(y.sseHead()),zo(t,c,y,g)}function Bt(){let t=!1;const c={inputTokens:0,outputTokens:0,cacheReadTokens:0,cacheWriteTokens:0};return{add(u){t=!0;for(const m of Object.keys(c))c[m]+=Math.max(0,Number(u?.[m])||0)},get value(){return t?c:null}}}async function gs(t,c,{kind:u,adapter:m,redactable:g,pathname:y,agentOverride:P,harness:N,trace:O,run:S=null,owner:x=null,link:C=null},J,V,E,H){if(!g)return O?.commit(),a(c,404,{error:`endpoint ${y} not supported by the bridge backend`});if(u==="openai"){const K=m.extractLatestToolResult(J);if(K){const v=oo(K.tool_call_id),se=v&&eo(v.gwId);if(se)return fs(c,se,K.content,J?.model,O)}const W=m.extractTools(J);if((W.length||x)&&J?.stream===!0){const v=P||jo(J?.model,E),se=C?Ot.begin({...C,agentId:v}):null;return ys(t,c,{kind:u,adapter:m,agent:v,run:S,owner:x,linkTurn:se},J,V,E,H,W,N,O)}}const{messages:L,system:te}=m.toTurn(J),Z=P||jo(J?.model,E),oe=C?Ot.begin({...C,agentId:Z}):null,ue=J?.stream===!0,Q=mt(u,J?.model||Z),Y=Je(E.bridge.token),z=new AbortController;c.on("close",()=>{c.writableFinished||z.abort()});const{agentModel:ke}=$t(J?.model,E),ye={bridgeUrl:await je(E),agent:Z,token:Y,messages:L,system:te,signal:z.signal,options:Po(E,{...ke?{model:ke}:{},...S||{}})};if(!ue)try{let K="";const W=Bt(),v=O?O.clock():0;await Zt(ye,$e=>{K+=$e},null,$e=>W.add($e)),O&&O.lap("upstream",v);const se=O?O.clock():0,Ue=Q.full(tr(K,V),W.value);return O&&O.lap("restore",se),c.writeHead(200,{"content-type":Q.contentType}),c.end(Ue),oe?.add(W.value),oe?.end("ok"),O?.commit()}catch(K){return oe?.end(z.signal.aborted?"aborted":"error",{code:"bridge_error"}),O?.commit(),a(c,502,{error:{message:`bridge backend failed: ${K.message}`,type:"bridge_error"}})}c.writeHead(200,{"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive"}),c.write(Q.sseHead());const n=Ft(V),o=O?O.clock():0;let f=o;const i=Bt();let X="",F=!1;try{let K=!0;await Zt(ye,v=>{O&&K&&(O.lap("upstream",o),f=O.clock(),K=!1);const se=n.push(v);se&&(X+=se,c.write(Q.sseDelta(se)))},Q.sseActivity?v=>{try{c.write(Q.sseActivity(er(v,V)))}catch{}}:null,v=>i.add(v));const W=n.flush();W&&(X+=W,c.write(Q.sseDelta(W))),c.write(Q.sseTail(i.value))}catch(K){F=!0,c.write(`data: ${JSON.stringify({error:{message:K.message,type:"bridge_error"}})}
18
+ `)},15e3);te.unref?.();let ye;try{ye=await z.inbox.ask(V,{partner:z.partner,device:z.device,conversation:z.conversation,signal:X.signal})}finally{clearInterval(te),t.off("close",ee)}if(X.signal.aborted||t.writableEnded){Nt(c);return}try{await to(c,JSON.stringify(ye))}catch(Y){E.onError(Y);return}}}function Nt(t){t.ownerApprovals?.turnScoped&&t.ownerApprovals.inbox.forget(t.ownerApprovals.conversation)}async function ys(t,c,{kind:u,adapter:p,agent:g,run:y=null,owner:P=null,linkTurn:N=null},O,S,x,I,L,V=null,E=null){const{messages:H,system:z}=p.toTurn(O),{agentModel:X}=$t(O?.model,x),ee=Po(x,{...X?{model:X}:{},...y||{}}),te=Je(x.bridge.token),ye=mt(u,O?.model||g),Y={tier:x.redaction.tier==="full"?"full":"basic",dictionary:or(x.redaction,I),entities:[]},ge=await je(x),C=Nr({vault:S,redactOpts:Y,bridgeUrl:ge,token:te,harness:V});P&&(C.ownerApprovals={...P,conversation:P.conversation||`partner.${P.device}.turn-${C.id}`,turnScoped:!P.conversation}),N&&(C.linkTurn=N,C.onEnd=()=>N.end("aborted")),S&&(C.redaction=x.redaction);let q;try{q=await Ar({bridgeUrl:ge,agent:g,token:te,messages:H,system:z,specs:Mr(L),options:ee,signal:void 0,approvals:!!P||Dr(L)})}catch(ue){return N?.end("error",{code:"bridge_error"}),Le(C.id),E?.commit(),a(c,502,{error:{message:`bridge: ${ue.message}`,type:"bridge_error"}})}return C.reader=q.body.getReader(),c.writeHead(200,{"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive"}),c.write(ye.sseHead()),zo(c,C,ye,E)}async function fs(t,c,u,p,g=null){et(c.id),c.rounds=(c.rounds||0)+1;try{const P=g?g.clock():0;await to(c,u),g&&g.lap("redact",P)}catch(P){return c.linkTurn?.end("error",{code:"tool_result"}),Le(c.id),g?.commit(),a(t,502,{error:{message:`tool-result: ${P.message}`,type:"bridge_error"}})}const y=mt("openai",p||"codex");return t.writeHead(200,{"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive"}),t.write(y.sseHead()),zo(t,c,y,g)}function Bt(){let t=!1;const c={inputTokens:0,outputTokens:0,cacheReadTokens:0,cacheWriteTokens:0};return{add(u){t=!0;for(const p of Object.keys(c))c[p]+=Math.max(0,Number(u?.[p])||0)},get value(){return t?c:null}}}async function gs(t,c,{kind:u,adapter:p,redactable:g,pathname:y,agentOverride:P,harness:N,trace:O,run:S=null,owner:x=null,link:I=null},L,V,E,H){if(!g)return O?.commit(),a(c,404,{error:`endpoint ${y} not supported by the bridge backend`});if(u==="openai"){const K=p.extractLatestToolResult(L);if(K){const v=oo(K.tool_call_id),se=v&&eo(v.gwId);if(se)return fs(c,se,K.content,L?.model,O)}const W=p.extractTools(L);if((W.length||x)&&L?.stream===!0){const v=P||jo(L?.model,E),se=I?Ot.begin({...I,agentId:v}):null;return ys(t,c,{kind:u,adapter:p,agent:v,run:S,owner:x,linkTurn:se},L,V,E,H,W,N,O)}}const{messages:z,system:X}=p.toTurn(L),ee=P||jo(L?.model,E),te=I?Ot.begin({...I,agentId:ee}):null,ye=L?.stream===!0,Y=mt(u,L?.model||ee),ge=Je(E.bridge.token),C=new AbortController;c.on("close",()=>{c.writableFinished||C.abort()});const{agentModel:q}=$t(L?.model,E),ue={bridgeUrl:await je(E),agent:ee,token:ge,messages:z,system:X,signal:C.signal,options:Po(E,{...q?{model:q}:{},...S||{}})};if(!ye)try{let K="";const W=Bt(),v=O?O.clock():0;await Zt(ue,$e=>{K+=$e},null,$e=>W.add($e)),O&&O.lap("upstream",v);const se=O?O.clock():0,Ue=Y.full(tr(K,V),W.value);return O&&O.lap("restore",se),c.writeHead(200,{"content-type":Y.contentType}),c.end(Ue),te?.add(W.value),te?.end("ok"),O?.commit()}catch(K){return te?.end(C.signal.aborted?"aborted":"error",{code:"bridge_error"}),O?.commit(),a(c,502,{error:{message:`bridge backend failed: ${K.message}`,type:"bridge_error"}})}c.writeHead(200,{"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive"}),c.write(Y.sseHead());const n=Ft(V),o=O?O.clock():0;let f=o;const i=Bt();let Z="",F=!1;try{let K=!0;await Zt(ue,v=>{O&&K&&(O.lap("upstream",o),f=O.clock(),K=!1);const se=n.push(v);se&&(Z+=se,c.write(Y.sseDelta(se)))},Y.sseActivity?v=>{try{c.write(Y.sseActivity(er(v,V)))}catch{}}:null,v=>i.add(v));const W=n.flush();W&&(Z+=W,c.write(Y.sseDelta(W))),c.write(Y.sseTail(i.value))}catch(K){F=!0,c.write(`data: ${JSON.stringify({error:{message:K.message,type:"bridge_error"}})}
19
19
 
20
- `)}O&&O.lap("stream",f),c.end(),oe&&(oe.add(i.value),oe.end(z.signal.aborted?"aborted":F?"error":"ok",{code:"bridge_error"})),O?.commit(),V&&X&&Vt(X,E.redaction)}function ws(t,c,u=""){const m=String(t||"").replace(/\/+$/,""),g=String(c||"").split("/")[1];return g&&m.endsWith(`/${g}`)?m.slice(0,-(g.length+1))+c+u:m+c+u}const bs=9e4;function ks(t,c,u){if(c===u)return t;const m=c/u,g=new Float32Array(Math.floor(t.length/m));for(let y=0;y<g.length;y++){const P=y*m,N=Math.floor(P),O=Math.min(t.length-1,N+1),S=P-N;g[y]=t[N]*(1-S)+t[O]*S}return g}const Go=new WeakMap,vs=["/tts","/stt","/ner","/diarize","/skills","/agent-defs","/agent-sessions","/a2a","/redact","/config","/logs","/status","/admin","/v1/browser","/v1/link"];function Mt(t,{installing:c=!1}={}){return t.stt?.diarize===!1?"off":c&&t.stt?.allowDownload!==!1?"download":"ondisk"}async function be(t,c,u,m,{method:g="GET",timeoutMs:y=8e3,pick:P=N=>N}={}){const N=await je(u);if(!N)return a(c,503,{error:{message:"no bridge is configured",type:"no_bridge"}});const O=Je(u.bridge?.token),S=g!=="GET"&&g!=="DELETE";try{const x=S?(await T(t,u.maxBodyBytes)).toString("utf8"):"",C=await fetch(`${N}${m}`,{method:g,headers:{Accept:"application/json",...S?{"content-type":"application/json"}:{},...O?{Authorization:`Bearer ${O}`}:{}},...S?{body:x||"{}"}:{},signal:AbortSignal.timeout(y)}),J=await C.json().catch(()=>({}));return C.ok?a(c,200,P(J)):a(c,C.status,{error:{message:J?.error||`bridge ${C.status}`,type:"bridge_error"}})}catch(x){return a(c,502,{error:{message:`bridge unreachable: ${x.message}`,type:"bridge_unreachable"}})}}function Dt(t){return!t||t==="."||t===".."||t.includes("/")||t.includes("\\")}function Ce(t,c){const u=new URLSearchParams;for(const y of t.searchParams.getAll("dir"))y&&u.append("dir",y);const m=t.searchParams.get("workdir")||String(c?.bridge?.workingDir||"").trim();m&&u.set("workdir",m);const g=u.toString();return g?`?${g}`:""}async function Ss(t,c,{adapter:u,kind:m,pathname:g,search:y,base:P,destKey:N,destProtocol:O,harness:S,trace:x,link:C=null},J,V){let E;const H=x?x.clock():0,L=C?Ot.begin(C):null;let te=!1;L&&c.on("close",()=>{c.writableFinished||(te=!0)});const Z=(Y,z)=>{L&&(L.add(z),L.end(te?"aborted":Y>=400?"error":"ok",{code:`http_${Y}`}))};try{const Y=hs(t.headers,P);N&&(O==="anthropic"?(Y["x-api-key"]=N,delete Y.authorization):Y.authorization=`Bearer ${N}`);const z=ir(ws(P,g,y)).toString();E=await fetch(z,{method:t.method,headers:Y,body:["GET","HEAD"].includes(t.method)?void 0:J})}catch(Y){return L?.end("error",{code:"upstream_unreachable"}),x?.commit(),a(c,502,{error:`upstream fetch failed: ${Y.message}`})}const oe=E.headers.get("content-type")||"",ue={};if(E.headers.forEach((Y,z)=>{Co.has(z.toLowerCase())||(ue[z]=Y)}),oe.includes("text/event-stream")&&E.body){x&&x.lap("upstream",H);const Y=x?x.clock():0;c.writeHead(E.status,ue);const z=L?bn():null,ke=z?E.body.pipeThrough(z.stream):E.body,ye=m==="openai"?qo(ke,c,V,S):Zo(ke,c,V);return Promise.resolve(ye).finally(()=>{x&&x.lap("stream",Y),Z(E.status,z?.usage()),x?.commit()})}const Q=Buffer.from(await E.arrayBuffer());if(x&&x.lap("upstream",H),L&&Z(E.status,oe.includes("json")?kn(Q.toString("utf8")):null),V&&oe.includes("application/json"))try{const Y=x?x.clock():0,z=u.restoreResponse(JSON.parse(Q.toString("utf8")),V,S);return x&&x.lap("restore",Y),c.writeHead(E.status,{...ue,"content-type":"application/json"}),c.end(Buffer.from(JSON.stringify(z),"utf8")),x?.commit()}catch{}c.writeHead(E.status,ue),c.end(Q),x?.commit()}function Ts(t=Ut()){const c=hr({first:async n=>{const o=Number(new URL(n).port),f=jn.find(i=>i.port===o&&(i.provides||[]).includes("chat"));return f&&(await J())(f.id)==="up"?{engine:f.id,label:f.label,models:null}:null}}),u=mr({confirm:n=>typeof t.pairing?.confirm=="function"?t.pairing.confirm(n):pr(n),newId:()=>yr()}),m=Kn({version:de}),g=da({log:n=>console.log(` ${n}`)}),y=t.link?.enabled===!1?null:Yn({settings:t.link||{},port:t.port,...t.link?.path?{path:t.link.path}:{},dispatch:({method:n,path:o,headers:f,body:i,device:X})=>fetch(`http://127.0.0.1:${ye.address()?.port||t.port}${o}`,{method:n,body:i,headers:{...f,"x-chatpanel-token":Be()||_e(),"x-chatpanel-link-device":String(X||"")}}),ownerIsPro:()=>Te(t.pro?.entitlementToken),log:n=>console.log(` ${n}`)});t.stt?.diarizeModel&&t.stt.diarizeModel!==M.activeModel()&&(ho(t.stt.diarizeModel)?M.setModel(t.stt.diarizeModel,{log:n=>console.log(n)}):console.warn(`[diarize] config names an unknown speaker model (${t.stt.diarizeModel}) — using ${wa}`));let P=null;const N=()=>{if(!P){const n=t.read||{};P=Wn({remote:n.remote?.url?{url:n.remote.url,key:n.remote.key||""}:null,defaultProvider:n.provider||"defuddle"})}return P};let O=null;const S=()=>(O||(O=Dn({wrap:(n,o,f,i)=>Cn().wrap(n,o,f,i),onLog:n=>console.warn(`[extract worker] ${n}`)})),O);let x={at:0,fn:()=>"unknown"},C=null;async function J(){if(Date.now()-x.at<1e4)return x.fn;let n=new Map;try{const i=await E().health();for(const[X,F]of Object.entries(i)){const K=(t.destinations||[]).filter(W=>W?.service===X).flatMap(W=>[W.id,...W.models||[]]);for(const W of[X,...K])n.set(W,F)}}catch{n=new Map}const o=i=>n.get(i)||"unknown",f=new Map((t.destinations||[]).filter(i=>i?.service).map(i=>[i.id,i.service]));return o.window=i=>{try{return E().contextWindow(f.get(i)||i)}catch{return null}},o.card=i=>{try{return E().modelCard(f.get(i)||i)}catch{return null}},o.sig=JSON.stringify([...n.entries()].sort()),x={at:Date.now(),fn:o},x.fn}let V=null;const E=()=>(V||(V=Rn({cfg:t,bridgeHealth:async()=>{const n=await je(t);if(!n)return null;const o=Je(t.bridge?.token),f=await fetch(`${n}/health`,{headers:{Accept:"application/json",...o?{Authorization:`Bearer ${o}`}:{}},signal:AbortSignal.timeout(4e3)});return f.ok?f.json():null},persist:()=>{try{we(t,le())}catch(n){console.warn(`[runtime] could not persist config: ${n.message}`)}},stateDir:ze.join(ze.dirname(le()),"runtime"),workers:()=>{const n=O?.status();return n?.running?[{id:"extract",kind:"worker",engine:"extract",command:"extract worker",label:"document extractor",pid:n.pid,sandbox:n.sandbox,refused:[]}]:[]},log:n=>console.log(n)})),V),H=Number(t.runtime?.idleMinutes),L=Ln({warmMs:(Number.isFinite(H)&&H>=0?H:10)*6e4,log:n=>console.log(n)}),te=Jn({cfg:t,wake:(n,o)=>E().wake(n,o),embedded:L});let Z=null;const oe=()=>(Z||(Z=Fn({store:Vn({log:n=>console.warn(`[kb] ${n}`)}),extract:S,embedded:L,cfg:t,rerank:async(n,o)=>{const f=await te.call("rerank",{query:n,documents:o.map(X=>String(X).slice(0,2e3))});if(f.status!==200)return null;const i=new Array(o.length).fill(0);for(const X of f.body.results||[])i[X.index]=X.relevance_score;return i},read:()=>N(),completer:n=>async(o,{maxTokens:f=160}={})=>{const i=new AbortController,X=setTimeout(()=>i.abort(),3e4);try{const F=Be()||_e(),K=await fetch(`http://127.0.0.1:${t.port}/v1/chat/completions`,{method:"POST",signal:i.signal,headers:{"content-type":"application/json",...F?{Authorization:`Bearer ${F}`}:{},"X-ChatPanel-Client":"kb"},body:JSON.stringify({model:n,messages:[{role:"user",content:o}],stream:!1,max_tokens:f,temperature:0})}),W=await K.json().catch(()=>({}));return K.ok?String(W?.choices?.[0]?.message?.content||""):""}finally{clearTimeout(X)}},log:n=>console.warn(n)})),Z),ue=()=>{t.search?.searxng?.url&&E().wake("searxng").catch(()=>{})};let Q=null;const Y=()=>{if(!Q){const n=t.search||{},o=n.searxng?.url?pa({url:n.searxng.url,token:n.searxng.token||"",engines:n.searxng.engines||"",safesearch:n.searxng.safesearch??null}):null;Q=ca({reader:N(),searxng:o,engines:()=>ha(t),wakeSearxng:()=>E().wake("searxng"),defaultProvider:n.provider||"auto",redact:async f=>{let i=f;return await Qe([ut(()=>i,X=>{i=X})],{...t.redaction,tier:"basic"},{isPro:!0}),i}})}return Q};dr(t.allowedExtensionIds||[]);const z=[],ke=n=>{z.push(n),z.length>50&&z.shift()},ye=Yo(async(n,o)=>{const f=new URL(n.url,"http://127.0.0.1"),i=f.pathname;if(!it(n.headers.host))return a(o,403,{error:"loopback only"});if(!as(n.headers.origin,t))return a(o,403,{error:"origin not allowed"});if(it(t.host)&&Xn(n.headers))return a(o,403,{error:{message:"this gateway answers a tunnel only on its Link path (/v1/link)",type:"forbidden"}});if(n.headers.origin&&ss(o,n.headers.origin),n.method==="OPTIONS")return o.writeHead(204),o.end();if(i==="/admin/token"&&n.method==="POST")return U(n)?a(o,200,{token:_e()}):a(o,403,{error:"admin: extension origin or gateway token required"});if(i==="/pair/code"&&n.method==="POST"){if(!U(n))return a(o,403,{error:"pair/code: extension origin or gateway token required"});const e=cr();return console.log("[gateway] pairing code issued — valid for 5 minutes, one use"),a(o,200,{ok:!0,...e})}if(i==="/pair"&&n.method==="POST"){let e=null;try{e=JSON.parse((await T(n,t.maxBodyBytes)).toString("utf8"))}catch{e=null}const r=ur(e?.code);if(!r.ok)return console.log(`[gateway] pairing refused (${r.reason}) from ${Ie(n)} caller`),a(o,403,{error:r.reason});console.log(`[gateway] paired a ${Ie(n)} client${n.headers.origin?` (${n.headers.origin})`:""}`);const{token:s,refused:l}=await qt(t);return l&&console.log(`[gateway] pairing: the bridge at ${l.url}${l.version?` (v${l.version})`:""} accepts none of the tokens this gateway holds — not handing one over`),a(o,200,{ok:!0,token:Be()||_e(),...s?{bridgeToken:s}:{},...l?{bridgeRefused:l}:{}})}if(i==="/pair/ask"&&n.method==="POST"){const e=Ie(n);if(t.pairing?.prompt===!1)return a(o,403,{error:"pairing by confirmation is switched off on this gateway — use a pairing code",type:"disabled"});if(Wt(e))return a(o,409,{error:"this client is already trusted by the gateway",type:"already"});if(e!=="unpaired")return a(o,403,{error:"pair/ask: only a browser extension may ask to be paired",type:"forbidden"});let r=null;try{r=JSON.parse((await T(n,t.maxBodyBytes)).toString("utf8")||"{}")}catch{r=null}const s=u.ask({browser:r?.browser,who:n.headers.origin||""});if(!s.ok){const l=s.reason==="busy"?"a pairing question is already on screen — answer it, or wait a minute":"too many pairing questions — wait a few minutes, or use a pairing code";return a(o,429,{error:l,type:s.reason})}return console.log(`[gateway] pairing: an unrecognised extension (${n.headers.origin}) asked — the question is on screen`),a(o,202,{ok:!0,id:s.id,number:s.number,expiresAt:s.expiresAt})}if(i==="/pair/ask/result"&&n.method==="POST"){let e=null;try{e=JSON.parse((await T(n,t.maxBodyBytes)).toString("utf8")||"{}")}catch{e=null}const{status:r}=u.result(e?.id,{who:n.headers.origin||""});if(r!=="allowed")return a(o,200,{ok:!0,status:r});console.log(`[gateway] paired ${n.headers.origin} — allowed in the dialog on this computer`);const{token:s,refused:l}=await qt(t);return a(o,200,{ok:!0,status:r,token:Be()||_e(),...s?{bridgeToken:s}:{},...l?{bridgeRefused:l}:{}})}if(i==="/whoami"&&n.method==="POST"){const e=Ie(n);return a(o,200,{ok:!0,trust:e,paired:Wt(e),version:de})}if(i==="/audit"&&n.method==="GET")return U(n)?a(o,200,gr(t,{version:de,startedAt:Io,managed:Re(),certificates:{...br(),wanted:Kt(t)},linkPartners:y?y.status().devices.filter(e=>e.kind==="partner"):[],confined:yt({stateDir:ze.dirname(le())})})):a(o,403,{error:"audit: extension origin or gateway token required"});if((i==="/config"||i==="/logs"||i==="/update"&&n.method!=="GET")&&!U(n))return a(o,403,{error:"admin route: extension origin or gateway token required"});if(i==="/update"&&n.method==="GET"){const e=await ln(de,{force:f.searchParams.get("force")==="1"}).catch(r=>({current:de,updateAvailable:!1,error:String(r?.message||r)}));return a(o,200,{ok:!0,update:e,job:un()})}if(i==="/update"&&n.method==="POST"){const e=cn(de);return a(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 a(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 a(o,403,{error:{message:"history write — extension origin or gateway token required",type:"forbidden"}});if((i==="/v1/history/ingest"||i==="/v1/history/clear")&&n.method==="POST"&&!U(n))return a(o,403,{error:{message:"history write — extension origin or gateway token required",type:"forbidden"}});if((i==="/v1/memory/remember"||i==="/v1/memory/forget"||i==="/v1/memory/sync"||i==="/v1/memory/clear")&&n.method==="POST"&&!U(n))return a(o,403,{error:{message:"memory write — extension origin or gateway token required",type:"forbidden"}});if((i==="/v1/prefs"||i.startsWith("/v1/prefs/")||i.startsWith("/v1/teams")||i.startsWith("/v1/agents")||i.startsWith("/v1/projects"))&&!U(n))return a(o,403,{error:{message:"prefs: extension origin or gateway token required",type:"forbidden"}});if((i==="/v1/browser"||i.startsWith("/v1/browser/"))&&!U(n))return a(o,403,{error:{message:"browser: extension origin or gateway token required",type:"forbidden"}});if((i==="/v1/link"||i.startsWith("/v1/link/"))&&!U(n))return a(o,403,{error:{message:"link: extension origin or gateway token required",type:"forbidden"}});if((i==="/v1/events"||i.startsWith("/v1/events/"))&&!U(n))return a(o,403,{error:{message:"events: extension origin or gateway token required",type:"forbidden"}});if(i.startsWith("/v1/observability")&&!U(n))return a(o,403,{error:{message:"observability: extension origin or gateway token required",type:"forbidden"}});if(n.method==="GET"&&i==="/")return o.writeHead(200,{"content-type":"text/plain; charset=utf-8","cache-control":"no-store"}),o.end(`ChatPanel Privacy Gateway v${de} is running.
20
+ `)}O&&O.lap("stream",f),c.end(),te&&(te.add(i.value),te.end(C.signal.aborted?"aborted":F?"error":"ok",{code:"bridge_error"})),O?.commit(),V&&Z&&Vt(Z,E.redaction)}function ws(t,c,u=""){const p=String(t||"").replace(/\/+$/,""),g=String(c||"").split("/")[1];return g&&p.endsWith(`/${g}`)?p.slice(0,-(g.length+1))+c+u:p+c+u}const bs=9e4;function ks(t,c,u){if(c===u)return t;const p=c/u,g=new Float32Array(Math.floor(t.length/p));for(let y=0;y<g.length;y++){const P=y*p,N=Math.floor(P),O=Math.min(t.length-1,N+1),S=P-N;g[y]=t[N]*(1-S)+t[O]*S}return g}const Go=new WeakMap,vs=["/tts","/stt","/ner","/diarize","/skills","/agent-defs","/agent-sessions","/a2a","/redact","/config","/logs","/status","/admin","/v1/browser","/v1/link"];function Mt(t,{installing:c=!1}={}){return t.stt?.diarize===!1?"off":c&&t.stt?.allowDownload!==!1?"download":"ondisk"}async function ke(t,c,u,p,{method:g="GET",timeoutMs:y=8e3,pick:P=N=>N}={}){const N=await je(u);if(!N)return a(c,503,{error:{message:"no bridge is configured",type:"no_bridge"}});const O=Je(u.bridge?.token),S=g!=="GET"&&g!=="DELETE";try{const x=S?(await T(t,u.maxBodyBytes)).toString("utf8"):"",I=await fetch(`${N}${p}`,{method:g,headers:{Accept:"application/json",...S?{"content-type":"application/json"}:{},...O?{Authorization:`Bearer ${O}`}:{}},...S?{body:x||"{}"}:{},signal:AbortSignal.timeout(y)}),L=await I.json().catch(()=>({}));return I.ok?a(c,200,P(L)):a(c,I.status,{error:{message:L?.error||`bridge ${I.status}`,type:"bridge_error"}})}catch(x){return a(c,502,{error:{message:`bridge unreachable: ${x.message}`,type:"bridge_unreachable"}})}}function Dt(t){return!t||t==="."||t===".."||t.includes("/")||t.includes("\\")}function Ce(t,c){const u=new URLSearchParams;for(const y of t.searchParams.getAll("dir"))y&&u.append("dir",y);const p=t.searchParams.get("workdir")||String(c?.bridge?.workingDir||"").trim();p&&u.set("workdir",p);const g=u.toString();return g?`?${g}`:""}async function Ss(t,c,{adapter:u,kind:p,pathname:g,search:y,base:P,destKey:N,destProtocol:O,harness:S,trace:x,link:I=null},L,V){let E;const H=x?x.clock():0,z=I?Ot.begin(I):null;let X=!1;const ee=new AbortController;c.on("close",()=>{c.writableFinished||(X=!0,ee.abort())});const te=(C,q)=>{z&&(z.add(q),z.end(X?"aborted":C>=400?"error":"ok",{code:`http_${C}`}))};try{const C=hs(t.headers,P);N&&(O==="anthropic"?(C["x-api-key"]=N,delete C.authorization):C.authorization=`Bearer ${N}`);const q=ir(ws(P,g,y)).toString();E=await fetch(q,{method:t.method,headers:C,body:["GET","HEAD"].includes(t.method)?void 0:L,signal:ee.signal})}catch(C){return X?(te(499),x?.commit()):(z?.end("error",{code:"upstream_unreachable"}),x?.commit(),a(c,502,{error:`upstream fetch failed: ${C.message}`}))}const ye=E.headers.get("content-type")||"",Y={};if(E.headers.forEach((C,q)=>{Co.has(q.toLowerCase())||(Y[q]=C)}),ye.includes("text/event-stream")&&E.body){x&&x.lap("upstream",H);const C=x?x.clock():0;c.writeHead(E.status,Y);const q=z?bn():null,ue=q?E.body.pipeThrough(q.stream):E.body,n=p==="openai"?qo(ue,c,V,S):Zo(ue,c,V);return Promise.resolve(n).catch(o=>{if(!X)throw o}).finally(()=>{x&&x.lap("stream",C),te(E.status,q?.usage()),x?.commit()})}let ge;try{ge=Buffer.from(await E.arrayBuffer())}catch(C){if(X)return te(499),x?.commit();throw C}if(x&&x.lap("upstream",H),z&&te(E.status,ye.includes("json")?kn(ge.toString("utf8")):null),V&&ye.includes("application/json"))try{const C=x?x.clock():0,q=u.restoreResponse(JSON.parse(ge.toString("utf8")),V,S);return x&&x.lap("restore",C),c.writeHead(E.status,{...Y,"content-type":"application/json"}),c.end(Buffer.from(JSON.stringify(q),"utf8")),x?.commit()}catch{}c.writeHead(E.status,Y),c.end(ge),x?.commit()}function Ts(t=Ut()){const c=hr({first:async n=>{const o=Number(new URL(n).port),f=jn.find(i=>i.port===o&&(i.provides||[]).includes("chat"));return f&&(await L())(f.id)==="up"?{engine:f.id,label:f.label,models:null}:null}}),u=mr({confirm:n=>typeof t.pairing?.confirm=="function"?t.pairing.confirm(n):pr(n),newId:()=>yr()}),p=Kn({version:de}),g=da({log:n=>console.log(` ${n}`)}),y=t.link?.enabled===!1?null:Qn({settings:t.link||{},port:t.port,...t.link?.path?{path:t.link.path}:{},dispatch:({method:n,path:o,headers:f,body:i,device:Z})=>fetch(`http://127.0.0.1:${ue.address()?.port||t.port}${o}`,{method:n,body:i,headers:{...f,"x-chatpanel-token":Be()||_e(),"x-chatpanel-link-device":String(Z||"")}}),ownerIsPro:()=>Te(t.pro?.entitlementToken),log:n=>console.log(` ${n}`)});t.stt?.diarizeModel&&t.stt.diarizeModel!==M.activeModel()&&(ho(t.stt.diarizeModel)?M.setModel(t.stt.diarizeModel,{log:n=>console.log(n)}):console.warn(`[diarize] config names an unknown speaker model (${t.stt.diarizeModel}) — using ${wa}`));let P=null;const N=()=>{if(!P){const n=t.read||{};P=Wn({remote:n.remote?.url?{url:n.remote.url,key:n.remote.key||""}:null,defaultProvider:n.provider||"defuddle"})}return P};let O=null;const S=()=>(O||(O=Dn({wrap:(n,o,f,i)=>Cn().wrap(n,o,f,i),onLog:n=>console.warn(`[extract worker] ${n}`)})),O);let x={at:0,fn:()=>"unknown"},I=null;async function L(){if(Date.now()-x.at<1e4)return x.fn;let n=new Map;try{const i=await E().health();for(const[Z,F]of Object.entries(i)){const K=(t.destinations||[]).filter(W=>W?.service===Z).flatMap(W=>[W.id,...W.models||[]]);for(const W of[Z,...K])n.set(W,F)}}catch{n=new Map}const o=i=>n.get(i)||"unknown",f=new Map((t.destinations||[]).filter(i=>i?.service).map(i=>[i.id,i.service]));return o.window=i=>{try{return E().contextWindow(f.get(i)||i)}catch{return null}},o.card=i=>{try{return E().modelCard(f.get(i)||i)}catch{return null}},o.sig=JSON.stringify([...n.entries()].sort()),x={at:Date.now(),fn:o},x.fn}let V=null;const E=()=>(V||(V=Rn({cfg:t,bridgeHealth:async()=>{const n=await je(t);if(!n)return null;const o=Je(t.bridge?.token),f=await fetch(`${n}/health`,{headers:{Accept:"application/json",...o?{Authorization:`Bearer ${o}`}:{}},signal:AbortSignal.timeout(4e3)});return f.ok?f.json():null},persist:()=>{try{be(t,le())}catch(n){console.warn(`[runtime] could not persist config: ${n.message}`)}},stateDir:ze.join(ze.dirname(le()),"runtime"),workers:()=>{const n=O?.status();return n?.running?[{id:"extract",kind:"worker",engine:"extract",command:"extract worker",label:"document extractor",pid:n.pid,sandbox:n.sandbox,refused:[]}]:[]},log:n=>console.log(n)})),V),H=Number(t.runtime?.idleMinutes),z=Ln({warmMs:(Number.isFinite(H)&&H>=0?H:10)*6e4,log:n=>console.log(n)}),X=Jn({cfg:t,wake:(n,o)=>E().wake(n,o),embedded:z});let ee=null;const te=()=>(ee||(ee=Fn({store:Vn({log:n=>console.warn(`[kb] ${n}`)}),extract:S,embedded:z,cfg:t,rerank:async(n,o)=>{const f=await X.call("rerank",{query:n,documents:o.map(Z=>String(Z).slice(0,2e3))});if(f.status!==200)return null;const i=new Array(o.length).fill(0);for(const Z of f.body.results||[])i[Z.index]=Z.relevance_score;return i},read:()=>N(),completer:n=>async(o,{maxTokens:f=160}={})=>{const i=new AbortController,Z=setTimeout(()=>i.abort(),3e4);try{const F=Be()||_e(),K=await fetch(`http://127.0.0.1:${t.port}/v1/chat/completions`,{method:"POST",signal:i.signal,headers:{"content-type":"application/json",...F?{Authorization:`Bearer ${F}`}:{},"X-ChatPanel-Client":"kb"},body:JSON.stringify({model:n,messages:[{role:"user",content:o}],stream:!1,max_tokens:f,temperature:0})}),W=await K.json().catch(()=>({}));return K.ok?String(W?.choices?.[0]?.message?.content||""):""}finally{clearTimeout(Z)}},log:n=>console.warn(n)})),ee),ye=()=>{t.search?.searxng?.url&&E().wake("searxng").catch(()=>{})};let Y=null;const ge=()=>{if(!Y){const n=t.search||{},o=n.searxng?.url?pa({url:n.searxng.url,token:n.searxng.token||"",engines:n.searxng.engines||"",safesearch:n.searxng.safesearch??null}):null;Y=ca({reader:N(),searxng:o,engines:()=>ha(t),wakeSearxng:()=>E().wake("searxng"),defaultProvider:n.provider||"auto",redact:async f=>{let i=f;return await Ye([ut(()=>i,Z=>{i=Z})],{...t.redaction,tier:"basic"},{isPro:!0}),i}})}return Y};dr(t.allowedExtensionIds||[]);const C=[],q=n=>{C.push(n),C.length>50&&C.shift()},ue=Qo(async(n,o)=>{const f=new URL(n.url,"http://127.0.0.1"),i=f.pathname;if(!it(n.headers.host))return a(o,403,{error:"loopback only"});if(!as(n.headers.origin,t))return a(o,403,{error:"origin not allowed"});if(it(t.host)&&Xn(n.headers))return a(o,403,{error:{message:"this gateway answers a tunnel only on its Link path (/v1/link)",type:"forbidden"}});if(n.headers.origin&&ss(o,n.headers.origin),n.method==="OPTIONS")return o.writeHead(204),o.end();if(i==="/admin/token"&&n.method==="POST")return U(n)?a(o,200,{token:_e()}):a(o,403,{error:"admin: extension origin or gateway token required"});if(i==="/pair/code"&&n.method==="POST"){if(!U(n))return a(o,403,{error:"pair/code: extension origin or gateway token required"});const e=cr();return console.log("[gateway] pairing code issued — valid for 5 minutes, one use"),a(o,200,{ok:!0,...e})}if(i==="/pair"&&n.method==="POST"){let e=null;try{e=JSON.parse((await T(n,t.maxBodyBytes)).toString("utf8"))}catch{e=null}const r=ur(e?.code);if(!r.ok)return console.log(`[gateway] pairing refused (${r.reason}) from ${Ie(n)} caller`),a(o,403,{error:r.reason});console.log(`[gateway] paired a ${Ie(n)} client${n.headers.origin?` (${n.headers.origin})`:""}`);const{token:s,refused:l}=await qt(t);return l&&console.log(`[gateway] pairing: the bridge at ${l.url}${l.version?` (v${l.version})`:""} accepts none of the tokens this gateway holds — not handing one over`),a(o,200,{ok:!0,token:Be()||_e(),...s?{bridgeToken:s}:{},...l?{bridgeRefused:l}:{}})}if(i==="/pair/ask"&&n.method==="POST"){const e=Ie(n);if(t.pairing?.prompt===!1)return a(o,403,{error:"pairing by confirmation is switched off on this gateway — use a pairing code",type:"disabled"});if(Wt(e))return a(o,409,{error:"this client is already trusted by the gateway",type:"already"});if(e!=="unpaired")return a(o,403,{error:"pair/ask: only a browser extension may ask to be paired",type:"forbidden"});let r=null;try{r=JSON.parse((await T(n,t.maxBodyBytes)).toString("utf8")||"{}")}catch{r=null}const s=u.ask({browser:r?.browser,who:n.headers.origin||""});if(!s.ok){const l=s.reason==="busy"?"a pairing question is already on screen — answer it, or wait a minute":"too many pairing questions — wait a few minutes, or use a pairing code";return a(o,429,{error:l,type:s.reason})}return console.log(`[gateway] pairing: an unrecognised extension (${n.headers.origin}) asked — the question is on screen`),a(o,202,{ok:!0,id:s.id,number:s.number,expiresAt:s.expiresAt})}if(i==="/pair/ask/result"&&n.method==="POST"){let e=null;try{e=JSON.parse((await T(n,t.maxBodyBytes)).toString("utf8")||"{}")}catch{e=null}const{status:r}=u.result(e?.id,{who:n.headers.origin||""});if(r!=="allowed")return a(o,200,{ok:!0,status:r});console.log(`[gateway] paired ${n.headers.origin} — allowed in the dialog on this computer`);const{token:s,refused:l}=await qt(t);return a(o,200,{ok:!0,status:r,token:Be()||_e(),...s?{bridgeToken:s}:{},...l?{bridgeRefused:l}:{}})}if(i==="/whoami"&&n.method==="POST"){const e=Ie(n);return a(o,200,{ok:!0,trust:e,paired:Wt(e),version:de})}if(i==="/audit"&&n.method==="GET")return U(n)?a(o,200,gr(t,{version:de,startedAt:Io,managed:Re(),certificates:{...br(),wanted:Kt(t)},linkPartners:y?y.status().devices.filter(e=>e.kind==="partner"):[],confined:yt({stateDir:ze.dirname(le())})})):a(o,403,{error:"audit: extension origin or gateway token required"});if((i==="/config"||i==="/logs"||i==="/update"&&n.method!=="GET")&&!U(n))return a(o,403,{error:"admin route: extension origin or gateway token required"});if(i==="/update"&&n.method==="GET"){const e=await ln(de,{force:f.searchParams.get("force")==="1"}).catch(r=>({current:de,updateAvailable:!1,error:String(r?.message||r)}));return a(o,200,{ok:!0,update:e,job:un()})}if(i==="/update"&&n.method==="POST"){const e=cn(de);return a(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 a(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 a(o,403,{error:{message:"history write — extension origin or gateway token required",type:"forbidden"}});if((i==="/v1/history/ingest"||i==="/v1/history/clear")&&n.method==="POST"&&!U(n))return a(o,403,{error:{message:"history write — extension origin or gateway token required",type:"forbidden"}});if((i==="/v1/memory/remember"||i==="/v1/memory/forget"||i==="/v1/memory/sync"||i==="/v1/memory/clear")&&n.method==="POST"&&!U(n))return a(o,403,{error:{message:"memory write — extension origin or gateway token required",type:"forbidden"}});if((i==="/v1/prefs"||i.startsWith("/v1/prefs/")||i.startsWith("/v1/teams")||i.startsWith("/v1/agents")||i.startsWith("/v1/projects"))&&!U(n))return a(o,403,{error:{message:"prefs: extension origin or gateway token required",type:"forbidden"}});if((i==="/v1/browser"||i.startsWith("/v1/browser/"))&&!U(n))return a(o,403,{error:{message:"browser: extension origin or gateway token required",type:"forbidden"}});if((i==="/v1/link"||i.startsWith("/v1/link/"))&&!U(n))return a(o,403,{error:{message:"link: extension origin or gateway token required",type:"forbidden"}});if((i==="/v1/events"||i.startsWith("/v1/events/"))&&!U(n))return a(o,403,{error:{message:"events: extension origin or gateway token required",type:"forbidden"}});if(i.startsWith("/v1/observability")&&!U(n))return a(o,403,{error:{message:"observability: extension origin or gateway token required",type:"forbidden"}});if(n.method==="GET"&&i==="/")return o.writeHead(200,{"content-type":"text/plain; charset=utf-8","cache-control":"no-store"}),o.end(`ChatPanel Privacy Gateway v${de} is running.
21
21
 
22
22
  This address is for ChatPanel's apps, not a web page — there is nothing to open here.
23
23
  Use ChatPanel itself (the browser extension's Settings, or the desktop app).
24
24
  In a terminal, \`chatpanel-gateway --status\` shows what is running.
25
- `);if(n.method==="GET"&&i==="/health"){const e=$.health(),r=D.health();return a(o,200,{ok:!0,version:de,backend:t.backend,tier:t.redaction.tier,pairing:!0,pairPrompt:t.pairing?.prompt!==!1,...Re()?{managed:Re()}:{},...process.env.CHATPANEL_MANAGED_BY?{managedBy:String(process.env.CHATPANEL_MANAGED_BY).slice(0,32)}:{},install:mn(),confined:yt({stateDir:ze.dirname(le())}),...hn({release:bt.release()})?{appleHelper:!!ft()}:{},...He?{bridge:He.status()}:lt?{bridge:lt}:{},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||ot,runtime:e.runtime,dtype:e.dtype},tts:{enabled:t.tts?.enabled!==!1,state:r.state,ready:r.ok,model:r.model||t.tts?.model||To,voice:t.tts?.voice||Oe,runtime:r.runtime,dtype:r.dtype},events:q?{count:q.count(),hosts:q.hosts().length}:null,browser:m.health()})}if(i==="/status"&&n.method==="GET"){Xo(t);const e=await Te(t.pro?.entitlementToken),r=await Lo(t);return a(o,200,{ok:!0,version:de,backend:t.backend,tier:t.redaction.tier,search:{provider:t.search?.provider||"auto",searxng:!!t.search?.searxng?.url},...Re()?{managed:Re()}:{},...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:At(t),pro:{unlocked:e},usage:za(t),uptimeSeconds:Math.floor((Date.now()-Io)/1e3),update:dn(de)})}if(i==="/v1/history/ingest"&&n.method==="POST")try{const e=JSON.parse((await T(n,t.maxBodyBytes)).toString("utf8"))||{},r=R.bulk({upserts:Array.isArray(e.upserts)?e.upserts:[],removes:Array.isArray(e.removes)?e.removes:[]});return a(o,200,{ok:!0,size:r})}catch(e){return a(o,400,{error:{message:`ingest failed: ${e.message}`,type:"ingest_error"}})}if(i==="/v1/prefs"&&n.method==="GET"){const e=String(f.searchParams.get("section")||"");return f.searchParams.get("stamps")?a(o,200,{ok:!0,revision:ce.revision,stamps:ce.stamps()}):a(o,200,{ok:!0,revision:ce.revision,sections:ce.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=ce.put(e.sections||{},{by:e.by||""});return r.applied.length&&No(r.applied,e.by||""),a(o,200,{ok:!0,...r})}catch(e){return a(o,400,{error:{message:`prefs write failed: ${e.message}`,type:"prefs_error"}})}if(i==="/v1/prefs"&&n.method==="DELETE"){const e=String(f.searchParams.get("section")||""),r=e?ce.remove(e):!1;return r&&No([e],""),a(o,200,{ok:!0,removed:r})}if(i==="/v1/prefs/events"&&n.method==="GET"){o.writeHead(200,{"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive"});const e=l=>o.write(`data: ${JSON.stringify(l)}
25
+ `);if(n.method==="GET"&&i==="/health"){const e=$.health(),r=D.health();return a(o,200,{ok:!0,version:de,backend:t.backend,tier:t.redaction.tier,pairing:!0,pairPrompt:t.pairing?.prompt!==!1,...Re()?{managed:Re()}:{},...process.env.CHATPANEL_MANAGED_BY?{managedBy:String(process.env.CHATPANEL_MANAGED_BY).slice(0,32)}:{},install:mn(),confined:yt({stateDir:ze.dirname(le())}),...hn({release:bt.release()})?{appleHelper:!!ft()}:{},...He?{bridge:He.status()}:lt?{bridge:lt}:{},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||ot,runtime:e.runtime,dtype:e.dtype},tts:{enabled:t.tts?.enabled!==!1,state:r.state,ready:r.ok,model:r.model||t.tts?.model||To,voice:t.tts?.voice||Oe,runtime:r.runtime,dtype:r.dtype},events:Q?{count:Q.count(),hosts:Q.hosts().length}:null,browser:p.health()})}if(i==="/status"&&n.method==="GET"){Xo(t);const e=await Te(t.pro?.entitlementToken),r=await Lo(t);return a(o,200,{ok:!0,version:de,backend:t.backend,tier:t.redaction.tier,search:{provider:t.search?.provider||"auto",searxng:!!t.search?.searxng?.url},...Re()?{managed:Re()}:{},...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:At(t),pro:{unlocked:e},usage:za(t),uptimeSeconds:Math.floor((Date.now()-Io)/1e3),update:dn(de)})}if(i==="/v1/history/ingest"&&n.method==="POST")try{const e=JSON.parse((await T(n,t.maxBodyBytes)).toString("utf8"))||{},r=j.bulk({upserts:Array.isArray(e.upserts)?e.upserts:[],removes:Array.isArray(e.removes)?e.removes:[]});return a(o,200,{ok:!0,size:r})}catch(e){return a(o,400,{error:{message:`ingest failed: ${e.message}`,type:"ingest_error"}})}if(i==="/v1/prefs"&&n.method==="GET"){const e=String(f.searchParams.get("section")||"");return f.searchParams.get("stamps")?a(o,200,{ok:!0,revision:ce.revision,stamps:ce.stamps()}):a(o,200,{ok:!0,revision:ce.revision,sections:ce.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=ce.put(e.sections||{},{by:e.by||""});return r.applied.length&&No(r.applied,e.by||""),a(o,200,{ok:!0,...r})}catch(e){return a(o,400,{error:{message:`prefs write failed: ${e.message}`,type:"prefs_error"}})}if(i==="/v1/prefs"&&n.method==="DELETE"){const e=String(f.searchParams.get("section")||""),r=e?ce.remove(e):!1;return r&&No([e],""),a(o,200,{ok:!0,removed:r})}if(i==="/v1/prefs/events"&&n.method==="GET"){o.writeHead(200,{"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive"});const e=l=>o.write(`data: ${JSON.stringify(l)}
26
26
 
27
27
  `);e({type:"hello",revision:ce.revision,stamps:ce.stamps()});const r=l=>e({type:"changed",...l});Et.add(r);const s=setInterval(()=>{try{o.write(`: keep-alive
28
28
 
29
- `)}catch{}},25e3);o.on("close",()=>{Et.delete(r),clearInterval(s)});return}if(i==="/v1/projects"&&n.method==="GET")return a(o,200,{ok:!0,projects:he.list({limit:f.searchParams.get("limit")||50,status:f.searchParams.get("status")||""})});if(i==="/v1/projects/jobs"&&n.method==="GET")return a(o,200,{ok:!0,jobs:he.openJobs()});if(i==="/v1/projects"&&n.method==="POST")try{const e=JSON.parse((await T(n,t.maxBodyBytes)).toString("utf8"))||{};return a(o,200,{ok:!0,project:he.create({id:e.id||e.project?.id,project:e.project||null,by:e.by})})}catch(e){return a(o,400,{error:{message:`project: ${e.message}`,type:"project_error"}})}{const e=/^\/v1\/projects\/([a-zA-Z0-9_-]{1,64})(\/events|\/jobs(?:\/([a-zA-Z0-9_-]{1,64})(\/applications|\/recruit)?)?)?$/.exec(i);if(e){const r=e[1],s=e[2]||"",l=e[3]||"",d=e[4]||"",p=()=>a(o,404,{error:{message:`no project ${r}`,type:"not_found"}});if(d){const h=he.get(r);if(!h)return p();const w=h.jobs.find(b=>b.id===l);if(!w)return a(o,404,{error:{message:`no job ${l}`,type:"not_found"}});const k={cfg:t,prefsStore:ce,scorecards:Me,engines:De,engineAt:c.engineAt};if(d==="/applications"&&n.method==="GET"){const b=await rn(w,{...k,reach:f.searchParams.get("reach")||"any",chatModel:f.searchParams.get("chatModel")||null});return a(o,200,{ok:!0,job:w,...b})}if(d==="/recruit"&&n.method==="POST"){if(!["open","evaluating"].includes(w.status))return a(o,400,{error:{message:`job ${l} is ${w.status}; only an open job is recruited`,type:"project_error"}});try{const b=JSON.parse((await T(n,t.maxBodyBytes)).toString("utf8"))||{},B=String(b.by||"evaluator").slice(0,80),_=await nn(w,{...k,record:h,reach:b.reach||"any",chatModel:b.chatModel||null,evaluation:b.evaluation||null,text:b.text??null,by:B});let j=null;for(const me of _.events)me.type==="job.updated"?j=he.updateJob(r,l,me.job,{by:me.by||B}):j=he.append(r,[me]);return a(o,200,{ok:!0,project:j,decision:_.decision,applications:_.applications,evaluation:_.evaluation})}catch(b){return a(o,400,{error:{message:`recruit: ${b.message}`,type:"project_error"}})}}return a(o,405,{error:{message:"method not allowed",type:"project_error"}})}if(!s&&n.method==="GET"){const h=he.get(r,{events:f.searchParams.get("events")==="1"});return h?a(o,200,{ok:!0,project:h}):p()}if(!s&&n.method==="DELETE")return a(o,200,{ok:!0,removed:he.remove(r)});if(n.method==="POST"&&(s==="/events"||s.startsWith("/jobs")))try{const h=JSON.parse((await T(n,t.maxBodyBytes)).toString("utf8"))||{},w=String(h.by||"person").slice(0,80),k=s==="/events"?he.append(r,h.events||[]):l?he.updateJob(r,l,h.patch||h,{by:w}):he.postJob(r,h.job||h,{by:w});return a(o,200,{ok:!0,project:k})}catch(h){return a(o,h.message.startsWith("no ")?404:400,{error:{message:`project: ${h.message}`,type:"project_error"}})}if(s==="/events"&&n.method==="GET"){if(!he.get(r))return p();o.writeHead(200,{"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive"});const h=B=>o.write(`data: ${JSON.stringify(B)}
29
+ `)}catch{}},25e3);o.on("close",()=>{Et.delete(r),clearInterval(s)});return}if(i==="/v1/projects"&&n.method==="GET")return a(o,200,{ok:!0,projects:he.list({limit:f.searchParams.get("limit")||50,status:f.searchParams.get("status")||""})});if(i==="/v1/projects/jobs"&&n.method==="GET")return a(o,200,{ok:!0,jobs:he.openJobs()});if(i==="/v1/projects"&&n.method==="POST")try{const e=JSON.parse((await T(n,t.maxBodyBytes)).toString("utf8"))||{};return a(o,200,{ok:!0,project:he.create({id:e.id||e.project?.id,project:e.project||null,by:e.by})})}catch(e){return a(o,400,{error:{message:`project: ${e.message}`,type:"project_error"}})}{const e=/^\/v1\/projects\/([a-zA-Z0-9_-]{1,64})(\/events|\/jobs(?:\/([a-zA-Z0-9_-]{1,64})(\/applications|\/recruit)?)?)?$/.exec(i);if(e){const r=e[1],s=e[2]||"",l=e[3]||"",d=e[4]||"",m=()=>a(o,404,{error:{message:`no project ${r}`,type:"not_found"}});if(d){const h=he.get(r);if(!h)return m();const w=h.jobs.find(b=>b.id===l);if(!w)return a(o,404,{error:{message:`no job ${l}`,type:"not_found"}});const k={cfg:t,prefsStore:ce,scorecards:Me,engines:De,engineAt:c.engineAt};if(d==="/applications"&&n.method==="GET"){const b=await rn(w,{...k,reach:f.searchParams.get("reach")||"any",chatModel:f.searchParams.get("chatModel")||null});return a(o,200,{ok:!0,job:w,...b})}if(d==="/recruit"&&n.method==="POST"){if(!["open","evaluating"].includes(w.status))return a(o,400,{error:{message:`job ${l} is ${w.status}; only an open job is recruited`,type:"project_error"}});try{const b=JSON.parse((await T(n,t.maxBodyBytes)).toString("utf8"))||{},B=String(b.by||"evaluator").slice(0,80),_=await nn(w,{...k,record:h,reach:b.reach||"any",chatModel:b.chatModel||null,evaluation:b.evaluation||null,text:b.text??null,by:B});let J=null;for(const me of _.events)me.type==="job.updated"?J=he.updateJob(r,l,me.job,{by:me.by||B}):J=he.append(r,[me]);return a(o,200,{ok:!0,project:J,decision:_.decision,applications:_.applications,evaluation:_.evaluation})}catch(b){return a(o,400,{error:{message:`recruit: ${b.message}`,type:"project_error"}})}}return a(o,405,{error:{message:"method not allowed",type:"project_error"}})}if(!s&&n.method==="GET"){const h=he.get(r,{events:f.searchParams.get("events")==="1"});return h?a(o,200,{ok:!0,project:h}):m()}if(!s&&n.method==="DELETE")return a(o,200,{ok:!0,removed:he.remove(r)});if(n.method==="POST"&&(s==="/events"||s.startsWith("/jobs")))try{const h=JSON.parse((await T(n,t.maxBodyBytes)).toString("utf8"))||{},w=String(h.by||"person").slice(0,80),k=s==="/events"?he.append(r,h.events||[]):l?he.updateJob(r,l,h.patch||h,{by:w}):he.postJob(r,h.job||h,{by:w});return a(o,200,{ok:!0,project:k})}catch(h){return a(o,h.message.startsWith("no ")?404:400,{error:{message:`project: ${h.message}`,type:"project_error"}})}if(s==="/events"&&n.method==="GET"){if(!he.get(r))return m();o.writeHead(200,{"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive"});const h=B=>o.write(`data: ${JSON.stringify(B)}
30
30
 
31
31
  `);let w=f.searchParams.has("after")?Number(f.searchParams.get("after")):-1;h({seq:-1,type:"hello",at:Date.now(),payload:{project:he.get(r),after:w}});const k=he.watch(r,B=>{B.seq>w&&(w=B.seq,h(B))});for(const B of he.eventsSince(r,w))w=B.seq,h(B);const b=setInterval(()=>{try{o.write(`: keep
32
32
 
33
- `)}catch{}},25e3);n.on("close",()=>{clearInterval(b),k()});return}}}if(i==="/v1/agents/scorecards"&&n.method==="GET")return a(o,200,{ok:!0,agents:Me.list()});{const e=/^\/v1\/agents\/([a-zA-Z0-9_.:@+-]{1,120})\/scorecard$/.exec(i);if(e){const r=decodeURIComponent(e[1]);if(n.method==="GET")return a(o,200,{ok:!0,...await Me.get(r)});if(n.method==="POST")try{const s=JSON.parse((await T(n,t.maxBodyBytes)).toString("utf8"))||{},l=await Me.append({agentId:r,kind:"rating",runId:s.runId,taskId:s.taskId,jobId:s.jobId,rating:{by:String(s.by||"person").slice(0,40),score:s.score,note:s.note,about:s.about},refs:s.refs});return De.fromRating(Me.chains.get(r)||[],{...l,jobKind:s.jobKind?String(s.jobKind).slice(0,60):void 0}),a(o,200,{ok:!0,entry:l})}catch(s){return a(o,400,{error:{message:`scorecard: ${s.message}`,type:"scorecard_error"}})}}}if(i==="/v1/capabilities"&&n.method==="GET")return a(o,200,Bn(t,{version:de,reader:P,searcher:Q,extract:S(),proxy:te}));if(i==="/v1/fusions"&&n.method==="GET"){const e={active:I.health().model||t.ner?.model||null,companions:I.companions()};let r=null;try{r=await E().status()}catch{r=null}return a(o,200,_n({cfg:t,ner:e,runtimeDoc:r}))}if(i==="/v1/runtime"&&n.method==="GET"){const e=Object.fromEntries(Gn.map(r=>{const s=St(t,r);return[r,{provider:s.kind,model:s.kind==="embedded"?s.model:null,models:zn[r],threads:L.threads,...s.kind==="embedded"?L.health(r,s.model):{}}]}));return a(o,200,{...await E().status(),inProcess:e})}if(i==="/v1/runtime/plan"&&n.method==="GET"){const e=new URL(n.url,"http://x").searchParams,r=await E().plan(String(e.get("service")||"mlx"),{model:e.get("model")||void 0,ctx:e.get("ctx"),needMB:e.get("need_mb")});return a(o,r.ok?200:400,r)}{const e=/^\/v1\/runtime\/(engines|services)\/([a-z0-9-]+)$/.exec(i);if(e&&n.method==="POST"){if(!U(n))return a(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 s=String(r.action||"start"),l=E(),d=e[1]==="engines"?s==="start"?await l.startEngine(e[2]):{ok:!1,error:`unknown action ${s}`}:s==="start"?await l.startService(e[2],{force:r.force===!0}):s==="stop"?await l.stopService(e[2]):s==="model"?await l.setModel(e[2],r.model):s==="tune"?await l.setTunings(e[2],r.tunings):s==="profile"?await l.setProfile(e[2],r.profile):s==="pull"?await l.pullModel(e[2]):s==="install"?await l.installRunner(e[2]):s==="cancel"?l.cancelJob(e[2]):{ok:!1,error:`unknown action ${s}`};return a(o,d.ok?200:400,d)}}if(i==="/v1/embeddings"&&n.method==="POST"){let e;try{e=JSON.parse((await T(n,t.maxBodyBytes)).toString("utf8"))}catch{return a(o,400,{error:{message:"embed: body must be JSON",type:"invalid_request"}})}const r=await te.call("embed",e);return a(o,r.status,r.body)}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 a(o,400,{error:{message:`${e}: body must be JSON`,type:"invalid_request"}})}const s=await te.call(e,r);return a(o,s.status,s.body)}if(i==="/v1/detect"&&n.method==="POST"){let e;try{e=JSON.parse((await T(n,t.maxBodyBytes)).toString("utf8"))}catch{return a(o,400,{error:{message:"detect: body must be JSON",type:"invalid_request"}})}try{const r=await Mn(e,{ensure:()=>tt(t),model:I.health().model});return a(o,r.status,r.body)}catch(r){return a(o,500,{error:{message:`detect: ${r.message}`,type:"detector_error"}})}}if(i==="/v1/extract/context"&&n.method==="POST"){let e;try{e=JSON.parse((await T(n,Math.max(t.maxBodyBytes,Math.ceil(kt*4/3)+1024))).toString("utf8"))}catch{return a(o,400,{error:{message:"extract/context: body must be JSON",type:"invalid_request"}})}const r=await Un(e,{service:S()});return a(o,r.status,r.body)}if((i==="/v1/files/write"||i==="/v1/files/exists")&&n.method==="POST"){if(!U(n)||vt(n.headers))return a(o,403,{error:{message:"files: a client on this computer with the gateway token or the pinned extension only",type:"forbidden"}});let e;try{e=JSON.parse((await T(n,Math.max(t.maxBodyBytes,la*6+4096))).toString("utf8"))}catch{return a(o,400,{error:{message:"files: body must be JSON",type:"invalid_request"}})}const r=await ia(i.slice(10),e);return a(o,r.status,r.body)}if(i==="/v1/extract"&&n.method==="POST"){let e;try{e=JSON.parse((await T(n,Math.max(t.maxBodyBytes,Math.ceil(kt*4/3)+1024))).toString("utf8"))}catch{return a(o,400,{error:{message:"extract: body must be JSON",type:"invalid_request"}})}const r=await Hn(e,{service:S()});return a(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 a(o,400,{error:{message:"read: body must be JSON",type:"invalid_request"}})}const r=await N().read(e);return a(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 a(o,400,{error:{message:"search: body must be JSON",type:"invalid_request"}})}ue();const r=await Y().search(e);return a(o,r.status,r.body)}if(/^\/v1\/search\/./.test(i)&&n.method==="GET"){let e;try{e=decodeURIComponent(i.slice(11))}catch{e=i.slice(11)}const r=f.searchParams.has("read")?Math.max(0,Math.min(10,Number(f.searchParams.get("read"))||0)):ma.aliasRead;ue();const s=await Y().search({q:e,read:r,limit:Math.max(r,5)});return a(o,s.status,s.status===200?ua(s.body):s.body)}if(/^\/v1\/read\/./.test(i)&&n.method==="GET"){const e=String(n.url||"").slice(9),r=/^https?:\/\//i.test(e)?e:decodeURIComponent(e),s=/application\/json/i.test(n.headers.accept||""),l=/^text$/i.test(n.headers["x-return-format"]||"")?"text":"markdown",d=await N().read({url:r,format:l});return d.status!==200||s?a(o,d.status,d.status===200?{code:200,status:2e4,data:d.body}:d.body):(o.writeHead(200,{"content-type":"text/plain; charset=utf-8","x-chatpanel-provider":d.body.provider}),o.end(ya(d.body)))}if(i==="/v1/engines"&&n.method==="GET"){const e=Number(f.searchParams.get("minCalls"))||void 0;return a(o,200,{ok:!0,engines:De.list({minCalls:e})})}{const e=/^\/v1\/engines\/(.+)\/(card|entries)$/.exec(i);if(e){const r=decodeURIComponent(e[1]).slice(0,300);if(e[2]==="card"&&n.method==="GET"){const s=Number(f.searchParams.get("minCalls"))||void 0;return a(o,200,{ok:!0,...await De.get(r,{entries:f.searchParams.get("entries")==="1",minCalls:s})})}if(e[2]==="entries"&&n.method==="POST")try{const s=JSON.parse((await T(n,t.maxBodyBytes)).toString("utf8"))||{},l=s.engine||ls(r);if(!l)return a(o,400,{error:{message:"model-ledger: engine required",type:"model_ledger_error"}});const d=await De.append({...s,engine:l,kind:s.kind||"call"});return d.key!==r?a(o,400,{error:{message:`model-ledger: entry is for ${d.key}, not ${r}`,type:"model_ledger_error"}}):a(o,200,{ok:!0,entry:d})}catch(s){return a(o,400,{error:{message:`model-ledger: ${s.message}`,type:"model_ledger_error"}})}}}if(i==="/v1/teams/stream"&&n.method==="GET"){o.writeHead(200,{"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive"});const e=l=>{try{o.write(`data: ${JSON.stringify(l)}
33
+ `)}catch{}},25e3);n.on("close",()=>{clearInterval(b),k()});return}}}if(i==="/v1/agents/scorecards"&&n.method==="GET")return a(o,200,{ok:!0,agents:Me.list()});{const e=/^\/v1\/agents\/([a-zA-Z0-9_.:@+-]{1,120})\/scorecard$/.exec(i);if(e){const r=decodeURIComponent(e[1]);if(n.method==="GET")return a(o,200,{ok:!0,...await Me.get(r)});if(n.method==="POST")try{const s=JSON.parse((await T(n,t.maxBodyBytes)).toString("utf8"))||{},l=await Me.append({agentId:r,kind:"rating",runId:s.runId,taskId:s.taskId,jobId:s.jobId,rating:{by:String(s.by||"person").slice(0,40),score:s.score,note:s.note,about:s.about},refs:s.refs});return De.fromRating(Me.chains.get(r)||[],{...l,jobKind:s.jobKind?String(s.jobKind).slice(0,60):void 0}),a(o,200,{ok:!0,entry:l})}catch(s){return a(o,400,{error:{message:`scorecard: ${s.message}`,type:"scorecard_error"}})}}}if(i==="/v1/capabilities"&&n.method==="GET")return a(o,200,Bn(t,{version:de,reader:P,searcher:Y,extract:S(),proxy:X}));if(i==="/v1/fusions"&&n.method==="GET"){const e={active:R.health().model||t.ner?.model||null,companions:R.companions()};let r=null;try{r=await E().status()}catch{r=null}return a(o,200,_n({cfg:t,ner:e,runtimeDoc:r}))}if(i==="/v1/runtime"&&n.method==="GET"){const e=Object.fromEntries(Gn.map(r=>{const s=St(t,r);return[r,{provider:s.kind,model:s.kind==="embedded"?s.model:null,models:zn[r],threads:z.threads,...s.kind==="embedded"?z.health(r,s.model):{}}]}));return a(o,200,{...await E().status(),inProcess:e})}if(i==="/v1/runtime/plan"&&n.method==="GET"){const e=new URL(n.url,"http://x").searchParams,r=await E().plan(String(e.get("service")||"mlx"),{model:e.get("model")||void 0,ctx:e.get("ctx"),needMB:e.get("need_mb")});return a(o,r.ok?200:400,r)}{const e=/^\/v1\/runtime\/(engines|services)\/([a-z0-9-]+)$/.exec(i);if(e&&n.method==="POST"){if(!U(n))return a(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 s=String(r.action||"start"),l=E(),d=e[1]==="engines"?s==="start"?await l.startEngine(e[2]):{ok:!1,error:`unknown action ${s}`}:s==="start"?await l.startService(e[2],{force:r.force===!0}):s==="stop"?await l.stopService(e[2]):s==="model"?await l.setModel(e[2],r.model):s==="tune"?await l.setTunings(e[2],r.tunings):s==="profile"?await l.setProfile(e[2],r.profile):s==="pull"?await l.pullModel(e[2]):s==="install"?await l.installRunner(e[2]):s==="cancel"?l.cancelJob(e[2]):{ok:!1,error:`unknown action ${s}`};return a(o,d.ok?200:400,d)}}if(i==="/v1/embeddings"&&n.method==="POST"){let e;try{e=JSON.parse((await T(n,t.maxBodyBytes)).toString("utf8"))}catch{return a(o,400,{error:{message:"embed: body must be JSON",type:"invalid_request"}})}const r=await X.call("embed",e);return a(o,r.status,r.body)}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 a(o,400,{error:{message:`${e}: body must be JSON`,type:"invalid_request"}})}const s=await X.call(e,r);return a(o,s.status,s.body)}if(i==="/v1/detect"&&n.method==="POST"){let e;try{e=JSON.parse((await T(n,t.maxBodyBytes)).toString("utf8"))}catch{return a(o,400,{error:{message:"detect: body must be JSON",type:"invalid_request"}})}try{const r=await Mn(e,{ensure:()=>tt(t),model:R.health().model});return a(o,r.status,r.body)}catch(r){return a(o,500,{error:{message:`detect: ${r.message}`,type:"detector_error"}})}}if(i==="/v1/extract/context"&&n.method==="POST"){let e;try{e=JSON.parse((await T(n,Math.max(t.maxBodyBytes,Math.ceil(kt*4/3)+1024))).toString("utf8"))}catch{return a(o,400,{error:{message:"extract/context: body must be JSON",type:"invalid_request"}})}const r=await Un(e,{service:S()});return a(o,r.status,r.body)}if((i==="/v1/files/write"||i==="/v1/files/exists")&&n.method==="POST"){if(!U(n)||vt(n.headers))return a(o,403,{error:{message:"files: a client on this computer with the gateway token or the pinned extension only",type:"forbidden"}});let e;try{e=JSON.parse((await T(n,Math.max(t.maxBodyBytes,la*6+4096))).toString("utf8"))}catch{return a(o,400,{error:{message:"files: body must be JSON",type:"invalid_request"}})}const r=await ia(i.slice(10),e);return a(o,r.status,r.body)}if(i==="/v1/extract"&&n.method==="POST"){let e;try{e=JSON.parse((await T(n,Math.max(t.maxBodyBytes,Math.ceil(kt*4/3)+1024))).toString("utf8"))}catch{return a(o,400,{error:{message:"extract: body must be JSON",type:"invalid_request"}})}const r=await Hn(e,{service:S()});return a(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 a(o,400,{error:{message:"read: body must be JSON",type:"invalid_request"}})}const r=await N().read(e);return a(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 a(o,400,{error:{message:"search: body must be JSON",type:"invalid_request"}})}ye();const r=await ge().search(e);return a(o,r.status,r.body)}if(/^\/v1\/search\/./.test(i)&&n.method==="GET"){let e;try{e=decodeURIComponent(i.slice(11))}catch{e=i.slice(11)}const r=f.searchParams.has("read")?Math.max(0,Math.min(10,Number(f.searchParams.get("read"))||0)):ma.aliasRead;ye();const s=await ge().search({q:e,read:r,limit:Math.max(r,5)});return a(o,s.status,s.status===200?ua(s.body):s.body)}if(/^\/v1\/read\/./.test(i)&&n.method==="GET"){const e=String(n.url||"").slice(9),r=/^https?:\/\//i.test(e)?e:decodeURIComponent(e),s=/application\/json/i.test(n.headers.accept||""),l=/^text$/i.test(n.headers["x-return-format"]||"")?"text":"markdown",d=await N().read({url:r,format:l});return d.status!==200||s?a(o,d.status,d.status===200?{code:200,status:2e4,data:d.body}:d.body):(o.writeHead(200,{"content-type":"text/plain; charset=utf-8","x-chatpanel-provider":d.body.provider}),o.end(ya(d.body)))}if(i==="/v1/engines"&&n.method==="GET"){const e=Number(f.searchParams.get("minCalls"))||void 0;return a(o,200,{ok:!0,engines:De.list({minCalls:e})})}{const e=/^\/v1\/engines\/(.+)\/(card|entries)$/.exec(i);if(e){const r=decodeURIComponent(e[1]).slice(0,300);if(e[2]==="card"&&n.method==="GET"){const s=Number(f.searchParams.get("minCalls"))||void 0;return a(o,200,{ok:!0,...await De.get(r,{entries:f.searchParams.get("entries")==="1",minCalls:s})})}if(e[2]==="entries"&&n.method==="POST")try{const s=JSON.parse((await T(n,t.maxBodyBytes)).toString("utf8"))||{},l=s.engine||ls(r);if(!l)return a(o,400,{error:{message:"model-ledger: engine required",type:"model_ledger_error"}});const d=await De.append({...s,engine:l,kind:s.kind||"call"});return d.key!==r?a(o,400,{error:{message:`model-ledger: entry is for ${d.key}, not ${r}`,type:"model_ledger_error"}}):a(o,200,{ok:!0,entry:d})}catch(s){return a(o,400,{error:{message:`model-ledger: ${s.message}`,type:"model_ledger_error"}})}}}if(i==="/v1/teams/stream"&&n.method==="GET"){o.writeHead(200,{"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive"});const e=l=>{try{o.write(`data: ${JSON.stringify(l)}
34
34
 
35
- `)}catch{}};e({type:"hello",at:Date.now()});const r=ee.watchAll(l=>e({type:"run",id:l.id,removed:!!l.removed})),s=setInterval(()=>{try{o.write(`: keep-alive
35
+ `)}catch{}};e({type:"hello",at:Date.now()});const r=oe.watchAll(l=>e({type:"run",id:l.id,removed:!!l.removed})),s=setInterval(()=>{try{o.write(`: keep-alive
36
36
 
37
- `)}catch{}},25e3);o.on("close",()=>{r(),clearInterval(s)});return}if(i==="/v1/teams/runs"&&n.method==="GET")return a(o,200,{ok:!0,runs:ee.list({limit:f.searchParams.get("limit")||50,team:f.searchParams.get("team")||""})});if(i==="/v1/teams/runs"&&n.method==="POST")try{const e=JSON.parse((await T(n,t.maxBodyBytes)).toString("utf8"))||{};return a(o,200,{ok:!0,run:ee.create({id:e.id,client:e.client,team:e.team,request:e.request})})}catch(e){return a(o,400,{error:{message:`team run: ${e.message}`,type:"team_error"}})}{const e=/^\/v1\/teams\/runs\/([a-zA-Z0-9_-]{4,64})(\/events|\/stop|\/answer|\/decide|\/post|\/handoff|\/checkpoint|\/claim|\/threads\/[a-zA-Z0-9_:-]{1,80})?$/.exec(i);if(e){const r=e[1],s=e[2]||"";if(!s&&n.method==="GET"){const l=ee.get(r,{events:f.searchParams.get("events")==="1"});return l?a(o,200,{ok:!0,run:l}):a(o,404,{error:{message:`no run ${r}`,type:"not_found"}})}if(!s&&n.method==="DELETE")return ee.stop(r),a(o,200,{ok:!0,removed:ee.remove(r)});if(s==="/stop"&&n.method==="POST"){const l=ee.stop(r);return l?a(o,200,{ok:!0,run:l}):a(o,404,{error:{message:`no run ${r}`,type:"not_found"}})}if(s==="/checkpoint"&&n.method==="GET")try{return a(o,200,{ok:!0,checkpoint:ee.checkpoint(r)})}catch(l){return a(o,404,{error:{message:`team run: ${l.message}`,type:"team_error"}})}if((s==="/handoff"||s==="/claim")&&n.method==="POST")try{const l=JSON.parse((await T(n,t.maxBodyBytes)).toString("utf8"))||{},d=s==="/handoff"?ee.handoff(r,{taskId:l.taskId,model:l.model,by:l.by,reason:l.reason}):ee.claim(r,{client:l.client});return a(o,200,{ok:!0,run:d})}catch(l){return a(o,l.message.startsWith("no ")?404:400,{error:{message:`team run: ${l.message}`,type:"team_error"}})}if(s.startsWith("/threads/")&&n.method==="DELETE")try{return a(o,200,{ok:!0,run:ee.removeThread(r,{threadId:s.slice(9),by:"person"})})}catch(l){return a(o,l.message.startsWith("no ")?404:400,{error:{message:`team run: ${l.message}`,type:"team_error"}})}if((s==="/answer"||s==="/decide"||s==="/post")&&n.method==="POST")try{const l=JSON.parse((await T(n,t.maxBodyBytes)).toString("utf8"))||{},d=String(l.by||"person").slice(0,40),p=s==="/answer"?ee.answer(r,{threadId:l.threadId,text:l.text,by:d}):s==="/decide"?ee.decide(r,{postId:l.postId,status:l.status,by:d}):ee.post(r,{threadId:l.threadId,text:l.text,by:d,kind:l.kind,replyTo:l.replyTo});return a(o,200,{ok:!0,run:p})}catch(l){return a(o,l.message.startsWith("no ")?404:400,{error:{message:`team run: ${l.message}`,type:"team_error"}})}if(s==="/events"&&n.method==="POST")try{const l=JSON.parse((await T(n,t.maxBodyBytes)).toString("utf8"))||{};return a(o,200,{ok:!0,run:ee.append(r,l.events||[])})}catch(l){return a(o,l.message.startsWith("no run")?404:400,{error:{message:`team run: ${l.message}`,type:"team_error"}})}if(s==="/events"&&n.method==="GET"){if(!ee.get(r))return a(o,404,{error:{message:`no run ${r}`,type:"not_found"}});o.writeHead(200,{"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive"});const l=k=>o.write(`data: ${JSON.stringify(k)}
37
+ `)}catch{}},25e3);o.on("close",()=>{r(),clearInterval(s)});return}if(i==="/v1/teams/runs"&&n.method==="GET")return a(o,200,{ok:!0,runs:oe.list({limit:f.searchParams.get("limit")||50,team:f.searchParams.get("team")||""})});if(i==="/v1/teams/runs"&&n.method==="POST")try{const e=JSON.parse((await T(n,t.maxBodyBytes)).toString("utf8"))||{};return a(o,200,{ok:!0,run:oe.create({id:e.id,client:e.client,team:e.team,request:e.request})})}catch(e){return a(o,400,{error:{message:`team run: ${e.message}`,type:"team_error"}})}{const e=/^\/v1\/teams\/runs\/([a-zA-Z0-9_-]{4,64})(\/events|\/stop|\/answer|\/decide|\/post|\/handoff|\/checkpoint|\/claim|\/threads\/[a-zA-Z0-9_:-]{1,80})?$/.exec(i);if(e){const r=e[1],s=e[2]||"";if(!s&&n.method==="GET"){const l=oe.get(r,{events:f.searchParams.get("events")==="1"});return l?a(o,200,{ok:!0,run:l}):a(o,404,{error:{message:`no run ${r}`,type:"not_found"}})}if(!s&&n.method==="DELETE")return oe.stop(r),a(o,200,{ok:!0,removed:oe.remove(r)});if(s==="/stop"&&n.method==="POST"){const l=oe.stop(r);return l?a(o,200,{ok:!0,run:l}):a(o,404,{error:{message:`no run ${r}`,type:"not_found"}})}if(s==="/checkpoint"&&n.method==="GET")try{return a(o,200,{ok:!0,checkpoint:oe.checkpoint(r)})}catch(l){return a(o,404,{error:{message:`team run: ${l.message}`,type:"team_error"}})}if((s==="/handoff"||s==="/claim")&&n.method==="POST")try{const l=JSON.parse((await T(n,t.maxBodyBytes)).toString("utf8"))||{},d=s==="/handoff"?oe.handoff(r,{taskId:l.taskId,model:l.model,by:l.by,reason:l.reason}):oe.claim(r,{client:l.client});return a(o,200,{ok:!0,run:d})}catch(l){return a(o,l.message.startsWith("no ")?404:400,{error:{message:`team run: ${l.message}`,type:"team_error"}})}if(s.startsWith("/threads/")&&n.method==="DELETE")try{return a(o,200,{ok:!0,run:oe.removeThread(r,{threadId:s.slice(9),by:"person"})})}catch(l){return a(o,l.message.startsWith("no ")?404:400,{error:{message:`team run: ${l.message}`,type:"team_error"}})}if((s==="/answer"||s==="/decide"||s==="/post")&&n.method==="POST")try{const l=JSON.parse((await T(n,t.maxBodyBytes)).toString("utf8"))||{},d=String(l.by||"person").slice(0,40),m=s==="/answer"?oe.answer(r,{threadId:l.threadId,text:l.text,by:d}):s==="/decide"?oe.decide(r,{postId:l.postId,status:l.status,by:d}):oe.post(r,{threadId:l.threadId,text:l.text,by:d,kind:l.kind,replyTo:l.replyTo});return a(o,200,{ok:!0,run:m})}catch(l){return a(o,l.message.startsWith("no ")?404:400,{error:{message:`team run: ${l.message}`,type:"team_error"}})}if(s==="/events"&&n.method==="POST")try{const l=JSON.parse((await T(n,t.maxBodyBytes)).toString("utf8"))||{};return a(o,200,{ok:!0,run:oe.append(r,l.events||[])})}catch(l){return a(o,l.message.startsWith("no run")?404:400,{error:{message:`team run: ${l.message}`,type:"team_error"}})}if(s==="/events"&&n.method==="GET"){if(!oe.get(r))return a(o,404,{error:{message:`no run ${r}`,type:"not_found"}});o.writeHead(200,{"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive"});const l=k=>o.write(`data: ${JSON.stringify(k)}
38
38
 
39
- `),d=f.searchParams.has("after")?Number(f.searchParams.get("after")):NaN;let p=Number.isFinite(d)?d:-1;l({seq:-1,type:"hello",at:Date.now(),payload:{run:ee.get(r),after:p}});const h=ee.watch(r,k=>{k.seq==null?l(k):k.seq>p&&(p=k.seq,l(k))});for(const k of ee.eventsSince(r,p))p=k.seq,l(k);const w=setInterval(()=>{try{o.write(`: keep-alive
39
+ `),d=f.searchParams.has("after")?Number(f.searchParams.get("after")):NaN;let m=Number.isFinite(d)?d:-1;l({seq:-1,type:"hello",at:Date.now(),payload:{run:oe.get(r),after:m}});const h=oe.watch(r,k=>{k.seq==null?l(k):k.seq>m&&(m=k.seq,l(k))});for(const k of oe.eventsSince(r,m))m=k.seq,l(k);const w=setInterval(()=>{try{o.write(`: keep-alive
40
40
 
41
- `)}catch{}},25e3);o.on("close",()=>{h(),clearInterval(w)});return}}}if(i==="/v1/memory/list"&&n.method==="GET")return a(o,200,{ok:!0,size:fe.size,memories:fe.list()});if(i==="/v1/memory/recall"&&n.method==="POST")try{const e=JSON.parse((await T(n,t.maxBodyBytes)).toString("utf8"))||{},r=fe.recall({text:String(e.text||""),scopes:Array.isArray(e.scopes)&&e.scopes.length?e.scopes.map(String):["global"],limit:Number(e.limit)||0,maxChars:Number(e.maxChars)||0});return a(o,200,{ok:!0,size:fe.size,...r})}catch(e){return a(o,400,{error:{message:`recall failed: ${e.message}`,type:"memory_error"}})}if(i==="/v1/memory/remember"&&n.method==="POST")try{const e=JSON.parse((await T(n,t.maxBodyBytes)).toString("utf8"))||{},r=fe.remember({text:String(e.text||""),kind:e.kind?String(e.kind):"fact",scope:e.scope?String(e.scope):"global",tags:Array.isArray(e.tags)?e.tags.map(String):[],source:{via:String(e.source?.via||"mcp"),surface:String(e.source?.surface||"mcp"),agent:String(e.source?.agent||""),ref:String(e.source?.ref||"")}});return a(o,200,{ok:!0,action:r.action,record:r.record,replaced:r.replaces||null,size:fe.size})}catch(e){return a(o,400,{error:{message:e.message,type:"memory_error"}})}if(i==="/v1/memory/forget"&&n.method==="POST")try{const e=JSON.parse((await T(n,t.maxBodyBytes)).toString("utf8"))||{},{removed:r}=fe.forget(String(e.query||""));return a(o,200,{ok:!0,removed:r,size:fe.size})}catch(e){return a(o,400,{error:{message:e.message,type:"memory_error"}})}if(i==="/v1/memory/sync"&&n.method==="POST")try{const e=JSON.parse((await T(n,t.maxBodyBytes)).toString("utf8"))||{},r=fe.bulk({upserts:Array.isArray(e.upserts)?e.upserts:[],removes:Array.isArray(e.removes)?e.removes:[]});return a(o,200,{ok:!0,...r,memories:fe.list()})}catch(e){return a(o,400,{error:{message:`memory sync failed: ${e.message}`,type:"memory_error"}})}if(i==="/v1/memory/clear"&&n.method==="POST")return a(o,200,{ok:!0,dropped:fe.clear(),size:fe.size});if(i==="/v1/history/clear"&&n.method==="POST"){const e=R.clear();return a(o,200,{ok:!0,dropped:e,size:R.size})}if(i==="/v1/history/search"&&n.method==="POST")try{const e=JSON.parse((await T(n,t.maxBodyBytes)).toString("utf8"))||{},r=R.search(String(e.query||""),{limit:Number(e.limit)||10,offset:Math.max(0,Number(e.offset)||0),type:e.type?String(e.type):null,since:e.since!=null?Number(e.since):null,before:e.before!=null?Number(e.before):null});return a(o,200,{ok:!0,size:R.size,newest:R.newest,results:r})}catch(e){return a(o,400,{error:{message:`search failed: ${e.message}`,type:"search_error"}})}if(i==="/v1/history/smart-search"&&n.method==="POST")try{const e=JSON.parse((await T(n,t.maxBodyBytes)).toString("utf8"))||{},r=String(e.question||e.query||""),s=Za(r,{extra:Array.isArray(e.queries)?e.queries.map(String):[],max:Math.min(6,Math.max(1,Number(e.maxQueries)||4))}),l={type:e.type?String(e.type):null,since:e.since!=null?Number(e.since):null,before:e.before!=null?Number(e.before):null},d=Math.min(30,Math.max(5,Number(e.limit)||10)*2),p=await qa(s,w=>R.search(w,{limit:d,...l}),{limit:Math.min(50,Math.max(1,Number(e.limit)||10))}),h=l.type?p:[...p.filter(w=>w.type==="brief"),...p.filter(w=>w.type!=="brief")];return a(o,200,{ok:!0,size:R.size,newest:R.newest,queries:s,results:h})}catch(e){return a(o,400,{error:{message:`smart search failed: ${e.message}`,type:"search_error"}})}if(i==="/v1/research"&&n.method==="POST"){let e;try{e=JSON.parse((await T(n,t.maxBodyBytes)).toString("utf8")||"{}")||{}}catch{return a(o,400,{error:{message:"research: the body must be JSON",type:"invalid_request_error"}})}const r=String(e.question||"").trim();if(!r)return a(o,400,{error:{message:"research: `question` is required",type:"invalid_request_error"}});const s=typeof e.model=="string"?e.model.trim():"";if(s&&!U(n))return a(o,403,{error:{message:"research with a model: extension origin or gateway token required",type:"forbidden"}});const l=`http://127.0.0.1:${n.socket.localPort}`,d=s?async(k,{maxTokens:b=220}={})=>{const B=new AbortController,_=setTimeout(()=>B.abort(),3e4);try{const j=Be()||_e(),me=await fetch(`${l}/v1/chat/completions`,{method:"POST",signal:B.signal,headers:{"content-type":"application/json",...j?{Authorization:`Bearer ${j}`}:{},"X-ChatPanel-Client":"research"},body:JSON.stringify({model:s,messages:[{role:"user",content:k}],stream:!1,max_tokens:b,temperature:.2})}),ge=await me.json().catch(()=>({}));return me.ok?String(ge?.choices?.[0]?.message?.content||""):""}finally{clearTimeout(_)}}:null,p=ce.get("identity")?.identity?.value||{},h=e.previous&&typeof e.previous=="object"&&e.previous.plan&&typeof e.previous.plan=="object"?{plan:e.previous.plan,top:typeof e.previous.top=="string"?e.previous.top:null,answer:String(e.previous.answer||"").slice(0,4e3)}:null,w=await Xr(r,{store:R,memories:fe.list(),complete:d,previous:h,self:String(p.selfName||"").trim(),excludeId:typeof e.excludeId=="string"?e.excludeId:null,parallel:3});return a(o,200,Zr(r,w,{size:R.size,newest:R.newest}))}if(i==="/v1/kb"||i.startsWith("/v1/kb/")){let e=null;if(n.method==="POST"||n.method==="PUT")try{const s=(await T(n,Math.max(t.maxBodyBytes,Math.ceil(kt*4/3)+1024))).toString("utf8");e=s?JSON.parse(s):{}}catch{return a(o,400,{error:{message:"kb: body must be JSON",type:"invalid_request"}})}const r=await oe().handle({method:n.method,pathname:i,query:f.searchParams,body:e,admin:U(n),agent:String(n.headers["x-chatpanel-agent"]||"")});return r.text!=null?(o.writeHead(r.status,{"content-type":r.contentType||"text/plain; charset=utf-8"}),o.end(r.text)):a(o,r.status,r.body)}if(i==="/v1/history/related"&&n.method==="GET"){const e=String(f.searchParams.get("id")||""),r=Math.min(30,Math.max(1,Number(f.searchParams.get("limit"))||5));return a(o,200,{ok:!0,results:R.related(e,{limit:r})})}if(i==="/v1/history/status"&&n.method==="GET")return a(o,200,{ok:!0,size:R.size,newest:R.newest,bytes:R.bytes,lossless:R.lossless?{records:R.lossless.size,newest:R.lossless.newest}:null});if(i==="/v1/observability"&&n.method==="GET"){const e=Math.min(500,Math.max(1,Number(f.searchParams.get("limit"))||200));return a(o,200,{ok:!0,storage:{warm:{records:R.size,bytes:R.bytes,newest:R.newest}},access:Pt.snapshot(e)})}if(i==="/v1/observability/access"&&n.method==="POST")try{const e=JSON.parse((await T(n,t.maxBodyBytes)).toString("utf8"))||{},r=Pt.push($o({ts:Date.now(),...e}));return a(o,200,{ok:!0,event:r})}catch(e){return a(o,400,{error:{message:`access log failed: ${e.message}`,type:"observability_error"}})}if(i==="/v1/history/records"&&n.method==="PUT"){const e=R.lossless;if(!e)return a(o,501,{error:{message:"lossless records need the SQLite warm store",type:"unavailable"}});try{const r=JSON.parse((await T(n,Math.max(t.maxBodyBytes||0,ps))).toString("utf8"))||{},s=String(r.host||"").slice(0,80),l=Number(r.at)||Date.now(),d=[];let p=0,h={},w=[],k=[];const b={upserts:[],removes:[]},B=_=>{if(!_||_.deletedAt){_?.id&&b.removes.push(_.id);return}try{const j=uo(_);j&&b.upserts.push(j)}catch{}};if(Array.isArray(r.records)){const _=e.write(r.records,{host:s,at:l,merge:r.merge===!0});d.push(..._.written),h=_.revs,w=_.conflicts,k=_.merged;for(const j of _.written)B(e.get(j))}if(Array.isArray(r.entries)){const _=pt(),j=_?$n((re,Se)=>En(_,{salt:re,iterations:Se})):null,me=async re=>{if(!j||!re.blob)return null;const Se=await j(re.blob),G=re.blob.compression&&re.blob.compression!=="none"?An(Nn,re.blob.compression):null;return Pn(re.blob,Se,{codec:G})},ge=await e.upsertEntries(r.entries,{open:me});d.push(...ge.written),p+=ge.sealed;for(const re of ge.written)B(e.get(re))}return(b.upserts.length||b.removes.length)&&R.bulk(b),d.length&&Ge({ids:d}),a(o,200,{ok:!0,written:d.length,ids:d,revs:h,conflicts:w,merged:k,sealed:p,size:e.size,rev:e.rev})}catch(r){return a(o,400,{error:{message:`records failed: ${r.message}`,type:"ingest_error"}})}}if(i==="/v1/events"&&n.method==="POST"){if(!q)return a(o,501,{error:{message:"the event log needs SQLite",type:"unavailable"}});try{const e=JSON.parse((await T(n,t.maxBodyBytes)).toString("utf8"))||{},r=Array.isArray(e)?e:e.events;if(!Array.isArray(r))return a(o,400,{error:{message:"events: an array of CloudEvents (or { events: [...] }) required",type:"invalid_request_error"}});if(r.length>2e3)return a(o,413,{error:{message:"events: at most 2000 per batch",type:"invalid_request_error"}});const s=p=>(typeof p?.host=="string"&&p.host?p.host:xn(p?.source))===lo,l=r.filter(s).map(p=>({id:p?.id??null,code:"RESERVED_HOST",message:`host "${lo}" is this gateway's own log`})),d=vn(q,l.length?r.filter(p=>!s(p)):r);return a(o,200,{ok:!0,appended:d.appended,duplicates:d.duplicates,rejected:[...l,...d.rejected],cursor:q.cursor()})}catch(e){return a(o,400,{error:{message:`events: ${e?.message||e}`,type:"invalid_request_error"}})}}if(i==="/v1/events/cursor"&&n.method==="GET")return q?a(o,200,{ok:!0,cursor:q.cursor(),count:q.count()}):a(o,501,{error:{message:"the event log needs SQLite",type:"unavailable"}});if(i==="/v1/events/stats"&&n.method==="GET"){if(!q)return a(o,501,{error:{message:"the event log needs SQLite",type:"unavailable"}});const e=Sn(q.all());return a(o,200,{ok:!0,stats:e,year:Tn(e)})}if(i==="/v1/events"&&n.method==="GET"){if(!q)return a(o,501,{error:{message:"the event log needs SQLite",type:"unavailable"}});let e={};try{e=co(JSON.parse(f.searchParams.get("cursor")||"{}"))}catch{return a(o,400,{error:{message:"events: cursor must be JSON { host: seq }",type:"invalid_request_error"}})}const r=q.since(e,{limit:Number(f.searchParams.get("limit"))||void 0,host:f.searchParams.get("host")||null});return a(o,200,{ok:!0,events:r.events.map(s=>gt(s)),cursor:r.cursor,more:r.more})}if(i==="/v1/events/stream"&&n.method==="GET"){if(!q)return a(o,501,{error:{message:"the event log needs SQLite",type:"unavailable"}});let e=null;if(f.searchParams.has("cursor"))try{e=co(JSON.parse(f.searchParams.get("cursor")||"{}"))}catch{e={}}if(o.writeHead(200,{"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive"}),o.write(`event: hello
42
- data: ${JSON.stringify({cursor:q.cursor(),count:q.count(),version:de})}
41
+ `)}catch{}},25e3);o.on("close",()=>{h(),clearInterval(w)});return}}}if(i==="/v1/memory/list"&&n.method==="GET")return a(o,200,{ok:!0,size:fe.size,memories:fe.list()});if(i==="/v1/memory/recall"&&n.method==="POST")try{const e=JSON.parse((await T(n,t.maxBodyBytes)).toString("utf8"))||{},r=fe.recall({text:String(e.text||""),scopes:Array.isArray(e.scopes)&&e.scopes.length?e.scopes.map(String):["global"],limit:Number(e.limit)||0,maxChars:Number(e.maxChars)||0});return a(o,200,{ok:!0,size:fe.size,...r})}catch(e){return a(o,400,{error:{message:`recall failed: ${e.message}`,type:"memory_error"}})}if(i==="/v1/memory/remember"&&n.method==="POST")try{const e=JSON.parse((await T(n,t.maxBodyBytes)).toString("utf8"))||{},r=fe.remember({text:String(e.text||""),kind:e.kind?String(e.kind):"fact",scope:e.scope?String(e.scope):"global",tags:Array.isArray(e.tags)?e.tags.map(String):[],source:{via:String(e.source?.via||"mcp"),surface:String(e.source?.surface||"mcp"),agent:String(e.source?.agent||""),ref:String(e.source?.ref||"")}});return a(o,200,{ok:!0,action:r.action,record:r.record,replaced:r.replaces||null,size:fe.size})}catch(e){return a(o,400,{error:{message:e.message,type:"memory_error"}})}if(i==="/v1/memory/forget"&&n.method==="POST")try{const e=JSON.parse((await T(n,t.maxBodyBytes)).toString("utf8"))||{},{removed:r}=fe.forget(String(e.query||""));return a(o,200,{ok:!0,removed:r,size:fe.size})}catch(e){return a(o,400,{error:{message:e.message,type:"memory_error"}})}if(i==="/v1/memory/sync"&&n.method==="POST")try{const e=JSON.parse((await T(n,t.maxBodyBytes)).toString("utf8"))||{},r=fe.bulk({upserts:Array.isArray(e.upserts)?e.upserts:[],removes:Array.isArray(e.removes)?e.removes:[]});return a(o,200,{ok:!0,...r,memories:fe.list()})}catch(e){return a(o,400,{error:{message:`memory sync failed: ${e.message}`,type:"memory_error"}})}if(i==="/v1/memory/clear"&&n.method==="POST")return a(o,200,{ok:!0,dropped:fe.clear(),size:fe.size});if(i==="/v1/history/clear"&&n.method==="POST"){const e=j.clear();return a(o,200,{ok:!0,dropped:e,size:j.size})}if(i==="/v1/history/search"&&n.method==="POST")try{const e=JSON.parse((await T(n,t.maxBodyBytes)).toString("utf8"))||{},r=j.search(String(e.query||""),{limit:Number(e.limit)||10,offset:Math.max(0,Number(e.offset)||0),type:e.type?String(e.type):null,since:e.since!=null?Number(e.since):null,before:e.before!=null?Number(e.before):null});return a(o,200,{ok:!0,size:j.size,newest:j.newest,results:r})}catch(e){return a(o,400,{error:{message:`search failed: ${e.message}`,type:"search_error"}})}if(i==="/v1/history/smart-search"&&n.method==="POST")try{const e=JSON.parse((await T(n,t.maxBodyBytes)).toString("utf8"))||{},r=String(e.question||e.query||""),s=Za(r,{extra:Array.isArray(e.queries)?e.queries.map(String):[],max:Math.min(6,Math.max(1,Number(e.maxQueries)||4))}),l={type:e.type?String(e.type):null,since:e.since!=null?Number(e.since):null,before:e.before!=null?Number(e.before):null},d=Math.min(30,Math.max(5,Number(e.limit)||10)*2),m=await qa(s,w=>j.search(w,{limit:d,...l}),{limit:Math.min(50,Math.max(1,Number(e.limit)||10))}),h=l.type?m:[...m.filter(w=>w.type==="brief"),...m.filter(w=>w.type!=="brief")];return a(o,200,{ok:!0,size:j.size,newest:j.newest,queries:s,results:h})}catch(e){return a(o,400,{error:{message:`smart search failed: ${e.message}`,type:"search_error"}})}if(i==="/v1/research"&&n.method==="POST"){let e;try{e=JSON.parse((await T(n,t.maxBodyBytes)).toString("utf8")||"{}")||{}}catch{return a(o,400,{error:{message:"research: the body must be JSON",type:"invalid_request_error"}})}const r=String(e.question||"").trim();if(!r)return a(o,400,{error:{message:"research: `question` is required",type:"invalid_request_error"}});const s=typeof e.model=="string"?e.model.trim():"";if(s&&!U(n))return a(o,403,{error:{message:"research with a model: extension origin or gateway token required",type:"forbidden"}});const l=`http://127.0.0.1:${n.socket.localPort}`,d=s?async(k,{maxTokens:b=220}={})=>{const B=new AbortController,_=setTimeout(()=>B.abort(),3e4);try{const J=Be()||_e(),me=await fetch(`${l}/v1/chat/completions`,{method:"POST",signal:B.signal,headers:{"content-type":"application/json",...J?{Authorization:`Bearer ${J}`}:{},"X-ChatPanel-Client":"research"},body:JSON.stringify({model:s,messages:[{role:"user",content:k}],stream:!1,max_tokens:b,temperature:.2})}),we=await me.json().catch(()=>({}));return me.ok?String(we?.choices?.[0]?.message?.content||""):""}finally{clearTimeout(_)}}:null,m=ce.get("identity")?.identity?.value||{},h=e.previous&&typeof e.previous=="object"&&e.previous.plan&&typeof e.previous.plan=="object"?{plan:e.previous.plan,top:typeof e.previous.top=="string"?e.previous.top:null,answer:String(e.previous.answer||"").slice(0,4e3)}:null,w=await Xr(r,{store:j,memories:fe.list(),complete:d,previous:h,self:String(m.selfName||"").trim(),excludeId:typeof e.excludeId=="string"?e.excludeId:null,parallel:3});return a(o,200,Zr(r,w,{size:j.size,newest:j.newest}))}if(i==="/v1/kb"||i.startsWith("/v1/kb/")){let e=null;if(n.method==="POST"||n.method==="PUT")try{const s=(await T(n,Math.max(t.maxBodyBytes,Math.ceil(kt*4/3)+1024))).toString("utf8");e=s?JSON.parse(s):{}}catch{return a(o,400,{error:{message:"kb: body must be JSON",type:"invalid_request"}})}const r=await te().handle({method:n.method,pathname:i,query:f.searchParams,body:e,admin:U(n),agent:String(n.headers["x-chatpanel-agent"]||"")});return r.text!=null?(o.writeHead(r.status,{"content-type":r.contentType||"text/plain; charset=utf-8"}),o.end(r.text)):a(o,r.status,r.body)}if(i==="/v1/history/related"&&n.method==="GET"){const e=String(f.searchParams.get("id")||""),r=Math.min(30,Math.max(1,Number(f.searchParams.get("limit"))||5));return a(o,200,{ok:!0,results:j.related(e,{limit:r})})}if(i==="/v1/history/status"&&n.method==="GET")return a(o,200,{ok:!0,size:j.size,newest:j.newest,bytes:j.bytes,lossless:j.lossless?{records:j.lossless.size,newest:j.lossless.newest}:null});if(i==="/v1/observability"&&n.method==="GET"){const e=Math.min(500,Math.max(1,Number(f.searchParams.get("limit"))||200));return a(o,200,{ok:!0,storage:{warm:{records:j.size,bytes:j.bytes,newest:j.newest}},access:Pt.snapshot(e)})}if(i==="/v1/observability/access"&&n.method==="POST")try{const e=JSON.parse((await T(n,t.maxBodyBytes)).toString("utf8"))||{},r=Pt.push($o({ts:Date.now(),...e}));return a(o,200,{ok:!0,event:r})}catch(e){return a(o,400,{error:{message:`access log failed: ${e.message}`,type:"observability_error"}})}if(i==="/v1/history/records"&&n.method==="PUT"){const e=j.lossless;if(!e)return a(o,501,{error:{message:"lossless records need the SQLite warm store",type:"unavailable"}});try{const r=JSON.parse((await T(n,Math.max(t.maxBodyBytes||0,ps))).toString("utf8"))||{},s=String(r.host||"").slice(0,80),l=Number(r.at)||Date.now(),d=[];let m=0,h={},w=[],k=[];const b={upserts:[],removes:[]},B=_=>{if(!_||_.deletedAt){_?.id&&b.removes.push(_.id);return}try{const J=uo(_);J&&b.upserts.push(J)}catch{}};if(Array.isArray(r.records)){const _=e.write(r.records,{host:s,at:l,merge:r.merge===!0});d.push(..._.written),h=_.revs,w=_.conflicts,k=_.merged;for(const J of _.written)B(e.get(J))}if(Array.isArray(r.entries)){const _=pt(),J=_?$n((re,Se)=>En(_,{salt:re,iterations:Se})):null,me=async re=>{if(!J||!re.blob)return null;const Se=await J(re.blob),G=re.blob.compression&&re.blob.compression!=="none"?An(Nn,re.blob.compression):null;return Pn(re.blob,Se,{codec:G})},we=await e.upsertEntries(r.entries,{open:me});d.push(...we.written),m+=we.sealed;for(const re of we.written)B(e.get(re))}return(b.upserts.length||b.removes.length)&&j.bulk(b),d.length&&Ge({ids:d}),a(o,200,{ok:!0,written:d.length,ids:d,revs:h,conflicts:w,merged:k,sealed:m,size:e.size,rev:e.rev})}catch(r){return a(o,400,{error:{message:`records failed: ${r.message}`,type:"ingest_error"}})}}if(i==="/v1/events"&&n.method==="DELETE"){if(!Q)return a(o,501,{error:{message:"the event log needs SQLite",type:"unavailable"}});const e=m=>/^(1|true|yes)$/i.test(f.searchParams.get(m)||""),r=f.searchParams.get("host"),s=e("all");if((r===null||r==="")==!s)return a(o,400,{error:{message:"events: name one host (?host=<id>) or the whole log (?all=1) — exactly one",type:"invalid_request_error"}});if(r!==null&&r.length>200)return a(o,400,{error:{message:"events: host is at most 200 characters",type:"invalid_request_error"}});const l=s?null:r;if(!e("force")){const m=Q.countOf(l);return a(o,409,{ok:!1,wouldDelete:m,...s?{all:!0}:{host:r},error:{message:`events: add force=1 to delete ${m} event(s) ${s?"in the whole log":`for host "${r}"`} — nothing was deleted`,type:"confirm_required",code:"confirm_required"}})}const d=Q.deleteOf(l);for(const m of Ee)try{m.write(`event: deleted
42
+ data: ${JSON.stringify({...s?{all:!0}:{host:r},deleted:d})}
43
43
 
44
- `),Pe.add(o),n.on("close",()=>Pe.delete(o)),e){let r={cursor:e,more:!0};for(;r.more;){r=q.since(r.cursor);for(const s of r.events)o.write(`event: cloudevent
44
+ `)}catch{}return a(o,200,{ok:!0,deleted:d,...s?{all:!0}:{host:r},cursor:Q.cursor()})}if(i==="/v1/events"&&n.method==="POST"){if(!Q)return a(o,501,{error:{message:"the event log needs SQLite",type:"unavailable"}});try{const e=JSON.parse((await T(n,t.maxBodyBytes)).toString("utf8"))||{},r=Array.isArray(e)?e:e.events;if(!Array.isArray(r))return a(o,400,{error:{message:"events: an array of CloudEvents (or { events: [...] }) required",type:"invalid_request_error"}});if(r.length>2e3)return a(o,413,{error:{message:"events: at most 2000 per batch",type:"invalid_request_error"}});const s=m=>(typeof m?.host=="string"&&m.host?m.host:xn(m?.source))===lo,l=r.filter(s).map(m=>({id:m?.id??null,code:"RESERVED_HOST",message:`host "${lo}" is this gateway's own log`})),d=vn(Q,l.length?r.filter(m=>!s(m)):r);return a(o,200,{ok:!0,appended:d.appended,duplicates:d.duplicates,rejected:[...l,...d.rejected],cursor:Q.cursor()})}catch(e){return a(o,400,{error:{message:`events: ${e?.message||e}`,type:"invalid_request_error"}})}}if(i==="/v1/events/cursor"&&n.method==="GET")return Q?a(o,200,{ok:!0,cursor:Q.cursor(),count:Q.count()}):a(o,501,{error:{message:"the event log needs SQLite",type:"unavailable"}});if(i==="/v1/events/stats"&&n.method==="GET"){if(!Q)return a(o,501,{error:{message:"the event log needs SQLite",type:"unavailable"}});const e=Sn(Q.all());return a(o,200,{ok:!0,stats:e,year:Tn(e)})}if(i==="/v1/events"&&n.method==="GET"){if(!Q)return a(o,501,{error:{message:"the event log needs SQLite",type:"unavailable"}});let e={};try{e=co(JSON.parse(f.searchParams.get("cursor")||"{}"))}catch{return a(o,400,{error:{message:"events: cursor must be JSON { host: seq }",type:"invalid_request_error"}})}const r=Q.since(e,{limit:Number(f.searchParams.get("limit"))||void 0,host:f.searchParams.get("host")||null});return a(o,200,{ok:!0,events:r.events.map(s=>gt(s)),cursor:r.cursor,more:r.more})}if(i==="/v1/events/stream"&&n.method==="GET"){if(!Q)return a(o,501,{error:{message:"the event log needs SQLite",type:"unavailable"}});let e=null;if(f.searchParams.has("cursor"))try{e=co(JSON.parse(f.searchParams.get("cursor")||"{}"))}catch{e={}}if(o.writeHead(200,{"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive"}),o.write(`event: hello
45
+ data: ${JSON.stringify({cursor:Q.cursor(),count:Q.count(),version:de})}
46
+
47
+ `),Ee.add(o),n.on("close",()=>Ee.delete(o)),e){let r={cursor:e,more:!0};for(;r.more;){r=Q.since(r.cursor);for(const s of r.events)o.write(`event: cloudevent
45
48
  data: ${JSON.stringify(gt(s))}
46
49
 
47
- `)}}return}if(i==="/v1/link"&&n.method==="GET")return a(o,200,{...y?{enabled:!0,...y.status()}:{enabled:!1,devices:[],pairing:null},agentSessions:t.link?.agentSessions!==!1});if(i==="/v1/link/settings"&&n.method==="POST"){if(n.headers["x-chatpanel-link-device"])return a(o,403,{error:{message:"a paired phone cannot change what it may reach",type:"forbidden"}});let e={};try{e=JSON.parse((await T(n,t.maxBodyBytes)).toString("utf8")||"{}")||{}}catch{e={}}if(typeof e.agentSessions!="boolean")return a(o,400,{error:{message:"link settings: { agentSessions: true|false }",type:"invalid_request"}});t.link={...t.link||{},agentSessions:e.agentSessions};try{we(t,le())}catch(r){console.warn(`[link] could not persist the settings: ${r.message}`)}return a(o,200,{ok:!0,agentSessions:t.link.agentSessions})}if(i==="/v1/link/pair"&&n.method==="POST"){if(!y)return a(o,409,{error:{message:"link is off (link.enabled: false)",type:"disabled"}});if(n.headers["x-chatpanel-link-device"])return a(o,403,{error:{message:"a paired phone cannot pair another",type:"forbidden"}});let e={};try{e=JSON.parse((await T(n,t.maxBodyBytes)).toString("utf8")||"{}")||{}}catch{e={}}if(e?.kind==="partner"){const r={partner:e.partner?.name,scopes:e.scopes,route:e.route||null,relay:String(e.relay||""),folder:typeof e.folder=="string"?e.folder:""};let s;try{s=y.previewPartner(r)}catch(l){return a(o,400,{error:{message:l?.message||String(l),type:"invalid_request",code:l?.code||"bad_partner"}})}if(e.confirm!==!0)return a(o,200,{confirmed:!1,preview:s});try{return a(o,200,{confirmed:!0,...await y.pairPartner(r)})}catch(l){return a(o,l?.code==="bad_partner"?400:502,{error:{message:l?.message||String(l),type:l?.code==="bad_partner"?"invalid_request":"relay"}})}}if(e?.kind&&e.kind!=="phone")return a(o,400,{error:{message:"link pair: kind is phone or partner",type:"invalid_request"}});try{return a(o,200,await y.pair({name:String(e?.name||"").slice(0,60)||void 0}))}catch(r){return a(o,502,{error:{message:r?.message||String(r),type:"relay"}})}}if(i==="/v1/link/route"&&n.method==="POST"){if(!y)return a(o,409,{error:{message:"link is off (link.enabled: false)",type:"disabled"}});if(n.headers["x-chatpanel-link-device"])return a(o,403,{error:{message:"a paired phone cannot change the route",type:"forbidden"}});let e={};try{e=JSON.parse((await T(n,t.maxBodyBytes)).toString("utf8")||"{}")||{}}catch{e={}}let r;try{r=Qn({id:String(e.route||"link"),url:String(e.url||"")})}catch(l){return a(o,400,{error:{message:l.message,type:"bad_route"}})}const s={...t.link||{},route:r.id,fallback:e.fallback!==!1};r.id==="relay"?s.relayUrl=r.url:r.id==="link"&&delete s.relayUrl,(r.id==="tailscale"||r.id==="cloudflare")&&(s.tunnelUrl=r.url),t.link=s;try{we(t,le())}catch(l){console.warn(`[link] could not persist the route: ${l.message}`)}return a(o,200,{enabled:!0,...await y.applySettings(s)})}if(i.startsWith("/v1/link/devices/")&&n.method==="DELETE"){if(!y)return a(o,404,{error:{message:"link is off",type:"disabled"}});const e=decodeURIComponent(i.slice(17));return await y.remove(e)?(g.cancelDevice(e),a(o,200,{ok:!0})):a(o,404,{error:{message:"no such device",type:"not_found"}})}if(i==="/v1/link/files"||i.startsWith("/v1/link/files/")){const e=vt(n.headers);if(e?.kind!=="partner"||!e.scopes.includes("files"))return a(o,403,{error:{message:"link files: a partner’s own folder, for a partner granted files",type:"forbidden",code:"link_scope"}});const r=y?.partnerFolderOf(e.device);if(!r)return a(o,403,{error:{message:"link files: this partner has no folder on this computer — pair it again with agents and files",type:"forbidden",code:"link_scope"}});const s=i.slice(14).replace(/^\//,"");let l=s;try{l=decodeURIComponent(s)}catch{}const d=n.method==="GET"&&(!s||/^(data|\.claude\/skills|\.claude\/agents|\.agents\/skills)\/?$/.test(l));let p;try{p=oa(s,{listing:d})}catch(h){return a(o,400,{error:{message:h.message,type:"invalid_request",code:"bad_path"}})}try{if(n.method==="GET"&&d)return a(o,200,{folder:"its own",files:ra(r,p.replace(/\/$/,""))});if(n.method==="GET"){const h=na(r,p);o.writeHead(200,{"content-type":"application/octet-stream","content-length":String(h.size)}),h.stream.pipe(o);return}return n.method==="PUT"?a(o,200,aa(r,p,await T(n,t.maxBodyBytes))):n.method==="DELETE"?sa(r,p)?a(o,200,{ok:!0}):a(o,404,{error:{message:`${p}: no such file`,type:"not_found"}}):a(o,405,{error:{message:"link files: GET, PUT or DELETE",type:"invalid_request"}})}catch(h){const w=h?.status||(h?.code===413?413:h?.code==="bad_partner"?400:500);return a(o,w,{error:{message:h?.message||String(h),type:w===404?"not_found":w===413?"too_large":"invalid_request"}})}}if(i==="/v1/link/approvals"||i.startsWith("/v1/link/approvals/")){if(n.headers["x-chatpanel-link-device"])return a(o,403,{error:{message:"an agent’s approval is the owner’s to give, on this computer",type:"forbidden"}});if(i==="/v1/link/approvals"&&n.method==="GET")return a(o,200,{pending:g.list()});if(i==="/v1/link/approvals/stream"&&n.method==="GET"){o.writeHead(200,{"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive"});const r=d=>o.write(`event: approvals
50
+ `)}}return}if(i==="/v1/link"&&n.method==="GET")return a(o,200,{...y?{enabled:!0,...y.status()}:{enabled:!1,devices:[],pairing:null},agentSessions:t.link?.agentSessions!==!1});if(i==="/v1/link/settings"&&n.method==="POST"){if(n.headers["x-chatpanel-link-device"])return a(o,403,{error:{message:"a paired phone cannot change what it may reach",type:"forbidden"}});let e={};try{e=JSON.parse((await T(n,t.maxBodyBytes)).toString("utf8")||"{}")||{}}catch{e={}}if(typeof e.agentSessions!="boolean")return a(o,400,{error:{message:"link settings: { agentSessions: true|false }",type:"invalid_request"}});t.link={...t.link||{},agentSessions:e.agentSessions};try{be(t,le())}catch(r){console.warn(`[link] could not persist the settings: ${r.message}`)}return a(o,200,{ok:!0,agentSessions:t.link.agentSessions})}if(i==="/v1/link/pair"&&n.method==="POST"){if(!y)return a(o,409,{error:{message:"link is off (link.enabled: false)",type:"disabled"}});if(n.headers["x-chatpanel-link-device"])return a(o,403,{error:{message:"a paired phone cannot pair another",type:"forbidden"}});let e={};try{e=JSON.parse((await T(n,t.maxBodyBytes)).toString("utf8")||"{}")||{}}catch{e={}}if(e?.kind==="partner"){const r={partner:e.partner?.name,scopes:e.scopes,route:e.route||null,relay:String(e.relay||""),folder:typeof e.folder=="string"?e.folder:""};let s;try{s=y.previewPartner(r)}catch(l){return a(o,400,{error:{message:l?.message||String(l),type:"invalid_request",code:l?.code||"bad_partner"}})}if(e.confirm!==!0)return a(o,200,{confirmed:!1,preview:s});try{return a(o,200,{confirmed:!0,...await y.pairPartner(r)})}catch(l){return a(o,l?.code==="bad_partner"?400:502,{error:{message:l?.message||String(l),type:l?.code==="bad_partner"?"invalid_request":"relay"}})}}if(e?.kind&&e.kind!=="phone")return a(o,400,{error:{message:"link pair: kind is phone or partner",type:"invalid_request"}});try{return a(o,200,await y.pair({name:String(e?.name||"").slice(0,60)||void 0}))}catch(r){return a(o,502,{error:{message:r?.message||String(r),type:"relay"}})}}if(i==="/v1/link/route"&&n.method==="POST"){if(!y)return a(o,409,{error:{message:"link is off (link.enabled: false)",type:"disabled"}});if(n.headers["x-chatpanel-link-device"])return a(o,403,{error:{message:"a paired phone cannot change the route",type:"forbidden"}});let e={};try{e=JSON.parse((await T(n,t.maxBodyBytes)).toString("utf8")||"{}")||{}}catch{e={}}let r;try{r=Yn({id:String(e.route||"link"),url:String(e.url||"")})}catch(l){return a(o,400,{error:{message:l.message,type:"bad_route"}})}const s={...t.link||{},route:r.id,fallback:e.fallback!==!1};r.id==="relay"?s.relayUrl=r.url:r.id==="link"&&delete s.relayUrl,(r.id==="tailscale"||r.id==="cloudflare")&&(s.tunnelUrl=r.url),t.link=s;try{be(t,le())}catch(l){console.warn(`[link] could not persist the route: ${l.message}`)}return a(o,200,{enabled:!0,...await y.applySettings(s)})}if(i.startsWith("/v1/link/devices/")&&n.method==="DELETE"){if(!y)return a(o,404,{error:{message:"link is off",type:"disabled"}});const e=decodeURIComponent(i.slice(17));return await y.remove(e)?(g.cancelDevice(e),a(o,200,{ok:!0})):a(o,404,{error:{message:"no such device",type:"not_found"}})}if(i==="/v1/link/files"||i.startsWith("/v1/link/files/")){const e=vt(n.headers);if(e?.kind!=="partner"||!e.scopes.includes("files"))return a(o,403,{error:{message:"link files: a partner’s own folder, for a partner granted files",type:"forbidden",code:"link_scope"}});const r=y?.partnerFolderOf(e.device);if(!r)return a(o,403,{error:{message:"link files: this partner has no folder on this computer — pair it again with agents and files",type:"forbidden",code:"link_scope"}});const s=i.slice(14).replace(/^\//,"");let l=s;try{l=decodeURIComponent(s)}catch{}const d=n.method==="GET"&&(!s||/^(data|\.claude\/skills|\.claude\/agents|\.agents\/skills)\/?$/.test(l));let m;try{m=oa(s,{listing:d})}catch(h){return a(o,400,{error:{message:h.message,type:"invalid_request",code:"bad_path"}})}try{if(n.method==="GET"&&d)return a(o,200,{folder:"its own",files:ra(r,m.replace(/\/$/,""))});if(n.method==="GET"){const h=na(r,m);o.writeHead(200,{"content-type":"application/octet-stream","content-length":String(h.size)}),h.stream.pipe(o);return}return n.method==="PUT"?a(o,200,aa(r,m,await T(n,t.maxBodyBytes))):n.method==="DELETE"?sa(r,m)?a(o,200,{ok:!0}):a(o,404,{error:{message:`${m}: no such file`,type:"not_found"}}):a(o,405,{error:{message:"link files: GET, PUT or DELETE",type:"invalid_request"}})}catch(h){const w=h?.status||(h?.code===413?413:h?.code==="bad_partner"?400:500);return a(o,w,{error:{message:h?.message||String(h),type:w===404?"not_found":w===413?"too_large":"invalid_request"}})}}if(i==="/v1/link/approvals"||i.startsWith("/v1/link/approvals/")){if(n.headers["x-chatpanel-link-device"])return a(o,403,{error:{message:"an agent’s approval is the owner’s to give, on this computer",type:"forbidden"}});if(i==="/v1/link/approvals"&&n.method==="GET")return a(o,200,{pending:g.list()});if(i==="/v1/link/approvals/stream"&&n.method==="GET"){o.writeHead(200,{"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive"});const r=d=>o.write(`event: approvals
48
51
  data: ${JSON.stringify({pending:d})}
49
52
 
50
53
  `);r(g.list());const s=g.subscribe(r),l=setInterval(()=>o.write(`:
51
54
 
52
- `),25e3);l.unref?.(),o.on("close",()=>{s(),clearInterval(l)});return}const e=/^\/v1\/link\/approvals\/([A-Za-z0-9_-]{1,40})$/.exec(i);if(e&&n.method==="POST"){let r={};try{r=JSON.parse((await T(n,t.maxBodyBytes)).toString("utf8")||"{}")||{}}catch{r={}}return mo.some(s=>s.id===r.decision)?g.answer(e[1],r.decision)?a(o,200,{ok:!0}):a(o,404,{error:{message:"nothing is waiting under that id — answered, withdrawn or expired",type:"not_found"}}):a(o,400,{error:{message:`link approvals: { decision: ${mo.map(s=>s.id).join(" | ")} }`,type:"invalid_request"}})}}if(i==="/v1/browser"&&n.method==="GET")return a(o,200,m.status());if(i==="/v1/browser/stream"&&n.method==="GET"){m.stream(n,o);return}if((i==="/v1/browser/call"||i==="/v1/browser/announce"||i==="/v1/browser/result")&&n.method==="POST"){let e;try{e=JSON.parse((await T(n,t.maxBodyBytes)).toString("utf8"))}catch{return a(o,400,{error:{message:"browser: body must be JSON",type:"invalid_request"}})}const r=i==="/v1/browser/call"?await m.call(e,n):i==="/v1/browser/announce"?m.announce(e):m.result(e);return a(o,r.status,r.body)}if(i==="/v1/history/stream"&&n.method==="GET"){const e=R.lossless;if(!e)return a(o,501,{error:{message:"lossless records need the SQLite warm store",type:"unavailable"}});o.writeHead(200,{"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive"}),o.write(`event: hello
55
+ `),25e3);l.unref?.(),o.on("close",()=>{s(),clearInterval(l)});return}const e=/^\/v1\/link\/approvals\/([A-Za-z0-9_-]{1,40})$/.exec(i);if(e&&n.method==="POST"){let r={};try{r=JSON.parse((await T(n,t.maxBodyBytes)).toString("utf8")||"{}")||{}}catch{r={}}return mo.some(s=>s.id===r.decision)?g.answer(e[1],r.decision)?a(o,200,{ok:!0}):a(o,404,{error:{message:"nothing is waiting under that id — answered, withdrawn or expired",type:"not_found"}}):a(o,400,{error:{message:`link approvals: { decision: ${mo.map(s=>s.id).join(" | ")} }`,type:"invalid_request"}})}}if(i==="/v1/browser"&&n.method==="GET")return a(o,200,p.status());if(i==="/v1/browser/stream"&&n.method==="GET"){p.stream(n,o);return}if((i==="/v1/browser/call"||i==="/v1/browser/announce"||i==="/v1/browser/result")&&n.method==="POST"){let e;try{e=JSON.parse((await T(n,t.maxBodyBytes)).toString("utf8"))}catch{return a(o,400,{error:{message:"browser: body must be JSON",type:"invalid_request"}})}const r=i==="/v1/browser/call"?await p.call(e,n):i==="/v1/browser/announce"?p.announce(e):p.result(e);return a(o,r.status,r.body)}if(i==="/v1/history/stream"&&n.method==="GET"){const e=j.lossless;if(!e)return a(o,501,{error:{message:"lossless records need the SQLite warm store",type:"unavailable"}});o.writeHead(200,{"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive"}),o.write(`event: hello
53
56
  data: ${JSON.stringify({newest:e.newest,rev:e.rev,size:e.size,version:de,prefsRevision:ce.revision})}
54
57
 
55
- `),xe.add(o),n.on("close",()=>xe.delete(o));return}if(i==="/v1/history/records"&&n.method==="GET"){const e=R.lossless;if(!e)return a(o,501,{error:{message:"lossless records need the SQLite warm store",type:"unavailable"}});const r=e.since({since:Number(f.searchParams.get("since"))||0,cursor:f.searchParams.get("cursor")||"",limit:Number(f.searchParams.get("limit"))||200,kind:f.searchParams.get("kind")||null,bytes:Number(f.searchParams.get("bytes"))||0,afterRev:f.searchParams.has("after_rev")?Number(f.searchParams.get("after_rev"))||0:null});return a(o,200,{ok:!0,...r,size:e.size,newest:e.newest})}if(i==="/v1/history/list"&&n.method==="GET"){const e=Math.min(500,Math.max(1,Number(f.searchParams.get("limit"))||50)),r=Math.max(0,Number(f.searchParams.get("offset"))||0),s=f.searchParams.get("type")||null;return a(o,200,{ok:!0,...R.list({limit:e,offset:r,type:s})})}if(i==="/v1/history/get"&&n.method==="GET"){const e=f.searchParams.get("maxChars")!=null?Math.max(1,Number(f.searchParams.get("maxChars"))||0):null,r=Math.max(0,Number(f.searchParams.get("offset"))||0),s=R.get(String(f.searchParams.get("id")||""),{maxChars:e,offset:r});return s?a(o,200,{ok:!0,record:s}):a(o,404,{error:{message:"no such record",type:"not_found"}})}if(i==="/v1/history/key"&&n.method==="GET")return a(o,200,{ok:!0,hasKey:no()});if(i==="/v1/history/key"&&n.method==="POST")try{const e=JSON.parse((await T(n,t.maxBodyBytes)).toString("utf8"))||{};e.passphrase?Jr(String(e.passphrase)):Lr();const r=e.passphrase?await wt(R,String(e.passphrase)):{ok:!0,ingested:0};return r.ok&&r.whole&&Ge(),a(o,200,{ok:!0,hasKey:!!e.passphrase,...r})}catch(e){return a(o,400,{error:{message:`key handoff failed: ${e.message}`,type:"key_error"}})}if(i==="/v1/history/ingest-backup"&&n.method==="POST")try{const e=await wt(R,pt());return e.ok&&e.whole&&Ge(),a(o,e.ok?200:409,e)}catch(e){return a(o,400,{error:{message:`backup ingest failed: ${e.message}`,type:"ingest_error"}})}if(i==="/ner"){if(n.method==="GET"){const e=await Lo(t);return a(o,e.ok?200:503,e)}if(n.method==="POST"){if(await tt(t),I.state()!=="off"){if(!I.isReady()){const r=I.health();return a(o,503,{error:{message:r.state==="error"?`NER model failed to load: ${r.error||"unknown error"}`:`NER model is ${r.state} — not ready yet`,type:r.state==="error"?"ner_error":"ner_loading"},state:r.state,model:r.model})}try{const r=await T(n,t.maxBodyBytes);let s="",l=!1;try{const p=JSON.parse(r.toString("utf8"));s=p?.text||"",l=p?.strict===!0}catch{}const d=await I.detect(s,{strict:l});return a(o,200,{entities:d})}catch(r){return a(o,500,{error:{message:`NER error: ${r.message}`,type:"ner_error"}})}}const e=Jo(t);if(!e){const r=I.modelOnDisk(t.ner?.model||void 0);return a(o,503,{error:{message:r?"the bundled detector could not start — deterministic-only redaction":"no entity detector is installed — deterministic-only redaction (install one from Gateway settings)",type:r?"ner_error":"ner_not_installed"},state:I.state(),model:t.ner?.model||null})}try{const r=await T(n,t.maxBodyBytes),s=await Ze(e,{method:"POST",headers:{"content-type":"application/json"},body:r,signal:AbortSignal.timeout(8e3)}),l=await s.text();return o.writeHead(s.status,{"content-type":"application/json"}),o.end(l)}catch(r){return a(o,502,{error:{message:`NER unreachable: ${r.message}`,type:"ner_unreachable"}})}}}if(i==="/redact"&&n.method==="POST"){let e="";try{e=String(JSON.parse((await T(n,t.maxBodyBytes)).toString("utf8"))?.text||"")}catch{e=""}if(!e)return a(o,200,{text:"",count:0,sanitized:0,entities:[],detector:At(t)});try{let r=e;const s=await Te(t.pro?.entitlementToken);await tt(t);const l=await Qe([ut(()=>r,d=>{r=d})],t.redaction,{isPro:s});return a(o,200,{text:r,count:l.count||0,sanitized:l.sanitized||0,tier:t.redaction?.tier==="full"?"full":"basic",entities:Ro(l.vault,"types")||[],detector:At(t)})}catch(r){return a(o,500,{error:{message:`redaction preview failed: ${r.message}`,type:"redact_error"}})}}if(i==="/ner/models"){if(n.method==="GET"){const e=I.health().model||t.ner?.model||null,r=Math.round(bt.totalmem()/1048576),s=va(fo,{totalRamMB:r}).map(l=>({...l,installed:I.modelOnDisk(l.id)}));for(const l of[e,...I.modelsOnDisk()])!l||s.some(d=>d.id===l)||s.push({id:l,label:l,lang:"—",custom:!0,installed:I.modelOnDisk(l),note:"Custom model (from Hugging Face)."});return a(o,200,{active:e,companions:I.companions(),union:Array.isArray(t.ner?.union)?t.ner.union:[],machine:{totalRamMB:r},skipped:Rr(),recommendation:ro(s,{totalRamMB:r},[]),state:I.state(),progress:I.progress(),available:s})}if(n.method==="POST"){let e=null;try{e=JSON.parse((await T(n,t.maxBodyBytes)).toString("utf8"))}catch{e=null}if(e&&e.recommended===!0){const s=Math.round(bt.totalmem()/1048576),l=ro(fo.map(d=>({...d,installed:I.modelOnDisk(d.id)})),{totalRamMB:s},[]);e={id:l.primary,union:l.union}}const r=e&&typeof e.id=="string"?e.id.trim():null;if(e&&Array.isArray(e.union)){const s=[...new Set(e.union.map(d=>String(d||"").trim()).filter(Boolean))];for(const d of s)if(!(go(d)||wo(d)))return a(o,400,{error:{message:`unknown or invalid model id in union: ${d}`,type:"bad_model"}});const l=r||t.ner?.model||I.health().model;t.ner=t.ner||{allowDownload:!0,enableFullTier:!0},t.ner.union=s.filter(d=>d!==l),r&&Eo(t,r);try{we(t,le())}catch{}return(async()=>{r&&await I.setModel(r,{onLog:p=>console.log(p)});const d=Ir(t.ner,{log:p=>console.log(p)});for(const p of I.companions())d.includes(p.model)||await I.removeCompanion(p.model);for(const p of d)await I.addCompanion(p,{onLog:h=>console.log(h),allowDownload:t.ner.allowDownload!==!1});I.setUnionOrder(d)})().catch(d=>console.log(`[ner] union update failed: ${d.message}`)),a(o,202,{accepted:!0,active:l,union:t.ner.union,companions:I.companions(),state:I.state()})}if(!r||!(go(r)||wo(r)))return a(o,400,{error:{message:"unknown or invalid model id",type:"bad_model"}});Eo(t,r);try{we(t,le())}catch{}return I.setModel(r,{onLog:s=>console.log(s)}).then(s=>{s&&t.ner?.enableFullTier&&t.redaction.tier!=="full"&&(t.redaction.tier="full")}),a(o,202,{accepted:!0,active:r,state:I.state(),progress:I.progress()})}}if(i==="/stt/models"){if(n.method==="GET"){const e=$.health().model||t.stt?.model||ot,r={platform:process.platform,arch:process.arch,helper:!!ft()},s=Sa.map(l=>{const d=bo(l,r);return{...l,installed:$.modelOnDisk(l.id),...d?{unavailable:d}:{}}});return e&&!s.some(l=>l.id===e)&&s.push({id:e,label:e,lang:"—",tier:"custom",custom:!0,installed:$.modelOnDisk(e),note:"Custom model (from Hugging Face)."}),a(o,200,{active:e,state:$.state(),progress:$.progress(),available:s,dtype:t.stt?.dtype||"auto",loadedDtype:$.health().dtype,runtime:$.health().runtime,dtypes:_a})}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||!(Ta(r)||xa(r)))return a(o,400,{error:{message:"unknown or invalid model id",type:"bad_model"}});const s=bo(Ea(r),{platform:process.platform,arch:process.arch,helper:!!ft()});if(s)return a(o,400,{error:{message:s,type:"bad_model"}});const l=typeof e.dtype=="string"&&Oa(e.dtype)?e.dtype:void 0;t.stt?t.stt.model=r:t.stt={enabled:!0,model:r,allowDownload:!0},l&&(t.stt.dtype=l==="auto"?null:l);try{we(t,le())}catch{}return $.setModel(r,{onLog:d=>console.log(d),dtype:l||t.stt.dtype||"auto",warmMs:t.stt.warmMs,allowDownload:t.stt?.allowDownload!==!1,segment:t.stt?.segment,speaker:Mt(t,{installing:!0})}),a(o,202,{accepted:!0,active:r,dtype:t.stt.dtype||"auto",state:$.state(),progress:$.progress(),speaker:{id:M.activeModel(),state:M.state(),installed:M.modelOnDisk()}})}}if(i==="/diarize/model"){if(n.method==="GET"){const e=M.activeModel(),r=ga.map(s=>({...s,installed:M.modelOnDisk(s.id)})).sort((s,l)=>(l.id===e?1:0)-(s.id===e?1:0));return a(o,200,{active:e,state:M.state(),threshold:M.activeThreshold(),segment:fa.health(),progress:M.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(!ho(r))return a(o,400,{error:{message:"unknown speaker model id",type:"bad_model"}});if(!await M.setModel(r,{log:s=>console.log(s)}))return a(o,409,{error:{message:"a diarizing session is using the current speaker model — try again when it ends",type:"model_busy"}});t.stt?t.stt.diarizeModel=r:t.stt={enabled:!0,diarize:!0,diarizeModel:r};try{we(t,le())}catch{}return M.init({allowDownload:t.stt?.allowDownload!==!1,warmMs:t.stt?.warmMs,onLog:s=>console.log(s)}),a(o,202,{accepted:!0,active:M.activeModel(),state:M.state(),threshold:M.activeThreshold(),progress:M.progress()})}return M.download({onLog:s=>console.log(s)}),a(o,202,{accepted:!0,active:M.activeModel(),state:M.state(),threshold:M.activeThreshold(),progress:M.progress()})}}if(i==="/tts/models"){if(n.method==="GET"){const e=D.health().model||t.tts?.model||_o(Tt()),r=Tt(),s=ko.find(d=>d.id===e)||null,l=ko.map(d=>({...d,installed:D.modelOnDisk(d.id),unavailable:d.requiresNative&&!r?"needs the npm gateway — the standalone binary cannot load this engine":void 0}));return e&&!l.some(d=>d.id===e)&&l.push({id:e,label:e,lang:"—",tier:"custom",custom:!0,installed:D.modelOnDisk(e),note:"Custom model (from Hugging Face)."}),a(o,200,{active:e,state:D.state(),progress:D.progress(),available:l,voice:t.tts?.voice||(at(e)==="pocket-tts"?rt:Oe),arch:D.arch(),supportsVoices:D.arch()?D.supportsVoices():s?s.arch==="style-tts2"&&!!s.voices:!0,supportsCustomVoices:D.arch()?D.supportsCustomVoices():!!s?.customVoices,sampleRate:D.sampleRate(),voices:D.isPocket()||!D.arch()&&at(e)==="pocket-tts"?(D.builtinVoices().length?D.builtinVoices():Da).map(d=>({id:d,label:d[0].toUpperCase()+d.slice(1),lang:"en",installed:D.builtinVoices().includes(d)})):D.arch()&&D.arch()!=="style-tts2"?[]:Pa.map(d=>({...d,installed:D.voiceOnDisk(d.id,e)})),dtype:t.tts?.dtype||"auto",loadedDtype:D.health().dtype,runtime:D.health().runtime,dtypes:Na})}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&&!($a(r)||Aa(r)))return a(o,400,{error:{message:"unknown or invalid model id",type:"bad_model"}});const s=e&&typeof e.voice=="string"?e.voice.trim():null;if(s){const d=pe.parseCustomVoice(s);if(!(d?!!pe.getVoice(d):nt(s)||vo(s)&&So(s)))return a(o,400,{error:{message:"unknown or invalid voice",type:"bad_voice"}})}const l=e&&typeof e.dtype=="string"&&Ba(e.dtype)?e.dtype:void 0;if(t.tts||(t.tts={enabled:!0,model:To,voice:Oe,allowDownload:!0}),r&&(t.tts.model=r),s&&(t.tts.voice=s),r&&!s){const d=Ma(r),p=pe.parseCustomVoice(t.tts.voice||""),h=!!(p&&pe.getVoice(p));if(d&&!h)if(at(r)==="pocket-tts")t.tts.voice=rt;else{const k=pe.listVoices();t.tts.voice=k.length?`custom:${k[0].id}`:""}else!d&&h&&(t.tts.voice=Oe);const w=at(r)==="pocket-tts";w&&!pe.parseCustomVoice(t.tts.voice||"")&&!nt(t.tts.voice)&&(t.tts.voice=rt),!w&&nt(t.tts.voice)&&(t.tts.voice=Oe)}l&&(t.tts.dtype=l==="auto"?null:l);try{we(t,le())}catch{}return r&&D.setModel(r,{onLog:d=>console.log(d),dtype:l||t.tts.dtype||"auto"}),a(o,202,{accepted:!0,active:t.tts.model,voice:t.tts.voice,dtype:t.tts.dtype||"auto",state:D.state(),progress:D.progress()})}}if(i==="/tts/voices"){if(n.method==="GET")return a(o,200,{voices:pe.listVoices(),usable:D.supportsCustomVoices(),embedder:M.activeModel(),embedderReady:M.isReady()});if(n.method==="POST"){let e=null;try{e=JSON.parse((await T(n,t.maxBodyBytes)).toString("utf8"))}catch{e=null}const r=e&&typeof e.name=="string"?e.name.trim():"",s=e&&Array.isArray(e.pcm)?e.pcm:null,l=e&&typeof e.id=="string"?e.id.trim():"";if(l){if(!pe.getVoice(l))return a(o,404,{error:{message:"no such saved voice",type:"bad_voice"}});if(!s){if(!r)return a(o,400,{error:{message:"a name is required",type:"bad_request"}});try{return a(o,200,{...pe.renameVoice(l,r),usable:D.supportsCustomVoices()})}catch(d){return a(o,400,{error:{message:d.message,type:"rename_failed"}})}}if(s.length<16e3)return a(o,400,{error:{message:"need at least 1 second of 16 kHz mono audio",type:"sample_too_short"}})}else if(!r)return a(o,400,{error:{message:"a name is required",type:"bad_request"}});if(!s||s.length<16e3)return a(o,400,{error:{message:"need at least 1 second of 16 kHz mono audio",type:"sample_too_short"}});try{if(!M.isReady()){const b=M.download({onLog:j=>console.log(j)}),B=Symbol("timeout"),_=await Promise.race([b.then(()=>null).catch(j=>j),new Promise(j=>setTimeout(()=>j(B),bs))]);if(_===B||!M.isReady())return a(o,503,{error:{message:_===B?"the speaker model is still downloading (~100 MB) — your recording was kept, press Save again shortly":`the speaker model failed to load: ${M.health().error||"unknown error"}`,type:"embedder_not_ready"},progress:M.progress()})}const d=Float32Array.from(s),p=await M.embed(d);let h=null;try{const b=await D.pocketForEncoding({allowDownload:t.tts?.allowDownload!==!1,log:B=>console.log(B)});b&&(h=await b.encodeVoice(ks(d,16e3,24e3)))}catch(b){console.log(`[tts] pocket conditioning unavailable for this voice (${b.message})`)}const w=l?pe.replaceVoice(l,{vec:p,pocket:h}):pe.saveVoice({name:r,vec:p,pocket:h}),k=l&&r&&r!==w.name?pe.renameVoice(l,r):w;return console.log(`[tts] ${l?"re-recorded":"saved"} custom voice "${k.name}" (${(w.kinds||[]).join(" + ")}, sample discarded)`),a(o,l?200:201,{...w,...k,usable:D.supportsCustomVoices()})}catch(d){return a(o,400,{error:{message:d.message,type:"save_failed"}})}}if(n.method==="DELETE"){const e=f.searchParams.get("id")||"",r=pe.deleteVoice(e);if(r&&t.tts?.voice===`custom:${e}`){const s=pe.listVoices();t.tts.voice=s.length?`custom:${s[0].id}`:Oe;try{we(t,le())}catch{}}return a(o,200,{deleted:r,voice:t.tts?.voice})}}if((i==="/tts"||i==="/v1/audio/speech")&&n.method==="POST"){if(t.tts?.enabled===!1)return a(o,503,{error:{message:"tts is disabled in gateway config",type:"tts_disabled"}});let e=null;try{e=JSON.parse((await T(n,t.maxBodyBytes)).toString("utf8"))}catch{e=null}const r=e&&typeof(e.input??e.text)=="string"?String(e.input??e.text).trim():"";if(!r)return a(o,400,{error:{message:"text is required",type:"bad_request"}});if(r.length>xo)return a(o,413,{error:{message:`text too long (max ${xo} chars)`,type:"too_long"}});const s=Number.isFinite(e.speed)?Math.min(2,Math.max(.5,e.speed)):1,l=Ca(t),d=e&&typeof e.voice=="string"&&e.voice.trim()?e.voice.trim():null,p=d||(l?l.voice:t.tts?.voice||Oe);if(l&&!Ra(p))return a(o,400,{error:{message:"unknown or invalid voice",type:"bad_voice"}});const h=e&&typeof e.response_format=="string"?e.response_format.toLowerCase():"wav";if(h!=="wav"&&h!=="pcm")return a(o,400,{error:{message:`unsupported response_format "${h}" — this gateway synthesizes wav`,type:"bad_format"}});try{if(l){const{audio:re,contentType:Se,redacted:G}=await Ia({dest:l,text:r,voice:p,speed:s,auth:n.headers.authorization||n.headers["xi-api-key"]||"",redaction:t.redaction,isPro:await Te(t.pro?.entitlementToken)});return o.writeHead(200,{"Content-Type":Se,"Content-Length":String(re.length),"Cache-Control":"no-store","X-Tts-Provider":l.kind,"X-Tts-Redacted":String(G)}),o.end(re)}if(!await D.ready({onLog:re=>console.log(re),allowDownload:t.tts?.allowDownload!==!1,model:t.tts?.model||_o(Tt()),dtype:t.tts?.dtype||"auto"}))return a(o,503,{error:{message:D.health().error||"tts model not ready",type:"tts_unavailable"}});const k=ja({requested:d,configured:p,engine:D,voices:pe,isPocketVoice:nt,isKnownVoice:vo,isValidVoiceId:So,defaultVoice:Oe,defaultPocketVoice:rt});if(!k.ok)return a(o,k.status,{error:{message:k.message,type:k.type}});const{voice:b,customId:B,speakerEmbedding:_}=k,j=await D.synth(r,{voice:b,speed:s,speakerEmbedding:_}),me=D.sampleRate(),ge=h==="pcm"?Buffer.from(new Float32Array(j).buffer):D.toWav(j,me);return o.writeHead(200,{"Content-Type":h==="pcm"?"application/octet-stream":"audio/wav","Content-Length":String(ge.length),"Cache-Control":"no-store","X-Tts-Sample-Rate":String(me),...B||D.isPocket()||D.supportsVoices()?{"X-Tts-Voice":b}:{}}),o.end(ge)}catch(w){return a(o,500,{error:{message:w.message,type:"tts_failed"}})}}if(i==="/v1/audio/transcriptions"&&n.method==="POST"){if(t.stt?.enabled===!1)return a(o,403,{error:{message:"STT disabled in gateway config",type:"stt_disabled"}});let e;try{e=ba(await T(n,Math.max(t.maxBodyBytes||0,64*1024*1024)),n.headers["content-type"])}catch(b){return a(o,b.code===413?413:415,{error:{message:b.message,type:"bad_request"}})}const r=b=>e.find(B=>B.name===b&&!B.filename)?.data.toString("utf8").trim()||"",s=e.find(b=>b.name==="file"&&b.filename)||e.find(b=>b.filename);if(!s?.data?.length)return a(o,400,{error:{message:"a `file` part is required",type:"bad_request"}});let l;try{l=await ka(s.data)}catch(b){return a(o,b.code===415?415:500,{error:{message:b.message,type:"unsupported_media"}})}const d=["json","text","verbose_json"].includes(r("response_format"))?r("response_format"):"json",p=St(t,"stt");let h=null;if(p.kind==="remote"||p.kind==="container")try{h=yo(p,{fetchImpl:Ze})}catch(b){return a(o,500,{error:{message:`stt provider: ${b.message}`,type:"bad_provider"}})}if(!h&&!$.isReady()&&await $.init({model:t.stt?.model||ot,allowDownload:t.stt?.allowDownload!==!1,dtype:t.stt?.dtype||void 0,warmMs:t.stt?.warmMs,segment:t.stt?.segment,speaker:Mt(t),onLog:b=>console.log(b)}),!h&&!$.isReady())return a(o,503,{error:{message:`speech model not ready: ${$.health().error||$.state()}`,type:"stt_not_ready"}});const w=r("diarize")==="true"&&t.stt?.diarize!==!1;w&&!M.isReady()&&await M.init({allowDownload:t.stt?.allowDownload!==!1,warmMs:t.stt?.warmMs,onLog:b=>console.log(b)});const k=Date.now();try{const{id:b}=$.createSession({lang:r("language")||void 0,diarize:w,interims:!1,remote:h}),B=[],_=[];let j=null;$.subscribe(b,G=>{G.type==="final"&&G.text?B.push(G):G.type==="language"?j=G.lang:G.type==="error"&&_.push(G.message||G.code)});const me=16e3*5;for(let G=0;G<l.pcm.length;G+=me)$.pushAudio(b,l.pcm.subarray(G,Math.min(l.pcm.length,G+me))),await $.decodeNow(b);if(await $.endSession(b),!B.length&&_.length)return a(o,500,{error:{message:_[0],type:"decode_failed"}});let ge=0;const re=B.map((G,Wo)=>{const Ht=typeof G.startMs=="number"?G.startMs/1e3:ge,Ko=(G.durationMs||0)/1e3;return ge=Ht+Ko,{id:Wo,start:Math.round(Ht*100)/100,end:Math.round(ge*100)/100,text:G.text,...G.speaker?{speaker:G.speaker}:{},...G.turns?{turns:G.turns.map(Ye=>({start:Math.round(Ye.startMs/10)/100,end:Math.round((Ye.startMs+Ye.durationMs)/10)/100,speaker:Ye.speaker}))}:{}}}),Se=re.map(G=>G.text).join(" ").replace(/\s+/g," ").trim();return d==="text"?(o.writeHead(200,{"content-type":"text/plain; charset=utf-8"}),o.end(Se)):d==="verbose_json"?a(o,200,{task:"transcribe",language:j||r("language")||null,duration:Math.round(l.seconds*100)/100,text:Se,segments:re,provider:p.kind,took_ms:Date.now()-k}):a(o,200,{text:Se})}catch(b){return a(o,b.code==="too_many_sessions"?429:500,{error:{message:b.message,type:b.code||"stt_error"}})}}if(i==="/stt/sessions"&&n.method==="POST"){if(t.stt?.enabled===!1)return a(o,403,{error:{message:"STT disabled in gateway config",type:"stt_disabled"}});let e=null;try{e=JSON.parse((await T(n,t.maxBodyBytes)).toString("utf8")||"{}")}catch{e=null}const r=St(t,"stt");let s=null;if(r.kind==="remote"||r.kind==="container")try{s=yo(r,{fetchImpl:Ze})}catch(d){return a(o,500,{error:{message:`stt provider: ${d.message}`,type:"bad_provider"}})}!s&&!$.isReady()&&$.init({model:t.stt?.model||ot,allowDownload:t.stt?.allowDownload!==!1,dtype:t.stt?.dtype||void 0,warmMs:t.stt?.warmMs,segment:t.stt?.segment,speaker:Mt(t),onLog:d=>console.log(d)});const l=e?.diarize===!0&&t.stt?.diarize!==!1;l&&!M.isReady()&&M.init({allowDownload:t.stt?.allowDownload!==!1,warmMs:t.stt?.warmMs,onLog:d=>console.log(d)});try{const d=e?.poll===!0,{id:p}=$.createSession({lang:e?.lang,redact:e?.redact===!0,diarize:l,speakerLabel:e?.speakerLabel,endSilenceMs:e?.endSilenceMs,interims:e?.interims!==!1,remote:s,poll:d});return a(o,201,{id:p,state:$.state(),...d?{poll:!0}:{}})}catch(d){return a(o,d.code==="too_many_sessions"?429:500,{error:{message:d.message,type:d.code||"stt_error"}})}}{const e=i.match(/^\/stt\/sessions\/([0-9a-f-]{36})(\/audio|\/events)?$/);if(e){const r=e[1],s=async(d,p,h)=>{if(p.type!=="final"||!d.redact)return p;try{let w=p.text;return await Qe([ut(()=>w,k=>{w=k})],t.redaction,{isPro:h}),{...p,text:w}}catch{return p}},l=async d=>{const p=$.drainEvents(r);if(!p)return null;const h=[];if(d&&!d.closed){const k=d.remote?"ready":$.state();k==="downloading"||k==="loading"?h.push({type:"progress",state:k,...$.progress()||{}}):k==="error"?h.push({type:"error",code:"model_failed",message:$.health().error||"model failed to load",fatal:!0}):d.diarize&&["downloading","loading"].includes(M.state())?h.push({type:"diarize-progress",state:M.state(),...M.progress()||{}}):Go.get(d)!==k&&(Go.set(d,k),h.push({type:"state",state:k}))}const w=d?.redact?await Te(t.pro?.entitlementToken):!0;for(const k of p)d?h.push(await s(d,k,w)):k.type!=="final"&&k.type!=="interim"&&h.push(k);return h};if(e[2]==="/audio"&&n.method==="POST"){const d=$.getSession(r)||$.endedSession(r);try{const p=await T(n,t.maxBodyBytes);$.pushAudio(r,$.toFloat32(p));const h=await l(d);return a(o,200,{ok:!0,state:$.state(),...h?{events:h}:{}})}catch(p){const h=p.code==="no_session"?await l(d).catch(()=>null):null;return a(o,p.code==="no_session"?404:400,{error:{message:p.message,type:p.code||"stt_error"},...h?{events:h}:{}})}}if(e[2]==="/events"&&n.method==="GET"){const d=$.getSession(r);if(!d)return a(o,404,{error:{message:"no such session",type:"no_session"}});o.writeHead(200,{"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive"});const p=_=>o.write(`data: ${JSON.stringify(_)}
58
+ `),xe.add(o),n.on("close",()=>xe.delete(o));return}if(i==="/v1/history/records"&&n.method==="GET"){const e=j.lossless;if(!e)return a(o,501,{error:{message:"lossless records need the SQLite warm store",type:"unavailable"}});const r=e.since({since:Number(f.searchParams.get("since"))||0,cursor:f.searchParams.get("cursor")||"",limit:Number(f.searchParams.get("limit"))||200,kind:f.searchParams.get("kind")||null,bytes:Number(f.searchParams.get("bytes"))||0,afterRev:f.searchParams.has("after_rev")?Number(f.searchParams.get("after_rev"))||0:null});return a(o,200,{ok:!0,...r,size:e.size,newest:e.newest})}if(i==="/v1/history/list"&&n.method==="GET"){const e=Math.min(500,Math.max(1,Number(f.searchParams.get("limit"))||50)),r=Math.max(0,Number(f.searchParams.get("offset"))||0),s=f.searchParams.get("type")||null;return a(o,200,{ok:!0,...j.list({limit:e,offset:r,type:s})})}if(i==="/v1/history/get"&&n.method==="GET"){const e=f.searchParams.get("maxChars")!=null?Math.max(1,Number(f.searchParams.get("maxChars"))||0):null,r=Math.max(0,Number(f.searchParams.get("offset"))||0),s=j.get(String(f.searchParams.get("id")||""),{maxChars:e,offset:r});return s?a(o,200,{ok:!0,record:s}):a(o,404,{error:{message:"no such record",type:"not_found"}})}if(i==="/v1/history/key"&&n.method==="GET")return a(o,200,{ok:!0,hasKey:no()});if(i==="/v1/history/key"&&n.method==="POST")try{const e=JSON.parse((await T(n,t.maxBodyBytes)).toString("utf8"))||{};e.passphrase?Jr(String(e.passphrase)):Lr();const r=e.passphrase?await wt(j,String(e.passphrase)):{ok:!0,ingested:0};return r.ok&&r.whole&&Ge(),a(o,200,{ok:!0,hasKey:!!e.passphrase,...r})}catch(e){return a(o,400,{error:{message:`key handoff failed: ${e.message}`,type:"key_error"}})}if(i==="/v1/history/ingest-backup"&&n.method==="POST")try{const e=await wt(j,pt());return e.ok&&e.whole&&Ge(),a(o,e.ok?200:409,e)}catch(e){return a(o,400,{error:{message:`backup ingest failed: ${e.message}`,type:"ingest_error"}})}if(i==="/ner"){if(n.method==="GET"){const e=await Lo(t);return a(o,e.ok?200:503,e)}if(n.method==="POST"){if(await tt(t),R.state()!=="off"){if(!R.isReady()){const r=R.health();return a(o,503,{error:{message:r.state==="error"?`NER model failed to load: ${r.error||"unknown error"}`:`NER model is ${r.state} — not ready yet`,type:r.state==="error"?"ner_error":"ner_loading"},state:r.state,model:r.model})}try{const r=await T(n,t.maxBodyBytes);let s="",l=!1;try{const m=JSON.parse(r.toString("utf8"));s=m?.text||"",l=m?.strict===!0}catch{}const d=await R.detect(s,{strict:l});return a(o,200,{entities:d})}catch(r){return a(o,500,{error:{message:`NER error: ${r.message}`,type:"ner_error"}})}}const e=Jo(t);if(!e){const r=R.modelOnDisk(t.ner?.model||void 0);return a(o,503,{error:{message:r?"the bundled detector could not start — deterministic-only redaction":"no entity detector is installed — deterministic-only redaction (install one from Gateway settings)",type:r?"ner_error":"ner_not_installed"},state:R.state(),model:t.ner?.model||null})}try{const r=await T(n,t.maxBodyBytes),s=await Ze(e,{method:"POST",headers:{"content-type":"application/json"},body:r,signal:AbortSignal.timeout(8e3)}),l=await s.text();return o.writeHead(s.status,{"content-type":"application/json"}),o.end(l)}catch(r){return a(o,502,{error:{message:`NER unreachable: ${r.message}`,type:"ner_unreachable"}})}}}if(i==="/redact"&&n.method==="POST"){let e="";try{e=String(JSON.parse((await T(n,t.maxBodyBytes)).toString("utf8"))?.text||"")}catch{e=""}if(!e)return a(o,200,{text:"",count:0,sanitized:0,entities:[],detector:At(t)});try{let r=e;const s=await Te(t.pro?.entitlementToken);await tt(t);const l=await Ye([ut(()=>r,d=>{r=d})],t.redaction,{isPro:s});return a(o,200,{text:r,count:l.count||0,sanitized:l.sanitized||0,tier:t.redaction?.tier==="full"?"full":"basic",entities:Ro(l.vault,"types")||[],detector:At(t)})}catch(r){return a(o,500,{error:{message:`redaction preview failed: ${r.message}`,type:"redact_error"}})}}if(i==="/ner/models"){if(n.method==="GET"){const e=R.health().model||t.ner?.model||null,r=Math.round(bt.totalmem()/1048576),s=va(fo,{totalRamMB:r}).map(l=>({...l,installed:R.modelOnDisk(l.id)}));for(const l of[e,...R.modelsOnDisk()])!l||s.some(d=>d.id===l)||s.push({id:l,label:l,lang:"—",custom:!0,installed:R.modelOnDisk(l),note:"Custom model (from Hugging Face)."});return a(o,200,{active:e,companions:R.companions(),union:Array.isArray(t.ner?.union)?t.ner.union:[],machine:{totalRamMB:r},skipped:Rr(),recommendation:ro(s,{totalRamMB:r},[]),state:R.state(),progress:R.progress(),available:s})}if(n.method==="POST"){let e=null;try{e=JSON.parse((await T(n,t.maxBodyBytes)).toString("utf8"))}catch{e=null}if(e&&e.recommended===!0){const s=Math.round(bt.totalmem()/1048576),l=ro(fo.map(d=>({...d,installed:R.modelOnDisk(d.id)})),{totalRamMB:s},[]);e={id:l.primary,union:l.union}}const r=e&&typeof e.id=="string"?e.id.trim():null;if(e&&Array.isArray(e.union)){const s=[...new Set(e.union.map(d=>String(d||"").trim()).filter(Boolean))];for(const d of s)if(!(go(d)||wo(d)))return a(o,400,{error:{message:`unknown or invalid model id in union: ${d}`,type:"bad_model"}});const l=r||t.ner?.model||R.health().model;t.ner=t.ner||{allowDownload:!0,enableFullTier:!0},t.ner.union=s.filter(d=>d!==l),r&&Eo(t,r);try{be(t,le())}catch{}return(async()=>{r&&await R.setModel(r,{onLog:m=>console.log(m)});const d=Ir(t.ner,{log:m=>console.log(m)});for(const m of R.companions())d.includes(m.model)||await R.removeCompanion(m.model);for(const m of d)await R.addCompanion(m,{onLog:h=>console.log(h),allowDownload:t.ner.allowDownload!==!1});R.setUnionOrder(d)})().catch(d=>console.log(`[ner] union update failed: ${d.message}`)),a(o,202,{accepted:!0,active:l,union:t.ner.union,companions:R.companions(),state:R.state()})}if(!r||!(go(r)||wo(r)))return a(o,400,{error:{message:"unknown or invalid model id",type:"bad_model"}});Eo(t,r);try{be(t,le())}catch{}return R.setModel(r,{onLog:s=>console.log(s)}).then(s=>{s&&t.ner?.enableFullTier&&t.redaction.tier!=="full"&&(t.redaction.tier="full")}),a(o,202,{accepted:!0,active:r,state:R.state(),progress:R.progress()})}}if(i==="/stt/models"){if(n.method==="GET"){const e=$.health().model||t.stt?.model||ot,r={platform:process.platform,arch:process.arch,helper:!!ft()},s=Sa.map(l=>{const d=bo(l,r);return{...l,installed:$.modelOnDisk(l.id),...d?{unavailable:d}:{}}});return e&&!s.some(l=>l.id===e)&&s.push({id:e,label:e,lang:"—",tier:"custom",custom:!0,installed:$.modelOnDisk(e),note:"Custom model (from Hugging Face)."}),a(o,200,{active:e,state:$.state(),progress:$.progress(),available:s,dtype:t.stt?.dtype||"auto",loadedDtype:$.health().dtype,runtime:$.health().runtime,dtypes:_a})}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||!(Ta(r)||xa(r)))return a(o,400,{error:{message:"unknown or invalid model id",type:"bad_model"}});const s=bo(Ea(r),{platform:process.platform,arch:process.arch,helper:!!ft()});if(s)return a(o,400,{error:{message:s,type:"bad_model"}});const l=typeof e.dtype=="string"&&Oa(e.dtype)?e.dtype:void 0;t.stt?t.stt.model=r:t.stt={enabled:!0,model:r,allowDownload:!0},l&&(t.stt.dtype=l==="auto"?null:l);try{be(t,le())}catch{}return $.setModel(r,{onLog:d=>console.log(d),dtype:l||t.stt.dtype||"auto",warmMs:t.stt.warmMs,allowDownload:t.stt?.allowDownload!==!1,segment:t.stt?.segment,speaker:Mt(t,{installing:!0})}),a(o,202,{accepted:!0,active:r,dtype:t.stt.dtype||"auto",state:$.state(),progress:$.progress(),speaker:{id:M.activeModel(),state:M.state(),installed:M.modelOnDisk()}})}}if(i==="/diarize/model"){if(n.method==="GET"){const e=M.activeModel(),r=ga.map(s=>({...s,installed:M.modelOnDisk(s.id)})).sort((s,l)=>(l.id===e?1:0)-(s.id===e?1:0));return a(o,200,{active:e,state:M.state(),threshold:M.activeThreshold(),segment:fa.health(),progress:M.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(!ho(r))return a(o,400,{error:{message:"unknown speaker model id",type:"bad_model"}});if(!await M.setModel(r,{log:s=>console.log(s)}))return a(o,409,{error:{message:"a diarizing session is using the current speaker model — try again when it ends",type:"model_busy"}});t.stt?t.stt.diarizeModel=r:t.stt={enabled:!0,diarize:!0,diarizeModel:r};try{be(t,le())}catch{}return M.init({allowDownload:t.stt?.allowDownload!==!1,warmMs:t.stt?.warmMs,onLog:s=>console.log(s)}),a(o,202,{accepted:!0,active:M.activeModel(),state:M.state(),threshold:M.activeThreshold(),progress:M.progress()})}return M.download({onLog:s=>console.log(s)}),a(o,202,{accepted:!0,active:M.activeModel(),state:M.state(),threshold:M.activeThreshold(),progress:M.progress()})}}if(i==="/tts/models"){if(n.method==="GET"){const e=D.health().model||t.tts?.model||_o(Tt()),r=Tt(),s=ko.find(d=>d.id===e)||null,l=ko.map(d=>({...d,installed:D.modelOnDisk(d.id),unavailable:d.requiresNative&&!r?"needs the npm gateway — the standalone binary cannot load this engine":void 0}));return e&&!l.some(d=>d.id===e)&&l.push({id:e,label:e,lang:"—",tier:"custom",custom:!0,installed:D.modelOnDisk(e),note:"Custom model (from Hugging Face)."}),a(o,200,{active:e,state:D.state(),progress:D.progress(),available:l,voice:t.tts?.voice||(at(e)==="pocket-tts"?rt:Oe),arch:D.arch(),supportsVoices:D.arch()?D.supportsVoices():s?s.arch==="style-tts2"&&!!s.voices:!0,supportsCustomVoices:D.arch()?D.supportsCustomVoices():!!s?.customVoices,sampleRate:D.sampleRate(),voices:D.isPocket()||!D.arch()&&at(e)==="pocket-tts"?(D.builtinVoices().length?D.builtinVoices():Da).map(d=>({id:d,label:d[0].toUpperCase()+d.slice(1),lang:"en",installed:D.builtinVoices().includes(d)})):D.arch()&&D.arch()!=="style-tts2"?[]:Pa.map(d=>({...d,installed:D.voiceOnDisk(d.id,e)})),dtype:t.tts?.dtype||"auto",loadedDtype:D.health().dtype,runtime:D.health().runtime,dtypes:Na})}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&&!($a(r)||Aa(r)))return a(o,400,{error:{message:"unknown or invalid model id",type:"bad_model"}});const s=e&&typeof e.voice=="string"?e.voice.trim():null;if(s){const d=pe.parseCustomVoice(s);if(!(d?!!pe.getVoice(d):nt(s)||vo(s)&&So(s)))return a(o,400,{error:{message:"unknown or invalid voice",type:"bad_voice"}})}const l=e&&typeof e.dtype=="string"&&Ba(e.dtype)?e.dtype:void 0;if(t.tts||(t.tts={enabled:!0,model:To,voice:Oe,allowDownload:!0}),r&&(t.tts.model=r),s&&(t.tts.voice=s),r&&!s){const d=Ma(r),m=pe.parseCustomVoice(t.tts.voice||""),h=!!(m&&pe.getVoice(m));if(d&&!h)if(at(r)==="pocket-tts")t.tts.voice=rt;else{const k=pe.listVoices();t.tts.voice=k.length?`custom:${k[0].id}`:""}else!d&&h&&(t.tts.voice=Oe);const w=at(r)==="pocket-tts";w&&!pe.parseCustomVoice(t.tts.voice||"")&&!nt(t.tts.voice)&&(t.tts.voice=rt),!w&&nt(t.tts.voice)&&(t.tts.voice=Oe)}l&&(t.tts.dtype=l==="auto"?null:l);try{be(t,le())}catch{}return r&&D.setModel(r,{onLog:d=>console.log(d),dtype:l||t.tts.dtype||"auto"}),a(o,202,{accepted:!0,active:t.tts.model,voice:t.tts.voice,dtype:t.tts.dtype||"auto",state:D.state(),progress:D.progress()})}}if(i==="/tts/voices"){if(n.method==="GET")return a(o,200,{voices:pe.listVoices(),usable:D.supportsCustomVoices(),embedder:M.activeModel(),embedderReady:M.isReady()});if(n.method==="POST"){let e=null;try{e=JSON.parse((await T(n,t.maxBodyBytes)).toString("utf8"))}catch{e=null}const r=e&&typeof e.name=="string"?e.name.trim():"",s=e&&Array.isArray(e.pcm)?e.pcm:null,l=e&&typeof e.id=="string"?e.id.trim():"";if(l){if(!pe.getVoice(l))return a(o,404,{error:{message:"no such saved voice",type:"bad_voice"}});if(!s){if(!r)return a(o,400,{error:{message:"a name is required",type:"bad_request"}});try{return a(o,200,{...pe.renameVoice(l,r),usable:D.supportsCustomVoices()})}catch(d){return a(o,400,{error:{message:d.message,type:"rename_failed"}})}}if(s.length<16e3)return a(o,400,{error:{message:"need at least 1 second of 16 kHz mono audio",type:"sample_too_short"}})}else if(!r)return a(o,400,{error:{message:"a name is required",type:"bad_request"}});if(!s||s.length<16e3)return a(o,400,{error:{message:"need at least 1 second of 16 kHz mono audio",type:"sample_too_short"}});try{if(!M.isReady()){const b=M.download({onLog:J=>console.log(J)}),B=Symbol("timeout"),_=await Promise.race([b.then(()=>null).catch(J=>J),new Promise(J=>setTimeout(()=>J(B),bs))]);if(_===B||!M.isReady())return a(o,503,{error:{message:_===B?"the speaker model is still downloading (~100 MB) — your recording was kept, press Save again shortly":`the speaker model failed to load: ${M.health().error||"unknown error"}`,type:"embedder_not_ready"},progress:M.progress()})}const d=Float32Array.from(s),m=await M.embed(d);let h=null;try{const b=await D.pocketForEncoding({allowDownload:t.tts?.allowDownload!==!1,log:B=>console.log(B)});b&&(h=await b.encodeVoice(ks(d,16e3,24e3)))}catch(b){console.log(`[tts] pocket conditioning unavailable for this voice (${b.message})`)}const w=l?pe.replaceVoice(l,{vec:m,pocket:h}):pe.saveVoice({name:r,vec:m,pocket:h}),k=l&&r&&r!==w.name?pe.renameVoice(l,r):w;return console.log(`[tts] ${l?"re-recorded":"saved"} custom voice "${k.name}" (${(w.kinds||[]).join(" + ")}, sample discarded)`),a(o,l?200:201,{...w,...k,usable:D.supportsCustomVoices()})}catch(d){return a(o,400,{error:{message:d.message,type:"save_failed"}})}}if(n.method==="DELETE"){const e=f.searchParams.get("id")||"",r=pe.deleteVoice(e);if(r&&t.tts?.voice===`custom:${e}`){const s=pe.listVoices();t.tts.voice=s.length?`custom:${s[0].id}`:Oe;try{be(t,le())}catch{}}return a(o,200,{deleted:r,voice:t.tts?.voice})}}if((i==="/tts"||i==="/v1/audio/speech")&&n.method==="POST"){if(t.tts?.enabled===!1)return a(o,503,{error:{message:"tts is disabled in gateway config",type:"tts_disabled"}});let e=null;try{e=JSON.parse((await T(n,t.maxBodyBytes)).toString("utf8"))}catch{e=null}const r=e&&typeof(e.input??e.text)=="string"?String(e.input??e.text).trim():"";if(!r)return a(o,400,{error:{message:"text is required",type:"bad_request"}});if(r.length>xo)return a(o,413,{error:{message:`text too long (max ${xo} chars)`,type:"too_long"}});const s=Number.isFinite(e.speed)?Math.min(2,Math.max(.5,e.speed)):1,l=Ca(t),d=e&&typeof e.voice=="string"&&e.voice.trim()?e.voice.trim():null,m=d||(l?l.voice:t.tts?.voice||Oe);if(l&&!Ra(m))return a(o,400,{error:{message:"unknown or invalid voice",type:"bad_voice"}});const h=e&&typeof e.response_format=="string"?e.response_format.toLowerCase():"wav";if(h!=="wav"&&h!=="pcm")return a(o,400,{error:{message:`unsupported response_format "${h}" — this gateway synthesizes wav`,type:"bad_format"}});try{if(l){const{audio:re,contentType:Se,redacted:G}=await Ia({dest:l,text:r,voice:m,speed:s,auth:n.headers.authorization||n.headers["xi-api-key"]||"",redaction:t.redaction,isPro:await Te(t.pro?.entitlementToken)});return o.writeHead(200,{"Content-Type":Se,"Content-Length":String(re.length),"Cache-Control":"no-store","X-Tts-Provider":l.kind,"X-Tts-Redacted":String(G)}),o.end(re)}if(!await D.ready({onLog:re=>console.log(re),allowDownload:t.tts?.allowDownload!==!1,model:t.tts?.model||_o(Tt()),dtype:t.tts?.dtype||"auto"}))return a(o,503,{error:{message:D.health().error||"tts model not ready",type:"tts_unavailable"}});const k=ja({requested:d,configured:m,engine:D,voices:pe,isPocketVoice:nt,isKnownVoice:vo,isValidVoiceId:So,defaultVoice:Oe,defaultPocketVoice:rt});if(!k.ok)return a(o,k.status,{error:{message:k.message,type:k.type}});const{voice:b,customId:B,speakerEmbedding:_}=k,J=await D.synth(r,{voice:b,speed:s,speakerEmbedding:_}),me=D.sampleRate(),we=h==="pcm"?Buffer.from(new Float32Array(J).buffer):D.toWav(J,me);return o.writeHead(200,{"Content-Type":h==="pcm"?"application/octet-stream":"audio/wav","Content-Length":String(we.length),"Cache-Control":"no-store","X-Tts-Sample-Rate":String(me),...B||D.isPocket()||D.supportsVoices()?{"X-Tts-Voice":b}:{}}),o.end(we)}catch(w){return a(o,500,{error:{message:w.message,type:"tts_failed"}})}}if(i==="/v1/audio/transcriptions"&&n.method==="POST"){if(t.stt?.enabled===!1)return a(o,403,{error:{message:"STT disabled in gateway config",type:"stt_disabled"}});let e;try{e=ba(await T(n,Math.max(t.maxBodyBytes||0,64*1024*1024)),n.headers["content-type"])}catch(b){return a(o,b.code===413?413:415,{error:{message:b.message,type:"bad_request"}})}const r=b=>e.find(B=>B.name===b&&!B.filename)?.data.toString("utf8").trim()||"",s=e.find(b=>b.name==="file"&&b.filename)||e.find(b=>b.filename);if(!s?.data?.length)return a(o,400,{error:{message:"a `file` part is required",type:"bad_request"}});let l;try{l=await ka(s.data)}catch(b){return a(o,b.code===415?415:500,{error:{message:b.message,type:"unsupported_media"}})}const d=["json","text","verbose_json"].includes(r("response_format"))?r("response_format"):"json",m=St(t,"stt");let h=null;if(m.kind==="remote"||m.kind==="container")try{h=yo(m,{fetchImpl:Ze})}catch(b){return a(o,500,{error:{message:`stt provider: ${b.message}`,type:"bad_provider"}})}if(!h&&!$.isReady()&&await $.init({model:t.stt?.model||ot,allowDownload:t.stt?.allowDownload!==!1,dtype:t.stt?.dtype||void 0,warmMs:t.stt?.warmMs,segment:t.stt?.segment,speaker:Mt(t),onLog:b=>console.log(b)}),!h&&!$.isReady())return a(o,503,{error:{message:`speech model not ready: ${$.health().error||$.state()}`,type:"stt_not_ready"}});const w=r("diarize")==="true"&&t.stt?.diarize!==!1;w&&!M.isReady()&&await M.init({allowDownload:t.stt?.allowDownload!==!1,warmMs:t.stt?.warmMs,onLog:b=>console.log(b)});const k=Date.now();try{const{id:b}=$.createSession({lang:r("language")||void 0,diarize:w,interims:!1,remote:h}),B=[],_=[];let J=null;$.subscribe(b,G=>{G.type==="final"&&G.text?B.push(G):G.type==="language"?J=G.lang:G.type==="error"&&_.push(G.message||G.code)});const me=16e3*5;for(let G=0;G<l.pcm.length;G+=me)$.pushAudio(b,l.pcm.subarray(G,Math.min(l.pcm.length,G+me))),await $.decodeNow(b);if(await $.endSession(b),!B.length&&_.length)return a(o,500,{error:{message:_[0],type:"decode_failed"}});let we=0;const re=B.map((G,Wo)=>{const Ht=typeof G.startMs=="number"?G.startMs/1e3:we,Ko=(G.durationMs||0)/1e3;return we=Ht+Ko,{id:Wo,start:Math.round(Ht*100)/100,end:Math.round(we*100)/100,text:G.text,...G.speaker?{speaker:G.speaker}:{},...G.turns?{turns:G.turns.map(Qe=>({start:Math.round(Qe.startMs/10)/100,end:Math.round((Qe.startMs+Qe.durationMs)/10)/100,speaker:Qe.speaker}))}:{}}}),Se=re.map(G=>G.text).join(" ").replace(/\s+/g," ").trim();return d==="text"?(o.writeHead(200,{"content-type":"text/plain; charset=utf-8"}),o.end(Se)):d==="verbose_json"?a(o,200,{task:"transcribe",language:J||r("language")||null,duration:Math.round(l.seconds*100)/100,text:Se,segments:re,provider:m.kind,took_ms:Date.now()-k}):a(o,200,{text:Se})}catch(b){return a(o,b.code==="too_many_sessions"?429:500,{error:{message:b.message,type:b.code||"stt_error"}})}}if(i==="/stt/sessions"&&n.method==="POST"){if(t.stt?.enabled===!1)return a(o,403,{error:{message:"STT disabled in gateway config",type:"stt_disabled"}});let e=null;try{e=JSON.parse((await T(n,t.maxBodyBytes)).toString("utf8")||"{}")}catch{e=null}const r=St(t,"stt");let s=null;if(r.kind==="remote"||r.kind==="container")try{s=yo(r,{fetchImpl:Ze})}catch(d){return a(o,500,{error:{message:`stt provider: ${d.message}`,type:"bad_provider"}})}!s&&!$.isReady()&&$.init({model:t.stt?.model||ot,allowDownload:t.stt?.allowDownload!==!1,dtype:t.stt?.dtype||void 0,warmMs:t.stt?.warmMs,segment:t.stt?.segment,speaker:Mt(t),onLog:d=>console.log(d)});const l=e?.diarize===!0&&t.stt?.diarize!==!1;l&&!M.isReady()&&M.init({allowDownload:t.stt?.allowDownload!==!1,warmMs:t.stt?.warmMs,onLog:d=>console.log(d)});try{const d=e?.poll===!0,{id:m}=$.createSession({lang:e?.lang,redact:e?.redact===!0,diarize:l,speakerLabel:e?.speakerLabel,endSilenceMs:e?.endSilenceMs,interims:e?.interims!==!1,remote:s,poll:d});return a(o,201,{id:m,state:$.state(),...d?{poll:!0}:{}})}catch(d){return a(o,d.code==="too_many_sessions"?429:500,{error:{message:d.message,type:d.code||"stt_error"}})}}{const e=i.match(/^\/stt\/sessions\/([0-9a-f-]{36})(\/audio|\/events)?$/);if(e){const r=e[1],s=async(d,m,h)=>{if(m.type!=="final"||!d.redact)return m;try{let w=m.text;return await Ye([ut(()=>w,k=>{w=k})],t.redaction,{isPro:h}),{...m,text:w}}catch{return m}},l=async d=>{const m=$.drainEvents(r);if(!m)return null;const h=[];if(d&&!d.closed){const k=d.remote?"ready":$.state();k==="downloading"||k==="loading"?h.push({type:"progress",state:k,...$.progress()||{}}):k==="error"?h.push({type:"error",code:"model_failed",message:$.health().error||"model failed to load",fatal:!0}):d.diarize&&["downloading","loading"].includes(M.state())?h.push({type:"diarize-progress",state:M.state(),...M.progress()||{}}):Go.get(d)!==k&&(Go.set(d,k),h.push({type:"state",state:k}))}const w=d?.redact?await Te(t.pro?.entitlementToken):!0;for(const k of m)d?h.push(await s(d,k,w)):k.type!=="final"&&k.type!=="interim"&&h.push(k);return h};if(e[2]==="/audio"&&n.method==="POST"){const d=$.getSession(r)||$.endedSession(r);try{const m=await T(n,t.maxBodyBytes);$.pushAudio(r,$.toFloat32(m));const h=await l(d);return a(o,200,{ok:!0,state:$.state(),...h?{events:h}:{}})}catch(m){const h=m.code==="no_session"?await l(d).catch(()=>null):null;return a(o,m.code==="no_session"?404:400,{error:{message:m.message,type:m.code||"stt_error"},...h?{events:h}:{}})}}if(e[2]==="/events"&&n.method==="GET"){const d=$.getSession(r);if(!d)return a(o,404,{error:{message:"no such session",type:"no_session"}});o.writeHead(200,{"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive"});const m=_=>o.write(`data: ${JSON.stringify(_)}
56
59
 
57
- `),h=d.redact?await Te(t.pro?.entitlementToken):!0,w=_=>s(d,_,h);p({type:"state",state:d.remote?"ready":$.state()});const k=setInterval(()=>{const _=d.remote?"ready":$.state();if(_==="downloading"||_==="loading"){p({type:"progress",state:_,...$.progress()||{}});return}if(_==="error"){p({type:"error",code:"model_failed",message:$.health().error||"model failed to load",fatal:!0}),clearInterval(k);return}if(d.diarize){const j=M.state();if(j==="downloading"||j==="loading"){p({type:"diarize-progress",state:j,...M.progress()||{}});return}}p({type:"state",state:_}),clearInterval(k)},500);k.unref?.();let b=Promise.resolve();const B=$.subscribe(r,_=>{b=b.then(async()=>{p(await w(_)),_.type==="end"&&(clearInterval(k),o.end())}).catch(()=>{})});n.on("close",()=>{clearInterval(k),B?.()});return}if(!e[2]&&n.method==="DELETE"){const d=$.getSession(r);await $.endSession(r);const p=d?.poll?await l(d).catch(()=>null):null;return a(o,200,{ok:!0,...p?{events:p}:{}})}}}if(i==="/logs"&&n.method==="GET")return a(o,200,{entries:[...z].reverse()});if(i==="/config"&&n.method==="GET"){const e=await Te(t.pro?.entitlementToken);return a(o,200,Oo(t,{proUnlocked:e,policy:Xe()}))}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 a(o,400,{error:"invalid config patch"});const r=JSON.stringify(t.sandbox||null);try{Ga(t,e)}catch(h){if(h?.code==="SHAPE")return a(o,400,{error:h.message});throw h}Yt(t),JSON.stringify(t.sandbox||null)!==r&&He?.restart("sandbox settings changed");try{we(t,le())}catch(h){return a(o,500,{error:`could not persist config: ${h.message}`})}const s=t.redaction?.detection,l=!s||!s.backend||s.backend==="off",d=I.state();t.ner?.autostart&&l&&d!=="ready"&&d!=="loading"&&d!=="downloading"&&I.setModel(t.ner.model,{onLog:h=>console.log(h)}).then(h=>{h&&t.ner?.enableFullTier&&t.redaction.tier!=="full"&&(t.redaction.tier="full")});const p=await Te(t.pro?.entitlementToken);return a(o,200,Oo(t,{proUnlocked:p,policy:Xe()}))}if(n.method==="GET"&&i==="/skills")return be(n,o,t,`/skills${Ce(f,t)}`,{pick:e=>({skills:Array.isArray(e?.skills)?e.skills:[]})});if(n.method==="POST"&&i==="/v1/threads/send"){if(!U(n))return a(o,403,{error:{message:"asking another chat: extension origin or gateway token required",type:"forbidden"}});if(n.headers["x-chatpanel-link-device"])return a(o,403,{error:{message:"asking another chat is not available from a linked phone yet",type:"forbidden"}});const e=R.lossless;if(!e)return a(o,501,{error:{message:"asking another chat needs the SQLite warm store",type:"unavailable"}});let r={};try{r=JSON.parse((await T(n,t.maxBodyBytes)).toString("utf8")||"{}")||{}}catch{return a(o,400,{error:{message:"threads/send: body must be JSON",type:"invalid_request"}})}const s=String(r.to||""),l=String(r.message||"").trim();if(!l||l.length>io)return a(o,400,{error:{message:`threads/send: a message of 1–${io} characters`,type:"invalid_request"}});const d=r.from&&typeof r.from=="object"?{id:String(r.from.id||"").slice(0,200),title:String(r.from.title||"").slice(0,200)}:null,p=e.get(s);if(!p||p.deletedAt)return a(o,404,{error:{message:"no such chat on this computer — it may not have synced here yet",type:"not_found"}});const h=Wr(p,{cards:ce.get("agentTools").agentTools?.value?.agents||[]});if(h.error)return a(o,409,{error:{message:h.error,type:"no_model"}});if(r.dryRun===!0)return a(o,200,{ok:!0,title:p.title,model:h.model});const w=Kr({fromTitle:d?.title,message:l}),k={thread:{id:h.thread,...p.title?{title:p.title}:{}},...h.workingDir?{workingDir:h.workingDir}:{}};let b="";try{const _=await fetch(`http://127.0.0.1:${n.socket.localPort}/v1/chat/completions`,{method:"POST",headers:{"content-type":"application/json","x-chatpanel-token":Be()||_e(),"x-chatpanel-run":encodeURIComponent(JSON.stringify(k))},body:JSON.stringify({model:h.model,messages:[...Yr(p),{role:"user",content:w}],stream:!1}),signal:AbortSignal.timeout(6e5)}),j=await _.json().catch(()=>null);if(!_.ok)return a(o,502,{error:{message:`that chat's ${h.model} did not answer: ${j?.error?.message||`HTTP ${_.status}`}`,type:"upstream"}});b=String(j?.choices?.[0]?.message?.content||"")}catch(_){return a(o,502,{error:{message:`that chat's ${h.model} did not answer: ${_?.message||_}`,type:"upstream"}})}const B=Qr(e.get(s)||p,{question:w,reply:b,model:h.model,from:d});e.write([B],{host:"gateway",at:Date.now()});try{const _=uo(e.get(s));_&&R.bulk({upserts:[_],removes:[]})}catch{}return Ge({ids:[s]}),a(o,200,{ok:!0,title:p.title,model:h.model,reply:b})}const X=/^(?:\/v1)?(\/agent-sessions(?:\/read|\/adopt|\/catchup)?)$/.exec(i)?.[1];if(n.method==="POST"&&X)return U(n)?n.headers["x-chatpanel-link-device"]&&t.link?.agentSessions===!1?a(o,403,{error:{message:"this computer does not share its coding agents' sessions with a linked phone — Settings › Link › Phones",type:"forbidden"}}):be(n,o,t,X,{method:"POST",timeoutMs:3e4}):a(o,403,{error:{message:"the agents' own sessions: extension origin or gateway token required",type:"forbidden"}});if(n.method==="GET"&&i==="/skills-quarantined")return be(n,o,t,`/skills-quarantined${Ce(f,t)}`,{pick:e=>({quarantined:Array.isArray(e?.quarantined)?e.quarantined:[]})});if(i==="/skills"&&n.method==="POST")return U(n)?be(n,o,t,"/skills",{method:"POST",timeoutMs:15e3}):a(o,403,{error:{message:"writing a skill: extension origin or gateway token required",type:"forbidden"}});if(/^\/skills\/[^/]+$/.test(i)&&n.method==="DELETE"){const e=decodeURIComponent(i.slice(8));return Dt(e)?a(o,400,{error:{message:"not a skill id",type:"invalid_request"}}):U(n)?be(n,o,t,`/skills/${encodeURIComponent(e)}`,{method:"DELETE"}):a(o,403,{error:{message:"deleting a skill: extension origin or gateway token required",type:"forbidden"}})}if(/^\/skills\/[^/]+\/file\/.+/.test(i)&&n.method==="PUT"){const e=/^\/skills\/([^/]+)\/file\/(.+)$/.exec(i),r=decodeURIComponent(e[1]);return Dt(r)||/(^|\/)\.\.(\/|$)/.test(decodeURIComponent(e[2]))?a(o,400,{error:{message:"not a skill file",type:"invalid_request"}}):U(n)?be(n,o,t,`/skills/${encodeURIComponent(r)}/file/${e[2]}`,{method:"PUT",timeoutMs:15e3}):a(o,403,{error:{message:"writing a skill file: extension origin or gateway token required",type:"forbidden"}})}if(n.method==="GET"&&i==="/agent-defs")return be(n,o,t,`/agent-defs${Ce(f,t)}`,{pick:e=>({agents:Array.isArray(e?.agents)?e.agents:[],...e?.quarantined?{quarantined:e.quarantined}:{},...e?.problems?{problems:e.problems}:{}})});if(n.method==="GET"&&/^\/agent-defs\/[^/]+$/.test(i)){const e=decodeURIComponent(i.slice(12));return Dt(e)?a(o,400,{error:{message:"not an agent id",type:"invalid_request"}}):be(n,o,t,`/agent-defs/${encodeURIComponent(e)}${Ce(f,t)}`)}if(i.startsWith("/a2a/")){if(!U(n))return a(o,403,{error:{message:"a2a: extension origin or gateway token required",type:"forbidden"}});try{if(n.method==="GET"&&i==="/a2a/agents")return a(o,200,{agents:$r()});if(n.method==="POST"&&i==="/a2a/card"){const e=JSON.parse((await T(n,t.maxBodyBytes)).toString("utf8")||"{}");e.forget&&xr(e.url||"");const r=await qe(e.url,{force:!!e.force,auth:String(e.auth||"")});return a(o,200,{ok:!0,card:r.card,fingerprint:r.fingerprint,fresh:r.fresh,changed:!!r.changed,url:r.url})}if(n.method==="POST"&&i==="/a2a/message"){const e=JSON.parse((await T(n,t.maxBodyBytes)).toString("utf8")||"{}"),r=e.card||(await qe(e.url,{auth:String(e.auth||"")})).card,s=await _r({card:r,message:e.message||{messageId:`cp_${Date.now().toString(36)}`,role:"ROLE_USER",parts:[{text:String(e.text||"")}]},auth:String(e.auth||""),returnImmediately:!!e.returnImmediately,contextId:String(e.contextId||""),taskId:String(e.taskId||"")});return a(o,200,{ok:!0,...s})}if(n.method==="POST"&&i==="/a2a/message/stream"){const e=JSON.parse((await T(n,t.maxBodyBytes)).toString("utf8")||"{}"),r=e.card||(await qe(e.url,{auth:String(e.auth||"")})).card;o.writeHead(200,{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"});const s=(l,d)=>o.write(`event: ${l}
60
+ `),h=d.redact?await Te(t.pro?.entitlementToken):!0,w=_=>s(d,_,h);m({type:"state",state:d.remote?"ready":$.state()});const k=setInterval(()=>{const _=d.remote?"ready":$.state();if(_==="downloading"||_==="loading"){m({type:"progress",state:_,...$.progress()||{}});return}if(_==="error"){m({type:"error",code:"model_failed",message:$.health().error||"model failed to load",fatal:!0}),clearInterval(k);return}if(d.diarize){const J=M.state();if(J==="downloading"||J==="loading"){m({type:"diarize-progress",state:J,...M.progress()||{}});return}}m({type:"state",state:_}),clearInterval(k)},500);k.unref?.();let b=Promise.resolve();const B=$.subscribe(r,_=>{b=b.then(async()=>{m(await w(_)),_.type==="end"&&(clearInterval(k),o.end())}).catch(()=>{})});n.on("close",()=>{clearInterval(k),B?.()});return}if(!e[2]&&n.method==="DELETE"){const d=$.getSession(r);await $.endSession(r);const m=d?.poll?await l(d).catch(()=>null):null;return a(o,200,{ok:!0,...m?{events:m}:{}})}}}if(i==="/logs"&&n.method==="GET")return a(o,200,{entries:[...C].reverse()});if(i==="/config"&&n.method==="GET"){const e=await Te(t.pro?.entitlementToken);return a(o,200,Oo(t,{proUnlocked:e,policy:Xe()}))}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 a(o,400,{error:"invalid config patch"});const r=JSON.stringify(t.sandbox||null);try{Ga(t,e)}catch(h){if(h?.code==="SHAPE")return a(o,400,{error:h.message});throw h}Qt(t),JSON.stringify(t.sandbox||null)!==r&&He?.restart("sandbox settings changed");try{be(t,le())}catch(h){return a(o,500,{error:`could not persist config: ${h.message}`})}const s=t.redaction?.detection,l=!s||!s.backend||s.backend==="off",d=R.state();t.ner?.autostart&&l&&d!=="ready"&&d!=="loading"&&d!=="downloading"&&R.setModel(t.ner.model,{onLog:h=>console.log(h)}).then(h=>{h&&t.ner?.enableFullTier&&t.redaction.tier!=="full"&&(t.redaction.tier="full")});const m=await Te(t.pro?.entitlementToken);return a(o,200,Oo(t,{proUnlocked:m,policy:Xe()}))}if(n.method==="GET"&&i==="/skills")return ke(n,o,t,`/skills${Ce(f,t)}`,{pick:e=>({skills:Array.isArray(e?.skills)?e.skills:[]})});if(n.method==="POST"&&i==="/v1/threads/send"){if(!U(n))return a(o,403,{error:{message:"asking another chat: extension origin or gateway token required",type:"forbidden"}});if(n.headers["x-chatpanel-link-device"])return a(o,403,{error:{message:"asking another chat is not available from a linked phone yet",type:"forbidden"}});const e=j.lossless;if(!e)return a(o,501,{error:{message:"asking another chat needs the SQLite warm store",type:"unavailable"}});let r={};try{r=JSON.parse((await T(n,t.maxBodyBytes)).toString("utf8")||"{}")||{}}catch{return a(o,400,{error:{message:"threads/send: body must be JSON",type:"invalid_request"}})}const s=String(r.to||""),l=String(r.message||"").trim();if(!l||l.length>io)return a(o,400,{error:{message:`threads/send: a message of 1–${io} characters`,type:"invalid_request"}});const d=r.from&&typeof r.from=="object"?{id:String(r.from.id||"").slice(0,200),title:String(r.from.title||"").slice(0,200)}:null,m=e.get(s);if(!m||m.deletedAt)return a(o,404,{error:{message:"no such chat on this computer — it may not have synced here yet",type:"not_found"}});const h=Wr(m,{cards:ce.get("agentTools").agentTools?.value?.agents||[]});if(h.error)return a(o,409,{error:{message:h.error,type:"no_model"}});if(r.dryRun===!0)return a(o,200,{ok:!0,title:m.title,model:h.model});const w=Kr({fromTitle:d?.title,message:l}),k={thread:{id:h.thread,...m.title?{title:m.title}:{}},...h.workingDir?{workingDir:h.workingDir}:{}};let b="";try{const _=await fetch(`http://127.0.0.1:${n.socket.localPort}/v1/chat/completions`,{method:"POST",headers:{"content-type":"application/json","x-chatpanel-token":Be()||_e(),"x-chatpanel-run":encodeURIComponent(JSON.stringify(k))},body:JSON.stringify({model:h.model,messages:[...Qr(m),{role:"user",content:w}],stream:!1}),signal:AbortSignal.timeout(6e5)}),J=await _.json().catch(()=>null);if(!_.ok)return a(o,502,{error:{message:`that chat's ${h.model} did not answer: ${J?.error?.message||`HTTP ${_.status}`}`,type:"upstream"}});b=String(J?.choices?.[0]?.message?.content||"")}catch(_){return a(o,502,{error:{message:`that chat's ${h.model} did not answer: ${_?.message||_}`,type:"upstream"}})}const B=Yr(e.get(s)||m,{question:w,reply:b,model:h.model,from:d});e.write([B],{host:"gateway",at:Date.now()});try{const _=uo(e.get(s));_&&j.bulk({upserts:[_],removes:[]})}catch{}return Ge({ids:[s]}),a(o,200,{ok:!0,title:m.title,model:h.model,reply:b})}const Z=/^(?:\/v1)?(\/agent-sessions(?:\/read|\/adopt|\/catchup)?)$/.exec(i)?.[1];if(n.method==="POST"&&Z)return U(n)?n.headers["x-chatpanel-link-device"]&&t.link?.agentSessions===!1?a(o,403,{error:{message:"this computer does not share its coding agents' sessions with a linked phone — Settings › Link › Phones",type:"forbidden"}}):ke(n,o,t,Z,{method:"POST",timeoutMs:3e4}):a(o,403,{error:{message:"the agents' own sessions: extension origin or gateway token required",type:"forbidden"}});if(n.method==="GET"&&i==="/skills-quarantined")return ke(n,o,t,`/skills-quarantined${Ce(f,t)}`,{pick:e=>({quarantined:Array.isArray(e?.quarantined)?e.quarantined:[]})});if(i==="/skills"&&n.method==="POST")return U(n)?ke(n,o,t,"/skills",{method:"POST",timeoutMs:15e3}):a(o,403,{error:{message:"writing a skill: extension origin or gateway token required",type:"forbidden"}});if(/^\/skills\/[^/]+$/.test(i)&&n.method==="DELETE"){const e=decodeURIComponent(i.slice(8));return Dt(e)?a(o,400,{error:{message:"not a skill id",type:"invalid_request"}}):U(n)?ke(n,o,t,`/skills/${encodeURIComponent(e)}`,{method:"DELETE"}):a(o,403,{error:{message:"deleting a skill: extension origin or gateway token required",type:"forbidden"}})}if(/^\/skills\/[^/]+\/file\/.+/.test(i)&&n.method==="PUT"){const e=/^\/skills\/([^/]+)\/file\/(.+)$/.exec(i),r=decodeURIComponent(e[1]);return Dt(r)||/(^|\/)\.\.(\/|$)/.test(decodeURIComponent(e[2]))?a(o,400,{error:{message:"not a skill file",type:"invalid_request"}}):U(n)?ke(n,o,t,`/skills/${encodeURIComponent(r)}/file/${e[2]}`,{method:"PUT",timeoutMs:15e3}):a(o,403,{error:{message:"writing a skill file: extension origin or gateway token required",type:"forbidden"}})}if(n.method==="GET"&&i==="/agent-defs")return ke(n,o,t,`/agent-defs${Ce(f,t)}`,{pick:e=>({agents:Array.isArray(e?.agents)?e.agents:[],...e?.quarantined?{quarantined:e.quarantined}:{},...e?.problems?{problems:e.problems}:{}})});if(n.method==="GET"&&/^\/agent-defs\/[^/]+$/.test(i)){const e=decodeURIComponent(i.slice(12));return Dt(e)?a(o,400,{error:{message:"not an agent id",type:"invalid_request"}}):ke(n,o,t,`/agent-defs/${encodeURIComponent(e)}${Ce(f,t)}`)}if(i.startsWith("/a2a/")){if(!U(n))return a(o,403,{error:{message:"a2a: extension origin or gateway token required",type:"forbidden"}});try{if(n.method==="GET"&&i==="/a2a/agents")return a(o,200,{agents:$r()});if(n.method==="POST"&&i==="/a2a/card"){const e=JSON.parse((await T(n,t.maxBodyBytes)).toString("utf8")||"{}");e.forget&&xr(e.url||"");const r=await qe(e.url,{force:!!e.force,auth:String(e.auth||"")});return a(o,200,{ok:!0,card:r.card,fingerprint:r.fingerprint,fresh:r.fresh,changed:!!r.changed,url:r.url})}if(n.method==="POST"&&i==="/a2a/message"){const e=JSON.parse((await T(n,t.maxBodyBytes)).toString("utf8")||"{}"),r=e.card||(await qe(e.url,{auth:String(e.auth||"")})).card,s=await _r({card:r,message:e.message||{messageId:`cp_${Date.now().toString(36)}`,role:"ROLE_USER",parts:[{text:String(e.text||"")}]},auth:String(e.auth||""),returnImmediately:!!e.returnImmediately,contextId:String(e.contextId||""),taskId:String(e.taskId||"")});return a(o,200,{ok:!0,...s})}if(n.method==="POST"&&i==="/a2a/message/stream"){const e=JSON.parse((await T(n,t.maxBodyBytes)).toString("utf8")||"{}"),r=e.card||(await qe(e.url,{auth:String(e.auth||"")})).card;o.writeHead(200,{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"});const s=(l,d)=>o.write(`event: ${l}
58
61
  data: ${JSON.stringify(d)}
59
62
 
60
- `);try{const l=await Or({card:r,message:e.message||{messageId:`cp_${Date.now().toString(36)}`,role:"ROLE_USER",parts:[{text:String(e.text||"")}]},auth:String(e.auth||""),contextId:String(e.contextId||""),taskId:String(e.taskId||""),onEvent:d=>s(d.kind,{kind:d.kind,task:d.task,message:d.message})});s("done",l)}catch(l){s("error",{code:l.code||"ERROR",message:l.message})}return o.end()}if(n.method==="POST"&&i==="/a2a/task"){const e=JSON.parse((await T(n,t.maxBodyBytes)).toString("utf8")||"{}"),r=e.card||(await qe(e.url,{auth:String(e.auth||"")})).card,s=e.cancel?await Pr({card:r,id:String(e.id||""),auth:String(e.auth||"")}):await Er({card:r,id:String(e.id||""),auth:String(e.auth||"")});return a(o,200,{ok:!0,...s})}return a(o,404,{error:{message:`no such a2a route: ${i}`,type:"invalid_request"}})}catch(e){const r=e instanceof Xt||e?.name==="A2AClientError"?e.code:"ERROR";return a(o,e instanceof Xt&&e.code==="UNREACHABLE"?502:400,{error:{message:e.message,type:"a2a_error",code:r}})}}if(n.method==="POST"&&(i==="/agent-defs/export"||i==="/agent-defs/export-plan"))return U(n)?be(n,o,t,i,{method:"POST",timeoutMs:15e3}):a(o,403,{error:{message:"exporting an agent: extension origin or gateway token required",type:"forbidden"}});if(n.method==="GET"&&/^\/skills\/[^/]+$/.test(i)){const e=decodeURIComponent(i.slice(8));return!e||e==="."||e===".."||e.includes("/")||e.includes("\\")?a(o,400,{error:{message:"not a skill id",type:"invalid_request"}}):be(n,o,t,`/skills/${encodeURIComponent(e)}${Ce(f,t)}`,{pick:r=>({skill:r?.skill||null})})}if(i==="/channels"||/^\/channels\/(connect|pair|unpair|settings|disconnect)$/.test(i)){if(!U(n))return a(o,403,{error:{message:"channels: extension origin or gateway token required",type:"forbidden"}});if(!(i==="/channels"&&n.method==="GET"||i!=="/channels"&&n.method==="POST"))return a(o,405,{error:{message:"method not allowed",type:"invalid_request"}});const e=await je(t);if(!e)return a(o,503,{error:{message:"no bridge is configured",type:"no_bridge"}});const r=Je(t.bridge?.token);try{const s=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:s||"{}"}:{},signal:AbortSignal.timeout(15e3)}),d=await l.json().catch(()=>({}));return a(o,l.status,d)}catch(s){return a(o,502,{error:{message:`bridge unreachable: ${s.message}`,type:"bridge_unreachable"}})}}if(n.method==="GET"&&/^\/skills\/[^/]+\/file\/.+/.test(i)){const e=/^\/skills\/([^/]+)\/file\/(.+)$/.exec(i),r=decodeURIComponent(e[1]),s=e[2];return!r||r==="."||r===".."||r.includes("/")||r.includes("\\")||/(^|\/)\.\.(\/|$)/.test(decodeURIComponent(s))?a(o,400,{error:{message:"not a skill file",type:"invalid_request"}}):be(n,o,t,`/skills/${encodeURIComponent(r)}/file/${s}${Ce(f,t)}`)}if(n.method==="GET"&&/\/models$/.test(i)){const e=await J(),r=e.sig!==void 0&&e.sig!==C;return C=e.sig,a(o,200,await Wa(t,{serviceHealth:async()=>e,fresh:r,engineAt:c.engineAt}))}if(vs.some(e=>i===e||i.startsWith(`${e}/`)))return a(o,404,{error:{message:`this gateway (${de}) has no ${i} — update it to use this feature`,type:"unknown_endpoint"}});const F=cs(i,n.headers,t);let K;try{K=await T(n,t.maxBodyBytes)}catch(e){a(o,e.code===413?413:400,{error:e.code===413?"payload too large":"bad request"}),n.destroy();return}let W=null,v=null,se=K,Ue=0,$e=0,It=0,ve=!1,Ee=!1,Rt="",Ae=!0;const ne=t.logRequests&&F.redactable&&n.method==="POST"?ds(ke):null,Ho=Date.now();if(F.redactable&&n.method==="POST"&&K.length){try{v=JSON.parse(K.toString("utf8"))}catch{v=null}if(v&&us(v,F.kind))se=K;else if(v){const e=t.tools||{};if(e.autoNarrow!==!1&&Array.isArray(v.tools)&&v.tools.length){const w=Number(e.maxPerTurn)>0?Number(e.maxPerTurn):ts,k=e.narrowAll?null:B=>!os.test(Mo(B)),b=v.tools.length;v.tools=rr(v.tools,ns(v,F.kind),{cap:w,keep:k,name:Mo,description:rs}),It=b-v.tools.length}if(Ae=await Te(t.pro?.entitlementToken),ve=String(n.headers["x-chatpanel-redaction"]||"").trim().toLowerCase()==="off"&&U(n),!ve){const w=st(v?.model,t,F.kind,{destination:String(n.headers["x-chatpanel-destination"]||v?.chatpanel?.destination||"").trim(),down:()=>!1}),k=w?.type==="api"?await c.decide(w,v?.model).catch(()=>null):null;Ee=k?.redact===!1,Rt=Ee?k.engine||"declared":""}if(!ve&&!Ee){const w=Ja(t,Ae);if(!w.allowed)return a(o,402,{error:{message:`ChatPanel Gateway free trial used up (${w.cap} redactions). Add a ChatPanel Pro entitlement token to unlock unlimited full-tier redaction (names/orgs).`,type:"free_limit_reached"}})}!ve&&!Ee&&await tt(t);const r=ve?[]:F.adapter.collectSegments(v,t.redaction,{skipPublic:U(n)}),s=new AbortController;o.on("close",()=>{o.writableFinished||s.abort()});const l=ne?ne.clock():0,{vault:d,count:p,sanitized:h}=ve?{vault:null,count:0,sanitized:0}:await Qe(r,t.redaction,{signal:s.signal,isPro:Ae,sanitizeOnly:Ee,onEgress:w=>Pt.push($o({ts:Date.now(),client:"redaction",tool:`detect:${w.backend}@${w.host||"local"}`,ok:w.ok,ms:w.ms,error:w.error}))});if(ne&&ne.lap("redact",l),F.adapter.joinTextParts?.(v),W=d,Ue=p,$e=h||0,p>0&&o.setHeader("x-chatpanel-redacted",String(p)),!Ae&&p>0){La(t,Ae);try{we(t,le())}catch{}}if(!ve&&!Ee&&Array.isArray(v.tools)&&v.tools.length&&typeof F.adapter.injectSystemNote=="function"){const w=st(v?.model,t,F.kind,{destination:String(n.headers["x-chatpanel-destination"]||v?.chatpanel?.destination||"").trim(),down:b=>!!b.service&&x.fn(b.id)==="down"}),k=!(w&&w.type==="api");F.adapter.injectSystemNote(v,ar({toolData:t.tools?.toolData,ownTools:k}))}else!ve&&p>0&&typeof F.adapter.injectSystemNote=="function"&&F.adapter.injectSystemNote(v,sr());se=Buffer.from(JSON.stringify(v),"utf8")}}const jt=nr({vault:W,toolData:t.tools?.toolData}),Ve=v&&typeof v.chatpanel=="object"&&v.chatpanel||null;if(Ve&&(delete v.chatpanel,se=Buffer.from(JSON.stringify(v),"utf8")),typeof v?.model=="string"&&v.model.startsWith("fusion:")){const e=On(v.model,t,await J());if(e?.error)return ne?.commit(),a(o,400,{error:{message:e.error,type:"fusion"}});e&&(v.model=e.model,se=Buffer.from(JSON.stringify(v),"utf8"),o.setHeader("x-chatpanel-fusion",`${e.fusion.id} -> ${e.model}`))}const ae={destination:String(n.headers["x-chatpanel-destination"]||Ve?.destination||"").trim(),reach:String(n.headers["x-chatpanel-reach"]||Ve?.reach||"").trim(),run:Ct(n.headers["x-chatpanel-run"],Ve?.run)},Fe=await J(),Jt=e=>!!e.service&&Fe(e.id)==="down";let A=st(v?.model,t,F.kind,{destination:ae.destination,down:Jt});A?.type==="agent"&&v?.model&&!ae.destination&&!Qa(A,v.model)&&(await Ya(t,{serviceHealth:async()=>Fe,engineAt:c.engineAt}),A=st(v?.model,t,F.kind,{destination:ae.destination,down:Jt}));const Lt=A?.service&&Fe(A.id)==="down"?await E().revive(A.service).catch(()=>null):null;if(Lt?.ok&&(x.at=0),A?.service&&Fe(A.id)==="down"&&!Lt?.ok)return ne?.commit(),a(o,503,{error:{message:`${A.id} is not running — the model ${JSON.stringify(v?.model||"")} is served by an engine the Runtime has stopped; start it under Settings › Runtime`,type:"engine_down",service:A.service}});if(ae.destination&&(!A||A.id!==ae.destination))return ne?.commit(),a(o,404,{error:{message:`no destination "${ae.destination}" is configured on this gateway`,type:"unknown_destination",known:Ka(t).map(e=>e.id)}});const ie=vt(n.headers);if(ie&&!qn(ie,A?.type==="api"?"api":"agent"))return ne?.commit(),a(o,403,{error:{message:`link: partner "${ie.partner}" may not use ${A?.type==="api"?"this model":"this computer’s coding agents"} — its scopes are ${ie.scopes.join(", ")||"none"}; the owner grants agents at pairing`,type:"forbidden",code:"link_scope"}});const We=ie&&F.redactable&&n.method==="POST"&&v?{caller:ie,surface:wn(ie,ie.kind==="partner"?"":y?.deviceNameOf(ie.device)),model:v.model||null,startedAt:Ho}:null;ne&&(ne.meta={t:Date.now(),model:v?.model||null,dest:A?A.id:null,type:A?A.type:null,redacted:Ue,sanitized:$e,narrowed:It,detail:Ro(W,t.logDetail),redaction:ve?"off":Ee?`on-device (${Rt})`:t.redaction.tier||"basic",...ie?.kind==="partner"?{via:ea(ie)}:{}});const Ke=Xe();if(Ke&&A){const e=A.type==="api"?Qt(Ke,{model:v?.model||"",endpoint:A.baseUrl||""}):Sr(Ke,A.agent||A.id)?Qt(Ke,{model:v?.model||""}):{ok:!1,reason:`agent "${A.agent||A.id}" is not allowed by your organisation’s policy`};if(!e.ok)return ne?.commit(),a(o,403,{error:{message:e.reason,type:"policy",code:"org_policy"}})}if(A&&A.type==="api")return A.baseUrl?ms(A.baseUrl,t)?(ne?.commit(),a(o,508,{error:{message:`destination "${A.id}" points back at the gateway (${A.baseUrl}) — refusing to forward (would loop).`,type:"loop_detected"}})):Ss(n,o,{...F,pathname:i,search:f.search,base:A.baseUrl,destKey:A.apiKey,destProtocol:A.protocol,harness:jt,trace:ne,link:We&&{...We,agentId:A.id,dest:{type:"api",id:A.id}}},se,W):(ne?.commit(),a(o,502,{error:`destination "${A.id}" has no baseUrl`}));const dt=Ie(n),zt=dt==="local"&&t.bridge?.openAgentLane?"token":dt;if(zt==="local")return ne?.commit(),a(o,401,{error:{message:"agent destinations require the gateway token: send `Authorization: Bearer $(cat ~/.chatpanel/gateway-token)`, or pair this client with `chatpanel-gateway pair`",type:"auth",code:"agent_lane_token_required"}});const Gt=Math.max(0,Math.min(8,Number(n.headers["x-chatpanel-ask-depth"])||0)),Uo=new Set(["thread","ephemeral","workingDir","worker"]),ct=ie?.kind==="partner";if(dt==="token"&&n.headers["x-chatpanel-link-device"]&&!ct&&!(ae.run&&Object.keys(ae.run).some(e=>!Uo.has(e)))){const e=Ct(null,so(ao(ce.get("agentTools").agentTools?.value,A?.agent||v?.model)));e&&(ae.run={...e,...ae.run||{}})}if(ct){const e=Ct(null,so(ao(ce.get("agentTools").agentTools?.value,A?.agent||v?.model)));ae.run={...e||{},...ta(ae.run,ie.device)};const r=y?.partnerFolderOf(ie.device);if(!r)return ne?.commit(),a(o,403,{error:{message:"link: this partner has no folder on this computer — pair it again with agents",type:"forbidden",code:"link_scope"}});ae.run.workingDir=r,ae.reach="",Array.isArray(v?.tools)&&(v.tools=v.tools.filter(s=>!po(s?.function?.name??s?.name)))}const Ne=lr({...ae.run||{},...ae.reach?{reach:ae.reach}:{},...Gt?{askDepth:Gt}:{}},zt);Ne.reach&&o.setHeader("x-chatpanel-reach-used",Ne.reach);const Vo=ct?{inbox:g,partner:ie.partner,device:ie.device,conversation:Ne.thread?.id||null}:null,Fo=We&&{...We,dest:{type:"agent",id:A?.id||"bridge"},threadId:Ne.thread?.id||null};return gs(n,o,{...F,pathname:i,agentOverride:A?.agent,harness:jt,trace:ne,run:Object.keys(Ne).length?Ne:null,owner:Vo,link:Fo},v,W,t,Ae)});return ye.on("close",()=>{O?.stop("closed"),In(),m.close(),y?.stop(),g.stop()}),ye.on("upgrade",(n,o,f)=>{o.on("error",()=>{});const i=String(n.url||"").split("?")[0];if(y&&i.startsWith(Zn)){y.acceptTunnel(n,o,f).catch(()=>{try{o.destroy()}catch{}});return}try{o.end(`HTTP/1.1 404 Not Found\r
63
+ `);try{const l=await Or({card:r,message:e.message||{messageId:`cp_${Date.now().toString(36)}`,role:"ROLE_USER",parts:[{text:String(e.text||"")}]},auth:String(e.auth||""),contextId:String(e.contextId||""),taskId:String(e.taskId||""),onEvent:d=>s(d.kind,{kind:d.kind,task:d.task,message:d.message})});s("done",l)}catch(l){s("error",{code:l.code||"ERROR",message:l.message})}return o.end()}if(n.method==="POST"&&i==="/a2a/task"){const e=JSON.parse((await T(n,t.maxBodyBytes)).toString("utf8")||"{}"),r=e.card||(await qe(e.url,{auth:String(e.auth||"")})).card,s=e.cancel?await Pr({card:r,id:String(e.id||""),auth:String(e.auth||"")}):await Er({card:r,id:String(e.id||""),auth:String(e.auth||"")});return a(o,200,{ok:!0,...s})}return a(o,404,{error:{message:`no such a2a route: ${i}`,type:"invalid_request"}})}catch(e){const r=e instanceof Xt||e?.name==="A2AClientError"?e.code:"ERROR";return a(o,e instanceof Xt&&e.code==="UNREACHABLE"?502:400,{error:{message:e.message,type:"a2a_error",code:r}})}}if(n.method==="POST"&&(i==="/agent-defs/export"||i==="/agent-defs/export-plan"))return U(n)?ke(n,o,t,i,{method:"POST",timeoutMs:15e3}):a(o,403,{error:{message:"exporting an agent: extension origin or gateway token required",type:"forbidden"}});if(n.method==="GET"&&/^\/skills\/[^/]+$/.test(i)){const e=decodeURIComponent(i.slice(8));return!e||e==="."||e===".."||e.includes("/")||e.includes("\\")?a(o,400,{error:{message:"not a skill id",type:"invalid_request"}}):ke(n,o,t,`/skills/${encodeURIComponent(e)}${Ce(f,t)}`,{pick:r=>({skill:r?.skill||null})})}if(i==="/channels"||/^\/channels\/(connect|pair|unpair|settings|disconnect)$/.test(i)){if(!U(n))return a(o,403,{error:{message:"channels: extension origin or gateway token required",type:"forbidden"}});if(!(i==="/channels"&&n.method==="GET"||i!=="/channels"&&n.method==="POST"))return a(o,405,{error:{message:"method not allowed",type:"invalid_request"}});const e=await je(t);if(!e)return a(o,503,{error:{message:"no bridge is configured",type:"no_bridge"}});const r=Je(t.bridge?.token);try{const s=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:s||"{}"}:{},signal:AbortSignal.timeout(15e3)}),d=await l.json().catch(()=>({}));return a(o,l.status,d)}catch(s){return a(o,502,{error:{message:`bridge unreachable: ${s.message}`,type:"bridge_unreachable"}})}}if(n.method==="GET"&&/^\/skills\/[^/]+\/file\/.+/.test(i)){const e=/^\/skills\/([^/]+)\/file\/(.+)$/.exec(i),r=decodeURIComponent(e[1]),s=e[2];return!r||r==="."||r===".."||r.includes("/")||r.includes("\\")||/(^|\/)\.\.(\/|$)/.test(decodeURIComponent(s))?a(o,400,{error:{message:"not a skill file",type:"invalid_request"}}):ke(n,o,t,`/skills/${encodeURIComponent(r)}/file/${s}${Ce(f,t)}`)}if(n.method==="GET"&&/\/models$/.test(i)){const e=await L(),r=e.sig!==void 0&&e.sig!==I;return I=e.sig,a(o,200,await Wa(t,{serviceHealth:async()=>e,fresh:r,engineAt:c.engineAt}))}if(vs.some(e=>i===e||i.startsWith(`${e}/`)))return a(o,404,{error:{message:`this gateway (${de}) has no ${i} — update it to use this feature`,type:"unknown_endpoint"}});const F=cs(i,n.headers,t);let K;try{K=await T(n,t.maxBodyBytes)}catch(e){a(o,e.code===413?413:400,{error:e.code===413?"payload too large":"bad request"}),n.destroy();return}let W=null,v=null,se=K,Ue=0,$e=0,It=0,ve=!1,Pe=!1,Rt="",Ae=!0;const ne=t.logRequests&&F.redactable&&n.method==="POST"?ds(q):null,Ho=Date.now();if(F.redactable&&n.method==="POST"&&K.length){try{v=JSON.parse(K.toString("utf8"))}catch{v=null}if(v&&us(v,F.kind))se=K;else if(v){const e=t.tools||{};if(e.autoNarrow!==!1&&Array.isArray(v.tools)&&v.tools.length){const w=Number(e.maxPerTurn)>0?Number(e.maxPerTurn):ts,k=e.narrowAll?null:B=>!os.test(Mo(B)),b=v.tools.length;v.tools=rr(v.tools,ns(v,F.kind),{cap:w,keep:k,name:Mo,description:rs}),It=b-v.tools.length}if(Ae=await Te(t.pro?.entitlementToken),ve=String(n.headers["x-chatpanel-redaction"]||"").trim().toLowerCase()==="off"&&U(n),!ve){const w=st(v?.model,t,F.kind,{destination:String(n.headers["x-chatpanel-destination"]||v?.chatpanel?.destination||"").trim(),down:()=>!1}),k=w?.type==="api"?await c.decide(w,v?.model).catch(()=>null):null;Pe=k?.redact===!1,Rt=Pe?k.engine||"declared":""}if(!ve&&!Pe){const w=Ja(t,Ae);if(!w.allowed)return a(o,402,{error:{message:`ChatPanel Gateway free trial used up (${w.cap} redactions). Add a ChatPanel Pro entitlement token to unlock unlimited full-tier redaction (names/orgs).`,type:"free_limit_reached"}})}!ve&&!Pe&&await tt(t);const r=ve?[]:F.adapter.collectSegments(v,t.redaction,{skipPublic:U(n)}),s=new AbortController;o.on("close",()=>{o.writableFinished||s.abort()});const l=ne?ne.clock():0,{vault:d,count:m,sanitized:h}=ve?{vault:null,count:0,sanitized:0}:await Ye(r,t.redaction,{signal:s.signal,isPro:Ae,sanitizeOnly:Pe,onEgress:w=>Pt.push($o({ts:Date.now(),client:"redaction",tool:`detect:${w.backend}@${w.host||"local"}`,ok:w.ok,ms:w.ms,error:w.error}))});if(ne&&ne.lap("redact",l),F.adapter.joinTextParts?.(v),W=d,Ue=m,$e=h||0,m>0&&o.setHeader("x-chatpanel-redacted",String(m)),!Ae&&m>0){La(t,Ae);try{be(t,le())}catch{}}if(!ve&&!Pe&&Array.isArray(v.tools)&&v.tools.length&&typeof F.adapter.injectSystemNote=="function"){const w=st(v?.model,t,F.kind,{destination:String(n.headers["x-chatpanel-destination"]||v?.chatpanel?.destination||"").trim(),down:b=>!!b.service&&x.fn(b.id)==="down"}),k=!(w&&w.type==="api");F.adapter.injectSystemNote(v,ar({toolData:t.tools?.toolData,ownTools:k}))}else!ve&&m>0&&typeof F.adapter.injectSystemNote=="function"&&F.adapter.injectSystemNote(v,sr());se=Buffer.from(JSON.stringify(v),"utf8")}}const jt=nr({vault:W,toolData:t.tools?.toolData}),Ve=v&&typeof v.chatpanel=="object"&&v.chatpanel||null;if(Ve&&(delete v.chatpanel,se=Buffer.from(JSON.stringify(v),"utf8")),typeof v?.model=="string"&&v.model.startsWith("fusion:")){const e=On(v.model,t,await L());if(e?.error)return ne?.commit(),a(o,400,{error:{message:e.error,type:"fusion"}});e&&(v.model=e.model,se=Buffer.from(JSON.stringify(v),"utf8"),o.setHeader("x-chatpanel-fusion",`${e.fusion.id} -> ${e.model}`))}const ae={destination:String(n.headers["x-chatpanel-destination"]||Ve?.destination||"").trim(),reach:String(n.headers["x-chatpanel-reach"]||Ve?.reach||"").trim(),run:Ct(n.headers["x-chatpanel-run"],Ve?.run)},Fe=await L(),Jt=e=>!!e.service&&Fe(e.id)==="down";let A=st(v?.model,t,F.kind,{destination:ae.destination,down:Jt});A?.type==="agent"&&v?.model&&!ae.destination&&!Ya(A,v.model)&&(await Qa(t,{serviceHealth:async()=>Fe,engineAt:c.engineAt}),A=st(v?.model,t,F.kind,{destination:ae.destination,down:Jt}));const Lt=A?.service&&Fe(A.id)==="down"?await E().revive(A.service).catch(()=>null):null;if(Lt?.ok&&(x.at=0),A?.service&&Fe(A.id)==="down"&&!Lt?.ok)return ne?.commit(),a(o,503,{error:{message:`${A.id} is not running — the model ${JSON.stringify(v?.model||"")} is served by an engine the Runtime has stopped; start it under Settings › Runtime`,type:"engine_down",service:A.service}});if(ae.destination&&(!A||A.id!==ae.destination))return ne?.commit(),a(o,404,{error:{message:`no destination "${ae.destination}" is configured on this gateway`,type:"unknown_destination",known:Ka(t).map(e=>e.id)}});const ie=vt(n.headers);if(ie&&!qn(ie,A?.type==="api"?"api":"agent"))return ne?.commit(),a(o,403,{error:{message:`link: partner "${ie.partner}" may not use ${A?.type==="api"?"this model":"this computer’s coding agents"} — its scopes are ${ie.scopes.join(", ")||"none"}; the owner grants agents at pairing`,type:"forbidden",code:"link_scope"}});const We=ie&&F.redactable&&n.method==="POST"&&v?{caller:ie,surface:wn(ie,ie.kind==="partner"?"":y?.deviceNameOf(ie.device)),model:v.model||null,startedAt:Ho}:null;ne&&(ne.meta={t:Date.now(),model:v?.model||null,dest:A?A.id:null,type:A?A.type:null,redacted:Ue,sanitized:$e,narrowed:It,detail:Ro(W,t.logDetail),redaction:ve?"off":Pe?`on-device (${Rt})`:t.redaction.tier||"basic",...ie?.kind==="partner"?{via:ea(ie)}:{}});const Ke=Xe();if(Ke&&A){const e=A.type==="api"?Yt(Ke,{model:v?.model||"",endpoint:A.baseUrl||""}):Sr(Ke,A.agent||A.id)?Yt(Ke,{model:v?.model||""}):{ok:!1,reason:`agent "${A.agent||A.id}" is not allowed by your organisation’s policy`};if(!e.ok)return ne?.commit(),a(o,403,{error:{message:e.reason,type:"policy",code:"org_policy"}})}if(A&&A.type==="api")return A.baseUrl?ms(A.baseUrl,t)?(ne?.commit(),a(o,508,{error:{message:`destination "${A.id}" points back at the gateway (${A.baseUrl}) — refusing to forward (would loop).`,type:"loop_detected"}})):Ss(n,o,{...F,pathname:i,search:f.search,base:A.baseUrl,destKey:A.apiKey,destProtocol:A.protocol,harness:jt,trace:ne,link:We&&{...We,agentId:A.id,dest:{type:"api",id:A.id}}},se,W):(ne?.commit(),a(o,502,{error:`destination "${A.id}" has no baseUrl`}));const dt=Ie(n),zt=dt==="local"&&t.bridge?.openAgentLane?"token":dt;if(zt==="local")return ne?.commit(),a(o,401,{error:{message:"agent destinations require the gateway token: send `Authorization: Bearer $(cat ~/.chatpanel/gateway-token)`, or pair this client with `chatpanel-gateway pair`",type:"auth",code:"agent_lane_token_required"}});const Gt=Math.max(0,Math.min(8,Number(n.headers["x-chatpanel-ask-depth"])||0)),Uo=new Set(["thread","ephemeral","workingDir","worker"]),ct=ie?.kind==="partner";if(dt==="token"&&n.headers["x-chatpanel-link-device"]&&!ct&&!(ae.run&&Object.keys(ae.run).some(e=>!Uo.has(e)))){const e=Ct(null,so(ao(ce.get("agentTools").agentTools?.value,A?.agent||v?.model)));e&&(ae.run={...e,...ae.run||{}})}if(ct){const e=Ct(null,so(ao(ce.get("agentTools").agentTools?.value,A?.agent||v?.model)));ae.run={...e||{},...ta(ae.run,ie.device)};const r=y?.partnerFolderOf(ie.device);if(!r)return ne?.commit(),a(o,403,{error:{message:"link: this partner has no folder on this computer — pair it again with agents",type:"forbidden",code:"link_scope"}});ae.run.workingDir=r,ae.reach="",Array.isArray(v?.tools)&&(v.tools=v.tools.filter(s=>!po(s?.function?.name??s?.name)))}const Ne=lr({...ae.run||{},...ae.reach?{reach:ae.reach}:{},...Gt?{askDepth:Gt}:{}},zt);Ne.reach&&o.setHeader("x-chatpanel-reach-used",Ne.reach);const Vo=ct?{inbox:g,partner:ie.partner,device:ie.device,conversation:Ne.thread?.id||null}:null,Fo=We&&{...We,dest:{type:"agent",id:A?.id||"bridge"},threadId:Ne.thread?.id||null};return gs(n,o,{...F,pathname:i,agentOverride:A?.agent,harness:jt,trace:ne,run:Object.keys(Ne).length?Ne:null,owner:Vo,link:Fo},v,W,t,Ae)});return ue.on("close",()=>{O?.stop("closed"),In(),p.close(),y?.stop(),g.stop()}),ue.on("upgrade",(n,o,f)=>{o.on("error",()=>{});const i=String(n.url||"").split("?")[0];if(y&&i.startsWith(Zn)){y.acceptTunnel(n,o,f).catch(()=>{try{o.destroy()}catch{}});return}try{o.end(`HTTP/1.1 404 Not Found\r
61
64
  connection: close\r
62
65
  content-length: 0\r
63
66
  \r
64
- `)}catch{}}),ye.once("listening",()=>{E()}),ye.linkHost=y,ye.runtimeDefaults=()=>E().ensureDefaults(),ye}function Ct(t,c){let u=c&&typeof c=="object"?c:null;if(!u&&t)try{u=JSON.parse(decodeURIComponent(String(t)))}catch{u=null}if(!u||typeof u!="object")return null;const m={};if(Array.isArray(u.grants)&&(m.grants=u.grants.map(y=>String(y).slice(0,80)).slice(0,32)),u.workspace&&typeof u.workspace=="object"&&u.workspace.repo){const y=u.workspace;m.workspace={repo:String(y.repo).slice(0,400),projectId:String(y.projectId||"").slice(0,120),jobId:String(y.jobId||"").slice(0,120),...y.base?{base:String(y.base).slice(0,120)}:{}}}if(u.connectionId&&(m.connectionId=String(u.connectionId).slice(0,64)),typeof u.workingDir=="string"&&u.workingDir.trim()&&/^([A-Za-z]:[\\/]|\/)/.test(u.workingDir.trim())&&(m.workingDir=u.workingDir.trim().slice(0,1024)),Ua.includes(u.permissionMode)&&u.permissionMode!=="default"&&(m.permissionMode=u.permissionMode),u.sandbox&&typeof u.sandbox=="object"){const y=(Array.isArray(u.sandbox.hosts)?u.sandbox.hosts:String(u.sandbox.hosts||"").split(/[\s,;]+/)).map(S=>String(S).trim().toLowerCase().slice(0,253)).filter(Boolean).slice(0,64),P=(Array.isArray(u.sandbox.write)?u.sandbox.write:[]).map(S=>String(S).slice(0,1024)).filter(Boolean).slice(0,32),N=u.sandbox.outside===!0,O=(Array.isArray(u.sandbox.signIn)?u.sandbox.signIn:[]).map(S=>String(S).trim().toLowerCase().slice(0,32)).filter(Boolean).slice(0,8);(y.length||P.length||N||O.length)&&(m.sandbox={...y.length?{hosts:y}:{},...P.length?{write:P}:{},...N?{outside:!0}:{},...O.length?{signIn:O}:{}})}const g=Hr(u.thread);return g&&(m.thread=g),u.ephemeral===!0&&(m.ephemeral=!0),u.worker===!0&&(m.worker=!0,m.ephemeral=!0),Object.keys(m).length?m:null}let He=null,lt=null;async function pl(t=Ut()){jr();let c=null;try{c=await kr()}catch(S){throw S instanceof vr&&(console.error(`[chatpanel-gateway] org policy: ${S.message}`),process.exit(78)),S}const u=c?.policy||null;u&&(Yt(t,u),console.log(`[chatpanel-gateway] ${c.label} — ${c.signed?"signed":"unsigned"} policy from ${c.source}`));const m=wr({enabled:Kt(t)});console.log(`[chatpanel-gateway] certificates: ${m.on?`this computer's list is trusted too (${m.added} added to the runtime's own)`:`the runtime's own list only — ${m.why}`}`),fr(globalThis,{allow:u?.egress?(S,{local:x})=>Tr(u,S,{local:x}):null}),_e();const g=Ts(t),y=Cr(t),P=Qo(t);let N=!1;g.on("error",S=>{if(S&&S.code==="EADDRINUSE"){const x=it(t.host)?"127.0.0.1":t.host;fetch(`http://${x}:${t.port}/health`,{signal:AbortSignal.timeout(1500)}).then(C=>C.ok?C.json():null).catch(()=>null).then(C=>{const J=!!(C?.version&&typeof C.tier=="string"),V=Ur({name:"gateway",self:de,holder:J?{ours:J,version:C.version}:null,managedBy:Vr(process.env),port:t.port});if(V.action==="standby"||N&&!C){if(!N)for(const E of V.lines)console.error(E);N=!0,setTimeout(()=>g.listen(t.port,t.host),Fr);return}if(J){const E=C.managedBy?` (run by ${C.managedBy})`:"";for(const[H,L]of V.lines.entries())console.error(H===0?L.replace(` on ${t.port}`,` at http://${x}:${t.port}${E}`):L)}else{const E=sn(t.port);console.error(`Port ${t.port} is held by ${E||"another program"}, which is not a ChatPanel gateway.`),console.error(`Fix: stop that program, or set a different port — edit "port" in ${le()} (or the extension's Gateway tab) and restart. The extension must point at the same port.`)}process.exit(1)});return}console.error(`Gateway server error: ${S?.message||S}`),process.exit(1)}),g.listen(t.port,t.host,()=>{N&&console.log(" standby : the other gateway is gone — this copy has the port now"),N=!1,console.log(`ChatPanel Privacy Gateway v${de} on http://${t.host}:${t.port}`),g.linkHost?.start().catch(S=>console.log(` link : not started (${S?.message||S})`)),g.runtimeDefaults?.().then(S=>{for(const x of S||[])console.log(` ${x.label.toLowerCase().padEnd(9).slice(0,9)}: ${x.ok?x.already?"running":x.adopted?"already running — adopted":"started":`not started (${x.skipped})`}`)}).catch(S=>console.log(` runtime : defaults not started (${S?.message||S})`)),console.log(` backend : ${t.backend}`+(t.backend==="bridge"?` (agent: ${t.bridge.agent}, via ${t.bridge.url})`:"")),t.bridge?.openAgentLane&&console.log(" ⚠ agents : bridge.openAgentLane is ON — any local process may drive a CLI agent through this gateway without a token");for(const S of Fa(t))console.log(` ⚠ sandbox : ${S}`);console.log(` confined : ${pn(yt({stateDir:ze.dirname(le())}))}`),lt={mode:"starting",version:null,pid:null,restarts:0,why:"deciding: adopt the bridge that answers, or start ours"},an(t,{childEnv:()=>({...Va(t,process.env,Xe()),...Ha(t)})}).then(S=>{He=S}).catch(S=>{lt={mode:"off",version:null,pid:null,restarts:0,why:`not supervised (${S?.message||S})`},console.log(` bridge : not supervised (${S?.message||S})`)}),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…)":"")),it(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.`)}),no()&&wt(R,pt()).then(S=>{S?.ok&&(console.log(` warm : seeded ${S.ingested} records from ${S.file}`),S.whole&&Ge())}).catch(()=>{});const O=()=>{y?.stop(),P.stop(),He?.stop(),es(g)};return process.on("SIGINT",O),process.on("SIGTERM",O),g}export{ps as RECORDS_MAX_BYTES,fl as VERSION,Ts as createGateway,ws as joinUpstream,$t as parseAgentModel,pl as start};
67
+ `)}catch{}}),ue.once("listening",()=>{E()}),ue.linkHost=y,ue.runtimeDefaults=()=>E().ensureDefaults(),ue}function Ct(t,c){let u=c&&typeof c=="object"?c:null;if(!u&&t)try{u=JSON.parse(decodeURIComponent(String(t)))}catch{u=null}if(!u||typeof u!="object")return null;const p={};if(Array.isArray(u.grants)&&(p.grants=u.grants.map(y=>String(y).slice(0,80)).slice(0,32)),u.workspace&&typeof u.workspace=="object"&&u.workspace.repo){const y=u.workspace;p.workspace={repo:String(y.repo).slice(0,400),projectId:String(y.projectId||"").slice(0,120),jobId:String(y.jobId||"").slice(0,120),...y.base?{base:String(y.base).slice(0,120)}:{}}}if(u.connectionId&&(p.connectionId=String(u.connectionId).slice(0,64)),typeof u.workingDir=="string"&&u.workingDir.trim()&&/^([A-Za-z]:[\\/]|\/)/.test(u.workingDir.trim())&&(p.workingDir=u.workingDir.trim().slice(0,1024)),Ua.includes(u.permissionMode)&&u.permissionMode!=="default"&&(p.permissionMode=u.permissionMode),u.sandbox&&typeof u.sandbox=="object"){const y=(Array.isArray(u.sandbox.hosts)?u.sandbox.hosts:String(u.sandbox.hosts||"").split(/[\s,;]+/)).map(S=>String(S).trim().toLowerCase().slice(0,253)).filter(Boolean).slice(0,64),P=(Array.isArray(u.sandbox.write)?u.sandbox.write:[]).map(S=>String(S).slice(0,1024)).filter(Boolean).slice(0,32),N=u.sandbox.outside===!0,O=(Array.isArray(u.sandbox.signIn)?u.sandbox.signIn:[]).map(S=>String(S).trim().toLowerCase().slice(0,32)).filter(Boolean).slice(0,8);(y.length||P.length||N||O.length)&&(p.sandbox={...y.length?{hosts:y}:{},...P.length?{write:P}:{},...N?{outside:!0}:{},...O.length?{signIn:O}:{}})}const g=Hr(u.thread);return g&&(p.thread=g),u.ephemeral===!0&&(p.ephemeral=!0),u.worker===!0&&(p.worker=!0,p.ephemeral=!0),Object.keys(p).length?p:null}let He=null,lt=null;async function pl(t=Ut()){jr();let c=null;try{c=await kr()}catch(S){throw S instanceof vr&&(console.error(`[chatpanel-gateway] org policy: ${S.message}`),process.exit(78)),S}const u=c?.policy||null;u&&(Qt(t,u),console.log(`[chatpanel-gateway] ${c.label} — ${c.signed?"signed":"unsigned"} policy from ${c.source}`));const p=wr({enabled:Kt(t)});console.log(`[chatpanel-gateway] certificates: ${p.on?`this computer's list is trusted too (${p.added} added to the runtime's own)`:`the runtime's own list only — ${p.why}`}`),fr(globalThis,{allow:u?.egress?(S,{local:x})=>Tr(u,S,{local:x}):null}),_e();const g=Ts(t),y=Cr(t),P=Yo(t);let N=!1;g.on("error",S=>{if(S&&S.code==="EADDRINUSE"){const x=it(t.host)?"127.0.0.1":t.host;fetch(`http://${x}:${t.port}/health`,{signal:AbortSignal.timeout(1500)}).then(I=>I.ok?I.json():null).catch(()=>null).then(I=>{const L=!!(I?.version&&typeof I.tier=="string"),V=Ur({name:"gateway",self:de,holder:L?{ours:L,version:I.version}:null,managedBy:Vr(process.env),port:t.port});if(V.action==="standby"||N&&!I){if(!N)for(const E of V.lines)console.error(E);N=!0,setTimeout(()=>g.listen(t.port,t.host),Fr);return}if(L){const E=I.managedBy?` (run by ${I.managedBy})`:"";for(const[H,z]of V.lines.entries())console.error(H===0?z.replace(` on ${t.port}`,` at http://${x}:${t.port}${E}`):z)}else{const E=sn(t.port);console.error(`Port ${t.port} is held by ${E||"another program"}, which is not a ChatPanel gateway.`),console.error(`Fix: stop that program, or set a different port — edit "port" in ${le()} (or the extension's Gateway tab) and restart. The extension must point at the same port.`)}process.exit(1)});return}console.error(`Gateway server error: ${S?.message||S}`),process.exit(1)}),g.listen(t.port,t.host,()=>{N&&console.log(" standby : the other gateway is gone — this copy has the port now"),N=!1,console.log(`ChatPanel Privacy Gateway v${de} on http://${t.host}:${t.port}`),g.linkHost?.start().catch(S=>console.log(` link : not started (${S?.message||S})`)),g.runtimeDefaults?.().then(S=>{for(const x of S||[])console.log(` ${x.label.toLowerCase().padEnd(9).slice(0,9)}: ${x.ok?x.already?"running":x.adopted?"already running — adopted":"started":`not started (${x.skipped})`}`)}).catch(S=>console.log(` runtime : defaults not started (${S?.message||S})`)),console.log(` backend : ${t.backend}`+(t.backend==="bridge"?` (agent: ${t.bridge.agent}, via ${t.bridge.url})`:"")),t.bridge?.openAgentLane&&console.log(" ⚠ agents : bridge.openAgentLane is ON — any local process may drive a CLI agent through this gateway without a token");for(const S of Fa(t))console.log(` ⚠ sandbox : ${S}`);console.log(` confined : ${pn(yt({stateDir:ze.dirname(le())}))}`),lt={mode:"starting",version:null,pid:null,restarts:0,why:"deciding: adopt the bridge that answers, or start ours"},an(t,{childEnv:()=>({...Va(t,process.env,Xe()),...Ha(t)})}).then(S=>{He=S}).catch(S=>{lt={mode:"off",version:null,pid:null,restarts:0,why:`not supervised (${S?.message||S})`},console.log(` bridge : not supervised (${S?.message||S})`)}),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…)":"")),it(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.`)}),no()&&wt(j,pt()).then(S=>{S?.ok&&(console.log(` warm : seeded ${S.ingested} records from ${S.file}`),S.whole&&Ge())}).catch(()=>{});const O=()=>{y?.stop(),P.stop(),He?.stop(),es(g)};return process.on("SIGINT",O),process.on("SIGTERM",O),g}export{ps as RECORDS_MAX_BYTES,fl as VERSION,Ts as createGateway,ws as joinUpstream,$t as parseAgentModel,pl as start};
package/src/stt-engine.js CHANGED
@@ -1 +1 @@
1
- import{join as Ee}from"node:path";import{existsSync as Te,readdirSync as ke}from"node:fs";import{randomUUID as xe}from"node:crypto";import{ensureLib as oe,modelRoot as ie}from"./ner-engine.js";import{runtimeDtype as B,runtimeName as le,DTYPE_SUFFIX as Se}from"./model-runtime.js";import{verifyModelWeights as be}from"./model-integrity.js";import{DEFAULT_STT_MODEL as ae,isEnglishOnly as se,sttModelDtype as q,isKnownSttModel as De,sttModelEngine as P}from"./stt-models.js";import*as D from"./parakeet-engine.js";import*as Q from"./coreml-stt-engine.js";import*as b from"./diarize-engine.js";import*as L from"./segment-engine.js";import{turnsFromSpans as Le,mainLocal as Ae,timeByLocal as ve,audioOfLocal as $e}from"@chatpanel/events/speaker-turns.js";import{diarizeApproxMB as Fe}from"./diarize-models.js";import{makeWarmTimer as V}from"./warm-timer.js";const h=16e3,ce=h,ue=3*h,Pe=2,Ne=new Set(["thank you","thanks","thank you for watching","thanks for watching","you","uh","um","hmm","hm","mm","amen","bye","okay","ok","yeah","oh","the","that","so","and","i","a","me","we","yes","no","thank you very much","subtitles by the amara.org community","you you"]);function Re(e,t){if(t>Pe*h)return!1;const n=String(e||"").toLowerCase().replace(/[^\p{L}\p{N}\s]/gu,"").replace(/\s+/g," ").trim();return n?Ne.has(n)||/^(you ?){2,}$/.test(n)||/^(thank you\.? ?){2,}$/.test(n):!0}let s="off",w=null,g=null,M=null,A=null,y=null,v=null,E=null;function Oe(e=w||ae,t=q(e)||B()){if(P(e)==="parakeet-tdt")return D.parakeetOnDisk(e,D.parakeetDtype(t));if(P(e)==="coreml-tdt")return Q.coremlOnDisk(e);const n=Ee(ie(),...e.split("/"),"onnx");if(!Te(n))return!1;const r=Se[t]??"";try{const o=ke(n);return o.includes(`encoder_model${r}.onnx`)&&o.some(i=>i===`decoder_model_merged${r}.onnx`||i===`decoder_model${r}.onnx`)}catch{return!1}}function mt(){return s}function K(){return s==="ready"&&!!g}function pt(){return y}function ht(){return{configured:s!=="off",ok:K(),state:s,model:w,dtype:v,runtime:le(),error:M,warmMs:E?.warmMs??null}}function gt(){return!!E?.pending()}function O(){return k.size>0||s==="loading"||s==="downloading"}async function J({log:e=()=>{}}={}){if(O())return!1;E?.disarm();const t=g;if(g=null,A=null,v=null,y=null,M=null,s="off",t)try{await t.dispose?.()}catch{}return t&&e(`[stt] idle for ${Math.round((E?.warmMs||0)/6e4)} min — model unloaded (reloads on next dictation)`),!0}function fe(e){return e.then(t=>(t&&!O()&&E?.arm(),t))}async function de(e,{log:t=()=>{},allowDownload:n=!0,dtype:r=null}={}){if(P(e)==="parakeet-tdt")return ze(e,{log:t,allowDownload:n,dtype:r});if(P(e)==="coreml-tdt")return He(e,{log:t,allowDownload:n});const o=g,i=w;let l;try{l=await oe()}catch(_){return s="error",M=`engine load failed: ${_.message}`,t(`[stt] transformers.js not available (${_.message}) — dictation falls back to the browser engine`),!1}const a=(r&&r!=="auto"?r:null)||q(e)||B(),f=Oe(e,a);if(l.env.allowRemoteModels=f?!1:!!n,!f&&!n)return s="error",M="model not on disk and downloads disabled",t(`[stt] model ${e} not installed and downloads disabled`),!1;const p=l.env.remoteHost,d=!De(e);if(!f&&d)try{l.env.remoteHost="https://huggingface.co/"}catch{}s=f?"loading":"downloading",f||(y={model:e,file:null,pct:0},t(`[stt] downloading model ${e} (one-time${d?", from Hugging Face":""})…`));try{const _=m=>{if(!m)return;const j=typeof m.progress=="number"?Math.round(m.progress):y?.pct??0;m.status==="progress"||m.status==="download"||m.status==="initiate"?y={model:e,file:m.file||y?.file||null,pct:j}:m.status==="done"&&m.file&&t(`[stt] fetched ${m.file}`)};let c;try{c=await l.pipeline("automatic-speech-recognition",e,{dtype:a,progress_callback:_})}catch(m){if(f||d||!n)throw m;t(`[stt] mirror fetch failed (${String(m.message).slice(0,80)}) — retrying from Hugging Face…`),l.env.remoteHost="https://huggingface.co/",l.env.allowRemoteModels=!0,c=await l.pipeline("automatic-speech-recognition",e,{dtype:a,progress_callback:_})}if(!f)try{be(e,{modelsDir:ie(),log:t})}catch(m){try{await c.dispose?.()}catch{}throw m}if(g=c,w=e,s="ready",M=null,y=null,v=a,o&&o!==c)try{await o.dispose?.()}catch{}return t(`[stt] ready — model ${e} @ ${a} (in-process, offline) — local dictation active`),!0}catch(_){return M=_.message,y=null,o?(g=o,w=i,s="ready"):s="error",t(`[stt] model load failed (${_.message})${o?" — keeping previous model":""}`),!1}finally{try{l.env.remoteHost=p}catch{}}}async function ze(e,{log:t=()=>{},allowDownload:n=!0,dtype:r=null}={}){const o=g,i=w,l=D.parakeetDtype(r&&r!=="auto"?r:Ce()),u=D.parakeetOnDisk(e,l);if(!u&&!n)return s="error",M="model not on disk and downloads disabled",t(`[stt] model ${e} not installed and downloads disabled`),!1;s=u?"loading":"downloading",u||(y={model:e,file:null,pct:0},t(`[stt] downloading model ${e} (one-time, from Hugging Face)…`));try{const a=await D.loadRecognizer({modelId:e,dtype:l,allowDownload:n,log:t,onProgress:p=>{y={model:e,file:p.file||null,pct:typeof p.pct=="number"?p.pct:y?.pct??0}}}),f=async p=>({text:await a.transcribe(p)});if(f.__transducer=!0,f.dispose=()=>a.dispose(),g=f,w=e,s="ready",M=null,y=null,v=l,o&&o!==f)try{await o.dispose?.()}catch{}return t(`[stt] ready — model ${e} @ ${l} (parakeet-tdt, in-process, offline) — local dictation active`),!0}catch(a){return M=a.message,y=null,o?(g=o,w=i,s="ready"):s="error",t(`[stt] model load failed (${a.message})${o?" — keeping previous model":""}`),!1}}function Ce(){return D.PARAKEET_DEFAULT_DTYPE}const me="fp16";async function He(e,{log:t=()=>{},allowDownload:n=!0}={}){const r=g,o=w,i=Q.coremlOnDisk(e);if(!i&&!n)return s="error",M="model not on disk and downloads disabled",t(`[stt] model ${e} not installed and downloads disabled`),!1;s=i?"loading":"downloading",i||(y={model:e,file:null,pct:0},t(`[stt] downloading model ${e} (one-time, from Hugging Face)…`));try{let l=null;const u=await Q.loadRecognizer({modelId:e,allowDownload:n,log:t,onProgress:a=>{y={model:e,file:a.file||null,pct:typeof a.pct=="number"?a.pct:y?.pct??0}},onExit:a=>{g===l&&(g=null,A=null,s="error",M=a,E?.disarm(),t(`[stt] ${a} — reloads on the next dictation`))}});if(l=async a=>({text:await u.transcribe(a)}),l.__transducer=!0,l.dispose=()=>u.dispose(),g=l,w=e,s="ready",M=null,y=null,v=me,r&&r!==l)try{await r.dispose?.()}catch{}return t(`[stt] ready — model ${e} (Core ML on the Neural Engine, helper ${u.version}, windows ${u.windows.join("/")} s, offline) — local dictation active`),!0}catch(l){return M=l.message,y=null,r?(g=r,w=o,s="ready"):s="error",t(`[stt] model load failed (${l.message})${r?" — keeping previous model":""}`),!1}}const Ue=30;function pe({mode:e="ondisk",onDisk:t=!1,ready:n=!1,approxMB:r=null}={}){return n||e==="off"?null:t?{allowDownload:!1}:typeof r=="number"&&r<=Ue||e==="download"?{allowDownload:!0}:null}function Z(e,{log:t=()=>{},warmMs:n,allowDownload:r=!0}={}){const o=pe({mode:e,onDisk:b.modelOnDisk(),ready:b.isReady(),approxMB:Fe(b.activeModel())});if(o&&b.init({allowDownload:o.allowDownload&&r!==!1,warmMs:n,onLog:t}),e==="off"||I)return;const i=pe({mode:e,onDisk:L.modelOnDisk(),ready:L.isReady(),approxMB:L.SEGMENT_MODEL_APPROX_MB});i&&L.init({allowDownload:i.allowDownload&&r!==!1,warmMs:n,onLog:t})}let I=!1;function yt(e={}){if(A)return A;const t=typeof e.onLog=="function"?e.onLog:()=>{};return w=e.model||ae,I=e.segment===!1,s="loading",E=V({warmMs:e.warmMs,busy:O,log:t,unload:()=>J({log:t})}),A=fe(de(w,{log:t,allowDownload:e.allowDownload!==!1,dtype:e.dtype})).then(n=>(n&&Z(e.speaker,{log:t,warmMs:e.warmMs,allowDownload:e.allowDownload!==!1}),n)),A}async function wt(e,t={}){const n=typeof t.onLog=="function"?t.onLog:()=>{};if(!e)return!1;t.segment!==void 0&&(I=t.segment===!1);const r=P(e)==="parakeet-tdt"?D.parakeetDtype(t.dtype&&t.dtype!=="auto"?t.dtype:D.PARAKEET_DEFAULT_DTYPE):P(e)==="coreml-tdt"?me:t.dtype&&t.dtype!=="auto"?t.dtype:q(e)||B();if(e===w&&K()&&v===r)return Z(t.speaker,{log:n,warmMs:t.warmMs,allowDownload:t.allowDownload!==!1}),!0;E??=V({warmMs:t.warmMs,busy:O,log:n,unload:()=>J({log:n})});const o=await fe(de(e,{log:n,allowDownload:t.allowDownload!==!1,dtype:t.dtype}));return o&&Z(t.speaker,{log:n,warmMs:t.warmMs,allowDownload:t.allowDownload!==!1}),o}const Be=8,Ke=12e4,Xe=6e4,je=1200,ee=12,te=700,ne=.008,Ye=.002,Ge=4;function We(e){return e>0?Math.min(ne,Math.max(Ye,e*Ge)):ne}function qe(e){const t=Math.round(.1*h),n=Math.floor(e.length/t);if(n<5)return null;const r=new Float32Array(n);for(let o=0;o<n;o++)r[o]=C(e,o*t,(o+1)*t);return r.sort(),r[Math.floor(n*.1)]}const he=30,k=new Map,$=new Map;let F=Promise.resolve();function _t(){return k.size}const Qe=300,Ve=3e3;function Je(e){const t=Number(e);return Number.isFinite(t)?Math.min(Ve,Math.max(Qe,Math.round(t))):te}function Mt({lang:e,redact:t=!1,diarize:n=!1,speakerLabel:r=null,endSilenceMs:o=te,interims:i=!0,remote:l=null,poll:u=!1}={}){if(k.size>=Be){const f=new Error("too many concurrent dictation sessions");throw f.code="too_many_sessions",f}const a={id:xe(),endSilenceMs:Je(o),lang:typeof e=="string"&&e?e.slice(0,12):null,langTried:!1,pushed:0,noiseFloor:null,redact:!!t,diarize:!!n,speakerLabel:typeof r=="string"&&r?r.slice(0,40):null,diarizer:n?new b.Diarizer:null,remote:l||null,interims:i!==!1&&!l,chunks:[],samples:0,listeners:new Set,poll:u?[]:null,lastDecodeAt:0,decodeTimer:null,lastInterim:"",closed:!1,idleTimer:null};return k.set(a.id,a),E?.disarm(),a.diarizer&&(b.retain(),L.retain()),ge(a),{id:a.id}}function X(e){return k.get(String(e||""))||null}function Et(e,t){const n=X(e);return n?(n.listeners.add(t),()=>n.listeners.delete(t)):null}function z(e,t){e.poll&&e.poll.push(t);for(const n of e.listeners)try{n(t)}catch{}}function Tt(e){const t=String(e||""),n=k.get(t);if(n)return n.poll?n.poll.splice(0):null;const r=$.get(t);return r?(clearTimeout(r.timer),$.delete(t),r.session.poll.splice(0)):null}function kt(e){return $.get(String(e||""))?.session||null}function ge(e){e.idleTimer&&clearTimeout(e.idleTimer),e.idleTimer=setTimeout(()=>nt(e.id).catch(()=>{}),Xe),e.idleTimer.unref?.()}function xt(e,t){const n=X(e);if(!n||n.closed){const r=new Error("no such session");throw r.code="no_session",r}!(t instanceof Float32Array)||!t.length||(n.chunks.push(t),n.samples+=t.length,n.pushed+=t.length,ge(n),Ze(n))}function St(e){const t=X(e);return!t||t.closed?Promise.resolve():(t.decodeTimer&&(clearTimeout(t.decodeTimer),t.decodeTimer=null),F=F.then(()=>re(t).catch(()=>{})),F)}function bt(e){const t=e.length-e.length%4,n=new Float32Array(t/4);for(let r=0;r<n.length;r++)n[r]=e.readFloatLE(r*4);return n}function Ze(e){if(e.closed||e.decodeTimer)return;const t=Math.max(0,e.lastDecodeAt+je-Date.now());e.decodeTimer=setTimeout(()=>{e.decodeTimer=null,F=F.then(()=>re(e).catch(()=>{}))},t),e.decodeTimer.unref?.()}function ye(e){const t=new Float32Array(e.samples);let n=0;for(const r of e.chunks)t.set(r,n),n+=r.length;return t}function Ie(e,t,n){const r=h/100,o=Math.max(0,e.length-t),i=Math.floor((e.length-o)/r),l=Math.max(1,Math.round(n/r));if(i<=l)return 0;const u=new Float32Array(i);for(let d=0;d<i;d++){let _=0;const c=o+d*r;for(let m=0;m<r;m++)_+=e[c+m]*e[c+m];u[d]=_/r}let a=-1,f=1/0,p=0;for(let d=0;d<l;d++)p+=u[d];for(let d=0;d+l<=i;d++)d>0&&(p+=u[d+l-1]-u[d-1]),p<f&&(f=p,a=d);return a<0?0:o+Math.round((a+l/2)*r)}function C(e,t=0,n=e.length){let r=0;const o=Math.max(1,n-t);for(let i=t;i<n;i++)r+=e[i]*e[i];return Math.sqrt(r/o)}function et(e,t=ne){const n=Math.round(.02*h);let r=0,o=e.length;for(let i=0;i+n<=e.length;i+=n)if(C(e,i,i+n)>=t){r=i;break}for(let i=e.length-n;i>=0;i-=n)if(C(e,i,i+n)>=t){o=i+n;break}return o>r?e.subarray(r,o):e}async function tt(e){try{const t=await oe(),n=g?.model?.generation_config;if(!n?.lang_to_id||!n.decoder_start_token_id||!t.Tensor)return null;const r=e.length>h*8?e.subarray(0,h*8):e,o=await g.processor(r),i=new t.Tensor("int64",new BigInt64Array([BigInt(n.decoder_start_token_id)]),[1,1]),l=await g.model({...o,decoder_input_ids:i});let u=null,a=-1/0;for(const[f,p]of Object.entries(n.lang_to_id)){const d=Number(l.logits.data[p]);d>a&&(a=d,u=f)}return u?u.slice(2,-2):null}catch{return null}}async function re(e,{flush:t=!1}={}){if(e.closed&&!t||!e.remote&&!K()||!e.samples)return;e.lastDecodeAt=Date.now();let n=ye(e);const r=n.length,o=Math.max(0,(e.pushed||0)-e.samples),i=Math.round((e.endSilenceMs||te)/1e3*h),l=qe(n);l!==null&&(e.noiseFloor==null||l<e.noiseFloor)&&(e.noiseFloor=l);const u=We(e.noiseFloor),a=n.length>i&&C(n,n.length-i)<u;if(C(n)<u){n.length>h*5&&(e.chunks=[n.subarray(n.length-h)],e.samples=h);return}if(!e.interims&&!t&&!a&&n.length<ee*h)return;let f=null;if(!t&&!a&&r>=ee*h&&r<he*h){const c=Ie(n,3*h,Math.round(.2*h));c>0&&c<n.length&&(f=n.subarray(c),n=n.subarray(0,c))}if(!e.remote&&!e.lang&&!e.langTried&&!se(w)&&!g?.__transducer&&n.length>=h){e.langTried=!0;const c=await tt(n);c&&(e.lang=c,z(e,{type:"language",lang:c}))}let p="";try{if(e.remote)p=(await e.remote.transcribe(n,{lang:e.lang})).text;else{const c=se(w)?{}:{language:e.lang||void 0,task:"transcribe"},m=await g(n,c);p=String(m?.text||"").trim()}}catch(c){z(e,{type:"error",code:"decode_failed",message:c.message,fatal:!1});return}if(!p)return;const d=r>=ee*h,_=r>=he*h;if(t||a||d||_){const c=t?"flush":a?"silence":_?"overflow":"length",m=c==="flush"||c==="silence",j=e.samples-r,H=[];f&&H.push(f),j>0&&H.push(ye(e).subarray(r)),e.chunks=H,e.samples=H.reduce((T,x)=>T+x.length,0),e.lastInterim="";const Y=et(n,u);if(Re(p,Y?Y.length:0))return;let N=null,G=null;if(e.diarizer)try{const T=e.speakerLabel?null:await L.spans(n),x=T?Le(T):[];if(x.length){const R=new Map;for(const{local:S}of ve(x)){const U=$e(n,x,S),we=U.length?await b.embed(U):null,_e=U.length<ce,Me=U.length<ue;R.set(S,e.diarizer.assign(we,{pinnedLabel:null,weak:_e,thin:Me}))}const W=Math.round(o/h*1e3);G=x.map(S=>({startMs:W+Math.round(S.start*1e3),durationMs:Math.round((S.end-S.start)*1e3),speaker:R.get(S.local)})).filter(S=>S.speaker),N=R.get(Ae(x))||null}}catch{}if(e.diarizer&&!N)try{const T=Y,x=T?await b.embed(T):null,R=!!T&&T.length<ce,W=!!T&&T.length<ue;N=e.diarizer.assign(x,{pinnedLabel:e.speakerLabel,weak:R,thin:W})}catch{}z(e,{type:"final",text:p,reason:c,endOfTurn:m,durationMs:Math.round(n.length/h*1e3),startMs:Math.round(o/h*1e3),...N?{speaker:N}:{},...G?.length?{turns:G}:{}})}else p!==e.lastInterim&&(e.lastInterim=p,z(e,{type:"interim",text:p}))}async function nt(e){const t=X(e);if(!t||t.closed)return!1;t.closed=!0,t.idleTimer&&clearTimeout(t.idleTimer),t.decodeTimer&&(clearTimeout(t.decodeTimer),t.decodeTimer=null);try{await(F=F.then(()=>re(t,{flush:!0}).catch(()=>{})))}finally{if(z(t,{type:"end"}),t.listeners.clear(),k.delete(t.id),t.poll){const n=setTimeout(()=>$.delete(t.id),Ke);n.unref?.(),$.set(t.id,{session:t,timer:n})}t.diarizer&&(b.release(),L.release()),k.size===0&&K()&&E?.arm()}return!0}function Dt(){for(const e of k.values())e.idleTimer&&clearTimeout(e.idleTimer),e.decodeTimer&&clearTimeout(e.decodeTimer);k.clear();for(const e of $.values())clearTimeout(e.timer);$.clear(),E?.disarm(),E=null,s="off",w=null,g=null,M=null,A=null,y=null}function Lt(e,t="test/fake",{warmMs:n=null,dtype:r=null}={}){g=e,w=t,s=e?"ready":"off",v=r,n!==null&&(E=V({warmMs:n,busy:O,unload:()=>J()}),e&&E.arm())}export{Ue as AUTO_FETCH_MAX_MB,h as SAMPLE_RATE,ue as THIN_SPEAKER_SAMPLES,ce as WEAK_SPEAKER_SAMPLES,Dt as _reset,Lt as _setPipeForTest,Je as clampEndSilence,Mt as createSession,St as decodeNow,Tt as drainEvents,nt as endSession,kt as endedSession,X as getSession,ht as health,yt as init,K as isReady,Re as looksHallucinated,Oe as modelOnDisk,qe as noiseFloorOf,pt as progress,xt as pushAudio,Ie as quietestCut,B as runtimeDtype,le as runtimeName,_t as sessionCount,wt as setModel,We as silenceGate,pe as speakerPlan,mt as state,Et as subscribe,bt as toFloat32,J as unload,gt as warmPending};
1
+ import{join as Ee}from"node:path";import{existsSync as Te,readdirSync as ke}from"node:fs";import{randomUUID as xe}from"node:crypto";import{ensureLib as oe,modelRoot as ie}from"./ner-engine.js";import{runtimeDtype as B,runtimeName as le,DTYPE_SUFFIX as Se}from"./model-runtime.js";import{verifyModelWeights as be}from"./model-integrity.js";import{DEFAULT_STT_MODEL as ae,isEnglishOnly as se,sttModelDtype as q,isKnownSttModel as De,sttModelEngine as P}from"./stt-models.js";import*as D from"./parakeet-engine.js";import*as Q from"./coreml-stt-engine.js";import*as b from"./diarize-engine.js";import*as L from"./segment-engine.js";import{turnsFromSpans as Le,mainLocal as Ae,timeByLocal as ve,audioOfLocal as $e}from"@chatpanel/events/speaker-turns.js";import{diarizeApproxMB as Fe}from"./diarize-models.js";import{makeWarmTimer as V}from"./warm-timer.js";const h=16e3,ce=h,ue=3*h,Pe=2,Ne=new Set(["thank you","thanks","thank you for watching","thanks for watching","you","uh","um","hmm","hm","mm","amen","bye","okay","ok","yeah","oh","the","that","so","and","i","a","me","we","yes","no","thank you very much","subtitles by the amara.org community","you you"]);function Re(e,t){if(t>Pe*h)return!1;const n=String(e||"").toLowerCase().replace(/[^\p{L}\p{N}\s]/gu,"").replace(/\s+/g," ").trim();return n?Ne.has(n)||/^(you ?){2,}$/.test(n)||/^(thank you\.? ?){2,}$/.test(n):!0}let s="off",w=null,g=null,M=null,A=null,y=null,v=null,E=null;function Oe(e=w||ae,t=q(e)||B()){if(P(e)==="parakeet-tdt")return D.parakeetOnDisk(e,D.parakeetDtype(t));if(P(e)==="coreml-tdt")return Q.coremlOnDisk(e);const n=Ee(ie(),...e.split("/"),"onnx");if(!Te(n))return!1;const r=Se[t]??"";try{const o=ke(n);return o.includes(`encoder_model${r}.onnx`)&&o.some(i=>i===`decoder_model_merged${r}.onnx`||i===`decoder_model${r}.onnx`)}catch{return!1}}function mt(){return s}function K(){return s==="ready"&&!!g}function pt(){return y}function ht(){return{configured:s!=="off",ok:K(),state:s,model:w,dtype:v,runtime:le(),error:M,warmMs:E?.warmMs??null}}function gt(){return!!E?.pending()}function O(){return k.size>0||s==="loading"||s==="downloading"}async function J({log:e=()=>{}}={}){if(O())return!1;E?.disarm();const t=g;if(g=null,A=null,v=null,y=null,M=null,s="off",t)try{await t.dispose?.()}catch{}return t&&e(`[stt] idle for ${Math.round((E?.warmMs||0)/6e4)} min — model unloaded (reloads on next dictation)`),!0}function fe(e){return e.then(t=>(t&&!O()&&E?.arm(),t))}async function de(e,{log:t=()=>{},allowDownload:n=!0,dtype:r=null}={}){if(P(e)==="parakeet-tdt")return ze(e,{log:t,allowDownload:n,dtype:r});if(P(e)==="coreml-tdt")return He(e,{log:t,allowDownload:n});const o=g,i=w;let l;try{l=await oe()}catch(_){return s="error",M=`engine load failed: ${_.message}`,t(`[stt] transformers.js not available (${_.message}) — dictation falls back to the browser engine`),!1}const a=(r&&r!=="auto"?r:null)||q(e)||B(),f=Oe(e,a);if(l.env.allowRemoteModels=f?!1:!!n,!f&&!n)return s="error",M="model not on disk and downloads disabled",t(`[stt] model ${e} not installed and downloads disabled`),!1;const p=l.env.remoteHost,d=!De(e);if(!f&&d)try{l.env.remoteHost="https://huggingface.co/"}catch{}s=f?"loading":"downloading",f||(y={model:e,file:null,pct:0},t(`[stt] downloading model ${e} (one-time${d?", from Hugging Face":""})…`));try{const _=m=>{if(!m)return;const j=typeof m.progress=="number"?Math.round(m.progress):y?.pct??0;m.status==="progress"||m.status==="download"||m.status==="initiate"?y={model:e,file:m.file||y?.file||null,pct:j}:m.status==="done"&&m.file&&t(`[stt] fetched ${m.file}`)};let c;try{c=await l.pipeline("automatic-speech-recognition",e,{dtype:a,progress_callback:_})}catch(m){if(f||d||!n)throw m;t(`[stt] mirror fetch failed (${String(m.message).slice(0,80)}) — retrying from Hugging Face…`),l.env.remoteHost="https://huggingface.co/",l.env.allowRemoteModels=!0,c=await l.pipeline("automatic-speech-recognition",e,{dtype:a,progress_callback:_})}if(!f)try{be(e,{modelsDir:ie(),log:t})}catch(m){try{await c.dispose?.()}catch{}throw m}if(g=c,w=e,s="ready",M=null,y=null,v=a,o&&o!==c)try{await o.dispose?.()}catch{}return t(`[stt] ready — model ${e} @ ${a} (in-process, offline) — local dictation active`),!0}catch(_){return M=_.message,y=null,o?(g=o,w=i,s="ready"):s="error",t(`[stt] model load failed (${_.message})${o?" — keeping previous model":""}`),!1}finally{try{l.env.remoteHost=p}catch{}}}async function ze(e,{log:t=()=>{},allowDownload:n=!0,dtype:r=null}={}){const o=g,i=w,l=D.parakeetDtype(r&&r!=="auto"?r:Ce()),u=D.parakeetOnDisk(e,l);if(!u&&!n)return s="error",M="model not on disk and downloads disabled",t(`[stt] model ${e} not installed and downloads disabled`),!1;s=u?"loading":"downloading",u||(y={model:e,file:null,pct:0},t(`[stt] downloading model ${e} (one-time, from Hugging Face)…`));try{const a=await D.loadRecognizer({modelId:e,dtype:l,allowDownload:n,log:t,onProgress:p=>{y={model:e,file:p.file||null,pct:typeof p.pct=="number"?p.pct:y?.pct??0}}}),f=async p=>({text:await a.transcribe(p)});if(f.__transducer=!0,f.dispose=()=>a.dispose(),g=f,w=e,s="ready",M=null,y=null,v=l,o&&o!==f)try{await o.dispose?.()}catch{}return t(`[stt] ready — model ${e} @ ${l} (parakeet-tdt, in-process, offline) — local dictation active`),!0}catch(a){return M=a.message,y=null,o?(g=o,w=i,s="ready"):s="error",t(`[stt] model load failed (${a.message})${o?" — keeping previous model":""}`),!1}}function Ce(){return D.PARAKEET_DEFAULT_DTYPE}const me="fp16";async function He(e,{log:t=()=>{},allowDownload:n=!0}={}){const r=g,o=w,i=Q.coremlOnDisk(e);if(!i&&!n)return s="error",M="model not on disk and downloads disabled",t(`[stt] model ${e} not installed and downloads disabled`),!1;s=i?"loading":"downloading",i||(y={model:e,file:null,pct:0},t(`[stt] downloading model ${e} (one-time, from Hugging Face)…`));try{let l=null;const u=await Q.loadRecognizer({modelId:e,allowDownload:n,log:t,onProgress:a=>{y={model:e,file:a.file||null,pct:typeof a.pct=="number"?a.pct:y?.pct??0}},onExit:a=>{g===l&&(g=null,A=null,s="error",M=a,E?.disarm(),t(`[stt] ${a} — reloads on the next dictation`))}});if(l=async a=>({text:await u.transcribe(a)}),l.__transducer=!0,l.dispose=()=>u.dispose(),g=l,w=e,s="ready",M=null,y=null,v=me,r&&r!==l)try{await r.dispose?.()}catch{}return t(`[stt] ready — model ${e} (Core ML on the Neural Engine, helper ${u.version}, windows ${u.windows.join("/")} s, offline) — local dictation active`),!0}catch(l){return M=l.message,y=null,r?(g=r,w=o,s="ready"):s="error",t(`[stt] model load failed (${l.message})${r?" — keeping previous model":""}`),!1}}const Ue=30;function pe({mode:e="ondisk",onDisk:t=!1,ready:n=!1,approxMB:r=null}={}){return n||e==="off"?null:t?{allowDownload:!1}:typeof r=="number"&&r<=Ue||e==="download"?{allowDownload:!0}:null}function Z(e,{log:t=()=>{},warmMs:n,allowDownload:r=!0}={}){const o=pe({mode:e,onDisk:b.modelOnDisk(),ready:b.isReady(),approxMB:Fe(b.activeModel())});if(o&&b.init({allowDownload:o.allowDownload&&r!==!1,warmMs:n,onLog:t}),e==="off"||I)return;const i=pe({mode:e,onDisk:L.modelOnDisk(),ready:L.isReady(),approxMB:L.SEGMENT_MODEL_APPROX_MB});i&&L.init({allowDownload:i.allowDownload&&r!==!1,warmMs:n,onLog:t})}let I=!1;function yt(e={}){if(A&&s!=="error")return A;const t=typeof e.onLog=="function"?e.onLog:()=>{};return w=e.model||ae,I=e.segment===!1,s="loading",E=V({warmMs:e.warmMs,busy:O,log:t,unload:()=>J({log:t})}),A=fe(de(w,{log:t,allowDownload:e.allowDownload!==!1,dtype:e.dtype})).then(n=>(n&&Z(e.speaker,{log:t,warmMs:e.warmMs,allowDownload:e.allowDownload!==!1}),n)),A}async function wt(e,t={}){const n=typeof t.onLog=="function"?t.onLog:()=>{};if(!e)return!1;t.segment!==void 0&&(I=t.segment===!1);const r=P(e)==="parakeet-tdt"?D.parakeetDtype(t.dtype&&t.dtype!=="auto"?t.dtype:D.PARAKEET_DEFAULT_DTYPE):P(e)==="coreml-tdt"?me:t.dtype&&t.dtype!=="auto"?t.dtype:q(e)||B();if(e===w&&K()&&v===r)return Z(t.speaker,{log:n,warmMs:t.warmMs,allowDownload:t.allowDownload!==!1}),!0;E??=V({warmMs:t.warmMs,busy:O,log:n,unload:()=>J({log:n})});const o=await fe(de(e,{log:n,allowDownload:t.allowDownload!==!1,dtype:t.dtype}));return o&&Z(t.speaker,{log:n,warmMs:t.warmMs,allowDownload:t.allowDownload!==!1}),o}const Be=8,Ke=12e4,Xe=6e4,je=1200,ee=12,te=700,ne=.008,Ye=.002,Ge=4;function We(e){return e>0?Math.min(ne,Math.max(Ye,e*Ge)):ne}function qe(e){const t=Math.round(.1*h),n=Math.floor(e.length/t);if(n<5)return null;const r=new Float32Array(n);for(let o=0;o<n;o++)r[o]=C(e,o*t,(o+1)*t);return r.sort(),r[Math.floor(n*.1)]}const he=30,k=new Map,$=new Map;let F=Promise.resolve();function _t(){return k.size}const Qe=300,Ve=3e3;function Je(e){const t=Number(e);return Number.isFinite(t)?Math.min(Ve,Math.max(Qe,Math.round(t))):te}function Mt({lang:e,redact:t=!1,diarize:n=!1,speakerLabel:r=null,endSilenceMs:o=te,interims:i=!0,remote:l=null,poll:u=!1}={}){if(k.size>=Be){const f=new Error("too many concurrent dictation sessions");throw f.code="too_many_sessions",f}const a={id:xe(),endSilenceMs:Je(o),lang:typeof e=="string"&&e?e.slice(0,12):null,langTried:!1,pushed:0,noiseFloor:null,redact:!!t,diarize:!!n,speakerLabel:typeof r=="string"&&r?r.slice(0,40):null,diarizer:n?new b.Diarizer:null,remote:l||null,interims:i!==!1&&!l,chunks:[],samples:0,listeners:new Set,poll:u?[]:null,lastDecodeAt:0,decodeTimer:null,lastInterim:"",closed:!1,idleTimer:null};return k.set(a.id,a),E?.disarm(),a.diarizer&&(b.retain(),L.retain()),ge(a),{id:a.id}}function X(e){return k.get(String(e||""))||null}function Et(e,t){const n=X(e);return n?(n.listeners.add(t),()=>n.listeners.delete(t)):null}function z(e,t){e.poll&&e.poll.push(t);for(const n of e.listeners)try{n(t)}catch{}}function Tt(e){const t=String(e||""),n=k.get(t);if(n)return n.poll?n.poll.splice(0):null;const r=$.get(t);return r?(clearTimeout(r.timer),$.delete(t),r.session.poll.splice(0)):null}function kt(e){return $.get(String(e||""))?.session||null}function ge(e){e.idleTimer&&clearTimeout(e.idleTimer),e.idleTimer=setTimeout(()=>nt(e.id).catch(()=>{}),Xe),e.idleTimer.unref?.()}function xt(e,t){const n=X(e);if(!n||n.closed){const r=new Error("no such session");throw r.code="no_session",r}!(t instanceof Float32Array)||!t.length||(n.chunks.push(t),n.samples+=t.length,n.pushed+=t.length,ge(n),Ze(n))}function St(e){const t=X(e);return!t||t.closed?Promise.resolve():(t.decodeTimer&&(clearTimeout(t.decodeTimer),t.decodeTimer=null),F=F.then(()=>re(t).catch(()=>{})),F)}function bt(e){const t=e.length-e.length%4,n=new Float32Array(t/4);for(let r=0;r<n.length;r++)n[r]=e.readFloatLE(r*4);return n}function Ze(e){if(e.closed||e.decodeTimer)return;const t=Math.max(0,e.lastDecodeAt+je-Date.now());e.decodeTimer=setTimeout(()=>{e.decodeTimer=null,F=F.then(()=>re(e).catch(()=>{}))},t),e.decodeTimer.unref?.()}function ye(e){const t=new Float32Array(e.samples);let n=0;for(const r of e.chunks)t.set(r,n),n+=r.length;return t}function Ie(e,t,n){const r=h/100,o=Math.max(0,e.length-t),i=Math.floor((e.length-o)/r),l=Math.max(1,Math.round(n/r));if(i<=l)return 0;const u=new Float32Array(i);for(let d=0;d<i;d++){let _=0;const c=o+d*r;for(let m=0;m<r;m++)_+=e[c+m]*e[c+m];u[d]=_/r}let a=-1,f=1/0,p=0;for(let d=0;d<l;d++)p+=u[d];for(let d=0;d+l<=i;d++)d>0&&(p+=u[d+l-1]-u[d-1]),p<f&&(f=p,a=d);return a<0?0:o+Math.round((a+l/2)*r)}function C(e,t=0,n=e.length){let r=0;const o=Math.max(1,n-t);for(let i=t;i<n;i++)r+=e[i]*e[i];return Math.sqrt(r/o)}function et(e,t=ne){const n=Math.round(.02*h);let r=0,o=e.length;for(let i=0;i+n<=e.length;i+=n)if(C(e,i,i+n)>=t){r=i;break}for(let i=e.length-n;i>=0;i-=n)if(C(e,i,i+n)>=t){o=i+n;break}return o>r?e.subarray(r,o):e}async function tt(e){try{const t=await oe(),n=g?.model?.generation_config;if(!n?.lang_to_id||!n.decoder_start_token_id||!t.Tensor)return null;const r=e.length>h*8?e.subarray(0,h*8):e,o=await g.processor(r),i=new t.Tensor("int64",new BigInt64Array([BigInt(n.decoder_start_token_id)]),[1,1]),l=await g.model({...o,decoder_input_ids:i});let u=null,a=-1/0;for(const[f,p]of Object.entries(n.lang_to_id)){const d=Number(l.logits.data[p]);d>a&&(a=d,u=f)}return u?u.slice(2,-2):null}catch{return null}}async function re(e,{flush:t=!1}={}){if(e.closed&&!t||!e.remote&&!K()||!e.samples)return;e.lastDecodeAt=Date.now();let n=ye(e);const r=n.length,o=Math.max(0,(e.pushed||0)-e.samples),i=Math.round((e.endSilenceMs||te)/1e3*h),l=qe(n);l!==null&&(e.noiseFloor==null||l<e.noiseFloor)&&(e.noiseFloor=l);const u=We(e.noiseFloor),a=n.length>i&&C(n,n.length-i)<u;if(C(n)<u){n.length>h*5&&(e.chunks=[n.subarray(n.length-h)],e.samples=h);return}if(!e.interims&&!t&&!a&&n.length<ee*h)return;let f=null;if(!t&&!a&&r>=ee*h&&r<he*h){const c=Ie(n,3*h,Math.round(.2*h));c>0&&c<n.length&&(f=n.subarray(c),n=n.subarray(0,c))}if(!e.remote&&!e.lang&&!e.langTried&&!se(w)&&!g?.__transducer&&n.length>=h){e.langTried=!0;const c=await tt(n);c&&(e.lang=c,z(e,{type:"language",lang:c}))}let p="";try{if(e.remote)p=(await e.remote.transcribe(n,{lang:e.lang})).text;else{const c=se(w)?{}:{language:e.lang||void 0,task:"transcribe"},m=await g(n,c);p=String(m?.text||"").trim()}}catch(c){z(e,{type:"error",code:"decode_failed",message:c.message,fatal:!1});return}if(!p)return;const d=r>=ee*h,_=r>=he*h;if(t||a||d||_){const c=t?"flush":a?"silence":_?"overflow":"length",m=c==="flush"||c==="silence",j=e.samples-r,H=[];f&&H.push(f),j>0&&H.push(ye(e).subarray(r)),e.chunks=H,e.samples=H.reduce((T,x)=>T+x.length,0),e.lastInterim="";const Y=et(n,u);if(Re(p,Y?Y.length:0))return;let N=null,G=null;if(e.diarizer)try{const T=e.speakerLabel?null:await L.spans(n),x=T?Le(T):[];if(x.length){const R=new Map;for(const{local:S}of ve(x)){const U=$e(n,x,S),we=U.length?await b.embed(U):null,_e=U.length<ce,Me=U.length<ue;R.set(S,e.diarizer.assign(we,{pinnedLabel:null,weak:_e,thin:Me}))}const W=Math.round(o/h*1e3);G=x.map(S=>({startMs:W+Math.round(S.start*1e3),durationMs:Math.round((S.end-S.start)*1e3),speaker:R.get(S.local)})).filter(S=>S.speaker),N=R.get(Ae(x))||null}}catch{}if(e.diarizer&&!N)try{const T=Y,x=T?await b.embed(T):null,R=!!T&&T.length<ce,W=!!T&&T.length<ue;N=e.diarizer.assign(x,{pinnedLabel:e.speakerLabel,weak:R,thin:W})}catch{}z(e,{type:"final",text:p,reason:c,endOfTurn:m,durationMs:Math.round(n.length/h*1e3),startMs:Math.round(o/h*1e3),...N?{speaker:N}:{},...G?.length?{turns:G}:{}})}else p!==e.lastInterim&&(e.lastInterim=p,z(e,{type:"interim",text:p}))}async function nt(e){const t=X(e);if(!t||t.closed)return!1;t.closed=!0,t.idleTimer&&clearTimeout(t.idleTimer),t.decodeTimer&&(clearTimeout(t.decodeTimer),t.decodeTimer=null);try{await(F=F.then(()=>re(t,{flush:!0}).catch(()=>{})))}finally{if(z(t,{type:"end"}),t.listeners.clear(),k.delete(t.id),t.poll){const n=setTimeout(()=>$.delete(t.id),Ke);n.unref?.(),$.set(t.id,{session:t,timer:n})}t.diarizer&&(b.release(),L.release()),k.size===0&&K()&&E?.arm()}return!0}function Dt(){for(const e of k.values())e.idleTimer&&clearTimeout(e.idleTimer),e.decodeTimer&&clearTimeout(e.decodeTimer);k.clear();for(const e of $.values())clearTimeout(e.timer);$.clear(),E?.disarm(),E=null,s="off",w=null,g=null,M=null,A=null,y=null}function Lt(e,t="test/fake",{warmMs:n=null,dtype:r=null}={}){g=e,w=t,s=e?"ready":"off",v=r,n!==null&&(E=V({warmMs:n,busy:O,unload:()=>J()}),e&&E.arm())}export{Ue as AUTO_FETCH_MAX_MB,h as SAMPLE_RATE,ue as THIN_SPEAKER_SAMPLES,ce as WEAK_SPEAKER_SAMPLES,Dt as _reset,Lt as _setPipeForTest,Je as clampEndSilence,Mt as createSession,St as decodeNow,Tt as drainEvents,nt as endSession,kt as endedSession,X as getSession,ht as health,yt as init,K as isReady,Re as looksHallucinated,Oe as modelOnDisk,qe as noiseFloorOf,pt as progress,xt as pushAudio,Ie as quietestCut,B as runtimeDtype,le as runtimeName,_t as sessionCount,wt as setModel,We as silenceGate,pe as speakerPlan,mt as state,Et as subscribe,bt as toFloat32,J as unload,gt as warmPending};
package/src/version.js CHANGED
@@ -1 +1 @@
1
- const o="0.104.0";export{o as VERSION};
1
+ const o="0.105.1";export{o as VERSION};