@chatpanel/gateway 0.139.4 → 0.140.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/package.json +2 -2
- package/src/diarize-engine.js +1 -1
- package/src/server.js +28 -28
- package/src/stt-engine.js +1 -1
- package/src/tts-remote.js +1 -1
- package/src/version.js +1 -1
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@chatpanel/gateway",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.140.0",
|
|
4
4
|
"description": "Local privacy gateway — redacts PII out of OpenAI/Anthropic API traffic before it reaches a model, then restores it in the reply. Point opencode, codex, aider, Claude Code, etc. at it.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"bin": {
|
|
@@ -24,7 +24,7 @@
|
|
|
24
24
|
"dependencies": {
|
|
25
25
|
"@anthropic-ai/sandbox-runtime": "^0.0.77",
|
|
26
26
|
"@chatpanel/bridge": "^0.52.0",
|
|
27
|
-
"@chatpanel/events": "^0.
|
|
27
|
+
"@chatpanel/events": "^0.464.0",
|
|
28
28
|
"@chatpanel/pii": "^0.15.6",
|
|
29
29
|
"@huggingface/transformers": "^4.2.0",
|
|
30
30
|
"defuddle": "^0.19.4",
|
package/src/diarize-engine.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{verifyFresh as R}from"./model-integrity.js";import{ensureLib as P,modelRoot as S,withModelSource as q}from"./ner-engine.js";import{join as I}from"node:path";import{existsSync as C,readdirSync as H}from"node:fs";import{makeWarmTimer as M}from"./warm-timer.js";import{engineLoadOptions as N}from"./ort.js";import{createSpeakerClusterer as W}from"@chatpanel/events/speaker-cluster.js";import{DEFAULT_DIARIZE_MODEL as b,diarizeThreshold as Z,isKnownDiarizeModel as j}from"./diarize-models.js";const te=b;let l="off",c=b,d=null,g=null,p=null,u=null,f=null,i=null,w=0,_=0;function re(){return c}function A(){return Z(c)}function z(){return globalThis.__CHATPANEL_WASM_PATHS__?"fp32":"q8"}function ne(){return l}function D(){return l==="ready"&&!!d&&!!g}function oe(){return f}function le(){return{configured:l!=="off",ok:D(),state:l,model:c,loaded:!!d,threshold:A(),error:p,warmMs:i?.warmMs??null}}function ie(){return!!i?.pending()}function ae(){w++,i?.disarm()}function se(){w=Math.max(0,w-1),w===0&&_===0&&D()&&i?.arm()}function h(){return w>0||_>0||l==="loading"||l==="downloading"}async function y({log:e=()=>{}}={}){if(h())return!1;i?.disarm();const t=d;if(d=null,g=null,u=null,f=null,p=null,l="off",t){try{await t.dispose?.()}catch{}e("[diarize] idle — speaker model unloaded (reloads on the next diarizing session)")}return!0}function J(e=c,t=z()){const n=I(S(),...e.split("/"),"onnx");if(!C(n))return!1;const r=t==="fp32"?"":t==="q8"?"_quantized":`_${t}`;try{return H(n).some(a=>a===`model${r}.onnx`)}catch{return!1}}async function T({log:e=()=>{},allowDownload:t=!0}={}){let n;try{n=await P()}catch(o){return l="error",p=o.message,e(`[diarize] engine unavailable (${o.message})`),!1}const r=c,a=J(r);if(!a&&!t)return l="error",p="model not on disk and downloads disabled",!1;l=a?"loading":"downloading",a||(f={model:r,file:null,pct:0},e(`[diarize] downloading ${r} (one-time)…`));try{const{AutoModel:o,AutoProcessor:s}=n,k=m=>{if(!m)return;const O=typeof m.progress=="number"?Math.round(m.progress):f?.pct??0;(m.status==="progress"||m.status==="download"||m.status==="initiate")&&(f={model:r,file:m.file||f?.file||null,pct:O})},{processor:E,model:$}=await q({host:a?null:"https://huggingface.co/",allowRemote:!a},async()=>({processor:await s.from_pretrained(r,{progress_callback:k}),model:await o.from_pretrained(r,{dtype:z(),progress_callback:k,...N({max:2})})}));return await R(!a,r,{modelsDir:S(),log:e,dispose:()=>$.dispose?.()}),g=E,d=$,l="ready",p=null,f=null,e(`[diarize] ready — ${r} @ ${z()} (speakers split at cosine ${A()})`),!0}catch(o){return p=o.message,f=null,l="error",e(`[diarize] load failed (${o.message}) — diarization off`),!1}}function ue(e={}){if(u&&l!=="error")return u;l="loading";const t=typeof e.onLog=="function"?e.onLog:()=>{};return i=M({warmMs:e.warmMs,busy:h,log:t,unload:()=>y({log:t})}),u=F(T({log:t,allowDownload:e.allowDownload!==!1})),u}function F(e){return e.then(t=>(t&&!h()&&i?.arm(),t))}async function fe(e,{log:t=()=>{}}={}){return j(e)?e===c?!0:h()?!1:(await y({log:()=>{}}),c=e,t(`[diarize] speaker model set to ${e} (loads on the next diarizing session)`),!0):!1}function ce({onLog:e}={}){return u=null,l="loading",i??=M({warmMs:void 0,busy:h,log:e||(()=>{}),unload:()=>y({log:e||(()=>{})})}),u=F(T({log:e,allowDownload:!0})),u}const L=16e3;function x(e){let t=0;for(const r of e)t+=r*r;t=Math.sqrt(t)||1;const n=new Float32Array(e.length);for(let r=0;r<e.length;r++)n[r]=e[r]/t;return n}async function v(e){try{const t=await g(e),n=await d(t),r=n.embeddings??n.logits??n.last_hidden_state;return r?.data?Float32Array.from(r.data):null}catch{return null}}async function de(e){if(!D()||!(e instanceof Float32Array)||!e.length)return null;_++;try{return await K(e)}finally{_--,h()||i?.arm()}}async function K(e){const t=2*L,n=Math.round(1.3*L);if(e.length<=Math.round(t*1.4)){const o=await v(e);return o?x(o):null}const r=[];for(let o=0;o+t<=e.length;o+=n){const s=await v(e.subarray(o,o+t));s&&r.push(x(s))}if(!r.length){const o=await v(e);return o?x(o):null}const a=new Float32Array(r[0].length);for(const o of r)for(let s=0;s<a.length;s++)a[s]+=o[s];return x(a)}function
|
|
1
|
+
import{verifyFresh as R}from"./model-integrity.js";import{ensureLib as P,modelRoot as S,withModelSource as q}from"./ner-engine.js";import{join as I}from"node:path";import{existsSync as C,readdirSync as H}from"node:fs";import{makeWarmTimer as M}from"./warm-timer.js";import{engineLoadOptions as N}from"./ort.js";import{createSpeakerClusterer as W}from"@chatpanel/events/speaker-cluster.js";import{DEFAULT_DIARIZE_MODEL as b,diarizeThreshold as Z,isKnownDiarizeModel as j}from"./diarize-models.js";const te=b;let l="off",c=b,d=null,g=null,p=null,u=null,f=null,i=null,w=0,_=0;function re(){return c}function A(){return Z(c)}function z(){return globalThis.__CHATPANEL_WASM_PATHS__?"fp32":"q8"}function ne(){return l}function D(){return l==="ready"&&!!d&&!!g}function oe(){return f}function le(){return{configured:l!=="off",ok:D(),state:l,model:c,loaded:!!d,threshold:A(),error:p,warmMs:i?.warmMs??null}}function ie(){return!!i?.pending()}function ae(){w++,i?.disarm()}function se(){w=Math.max(0,w-1),w===0&&_===0&&D()&&i?.arm()}function h(){return w>0||_>0||l==="loading"||l==="downloading"}async function y({log:e=()=>{}}={}){if(h())return!1;i?.disarm();const t=d;if(d=null,g=null,u=null,f=null,p=null,l="off",t){try{await t.dispose?.()}catch{}e("[diarize] idle — speaker model unloaded (reloads on the next diarizing session)")}return!0}function J(e=c,t=z()){const n=I(S(),...e.split("/"),"onnx");if(!C(n))return!1;const r=t==="fp32"?"":t==="q8"?"_quantized":`_${t}`;try{return H(n).some(a=>a===`model${r}.onnx`)}catch{return!1}}async function T({log:e=()=>{},allowDownload:t=!0}={}){let n;try{n=await P()}catch(o){return l="error",p=o.message,e(`[diarize] engine unavailable (${o.message})`),!1}const r=c,a=J(r);if(!a&&!t)return l="error",p="model not on disk and downloads disabled",!1;l=a?"loading":"downloading",a||(f={model:r,file:null,pct:0},e(`[diarize] downloading ${r} (one-time)…`));try{const{AutoModel:o,AutoProcessor:s}=n,k=m=>{if(!m)return;const O=typeof m.progress=="number"?Math.round(m.progress):f?.pct??0;(m.status==="progress"||m.status==="download"||m.status==="initiate")&&(f={model:r,file:m.file||f?.file||null,pct:O})},{processor:E,model:$}=await q({host:a?null:"https://huggingface.co/",allowRemote:!a},async()=>({processor:await s.from_pretrained(r,{progress_callback:k}),model:await o.from_pretrained(r,{dtype:z(),progress_callback:k,...N({max:2})})}));return await R(!a,r,{modelsDir:S(),log:e,dispose:()=>$.dispose?.()}),g=E,d=$,l="ready",p=null,f=null,e(`[diarize] ready — ${r} @ ${z()} (speakers split at cosine ${A()})`),!0}catch(o){return p=o.message,f=null,l="error",e(`[diarize] load failed (${o.message}) — diarization off`),!1}}function ue(e={}){if(u&&l!=="error")return u;l="loading";const t=typeof e.onLog=="function"?e.onLog:()=>{};return i=M({warmMs:e.warmMs,busy:h,log:t,unload:()=>y({log:t})}),u=F(T({log:t,allowDownload:e.allowDownload!==!1})),u}function F(e){return e.then(t=>(t&&!h()&&i?.arm(),t))}async function fe(e,{log:t=()=>{}}={}){return j(e)?e===c?!0:h()?!1:(await y({log:()=>{}}),c=e,t(`[diarize] speaker model set to ${e} (loads on the next diarizing session)`),!0):!1}function ce({onLog:e}={}){return u=null,l="loading",i??=M({warmMs:void 0,busy:h,log:e||(()=>{}),unload:()=>y({log:e||(()=>{})})}),u=F(T({log:e,allowDownload:!0})),u}const L=16e3;function x(e){let t=0;for(const r of e)t+=r*r;t=Math.sqrt(t)||1;const n=new Float32Array(e.length);for(let r=0;r<e.length;r++)n[r]=e[r]/t;return n}async function v(e){try{const t=await g(e),n=await d(t),r=n.embeddings??n.logits??n.last_hidden_state;return r?.data?Float32Array.from(r.data):null}catch{return null}}async function de(e){if(!D()||!(e instanceof Float32Array)||!e.length)return null;_++;try{return await K(e)}finally{_--,h()||i?.arm()}}function me(e){return Array.from(e,t=>Math.round(t*1e5)/1e5)}async function K(e){const t=2*L,n=Math.round(1.3*L);if(e.length<=Math.round(t*1.4)){const o=await v(e);return o?x(o):null}const r=[];for(let o=0;o+t<=e.length;o+=n){const s=await v(e.subarray(o,o+t));s&&r.push(x(s))}if(!r.length){const o=await v(e);return o?x(o):null}const a=new Float32Array(r[0].length);for(const o of r)for(let s=0;s<a.length;s++)a[s]+=o[s];return x(a)}function pe(){i?.disarm(),i=null,w=0,_=0,l="off",c=b,d=null,g=null,p=null,u=null,f=null}function he(e,t,{warmMs:n=null}={}){d=e,g=t,l=e?"ready":"off",n!==null&&(i=M({warmMs:n,busy:h,unload:()=>y()}),e&&i.arm())}class ge{constructor({threshold:t=A(),maxSpeakers:n=12}={}){this.threshold=t,this.maxSpeakers=n,this._voices=W({threshold:t,maxSpeakers:n})}assign(t,n){return this._voices.assign(t,n)}get centroids(){return this._voices.toJSON().centroids}}export{te as DIARIZE_MODEL,ge as Diarizer,pe as _reset,he as _setForTest,re as activeModel,A as activeThreshold,ce as download,de as embed,le as health,ue as init,D as isReady,J as modelOnDisk,me as plainVector,oe as progress,se as release,ae as retain,fe as setModel,ne as state,y as unload,ie as warmPending};
|
package/src/server.js
CHANGED
|
@@ -1,67 +1,67 @@
|
|
|
1
|
-
import{createServer as
|
|
1
|
+
import{createServer as nr}from"node:http";import{loadConfig as Kt}from"./config.js";import{startEntitlementRefresh as ar,maybeRevalidate as sr}from"./entitlement-refresh.js";import{redactSegments as qe,segment as ht,rememberAnswer as Yt}from"./redact.js";import{pipeRestoredStream as ir,pipeRestoredOpenAIStream as lr,makeTokenRestorer as Qt,restoreDeep as dr}from"./stream.js";import{restoreText as cr,gatedDictionary as ur,narrowSpecs as mr,makeToolHarness as pr,placeholderToolNote as hr,placeholderNote as yr,assertEndpointUrl as fr,capRunOptions as gr,isPaired as Xt}from"@chatpanel/pii";import{ensureGatewayToken as _e,currentGatewayToken as Be,isAdminAuthorized as G,callerTrustOf as Le,setPinnedExtensionIds as wr,issuePairingCode as br,claimPairingCode as vr}from"./gateway-token.js";import{createPairAsk as kr,nativeConfirm as Sr}from"./pair-prompt.js";import{createEngineProbe as Tr}from"./local-engine-probe.js";import{randomUUID as xr}from"node:crypto";import{installEgressLedger as _r,egressAudit as Or}from"./egress.js";import{trustSystemCertificates as Er,systemCaWanted as Zt,systemCaState as Pr}from"./system-ca.js";import{initPolicy as $r,activePolicy as et,applyPolicyToConfig as qt,managedSummary as Je,PolicyLoadError as Ar}from"./policy.js";import{routeAllowed as eo,agentAllowed as Nr,egressAllowed as Mr}from"@chatpanel/events/policy.js";import{resolveBridgeUrl as je}from"./bridge.js";import{secureFetch as tt}from"./secure-fetch.js";import{fetchCard as ot,forgetCard as Br,sendMessage as Dr,streamMessage as Cr,getTask as Ir,cancelTask as Rr,knownAgents as Lr,A2AError as to}from"./a2a.js";import{streamBridgeChat as oo,readBridgeToken as ze,openBridgeChat as Jr,acceptedBridgeToken as ro}from"./bridge.js";import{createRelaySession as jr,getRelaySession as no,endRelaySession as Ge,pumpBridgeStream as zr,deliverToolResult as ao,toolsToSpecs as Gr,wantsApprovals as Hr,parseToolCallId as so,touchRelaySession as rt}from"./toolrelay.js";import{shaperFor as yt}from"./shape.js";import{startNer as Ur,ensureNer as nt,unionForThisMachine as Vr,skippedCompanions as Fr}from"./ner.js";import{recommendDetector as io}from"@chatpanel/pii/detector-router.js";import{installTimestampedConsole as Wr}from"./log.js";import{saveBackupSecret as Kr,clearBackupSecret as Yr,loadBackupSecret as ft,hasBackupSecret as lo}from"./history-store.js";import{createMemoryStore as Qr}from"./memory-store.js";import{createPrefsStore as Xr}from"./prefs-store.js";import{agentCardFor as co,runHintFor as uo}from"@chatpanel/events/agent-run-hint.js";import{normalizeThread as Zr}from"@chatpanel/events/agent-thread.js";import{portClashPlan as qr,serviceManagerOf as en,STANDBY_POLL_MS as tn}from"@chatpanel/events/service-standby.js";import{threadTarget as on,frameQuestion as rn,wireMessages as nn,appendExchange as an,MAX_MESSAGE as mo}from"@chatpanel/events/thread-send.js";import{researchStore as sn,researchResponse as ln}from"./research.js";import{createTeamStore as dn,loadOrCreateKey as gt}from"./team-store.js";import{createScorecardStore as cn}from"./scorecard-store.js";import{createEngineLedgerStore as un}from"./engine-ledger-store.js";import{createProjectStore as mn}from"./project-store.js";import{applicationsFor as pn,recruitPass as hn}from"./recruiting.js";import{ensureBridge as yn,holderOf as fn}from"./bridge-supervisor.js";import{checkForUpdate as gn,updateStatus as wn,startUpdate as bn,updateJob as vn,installKind as kn}from"./update.js";import{confinedStatus as wt,confinedLine as Sn}from"./confine.js";import{appleHelperWanted as Tn,findAppleHelper as bt}from"./apple-helper-fetch.js";import{createHistoryStore as xn}from"./sqlite-store.js";import{createEventStore as _n}from"./event-store.js";import{createLinkActivity as On,linkSurface as En,sseUsageTap as Pn,usageOfBody as $n,GATEWAY_HOST as po}from"./link-activity.js";import{ingestCloudEvents as An,cursorOf as ho}from"./event-sync.js";import{eventStats as Nn,projectYear as Mn}from"./event-stats.js";import{toCloudEvent as vt,ceHostOf as Bn}from"./cloudevents.js";import{fusionsDocument as Dn,resolveFusionModel as Cn}from"./fusions.js";import{ingestBackups as kt}from"./backup-ingest.js";import{toSearchRecord as yo}from"@chatpanel/events/library.js";import{deriveBackupKey as In,openRecord as Rn,keyCache as Ln,nodeCodec as Jn}from"@chatpanel/events/backup-envelope.js";import jn from"node:zlib";import*as L from"./ner-engine.js";import St from"node:os";import{capabilitiesDocument as zn,handleDetect as Gn}from"./capabilities.js";import{createExtractService as Hn}from"./extract/service.js";import{workerSandbox as Un,disposeWorkerSandbox as Vn}from"./worker-sandbox.js";import{createRuntime as Fn,SERVICES as Wn}from"./runtime.js";import{createCapabilityProxy as Kn}from"./capability-proxy.js";import{createEmbeddedCapabilities as Yn}from"./capability-embedded.js";import{EMBEDDED_MODELS as Qn,EMBEDDED_IDS as Xn}from"./embedded-models.js";import{handleExtract as Zn,handleExtractContext as qn}from"./extract/handler.js";import{createKbStore as ea}from"./kb-store.js";import{createKbService as ta}from"./kb.js";import{MAX_DOCUMENT_BYTES as Tt}from"./extract-capability.js";import{createReader as oa}from"./retrieval/read.js";import{createBrowserRelayHost as ra}from"./browser-relay.js";import{createLinkHost as na}from"./link-host.js";import{checkLinkRoute as aa,tunnelHeader as sa,LINK_TUNNEL_ROOM_PATH as ia}from"@chatpanel/events/link-routes.js";import{linkCallerOf as He,linkDestinationAllowed as la,linkVia as da,partnerRunHint as ca,PARTNER_APPROVAL_DECISIONS as fo,partnerFilePath as ua}from"@chatpanel/events/link-scopes.js";import{listPartnerFiles as ma,readPartnerFile as pa,writePartnerFile as ha,removePartnerFile as ya}from"./link-files.js";import{handleFileWrite as fa}from"./file-write.js";import{handleFileRead as ga}from"./file-read.js";import{handleAppleNotes as wa}from"./apple-notes.js";import{WRITE_MAX_BYTES as ba}from"@chatpanel/events/file-write.js";import{isPermissionTool as go}from"@chatpanel/events/agent-permission.js";import{createApprovalInbox as va}from"./link-approvals.js";import{createSearcher as ka,toJinaSearch as Sa,SEARCH_DEFAULTS as Ta}from"./retrieval/search.js";import{createSearxng as xa}from"./retrieval/search-searxng.js";import{searchEngines as _a}from"./retrieval/search-apis.js";import{toJinaText as Oa}from"./read-document.js";import*as N from"./stt-engine.js";import*as $ from"./diarize-engine.js";import*as $e from"./translate-engine.js";import*as Ea from"./indictrans-engine.js";import*as xt from"./aec-engine.js";import{speechCoverage as Pa}from"@chatpanel/events/speech-language.js";import*as $a from"./segment-engine.js";import{DIARIZE_MODEL_CATALOG as Aa,DEFAULT_DIARIZE_MODEL as Na,isKnownDiarizeModel as wo,diarizeModelEntry as Ma}from"./diarize-models.js";import{providerOf as _t}from"./providers.js";import{createRemoteTranscriber as bo}from"./stt-remote.js";import{parseMultipart as Ba,decodeAudioFile as Da}from"./audio-file.js";import{MODEL_CATALOG as vo,isKnownModel as ko,isValidCustomModelId as So,recommendFor as Ca}from"./models.js";import{STT_MODEL_CATALOG as Ia,isKnownSttModel as Ra,isValidCustomSttId as La,DEFAULT_STT_MODEL as De,STT_DTYPES as Ja,isValidDtype as ja,sttModel as at,sttModelUnavailable as To,licenseAcceptance as xo}from"./stt-models.js";import*as C from"./tts-engine.js";import{TTS_MODEL_CATALOG as _o,TTS_VOICES as za,isKnownTtsModel as Ga,isValidCustomTtsId as Ha,isKnownVoice as Oo,isValidVoiceId as Eo,DEFAULT_TTS_MODEL as Po,DEFAULT_TTS_VOICE as Oe,TTS_DTYPES as Ua,isValidTtsDtype as Va,MAX_TTS_CHARS as $o,ttsModelHasCustomVoices as Fa,resolveDefaultModel as Ao,POCKET_VOICES as Wa,DEFAULT_POCKET_VOICE as st,isPocketVoice as it,ttsModelEngine as lt}from"./tts-models.js";import{ttsDestination as Ka,synthesizeRemote as Ya,isValidRemoteVoice as Qa}from"./tts-remote.js";import{rawOrtAvailable as Ot}from"./ort.js";import*as de from"./tts-voices.js";import{resolveTtsVoice as Xa}from"./tts-voice-resolve.js";import{resolvePro as ke,checkQuota as Za,consume as qa,usage as es}from"./freegate.js";import{publicConfig as No,applyConfigPatch as Mo,registryChildEnv as ts,applyNerModelSelection as Bo,persistConfig as be,configPath as ce,bridgeAgentOptions as Do,PERMISSION_MODES as os,sandboxEnvFor as rs,sandboxProblems as ns}from"./configstore.js";import{freeLimitProblem as as}from"./capability-config.js";import Ue from"node:path";import{resolveDestination as dt,aggregateModelsAsync as ss,listDestinations as is,ensureModelCatalog as ls,agentOwnsModel as ds}from"./router.js";import{makeAccessEvent as Co}from"./observability.js";import{createPersistentAccessLog as cs}from"./access-log-store.js";import{planQueries as us,multiSearch as ms}from"./rrf.js";import*as Et from"./openai.js";import*as Io from"./responses.js";import*as Pt from"./anthropic.js";import{closeAndExit as ps}from"./shutdown.js";import{VERSION as ue}from"./version.js";import{VERSION as Bl}from"./version.js";const J=await xn(),xe=new Set;function Ve({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
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
|
|
6
|
+
`)}catch{xe.delete(t)}},25e3).unref?.();const Q=await _n(),$t=On({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(vt(t))}
|
|
8
8
|
|
|
9
|
-
`;for(const u of Ee)try{u.write(
|
|
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{Ee.delete(t)}},25e3).unref?.();const fe=await
|
|
11
|
+
`)}catch{Ee.delete(t)}},25e3).unref?.();const fe=await Qr(),me=Xr(),Ce=cn({key:gt()}),Ie=un({key:gt()}),he=mn({key:gt()}),re=dn({scorecards:Ce,engines:Ie}),At=new Set,Ro=(t,c)=>{for(const p of At)try{p({applied:t,by:c,revision:me.revision})}catch{}const u=JSON.stringify({revision:me.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(p)}},Nt=
|
|
14
|
+
`)}catch{xe.delete(p)}},Nt=cs(),Lo=new Set(["codex","claude","opencode","pi","kiro","antigravity","hermes"]),hs=16,ys=/^mcp[_-]/i,Jo=t=>t&&t.function&&t.function.name||t&&t.name||"",fs=t=>t&&t.function&&t.function.description||t&&t.description||"";function jo(t){return typeof t=="string"?t:Array.isArray(t)?t.map(c=>typeof c=="string"?c:c&&(c.text||c.content)||"").join(" "):""}function gs(t,c){if(!t)return"";if(c==="responses"){const p=t.input;return typeof p=="string"?p:Array.isArray(p)?p.map(b=>jo(b&&(b.content??b))).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 jo(u[p].content);return""}const zo=new Set(["host","connection","content-length","transfer-encoding","accept-encoding","content-encoding","keep-alive"]);function ct(t){if(!t)return!1;const c=t.replace(/:\d+$/,"").replace(/^\[|\]$/g,"");return c==="localhost"||c==="127.0.0.1"||c==="::1"}function ws(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 bs(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 Go=Date.now();function vs(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 ks(t){const c=/^(model|harness):([^/]+)(?:\/(.+))?$/.exec(String(t||""));return c?{kind:c[1],id:c[2],...c[3]?{model:c[3]}:{}}:null}function Ss(t){const c=performance.now(),u={};let p=!1;const b=(f,A)=>{u[f]=Math.round(A*10)/10};return{meta:{},timings:u,mark:b,lap(f,A){b(f,performance.now()-A)},clock(){return performance.now()},commit(){if(p)return;p=!0,b("total",performance.now()-c);const f={...this.meta,timings:u};setImmediate(()=>{t(f),console.log(`[gateway] model=${f.model||"-"} → ${f.dest?`${f.dest}(${f.type})`:"none"} · ${f.redaction==="off"?"redaction OFF (client request)":`redacted ${f.redacted||0}`}${f.sanitized?` · scrubbed ${f.sanitized} hidden`:""}${f.narrowed?` · narrowed -${f.narrowed}`:""} · ${vs(u)}`)})}}}function Ho(t,c){if(!t||!t.byToken||c!=="types"&&c!=="values")return;const u=[];for(const[p,b]of t.byToken){const f=/^\[\[([A-Z][A-Z0-9]*)_\d+\]\]$/.exec(p),A=f?f[1]:"PII",B=p.replace(/^\[\[|\]\]$/g,"");u.push(c==="values"?{token:B,type:A,value:b}:{token:B,type:A})}return u}function Ts(t,c,u){return Pt.matches(t)||"anthropic-version"in c?{kind:"anthropic",adapter:Pt,redactable:Pt.matches(t),base:u.upstreams?.anthropic?.baseUrl}:Io.matches(t)?{kind:"responses",adapter:Io,redactable:!0,base:u.upstreams?.openai?.baseUrl}:{kind:"openai",adapter:Et,redactable:Et.matches(t),base:u.upstreams?.openai?.baseUrl}}function Mt(t,c){const u=String(t||"");if(Lo.has(u))return{agent:u,agentModel:""};const p=u.indexOf("/");if(p>0){const b=u.slice(0,p);if(Lo.has(b))return{agent:b,agentModel:u.slice(p+1)}}return{agent:c.bridge.agent,agentModel:""}}function Uo(t,c){return Mt(t,c).agent}function xs(t,c){if(c!=="openai"||!t)return!1;const u=Et.extractLatestToolResult(t);if(!u)return!1;const p=so(u.tool_call_id);return!!(p&&no(p.gwId))}function _s(t,c){try{const u=new URL(t),p=u.hostname.replace(/^\[|\]$/g,""),b=p==="127.0.0.1"||p==="localhost"||p==="::1",f=u.port||(u.protocol==="https:"?"443":"80");return b&&String(f)===String(c.port)}catch{return!1}}const Os=25*1024*1024;async function k(t,c){const u=[];let p=0;for await(const b of t){if(p+=b.length,c&&p>c){const f=new Error("payload too large");throw f.code=413,f}u.push(b)}return Buffer.concat(u)}function a(t,c,u){t.writeHead(c,{"content-type":"application/json"}),t.end(JSON.stringify(u))}function Vo(t){const c=t.redaction?.detection?.url;return!c||t.redaction?.detection?.backend==="off"?null:c}function Bt(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=L.health(),b=p.ok&&u==="full";return{source:"bundled",state:p.state,model:p.model||t?.ner?.model||null,installed:L.modelOnDisk(t?.ner?.model||void 0),error:p.error||null,ready:b,tier:u,coverage:b?"names":"patterns"}}async function Fo(t){if(L.state()!=="off"){const u=L.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=Vo(t);if(!c)return{configured:!1,ok:!1,url:null,model:null};try{const u=await tt(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 Es(t,c){const u={};for(const[p,b]of Object.entries(t)){const f=p.toLowerCase();f.startsWith("x-chatpanel-")||zo.has(f)||(u[p]=b)}u["accept-encoding"]="identity";try{u.host=new URL(c).host}catch{}return u}async function Wo(t,c,u,p){const b=Qt(c.vault),f=Ct();t.on("close",()=>{t.writableFinished||Ge(c.id)});const A=c.linkTurn||null,B=p?p.clock():0;let E=B,T=!0;const _=()=>{p&&T&&(p.lap("upstream",B),E=p.clock(),T=!1)};let R="";const j=()=>{c.redaction&&R&&Yt(R,c.redaction),R=""};let F=null;const P={onText:V=>{_(),rt(c.id);const z=b.push(V);z&&(R+=z,t.write(u.sseDelta(z)))},onToolRequest:({name:V,restoredArgs:z,toolId:Z})=>{if(_(),rt(c.id),c.ownerApprovals&&go(V)){F=z;return}const te=b.flush();te&&(R+=te,t.write(u.sseDelta(te))),t.write(u.sseToolCalls([{id:Z,name:V,arguments:JSON.stringify(z)}])),t.write(u.sseToolFinish(f.value)),p&&p.lap("stream",E),t.end(),p?.commit(),j()},onDone:()=>{const V=b.flush();V&&(R+=V,t.write(u.sseDelta(V))),t.write(u.sseTail(f.value)),p&&p.lap("stream",E),t.end(),A?.end("ok"),Ge(c.id),p?.commit(),j(),Dt(c)},onError:V=>{t.write(`data: ${JSON.stringify({error:{message:V.message,type:"bridge_error"}})}
|
|
15
15
|
|
|
16
|
-
`),t.end()
|
|
16
|
+
`),t.end(),A?.end("error",{code:"bridge_error"}),Ge(c.id),p?.commit(),Dt(c)},onUsage:V=>{f.add(V),A?.add(V)}};for(;;){if(F=null,await zr(c,P)!=="parked"||!F)return;const z=c.ownerApprovals,Z=new AbortController,te=()=>Z.abort();t.once("close",te);const oe=setInterval(()=>{rt(c.id),t.writableEnded||t.write(`: waiting for the owner’s approval
|
|
17
17
|
|
|
18
|
-
`)},15e3);oe.unref?.();let ye;try{ye=await z.inbox.ask(F,{partner:z.partner,device:z.device,conversation:z.conversation,signal:
|
|
18
|
+
`)},15e3);oe.unref?.();let ye;try{ye=await z.inbox.ask(F,{partner:z.partner,device:z.device,conversation:z.conversation,signal:Z.signal})}finally{clearInterval(oe),t.off("close",te)}if(Z.signal.aborted||t.writableEnded){Dt(c);return}try{await ao(c,JSON.stringify(ye))}catch(X){P.onError(X);return}}}function Dt(t){t.ownerApprovals?.turnScoped&&t.ownerApprovals.inbox.forget(t.ownerApprovals.conversation)}async function Ps(t,c,{kind:u,adapter:p,agent:b,run:f=null,owner:A=null,linkTurn:B=null},E,T,_,R,j,F=null,P=null){const{messages:V,system:z}=p.toTurn(E),{agentModel:Z}=Mt(E?.model,_),te=Do(_,{...Z?{model:Z}:{},...f||{}}),oe=ze(_.bridge.token),ye=yt(u,E?.model||b),X={tier:_.redaction.tier==="full"?"full":"basic",dictionary:ur(_.redaction,R),entities:[]},ge=await je(_),I=jr({vault:T,redactOpts:X,bridgeUrl:ge,token:oe,harness:F});A&&(I.ownerApprovals={...A,conversation:A.conversation||`partner.${A.device}.turn-${I.id}`,turnScoped:!A.conversation}),B&&(I.linkTurn=B,I.onEnd=()=>B.end("aborted")),T&&(I.redaction=_.redaction);let ee;try{ee=await Jr({bridgeUrl:ge,agent:b,token:oe,messages:V,system:z,specs:Gr(j),options:te,signal:void 0,approvals:!!A||Hr(j)})}catch(pe){return B?.end("error",{code:"bridge_error"}),Ge(I.id),P?.commit(),a(c,502,{error:{message:`bridge: ${pe.message}`,type:"bridge_error"}})}return I.reader=ee.body.getReader(),c.writeHead(200,{"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive"}),c.write(ye.sseHead()),Wo(c,I,ye,P)}async function $s(t,c,u,p,b=null){rt(c.id),c.rounds=(c.rounds||0)+1;try{const A=b?b.clock():0;await ao(c,u),b&&b.lap("redact",A)}catch(A){return c.linkTurn?.end("error",{code:"tool_result"}),Ge(c.id),b?.commit(),a(t,502,{error:{message:`tool-result: ${A.message}`,type:"bridge_error"}})}const f=yt("openai",p||"codex");return t.writeHead(200,{"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive"}),t.write(f.sseHead()),Wo(t,c,f,b)}function Ct(){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 As(t,c,{kind:u,adapter:p,redactable:b,pathname:f,agentOverride:A,harness:B,trace:E,run:T=null,owner:_=null,link:R=null},j,F,P,V){if(!b)return E?.commit(),a(c,404,{error:`endpoint ${f} not supported by the bridge backend`});if(u==="openai"){const K=p.extractLatestToolResult(j);if(K){const S=so(K.tool_call_id),ie=S&&no(S.gwId);if(ie)return $s(c,ie,K.content,j?.model,E)}const W=p.extractTools(j);if((W.length||_)&&j?.stream===!0){const S=A||Uo(j?.model,P),ie=R?$t.begin({...R,agentId:S}):null;return Ps(t,c,{kind:u,adapter:p,agent:S,run:T,owner:_,linkTurn:ie},j,F,P,V,W,B,E)}}const{messages:z,system:Z}=p.toTurn(j),te=A||Uo(j?.model,P),oe=R?$t.begin({...R,agentId:te}):null,ye=j?.stream===!0,X=yt(u,j?.model||te),ge=ze(P.bridge.token),I=new AbortController;c.on("close",()=>{c.writableFinished||I.abort()});const{agentModel:ee}=Mt(j?.model,P),pe={bridgeUrl:await je(P),agent:te,token:ge,messages:z,system:Z,signal:I.signal,options:Do(P,{...ee?{model:ee}:{},...T||{}})};if(!ye)try{let K="";const W=Ct(),S=E?E.clock():0;await oo(pe,Ae=>{K+=Ae},null,Ae=>W.add(Ae)),E&&E.lap("upstream",S);const ie=E?E.clock():0,We=X.full(cr(K,F),W.value);return E&&E.lap("restore",ie),c.writeHead(200,{"content-type":X.contentType}),c.end(We),oe?.add(W.value),oe?.end("ok"),E?.commit()}catch(K){return oe?.end(I.signal.aborted?"aborted":"error",{code:"bridge_error"}),E?.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(X.sseHead());const n=Qt(F),o=E?E.clock():0;let g=o;const l=Ct();let q="",H=!1;try{let K=!0;await oo(pe,S=>{E&&K&&(E.lap("upstream",o),g=E.clock(),K=!1);const ie=n.push(S);ie&&(q+=ie,c.write(X.sseDelta(ie)))},X.sseActivity?S=>{try{c.write(X.sseActivity(dr(S,F)))}catch{}}:null,S=>l.add(S));const W=n.flush();W&&(q+=W,c.write(X.sseDelta(W))),c.write(X.sseTail(l.value))}catch(K){H=!0,c.write(`data: ${JSON.stringify({error:{message:K.message,type:"bridge_error"}})}
|
|
19
19
|
|
|
20
|
-
`)}E&&E.lap("stream",f),d.end(),oe&&(oe.add(i.value),oe.end(C.signal.aborted?"aborted":H?"error":"ok",{code:"bridge_error"})),E?.commit(),F&&Z&&Kt(Z,P.redaction)}function Ps(t,d,u=""){const p=String(t||"").replace(/\/+$/,""),b=String(d||"").split("/")[1];return b&&p.endsWith(`/${b}`)?p.slice(0,-(b.length+1))+d+u:p+d+u}const $s=9e4;function As(t,d,u){if(d===u)return t;const p=d/u,b=new Float32Array(Math.floor(t.length/p));for(let y=0;y<b.length;y++){const $=y*p,B=Math.floor($),E=Math.min(t.length-1,B+1),T=$-B;b[y]=t[B]*(1-T)+t[E]*T}return b}const Wo=new WeakMap,Ns=["/tts","/stt","/ner","/diarize","/skills","/agent-defs","/agent-sessions","/a2a","/redact","/config","/logs","/status","/admin","/v1/browser","/v1/link"];function Ko(t,d){const u=at(d)?.license;return u&&t.stt?.licenses?.[u.id]?.version===u.version?To(u):null}function It(t,{installing:d=!1}={}){return t.stt?.diarize===!1?"off":d&&t.stt?.allowDownload!==!1?"download":"ondisk"}async function ve(t,d,u,p,{method:b="GET",timeoutMs:y=8e3,pick:$=B=>B}={}){const B=await je(u);if(!B)return a(d,503,{error:{message:"no bridge is configured",type:"no_bridge"}});const E=ze(u.bridge?.token),T=b!=="GET"&&b!=="DELETE";try{const _=T?(await S(t,u.maxBodyBytes)).toString("utf8"):"",R=await fetch(`${B}${p}`,{method:b,headers:{Accept:"application/json",...T?{"content-type":"application/json"}:{},...E?{Authorization:`Bearer ${E}`}:{}},...T?{body:_||"{}"}:{},signal:AbortSignal.timeout(y)}),j=await R.json().catch(()=>({}));return R.ok?a(d,200,$(j)):a(d,R.status,{error:{message:j?.error||`bridge ${R.status}`,type:"bridge_error"}})}catch(_){return a(d,502,{error:{message:`bridge unreachable: ${_.message}`,type:"bridge_unreachable"}})}}function Rt(t){return!t||t==="."||t===".."||t.includes("/")||t.includes("\\")}function Re(t,d){const u=new URLSearchParams;for(const y of t.searchParams.getAll("dir"))y&&u.append("dir",y);const p=t.searchParams.get("workdir")||String(d?.bridge?.workingDir||"").trim();p&&u.set("workdir",p);const b=u.toString();return b?`?${b}`:""}async function Bs(t,d,{adapter:u,kind:p,pathname:b,search:y,base:$,destKey:B,destProtocol:E,harness:T,trace:_,link:R=null},j,F){let P;const V=_?_.clock():0,z=R?$t.begin(R):null;let X=!1;const te=new AbortController;d.on("close",()=>{d.writableFinished||(X=!0,te.abort())});const oe=(C,ee)=>{z&&(z.add(ee),z.end(X?"aborted":C>=400?"error":"ok",{code:`http_${C}`}))};try{const C=xs(t.headers,$);B&&(E==="anthropic"?(C["x-api-key"]=B,delete C.authorization):C.authorization=`Bearer ${B}`);const ee=pr(Ps($,b,y)).toString();P=await fetch(ee,{method:t.method,headers:C,body:["GET","HEAD"].includes(t.method)?void 0:j,signal:te.signal})}catch(C){return X?(oe(499),_?.commit()):(z?.end("error",{code:"upstream_unreachable"}),_?.commit(),a(d,502,{error:`upstream fetch failed: ${C.message}`}))}const ye=P.headers.get("content-type")||"",Y={};if(P.headers.forEach((C,ee)=>{jo.has(ee.toLowerCase())||(Y[ee]=C)}),ye.includes("text/event-stream")&&P.body){_&&_.lap("upstream",V);const C=_?_.clock():0;d.writeHead(P.status,Y);const ee=z?_n():null,pe=ee?P.body.pipeThrough(ee.stream):P.body,n=p==="openai"?ar(pe,d,F,T):nr(pe,d,F);return Promise.resolve(n).catch(o=>{if(!X)throw o}).finally(()=>{_&&_.lap("stream",C),oe(P.status,ee?.usage()),_?.commit()})}let ge;try{ge=Buffer.from(await P.arrayBuffer())}catch(C){if(X)return oe(499),_?.commit();throw C}if(_&&_.lap("upstream",V),z&&oe(P.status,ye.includes("json")?On(ge.toString("utf8")):null),F&&ye.includes("application/json"))try{const C=_?_.clock():0,ee=u.restoreResponse(JSON.parse(ge.toString("utf8")),F,T);return _&&_.lap("restore",C),d.writeHead(P.status,{...Y,"content-type":"application/json"}),d.end(Buffer.from(JSON.stringify(ee),"utf8")),_?.commit()}catch{}d.writeHead(P.status,Y),d.end(ge),_?.commit()}function Ms(t=Wt()){const d=vr({first:async n=>{const o=Number(new URL(n).port),f=Un.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=wr({confirm:n=>typeof t.pairing?.confirm=="function"?t.pairing.confirm(n):br(n),newId:()=>kr()}),p=ea({version:ue}),b=ga({log:n=>console.log(` ${n}`)}),y=t.link?.enabled===!1?null:ta({settings:t.link||{},port:t.port,...t.link?.path?{path:t.link.path}:{},dispatch:({method:n,path:o,headers:f,body:i,device:Z,signal:H})=>fetch(`http://127.0.0.1:${pe.address()?.port||t.port}${o}`,{method:n,body:i,...H?{signal:H}:{},headers:{...f,"x-chatpanel-token":Me()||_e(),"x-chatpanel-link-device":String(Z||"")}}),ownerIsPro:()=>ke(t.pro?.entitlementToken),log:n=>console.log(` ${n}`)});t.stt?.diarizeModel&&t.stt.diarizeModel!==M.activeModel()&&(go(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 ${Pa}`));let $=null;const B=()=>{if(!$){const n=t.read||{};$=qn({remote:n.remote?.url?{url:n.remote.url,key:n.remote.key||""}:null,defaultProvider:n.provider||"defuddle"})}return $};let E=null;const T=()=>(E||(E=jn({wrap:(n,o,f,i)=>zn().wrap(n,o,f,i),onLog:n=>console.warn(`[extract worker] ${n}`)})),E);let _={at:0,fn:()=>"unknown"},R=null;async function j(){if(Date.now()-_.at<1e4)return _.fn;let n=new Map;try{const i=await P().health();for(const[Z,H]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,H)}}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 P().contextWindow(f.get(i)||i)}catch{return null}},o.card=i=>{try{return P().modelCard(f.get(i)||i)}catch{return null}},o.sig=JSON.stringify([...n.entries()].sort()),_={at:Date.now(),fn:o},_.fn}let F=null;const P=()=>(F||(F=Hn({cfg:t,bridgeHealth:async()=>{const n=await je(t);if(!n)return null;const o=ze(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,ce())}catch(n){console.warn(`[runtime] could not persist config: ${n.message}`)}},stateDir:Ue.join(Ue.dirname(ce()),"runtime"),workers:()=>{const n=E?.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)})),F),V=Number(t.runtime?.idleMinutes),z=Fn({warmMs:(Number.isFinite(V)&&V>=0?V:10)*6e4,log:n=>console.log(n)}),X=Vn({cfg:t,wake:(n,o)=>P().wake(n,o),embedded:z,asleep:n=>P().isAsleep(n)});let te=null;const oe=()=>(te||(te=Zn({store:Xn({log:n=>console.warn(`[kb] ${n}`)}),extract:T,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:()=>B(),completer:n=>async(o,{maxTokens:f=160}={})=>{const i=new AbortController,Z=setTimeout(()=>i.abort(),3e4);try{const H=Me()||_e(),K=await fetch(`http://127.0.0.1:${t.port}/v1/chat/completions`,{method:"POST",signal:i.signal,headers:{"content-type":"application/json",...H?{Authorization:`Bearer ${H}`}:{},"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)})),te),ye=()=>{t.search?.searxng?.url&&P().wake("searxng").catch(()=>{})};let Y=null;const ge=()=>{if(!Y){const n=t.search||{},o=n.searxng?.url?ka({url:n.searxng.url,token:n.searxng.token||"",engines:n.searxng.engines||"",safesearch:n.searxng.safesearch??null}):null;Y=wa({reader:B(),searxng:o,engines:()=>Sa(t),wakeSearxng:()=>P().wake("searxng"),defaultProvider:n.provider||"auto",redact:async f=>{let i=f;return await qe([ht(()=>i,Z=>{i=Z})],{...t.redaction,tier:"basic"},{isPro:!0}),i}})}return Y};yr(t.allowedExtensionIds||[]);const C=[],ee=n=>{C.push(n),C.length>50&&C.shift()},pe=tr(async(n,o)=>{const f=new URL(n.url,"http://127.0.0.1");let i=f.pathname;if(!ct(n.headers.host))return a(o,403,{error:"loopback only"});if(!ys(n.headers.origin,t))return a(o,403,{error:"origin not allowed"});if(ct(t.host)&&ra(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&&fs(o,n.headers.origin),n.method==="OPTIONS")return o.writeHead(204),o.end();if(i==="/admin/token"&&n.method==="POST")return G(n)?a(o,200,{token:_e()}):a(o,403,{error:"admin: extension origin or gateway token required"});if(i==="/pair/code"&&n.method==="POST"){if(!G(n))return a(o,403,{error:"pair/code: extension origin or gateway token required"});const e=fr();return console.log("[gateway] pairing code issued — valid for 5 minutes, one use"),a(o,200,{ok:!0,...e})}if(i==="/pair"&&n.method==="POST"){let e=null;try{e=JSON.parse((await S(n,t.maxBodyBytes)).toString("utf8"))}catch{e=null}const r=gr(e?.code);if(!r.ok)return console.log(`[gateway] pairing refused (${r.reason}) from ${Je(n)} caller`),a(o,403,{error:r.reason});console.log(`[gateway] paired a ${Je(n)} client${n.headers.origin?` (${n.headers.origin})`:""}`);const{token:s,refused:l}=await oo(t);return l&&console.log(`[gateway] pairing: the bridge at ${l.url}${l.version?` (v${l.version})`:""} accepts none of the tokens this gateway holds — not handing one over`),a(o,200,{ok:!0,token:Me()||_e(),...s?{bridgeToken:s}:{},...l?{bridgeRefused:l}:{}})}if(i==="/pair/ask"&&n.method==="POST"){const e=Je(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(Yt(e))return a(o,409,{error:"this client is already trusted by the gateway",type:"already"});if(e!=="unpaired")return a(o,403,{error:"pair/ask: only a browser extension may ask to be paired",type:"forbidden"});let r=null;try{r=JSON.parse((await S(n,t.maxBodyBytes)).toString("utf8")||"{}")}catch{r=null}const s=u.ask({browser:r?.browser,who:n.headers.origin||""});if(!s.ok){const l=s.reason==="busy"?"a pairing question is already on screen — answer it, or wait a minute":"too many pairing questions — wait a few minutes, or use a pairing code";return a(o,429,{error:l,type:s.reason})}return console.log(`[gateway] pairing: an unrecognised extension (${n.headers.origin}) asked — the question is on screen`),a(o,202,{ok:!0,id:s.id,number:s.number,expiresAt:s.expiresAt})}if(i==="/pair/ask/result"&&n.method==="POST"){let e=null;try{e=JSON.parse((await S(n,t.maxBodyBytes)).toString("utf8")||"{}")}catch{e=null}const{status:r}=u.result(e?.id,{who:n.headers.origin||""});if(r!=="allowed")return a(o,200,{ok:!0,status:r});console.log(`[gateway] paired ${n.headers.origin} — allowed in the dialog on this computer`);const{token:s,refused:l}=await oo(t);return a(o,200,{ok:!0,status:r,token:Me()||_e(),...s?{bridgeToken:s}:{},...l?{bridgeRefused:l}:{}})}if(i==="/whoami"&&n.method==="POST"){const e=Je(n);return a(o,200,{ok:!0,trust:e,paired:Yt(e),version:ue})}if(i==="/audit"&&n.method==="GET")return G(n)?a(o,200,Tr(t,{version:ue,startedAt:zo,managed:Le(),certificates:{..._r(),wanted:Xt(t)},linkPartners:y?y.status().devices.filter(e=>e.kind==="partner"):[],confined:wt({stateDir:Ue.dirname(ce())})})):a(o,403,{error:"audit: extension origin or gateway token required"});if((i==="/config"||i==="/logs"||i==="/update"&&n.method!=="GET")&&!G(n))return a(o,403,{error:"admin route: extension origin or gateway token required"});if(i==="/update"&&n.method==="GET"){const e=await hn(ue,{force:f.searchParams.get("force")==="1"}).catch(r=>({current:ue,updateAvailable:!1,error:String(r?.message||r)}));return a(o,200,{ok:!0,update:e,job:gn()})}if(i==="/update"&&n.method==="POST"){const e=fn(ue);return a(o,e.already?409:202,{ok:!0,job:e})}if((i==="/v1/history/key"||i==="/v1/history/ingest-backup")&&n.method==="POST"&&!G(n))return a(o,403,{error:{message:"history key route: extension origin or gateway token required",type:"forbidden"}});if(i==="/v1/history/records"&&n.method==="PUT"&&!G(n))return a(o,403,{error:{message:"history write — extension origin or gateway token required",type:"forbidden"}});if((i==="/v1/history/ingest"||i==="/v1/history/clear")&&n.method==="POST"&&!G(n))return a(o,403,{error:{message:"history write — extension origin or gateway token required",type:"forbidden"}});if((i==="/v1/memory/remember"||i==="/v1/memory/forget"||i==="/v1/memory/sync"||i==="/v1/memory/clear")&&n.method==="POST"&&!G(n))return a(o,403,{error:{message:"memory write — extension origin or gateway token required",type:"forbidden"}});if((i==="/v1/prefs"||i.startsWith("/v1/prefs/")||i.startsWith("/v1/teams")||i.startsWith("/v1/agents")||i.startsWith("/v1/projects"))&&!G(n))return a(o,403,{error:{message:"prefs: extension origin or gateway token required",type:"forbidden"}});if((i==="/v1/browser"||i.startsWith("/v1/browser/"))&&!G(n))return a(o,403,{error:{message:"browser: extension origin or gateway token required",type:"forbidden"}});if((i==="/v1/link"||i.startsWith("/v1/link/"))&&!G(n))return a(o,403,{error:{message:"link: extension origin or gateway token required",type:"forbidden"}});if((i==="/v1/events"||i.startsWith("/v1/events/"))&&!G(n))return a(o,403,{error:{message:"events: extension origin or gateway token required",type:"forbidden"}});if(i.startsWith("/v1/observability")&&!G(n))return a(o,403,{error:{message:"observability: extension origin or gateway token required",type:"forbidden"}});if(n.method==="GET"&&i==="/")return o.writeHead(200,{"content-type":"text/plain; charset=utf-8","cache-control":"no-store"}),o.end(`ChatPanel Privacy Gateway v${ue} is running.
|
|
20
|
+
`)}E&&E.lap("stream",g),c.end(),oe&&(oe.add(l.value),oe.end(I.signal.aborted?"aborted":H?"error":"ok",{code:"bridge_error"})),E?.commit(),F&&q&&Yt(q,P.redaction)}function Ns(t,c,u=""){const p=String(t||"").replace(/\/+$/,""),b=String(c||"").split("/")[1];return b&&p.endsWith(`/${b}`)?p.slice(0,-(b.length+1))+c+u:p+c+u}const Ko=9e4,It=60,Yo=It*16e3*4,Ms=4e3;function Bs(t,c,u){if(c===u)return t;const p=c/u,b=new Float32Array(Math.floor(t.length/p));for(let f=0;f<b.length;f++){const A=f*p,B=Math.floor(A),E=Math.min(t.length-1,B+1),T=A-B;b[f]=t[B]*(1-T)+t[E]*T}return b}const Qo=new WeakMap,Ds=["/tts","/stt","/ner","/diarize","/skills","/agent-defs","/agent-sessions","/a2a","/redact","/config","/logs","/status","/admin","/v1/browser","/v1/link","/v1/voice"];function Xo(t,c){const u=at(c)?.license;return u&&t.stt?.licenses?.[u.id]?.version===u.version?xo(u):null}function Rt(t,{installing:c=!1}={}){return t.stt?.diarize===!1?"off":c&&t.stt?.allowDownload!==!1?"download":"ondisk"}async function ve(t,c,u,p,{method:b="GET",timeoutMs:f=8e3,pick:A=B=>B}={}){const B=await je(u);if(!B)return a(c,503,{error:{message:"no bridge is configured",type:"no_bridge"}});const E=ze(u.bridge?.token),T=b!=="GET"&&b!=="DELETE";try{const _=T?(await k(t,u.maxBodyBytes)).toString("utf8"):"",R=await fetch(`${B}${p}`,{method:b,headers:{Accept:"application/json",...T?{"content-type":"application/json"}:{},...E?{Authorization:`Bearer ${E}`}:{}},...T?{body:_||"{}"}:{},signal:AbortSignal.timeout(f)}),j=await R.json().catch(()=>({}));return R.ok?a(c,200,A(j)):a(c,R.status,{error:{message:j?.error||`bridge ${R.status}`,type:"bridge_error"}})}catch(_){return a(c,502,{error:{message:`bridge unreachable: ${_.message}`,type:"bridge_unreachable"}})}}function Lt(t){return!t||t==="."||t===".."||t.includes("/")||t.includes("\\")}function Re(t,c){const u=new URLSearchParams;for(const f of t.searchParams.getAll("dir"))f&&u.append("dir",f);const p=t.searchParams.get("workdir")||String(c?.bridge?.workingDir||"").trim();p&&u.set("workdir",p);const b=u.toString();return b?`?${b}`:""}async function Cs(t,c,{adapter:u,kind:p,pathname:b,search:f,base:A,destKey:B,destProtocol:E,harness:T,trace:_,link:R=null},j,F){let P;const V=_?_.clock():0,z=R?$t.begin(R):null;let Z=!1;const te=new AbortController;c.on("close",()=>{c.writableFinished||(Z=!0,te.abort())});const oe=(I,ee)=>{z&&(z.add(ee),z.end(Z?"aborted":I>=400?"error":"ok",{code:`http_${I}`}))};try{const I=Es(t.headers,A);B&&(E==="anthropic"?(I["x-api-key"]=B,delete I.authorization):I.authorization=`Bearer ${B}`);const ee=fr(Ns(A,b,f)).toString();P=await fetch(ee,{method:t.method,headers:I,body:["GET","HEAD"].includes(t.method)?void 0:j,signal:te.signal})}catch(I){return Z?(oe(499),_?.commit()):(z?.end("error",{code:"upstream_unreachable"}),_?.commit(),a(c,502,{error:`upstream fetch failed: ${I.message}`}))}const ye=P.headers.get("content-type")||"",X={};if(P.headers.forEach((I,ee)=>{zo.has(ee.toLowerCase())||(X[ee]=I)}),ye.includes("text/event-stream")&&P.body){_&&_.lap("upstream",V);const I=_?_.clock():0;c.writeHead(P.status,X);const ee=z?Pn():null,pe=ee?P.body.pipeThrough(ee.stream):P.body,n=p==="openai"?lr(pe,c,F,T):ir(pe,c,F);return Promise.resolve(n).catch(o=>{if(!Z)throw o}).finally(()=>{_&&_.lap("stream",I),oe(P.status,ee?.usage()),_?.commit()})}let ge;try{ge=Buffer.from(await P.arrayBuffer())}catch(I){if(Z)return oe(499),_?.commit();throw I}if(_&&_.lap("upstream",V),z&&oe(P.status,ye.includes("json")?$n(ge.toString("utf8")):null),F&&ye.includes("application/json"))try{const I=_?_.clock():0,ee=u.restoreResponse(JSON.parse(ge.toString("utf8")),F,T);return _&&_.lap("restore",I),c.writeHead(P.status,{...X,"content-type":"application/json"}),c.end(Buffer.from(JSON.stringify(ee),"utf8")),_?.commit()}catch{}c.writeHead(P.status,X),c.end(ge),_?.commit()}function Is(t=Kt()){const c=Tr({first:async n=>{const o=Number(new URL(n).port),g=Wn.find(l=>l.port===o&&(l.provides||[]).includes("chat"));return g&&(await j())(g.id)==="up"?{engine:g.id,label:g.label,models:null}:null}}),u=kr({confirm:n=>typeof t.pairing?.confirm=="function"?t.pairing.confirm(n):Sr(n),newId:()=>xr()}),p=ra({version:ue}),b=va({log:n=>console.log(` ${n}`)}),f=t.link?.enabled===!1?null:na({settings:t.link||{},port:t.port,...t.link?.path?{path:t.link.path}:{},dispatch:({method:n,path:o,headers:g,body:l,device:q,signal:H})=>fetch(`http://127.0.0.1:${pe.address()?.port||t.port}${o}`,{method:n,body:l,...H?{signal:H}:{},headers:{...g,"x-chatpanel-token":Be()||_e(),"x-chatpanel-link-device":String(q||"")}}),ownerIsPro:()=>ke(t.pro?.entitlementToken),log:n=>console.log(` ${n}`)});t.stt?.diarizeModel&&t.stt.diarizeModel!==$.activeModel()&&(wo(t.stt.diarizeModel)?$.setModel(t.stt.diarizeModel,{log:n=>console.log(n)}):console.warn(`[diarize] config names an unknown speaker model (${t.stt.diarizeModel}) — using ${Na}`));let A=null;const B=()=>{if(!A){const n=t.read||{};A=oa({remote:n.remote?.url?{url:n.remote.url,key:n.remote.key||""}:null,defaultProvider:n.provider||"defuddle"})}return A};let E=null;const T=()=>(E||(E=Hn({wrap:(n,o,g,l)=>Un().wrap(n,o,g,l),onLog:n=>console.warn(`[extract worker] ${n}`)})),E);let _={at:0,fn:()=>"unknown"},R=null;async function j(){if(Date.now()-_.at<1e4)return _.fn;let n=new Map;try{const l=await P().health();for(const[q,H]of Object.entries(l)){const K=(t.destinations||[]).filter(W=>W?.service===q).flatMap(W=>[W.id,...W.models||[]]);for(const W of[q,...K])n.set(W,H)}}catch{n=new Map}const o=l=>n.get(l)||"unknown",g=new Map((t.destinations||[]).filter(l=>l?.service).map(l=>[l.id,l.service]));return o.window=l=>{try{return P().contextWindow(g.get(l)||l)}catch{return null}},o.card=l=>{try{return P().modelCard(g.get(l)||l)}catch{return null}},o.sig=JSON.stringify([...n.entries()].sort()),_={at:Date.now(),fn:o},_.fn}let F=null;const P=()=>(F||(F=Fn({cfg:t,bridgeHealth:async()=>{const n=await je(t);if(!n)return null;const o=ze(t.bridge?.token),g=await fetch(`${n}/health`,{headers:{Accept:"application/json",...o?{Authorization:`Bearer ${o}`}:{}},signal:AbortSignal.timeout(4e3)});return g.ok?g.json():null},persist:()=>{try{be(t,ce())}catch(n){console.warn(`[runtime] could not persist config: ${n.message}`)}},stateDir:Ue.join(Ue.dirname(ce()),"runtime"),workers:()=>{const n=E?.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)})),F),V=Number(t.runtime?.idleMinutes),z=Yn({warmMs:(Number.isFinite(V)&&V>=0?V:10)*6e4,log:n=>console.log(n)}),Z=Kn({cfg:t,wake:(n,o)=>P().wake(n,o),embedded:z,asleep:n=>P().isAsleep(n)});let te=null;const oe=()=>(te||(te=ta({store:ea({log:n=>console.warn(`[kb] ${n}`)}),extract:T,embedded:z,cfg:t,rerank:async(n,o)=>{const g=await Z.call("rerank",{query:n,documents:o.map(q=>String(q).slice(0,2e3))});if(g.status!==200)return null;const l=new Array(o.length).fill(0);for(const q of g.body.results||[])l[q.index]=q.relevance_score;return l},read:()=>B(),completer:n=>async(o,{maxTokens:g=160}={})=>{const l=new AbortController,q=setTimeout(()=>l.abort(),3e4);try{const H=Be()||_e(),K=await fetch(`http://127.0.0.1:${t.port}/v1/chat/completions`,{method:"POST",signal:l.signal,headers:{"content-type":"application/json",...H?{Authorization:`Bearer ${H}`}:{},"X-ChatPanel-Client":"kb"},body:JSON.stringify({model:n,messages:[{role:"user",content:o}],stream:!1,max_tokens:g,temperature:0})}),W=await K.json().catch(()=>({}));return K.ok?String(W?.choices?.[0]?.message?.content||""):""}finally{clearTimeout(q)}},log:n=>console.warn(n)})),te),ye=()=>{t.search?.searxng?.url&&P().wake("searxng").catch(()=>{})};let X=null;const ge=()=>{if(!X){const n=t.search||{},o=n.searxng?.url?xa({url:n.searxng.url,token:n.searxng.token||"",engines:n.searxng.engines||"",safesearch:n.searxng.safesearch??null}):null;X=ka({reader:B(),searxng:o,engines:()=>_a(t),wakeSearxng:()=>P().wake("searxng"),defaultProvider:n.provider||"auto",redact:async g=>{let l=g;return await qe([ht(()=>l,q=>{l=q})],{...t.redaction,tier:"basic"},{isPro:!0}),l}})}return X};wr(t.allowedExtensionIds||[]);const I=[],ee=n=>{I.push(n),I.length>50&&I.shift()},pe=nr(async(n,o)=>{const g=new URL(n.url,"http://127.0.0.1");let l=g.pathname;if(!ct(n.headers.host))return a(o,403,{error:"loopback only"});if(!ws(n.headers.origin,t))return a(o,403,{error:"origin not allowed"});if(ct(t.host)&&sa(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&&bs(o,n.headers.origin),n.method==="OPTIONS")return o.writeHead(204),o.end();if(l==="/admin/token"&&n.method==="POST")return G(n)?a(o,200,{token:_e()}):a(o,403,{error:"admin: extension origin or gateway token required"});if(l==="/pair/code"&&n.method==="POST"){if(!G(n))return a(o,403,{error:"pair/code: extension origin or gateway token required"});const e=br();return console.log("[gateway] pairing code issued — valid for 5 minutes, one use"),a(o,200,{ok:!0,...e})}if(l==="/pair"&&n.method==="POST"){let e=null;try{e=JSON.parse((await k(n,t.maxBodyBytes)).toString("utf8"))}catch{e=null}const r=vr(e?.code);if(!r.ok)return console.log(`[gateway] pairing refused (${r.reason}) from ${Le(n)} caller`),a(o,403,{error:r.reason});console.log(`[gateway] paired a ${Le(n)} client${n.headers.origin?` (${n.headers.origin})`:""}`);const{token:s,refused:i}=await ro(t);return i&&console.log(`[gateway] pairing: the bridge at ${i.url}${i.version?` (v${i.version})`:""} accepts none of the tokens this gateway holds — not handing one over`),a(o,200,{ok:!0,token:Be()||_e(),...s?{bridgeToken:s}:{},...i?{bridgeRefused:i}:{}})}if(l==="/pair/ask"&&n.method==="POST"){const e=Le(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(Xt(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 k(n,t.maxBodyBytes)).toString("utf8")||"{}")}catch{r=null}const s=u.ask({browser:r?.browser,who:n.headers.origin||""});if(!s.ok){const i=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:i,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(l==="/pair/ask/result"&&n.method==="POST"){let e=null;try{e=JSON.parse((await k(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:i}=await ro(t);return a(o,200,{ok:!0,status:r,token:Be()||_e(),...s?{bridgeToken:s}:{},...i?{bridgeRefused:i}:{}})}if(l==="/whoami"&&n.method==="POST"){const e=Le(n);return a(o,200,{ok:!0,trust:e,paired:Xt(e),version:ue})}if(l==="/audit"&&n.method==="GET")return G(n)?a(o,200,Or(t,{version:ue,startedAt:Go,managed:Je(),certificates:{...Pr(),wanted:Zt(t)},linkPartners:f?f.status().devices.filter(e=>e.kind==="partner"):[],confined:wt({stateDir:Ue.dirname(ce())})})):a(o,403,{error:"audit: extension origin or gateway token required"});if((l==="/config"||l==="/logs"||l==="/update"&&n.method!=="GET")&&!G(n))return a(o,403,{error:"admin route: extension origin or gateway token required"});if(l==="/update"&&n.method==="GET"){const e=await gn(ue,{force:g.searchParams.get("force")==="1"}).catch(r=>({current:ue,updateAvailable:!1,error:String(r?.message||r)}));return a(o,200,{ok:!0,update:e,job:vn()})}if(l==="/update"&&n.method==="POST"){const e=bn(ue);return a(o,e.already?409:202,{ok:!0,job:e})}if((l==="/v1/history/key"||l==="/v1/history/ingest-backup")&&n.method==="POST"&&!G(n))return a(o,403,{error:{message:"history key route: extension origin or gateway token required",type:"forbidden"}});if(l==="/v1/history/records"&&n.method==="PUT"&&!G(n))return a(o,403,{error:{message:"history write — extension origin or gateway token required",type:"forbidden"}});if((l==="/v1/history/ingest"||l==="/v1/history/clear")&&n.method==="POST"&&!G(n))return a(o,403,{error:{message:"history write — extension origin or gateway token required",type:"forbidden"}});if((l==="/v1/memory/remember"||l==="/v1/memory/forget"||l==="/v1/memory/sync"||l==="/v1/memory/clear")&&n.method==="POST"&&!G(n))return a(o,403,{error:{message:"memory write — extension origin or gateway token required",type:"forbidden"}});if((l==="/v1/prefs"||l.startsWith("/v1/prefs/")||l.startsWith("/v1/teams")||l.startsWith("/v1/agents")||l.startsWith("/v1/projects"))&&!G(n))return a(o,403,{error:{message:"prefs: extension origin or gateway token required",type:"forbidden"}});if((l==="/v1/browser"||l.startsWith("/v1/browser/"))&&!G(n))return a(o,403,{error:{message:"browser: extension origin or gateway token required",type:"forbidden"}});if((l==="/v1/link"||l.startsWith("/v1/link/"))&&!G(n))return a(o,403,{error:{message:"link: extension origin or gateway token required",type:"forbidden"}});if((l==="/v1/events"||l.startsWith("/v1/events/"))&&!G(n))return a(o,403,{error:{message:"events: extension origin or gateway token required",type:"forbidden"}});if(l.startsWith("/v1/observability")&&!G(n))return a(o,403,{error:{message:"observability: extension origin or gateway token required",type:"forbidden"}});if(n.method==="GET"&&l==="/")return o.writeHead(200,{"content-type":"text/plain; charset=utf-8","cache-control":"no-store"}),o.end(`ChatPanel Privacy Gateway v${ue} 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"&&
|
|
25
|
+
`);if(n.method==="GET"&&l==="/health"){const e=N.health(),r=C.health();return a(o,200,{ok:!0,version:ue,backend:t.backend,tier:t.redaction.tier,pairing:!0,pairPrompt:t.pairing?.prompt!==!1,...Je()?{managed:Je()}:{},...process.env.CHATPANEL_MANAGED_BY?{managedBy:String(process.env.CHATPANEL_MANAGED_BY).slice(0,32)}:{},install:kn(),confined:wt({stateDir:Ue.dirname(ce())}),...Tn({release:St.release()})?{appleHelper:!!bt()}:{},...Fe?{bridge:Fe.status()}:ut?{bridge:ut}:{},search:{provider:t.search?.provider||"auto",searxng:!!t.search?.searxng?.url},stt:{enabled:t.stt?.enabled!==!1,state:e.state,ready:e.ok,model:e.model||t.stt?.model||De,runtime:e.runtime,dtype:e.dtype},tts:{enabled:t.tts?.enabled!==!1,state:r.state,ready:r.ok,model:r.model||t.tts?.model||Po,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(l==="/status"&&n.method==="GET"){sr(t);const e=await ke(t.pro?.entitlementToken),r=await Fo(t);return a(o,200,{ok:!0,version:ue,backend:t.backend,tier:t.redaction.tier,search:{provider:t.search?.provider||"auto",searxng:!!t.search?.searxng?.url},...Je()?{managed:Je()}:{},...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:Bt(t),pro:{unlocked:e},usage:es(t),uptimeSeconds:Math.floor((Date.now()-Go)/1e3),update:wn(ue)})}if(l==="/v1/history/ingest"&&n.method==="POST")try{const e=JSON.parse((await k(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(l==="/v1/prefs"&&n.method==="GET"){const e=String(g.searchParams.get("section")||"");return g.searchParams.get("stamps")?a(o,200,{ok:!0,revision:me.revision,stamps:me.stamps()}):a(o,200,{ok:!0,revision:me.revision,sections:me.get(e)})}if(l==="/v1/prefs"&&(n.method==="POST"||n.method==="PUT"))try{const e=JSON.parse((await k(n,t.maxBodyBytes)).toString("utf8"))||{},r=me.put(e.sections||{},{by:e.by||""});return r.applied.length&&Ro(r.applied,e.by||""),a(o,200,{ok:!0,...r})}catch(e){return a(o,400,{error:{message:`prefs write failed: ${e.message}`,type:"prefs_error"}})}if(l==="/v1/prefs"&&n.method==="DELETE"){const e=String(g.searchParams.get("section")||""),r=e?me.remove(e):!1;return r&&Ro([e],""),a(o,200,{ok:!0,removed:r})}if(l==="/v1/prefs/events"&&n.method==="GET"){o.writeHead(200,{"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive"});const e=i=>o.write(`data: ${JSON.stringify(i)}
|
|
26
26
|
|
|
27
|
-
`);e({type:"hello",revision:me.revision,stamps:me.stamps()});const r=
|
|
27
|
+
`);e({type:"hello",revision:me.revision,stamps:me.stamps()});const r=i=>e({type:"changed",...i});At.add(r);const s=setInterval(()=>{try{o.write(`: keep-alive
|
|
28
28
|
|
|
29
|
-
`)}catch{}},25e3);o.on("close",()=>{At.delete(r),clearInterval(s)});return}if(
|
|
29
|
+
`)}catch{}},25e3);o.on("close",()=>{At.delete(r),clearInterval(s)});return}if(l==="/v1/projects"&&n.method==="GET")return a(o,200,{ok:!0,projects:he.list({limit:g.searchParams.get("limit")||50,status:g.searchParams.get("status")||""})});if(l==="/v1/projects/jobs"&&n.method==="GET")return a(o,200,{ok:!0,jobs:he.openJobs()});if(l==="/v1/projects"&&n.method==="POST")try{const e=JSON.parse((await k(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(l);if(e){const r=e[1],s=e[2]||"",i=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 y=h.jobs.find(v=>v.id===i);if(!y)return a(o,404,{error:{message:`no job ${i}`,type:"not_found"}});const w={cfg:t,prefsStore:me,scorecards:Ce,engines:Ie,engineAt:c.engineAt};if(d==="/applications"&&n.method==="GET"){const v=await pn(y,{...w,reach:g.searchParams.get("reach")||"any",chatModel:g.searchParams.get("chatModel")||null});return a(o,200,{ok:!0,job:y,...v})}if(d==="/recruit"&&n.method==="POST"){if(!["open","evaluating"].includes(y.status))return a(o,400,{error:{message:`job ${i} is ${y.status}; only an open job is recruited`,type:"project_error"}});try{const v=JSON.parse((await k(n,t.maxBodyBytes)).toString("utf8"))||{},O=String(v.by||"evaluator").slice(0,80),x=await hn(y,{...w,record:h,reach:v.reach||"any",chatModel:v.chatModel||null,evaluation:v.evaluation||null,text:v.text??null,by:O});let D=null;for(const Y of x.events)Y.type==="job.updated"?D=he.updateJob(r,i,Y.job,{by:Y.by||O}):D=he.append(r,[Y]);return a(o,200,{ok:!0,project:D,decision:x.decision,applications:x.applications,evaluation:x.evaluation})}catch(v){return a(o,400,{error:{message:`recruit: ${v.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:g.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 k(n,t.maxBodyBytes)).toString("utf8"))||{},y=String(h.by||"person").slice(0,80),w=s==="/events"?he.append(r,h.events||[]):i?he.updateJob(r,i,h.patch||h,{by:y}):he.postJob(r,h.job||h,{by:y});return a(o,200,{ok:!0,project:w})}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=O=>o.write(`data: ${JSON.stringify(O)}
|
|
30
30
|
|
|
31
|
-
`);let g
|
|
31
|
+
`);let y=g.searchParams.has("after")?Number(g.searchParams.get("after")):-1;h({seq:-1,type:"hello",at:Date.now(),payload:{project:he.get(r),after:y}});const w=he.watch(r,O=>{O.seq>y&&(y=O.seq,h(O))});for(const O of he.eventsSince(r,y))y=O.seq,h(O);const v=setInterval(()=>{try{o.write(`: keep
|
|
32
32
|
|
|
33
|
-
`)}catch{}},25e3);n.on("close",()=>{clearInterval(v),w()});return}}}if(
|
|
33
|
+
`)}catch{}},25e3);n.on("close",()=>{clearInterval(v),w()});return}}}if(l==="/v1/agents/scorecards"&&n.method==="GET")return a(o,200,{ok:!0,agents:Ce.list()});{const e=/^\/v1\/agents\/([a-zA-Z0-9_.:@+-]{1,120})\/scorecard$/.exec(l);if(e){const r=decodeURIComponent(e[1]);if(n.method==="GET")return a(o,200,{ok:!0,...await Ce.get(r)});if(n.method==="POST")try{const s=JSON.parse((await k(n,t.maxBodyBytes)).toString("utf8"))||{},i=await Ce.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 Ie.fromRating(Ce.chains.get(r)||[],{...i,jobKind:s.jobKind?String(s.jobKind).slice(0,60):void 0}),a(o,200,{ok:!0,entry:i})}catch(s){return a(o,400,{error:{message:`scorecard: ${s.message}`,type:"scorecard_error"}})}}}if(l==="/v1/capabilities"&&n.method==="GET")return a(o,200,zn(t,{version:ue,reader:A,searcher:X,extract:T(),proxy:Z}));if(l==="/v1/fusions"&&n.method==="GET"){const e={active:L.health().model||t.ner?.model||null,companions:L.companions()};let r=null;try{r=await P().status()}catch{r=null}return a(o,200,Dn({cfg:t,ner:e,runtimeDoc:r}))}if(l==="/v1/runtime"&&n.method==="GET"){const e=Object.fromEntries(Xn.map(r=>{const s=_t(t,r);return[r,{provider:s.kind,model:s.kind==="embedded"?s.model:null,models:Qn[r],threads:z.threads,...s.kind==="embedded"?z.health(r,s.model):{}}]}));return a(o,200,{...await P().status(),inProcess:e})}if(l==="/v1/runtime/recipe"&&n.method==="GET"){if(!G(n))return a(o,403,{error:"runtime: extension origin or gateway token required"});const e=new URL(n.url,"http://x").searchParams,r=await P().recipe(String(e.get("service")||"llama"),e.get("model"));return a(o,r.ok?200:400,r)}if(l==="/v1/runtime/plan"&&n.method==="GET"){const e=new URL(n.url,"http://x").searchParams,r=await P().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(l);if(e&&n.method==="POST"){if(!G(n))return a(o,403,{error:"runtime: extension origin or gateway token required"});let r={};try{r=JSON.parse((await k(n,t.maxBodyBytes)).toString("utf8")||"{}")}catch{r={}}const s=String(r.action||"start"),i=P(),d=e[1]==="engines"?s==="start"?await i.startEngine(e[2]):{ok:!1,error:`unknown action ${s}`}:s==="start"?await i.startService(e[2],{force:r.force===!0}):s==="stop"?await i.stopService(e[2]):s==="model"?await i.setModel(e[2],r.model,{tunings:r.tunings||null}):s==="tune"?await i.setTunings(e[2],r.tunings):s==="profile"?await i.setProfile(e[2],r.profile):s==="pull"?await i.pullModel(e[2]):s==="install"?await i.installRunner(e[2]):s==="update"?await i.updateRunner(e[2]):s==="build"?await i.setBuild(e[2],String(r.build||"")):s==="cancel"?i.cancelJob(e[2]):s==="remove"?await i.removeService(e[2]):{ok:!1,error:`unknown action ${s}`};return a(o,d.ok?200:400,d)}}if(l==="/v1/embeddings"&&n.method==="POST"){let e;try{e=JSON.parse((await k(n,t.maxBodyBytes)).toString("utf8"))}catch{return a(o,400,{error:{message:"embed: body must be JSON",type:"invalid_request"}})}const r=await Z.call("embed",e);return a(o,r.status,r.body)}if((l==="/v1/rerank"||l==="/v1/decide")&&n.method==="POST"){const e=l.slice(4);let r;try{r=JSON.parse((await k(n,t.maxBodyBytes)).toString("utf8"))}catch{return a(o,400,{error:{message:`${e}: body must be JSON`,type:"invalid_request"}})}const s=await Z.call(e,r);return a(o,s.status,s.body)}if(l==="/v1/detect"&&n.method==="POST"){let e;try{e=JSON.parse((await k(n,t.maxBodyBytes)).toString("utf8"))}catch{return a(o,400,{error:{message:"detect: body must be JSON",type:"invalid_request"}})}try{const r=await Gn(e,{ensure:()=>nt(t),model:L.health().model});return a(o,r.status,r.body)}catch(r){return a(o,500,{error:{message:`detect: ${r.message}`,type:"detector_error"}})}}if(l==="/v1/extract/context"&&n.method==="POST"){let e;try{e=JSON.parse((await k(n,Math.max(t.maxBodyBytes,Math.ceil(Tt*4/3)+1024))).toString("utf8"))}catch{return a(o,400,{error:{message:"extract/context: body must be JSON",type:"invalid_request"}})}const r=await qn(e,{service:T()});return a(o,r.status,r.body)}if((l==="/v1/files/write"||l==="/v1/files/exists")&&n.method==="POST"){if(!G(n)||He(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 k(n,Math.max(t.maxBodyBytes,ba*6+4096))).toString("utf8"))}catch{return a(o,400,{error:{message:"files: body must be JSON",type:"invalid_request"}})}const r=await fa(l.slice(10),e);return a(o,r.status,r.body)}if(l==="/v1/files/fs"&&n.method==="POST"){if(!G(n)||He(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 k(n,64*1024)).toString("utf8"))}catch{return a(o,400,{error:{message:"files: body must be JSON",type:"invalid_request"}})}const r=await ga(e);return a(o,r.status,r.body)}if(l==="/v1/import/apple-notes"&&n.method==="POST"){if(!G(n)||He(n.headers))return a(o,403,{error:{message:"apple-notes: a client on this computer with the gateway token or the pinned extension only",type:"forbidden"}});let e;try{e=JSON.parse((await k(n,t.maxBodyBytes)).toString("utf8"))}catch{return a(o,400,{error:{message:"apple-notes: body must be JSON",type:"invalid_request"}})}const r=await wa(e);return a(o,r.status,r.body)}if(l==="/v1/extract"&&n.method==="POST"){let e;try{e=JSON.parse((await k(n,Math.max(t.maxBodyBytes,Math.ceil(Tt*4/3)+1024))).toString("utf8"))}catch{return a(o,400,{error:{message:"extract: body must be JSON",type:"invalid_request"}})}const r=await Zn(e,{service:T()});return a(o,r.status,r.body)}if(l==="/v1/read"&&n.method==="POST"){let e;try{e=JSON.parse((await k(n,t.maxBodyBytes)).toString("utf8"))}catch{return a(o,400,{error:{message:"read: body must be JSON",type:"invalid_request"}})}const r=await B().read(e);return a(o,r.status,r.body)}if(l==="/v1/search"&&n.method==="POST"){let e;try{e=JSON.parse((await k(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(l)&&n.method==="GET"){let e;try{e=decodeURIComponent(l.slice(11))}catch{e=l.slice(11)}const r=g.searchParams.has("read")?Math.max(0,Math.min(10,Number(g.searchParams.get("read"))||0)):Ta.aliasRead;ye();const s=await ge().search({q:e,read:r,limit:Math.max(r,5)});return a(o,s.status,s.status===200?Sa(s.body):s.body)}if(/^\/v1\/read\/./.test(l)&&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||""),i=/^text$/i.test(n.headers["x-return-format"]||"")?"text":"markdown",d=await B().read({url:r,format:i});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(Oa(d.body)))}if(l==="/v1/engines"&&n.method==="GET"){const e=Number(g.searchParams.get("minCalls"))||void 0;return a(o,200,{ok:!0,engines:Ie.list({minCalls:e})})}{const e=/^\/v1\/engines\/(.+)\/(card|entries)$/.exec(l);if(e){const r=decodeURIComponent(e[1]).slice(0,300);if(e[2]==="card"&&n.method==="GET"){const s=Number(g.searchParams.get("minCalls"))||void 0;return a(o,200,{ok:!0,...await Ie.get(r,{entries:g.searchParams.get("entries")==="1",minCalls:s})})}if(e[2]==="entries"&&n.method==="POST")try{const s=JSON.parse((await k(n,t.maxBodyBytes)).toString("utf8"))||{},i=s.engine||ks(r);if(!i)return a(o,400,{error:{message:"model-ledger: engine required",type:"model_ledger_error"}});const d=await Ie.append({...s,engine:i,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(l==="/v1/teams/stream"&&n.method==="GET"){o.writeHead(200,{"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive"});const e=i=>{try{o.write(`data: ${JSON.stringify(i)}
|
|
34
34
|
|
|
35
|
-
`)}catch{}};e({type:"hello",at:Date.now()});const r=re.watchAll(
|
|
35
|
+
`)}catch{}};e({type:"hello",at:Date.now()});const r=re.watchAll(i=>e({type:"run",id:i.id,removed:!!i.removed})),s=setInterval(()=>{try{o.write(`: keep-alive
|
|
36
36
|
|
|
37
|
-
`)}catch{}},25e3);o.on("close",()=>{r(),clearInterval(s)});return}if(
|
|
37
|
+
`)}catch{}},25e3);o.on("close",()=>{r(),clearInterval(s)});return}if(l==="/v1/teams/runs"&&n.method==="GET")return a(o,200,{ok:!0,runs:re.list({limit:g.searchParams.get("limit")||50,team:g.searchParams.get("team")||""})});if(l==="/v1/teams/runs"&&n.method==="POST")try{const e=JSON.parse((await k(n,t.maxBodyBytes)).toString("utf8"))||{};return a(o,200,{ok:!0,run:re.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(l);if(e){const r=e[1],s=e[2]||"";if(!s&&n.method==="GET"){const i=re.get(r,{events:g.searchParams.get("events")==="1"});return i?a(o,200,{ok:!0,run:i}):a(o,404,{error:{message:`no run ${r}`,type:"not_found"}})}if(!s&&n.method==="DELETE")return re.stop(r),a(o,200,{ok:!0,removed:re.remove(r)});if(s==="/stop"&&n.method==="POST"){const i=re.stop(r);return i?a(o,200,{ok:!0,run:i}):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:re.checkpoint(r)})}catch(i){return a(o,404,{error:{message:`team run: ${i.message}`,type:"team_error"}})}if((s==="/handoff"||s==="/claim")&&n.method==="POST")try{const i=JSON.parse((await k(n,t.maxBodyBytes)).toString("utf8"))||{},d=s==="/handoff"?re.handoff(r,{taskId:i.taskId,model:i.model,by:i.by,reason:i.reason}):re.claim(r,{client:i.client});return a(o,200,{ok:!0,run:d})}catch(i){return a(o,i.message.startsWith("no ")?404:400,{error:{message:`team run: ${i.message}`,type:"team_error"}})}if(s.startsWith("/threads/")&&n.method==="DELETE")try{return a(o,200,{ok:!0,run:re.removeThread(r,{threadId:s.slice(9),by:"person"})})}catch(i){return a(o,i.message.startsWith("no ")?404:400,{error:{message:`team run: ${i.message}`,type:"team_error"}})}if((s==="/answer"||s==="/decide"||s==="/post")&&n.method==="POST")try{const i=JSON.parse((await k(n,t.maxBodyBytes)).toString("utf8"))||{},d=String(i.by||"person").slice(0,40),m=s==="/answer"?re.answer(r,{threadId:i.threadId,text:i.text,by:d}):s==="/decide"?re.decide(r,{postId:i.postId,status:i.status,by:d}):re.post(r,{threadId:i.threadId,text:i.text,by:d,kind:i.kind,replyTo:i.replyTo});return a(o,200,{ok:!0,run:m})}catch(i){return a(o,i.message.startsWith("no ")?404:400,{error:{message:`team run: ${i.message}`,type:"team_error"}})}if(s==="/events"&&n.method==="POST")try{const i=JSON.parse((await k(n,t.maxBodyBytes)).toString("utf8"))||{};return a(o,200,{ok:!0,run:re.append(r,i.events||[])})}catch(i){return a(o,i.message.startsWith("no run")?404:400,{error:{message:`team run: ${i.message}`,type:"team_error"}})}if(s==="/events"&&n.method==="GET"){if(!re.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 i=w=>o.write(`data: ${JSON.stringify(w)}
|
|
38
38
|
|
|
39
|
-
`),
|
|
39
|
+
`),d=g.searchParams.has("after")?Number(g.searchParams.get("after")):NaN;let m=Number.isFinite(d)?d:-1;i({seq:-1,type:"hello",at:Date.now(),payload:{run:re.get(r),after:m}});const h=re.watch(r,w=>{w.seq==null?i(w):w.seq>m&&(m=w.seq,i(w))});for(const w of re.eventsSince(r,m))m=w.seq,i(w);const y=setInterval(()=>{try{o.write(`: keep-alive
|
|
40
40
|
|
|
41
|
-
`)}catch{}},25e3);o.on("close",()=>{h(),clearInterval(
|
|
42
|
-
data: ${JSON.stringify({...s?{all:!0}:{host:r},deleted:
|
|
41
|
+
`)}catch{}},25e3);o.on("close",()=>{h(),clearInterval(y)});return}}}if(l==="/v1/memory/list"&&n.method==="GET")return a(o,200,{ok:!0,size:fe.size,memories:fe.list()});if(l==="/v1/memory/recall"&&n.method==="POST")try{const e=JSON.parse((await k(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(l==="/v1/memory/remember"&&n.method==="POST")try{const e=JSON.parse((await k(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(l==="/v1/memory/forget"&&n.method==="POST")try{const e=JSON.parse((await k(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(l==="/v1/memory/sync"&&n.method==="POST")try{const e=JSON.parse((await k(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(l==="/v1/memory/clear"&&n.method==="POST")return a(o,200,{ok:!0,dropped:fe.clear(),size:fe.size});if(l==="/v1/history/clear"&&n.method==="POST"){const e=J.clear();return a(o,200,{ok:!0,dropped:e,size:J.size})}if(l==="/v1/history/search"&&n.method==="POST")try{const e=JSON.parse((await k(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(l==="/v1/history/smart-search"&&n.method==="POST")try{const e=JSON.parse((await k(n,t.maxBodyBytes)).toString("utf8"))||{},r=String(e.question||e.query||""),s=us(r,{extra:Array.isArray(e.queries)?e.queries.map(String):[],max:Math.min(6,Math.max(1,Number(e.maxQueries)||4))}),i={type:e.type?String(e.type):null,since:e.since!=null?Number(e.since):null,before:e.before!=null?Number(e.before):null},d=Math.min(30,Math.max(5,Number(e.limit)||10)*2),m=await ms(s,y=>J.search(y,{limit:d,...i}),{limit:Math.min(50,Math.max(1,Number(e.limit)||10))}),h=i.type?m:[...m.filter(y=>y.type==="brief"),...m.filter(y=>y.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(l==="/v1/research"&&n.method==="POST"){let e;try{e=JSON.parse((await k(n,t.maxBodyBytes)).toString("utf8")||"{}")||{}}catch{return a(o,400,{error:{message:"research: the body must be JSON",type:"invalid_request_error"}})}const r=String(e.question||"").trim();if(!r)return a(o,400,{error:{message:"research: `question` is required",type:"invalid_request_error"}});const s=typeof e.model=="string"?e.model.trim():"";if(s&&!G(n))return a(o,403,{error:{message:"research with a model: extension origin or gateway token required",type:"forbidden"}});const i=`http://127.0.0.1:${n.socket.localPort}`,d=s?async(w,{maxTokens:v=220}={})=>{const O=new AbortController,x=setTimeout(()=>O.abort(),3e4);try{const D=Be()||_e(),Y=await fetch(`${i}/v1/chat/completions`,{method:"POST",signal:O.signal,headers:{"content-type":"application/json",...D?{Authorization:`Bearer ${D}`}:{},"X-ChatPanel-Client":"research"},body:JSON.stringify({model:s,messages:[{role:"user",content:w}],stream:!1,max_tokens:v,temperature:.2})}),we=await Y.json().catch(()=>({}));return Y.ok?String(we?.choices?.[0]?.message?.content||""):""}finally{clearTimeout(x)}}:null,m=me.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,y=await sn(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,ln(r,y,{size:J.size,newest:J.newest}))}if(l==="/v1/kb"||l.startsWith("/v1/kb/")){let e=null;if(n.method==="POST"||n.method==="PUT")try{const s=(await k(n,Math.max(t.maxBodyBytes,Math.ceil(Tt*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:l,query:g.searchParams,body:e,admin:G(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(l==="/v1/history/related"&&n.method==="GET"){const e=String(g.searchParams.get("id")||""),r=Math.min(30,Math.max(1,Number(g.searchParams.get("limit"))||5));return a(o,200,{ok:!0,results:J.related(e,{limit:r})})}if(l==="/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(l==="/v1/observability"&&n.method==="GET"){const e=Math.min(500,Math.max(1,Number(g.searchParams.get("limit"))||200));return a(o,200,{ok:!0,storage:{warm:{records:J.size,bytes:J.bytes,newest:J.newest}},access:Nt.snapshot(e)})}if(l==="/v1/observability/access"&&n.method==="POST")try{const e=JSON.parse((await k(n,t.maxBodyBytes)).toString("utf8"))||{},r=Nt.push(Co({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(l==="/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 k(n,Math.max(t.maxBodyBytes||0,Os))).toString("utf8"))||{},s=String(r.host||"").slice(0,80),i=Number(r.at)||Date.now(),d=[];let m=0,h={},y=[],w=[];const v={upserts:[],removes:[]},O=x=>{if(!x||x.deletedAt){x?.id&&v.removes.push(x.id);return}try{const D=yo(x);D&&v.upserts.push(D)}catch{}};if(Array.isArray(r.records)){const x=e.write(r.records,{host:s,at:i,merge:r.merge===!0});d.push(...x.written),h=x.revs,y=x.conflicts,w=x.merged;for(const D of x.written)O(e.get(D))}if(Array.isArray(r.entries)){const x=ft(),D=x?Ln((ne,Te)=>In(x,{salt:ne,iterations:Te})):null,Y=async ne=>{if(!D||!ne.blob)return null;const Te=await D(ne.blob),U=ne.blob.compression&&ne.blob.compression!=="none"?Jn(jn,ne.blob.compression):null;return Rn(ne.blob,Te,{codec:U})},we=await e.upsertEntries(r.entries,{open:Y});d.push(...we.written),m+=we.sealed;for(const ne of we.written)O(e.get(ne))}return(v.upserts.length||v.removes.length)&&J.bulk(v),d.length&&Ve({ids:d}),a(o,200,{ok:!0,written:d.length,ids:d,revs:h,conflicts:y,merged:w,sealed:m,size:e.size,rev:e.rev})}catch(r){return a(o,400,{error:{message:`records failed: ${r.message}`,type:"ingest_error"}})}}if(l==="/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(g.searchParams.get(m)||""),r=g.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 i=s?null:r;if(!e("force")){const m=Q.countOf(i);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(i);for(const m of Ee)try{m.write(`event: deleted
|
|
42
|
+
data: ${JSON.stringify({...s?{all:!0}:{host:r},deleted:d})}
|
|
43
43
|
|
|
44
|
-
`)}catch{}return a(o,200,{ok:!0,deleted:
|
|
44
|
+
`)}catch{}return a(o,200,{ok:!0,deleted:d,...s?{all:!0}:{host:r},cursor:Q.cursor()})}if(l==="/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 k(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:Bn(m?.source))===po,i=r.filter(s).map(m=>({id:m?.id??null,code:"RESERVED_HOST",message:`host "${po}" is this gateway's own log`})),d=An(Q,i.length?r.filter(m=>!s(m)):r);return a(o,200,{ok:!0,appended:d.appended,duplicates:d.duplicates,rejected:[...i,...d.rejected],cursor:Q.cursor()})}catch(e){return a(o,400,{error:{message:`events: ${e?.message||e}`,type:"invalid_request_error"}})}}if(l==="/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(l==="/v1/events/stats"&&n.method==="GET"){if(!Q)return a(o,501,{error:{message:"the event log needs SQLite",type:"unavailable"}});const e=Nn(Q.all());return a(o,200,{ok:!0,stats:e,year:Mn(e)})}if(l==="/v1/events"&&n.method==="GET"){if(!Q)return a(o,501,{error:{message:"the event log needs SQLite",type:"unavailable"}});let e={};try{e=ho(JSON.parse(g.searchParams.get("cursor")||"{}"))}catch{return a(o,400,{error:{message:"events: cursor must be JSON { host: seq }",type:"invalid_request_error"}})}const r=Q.since(e,{limit:Number(g.searchParams.get("limit"))||void 0,host:g.searchParams.get("host")||null});return a(o,200,{ok:!0,events:r.events.map(s=>vt(s)),cursor:r.cursor,more:r.more})}if(l==="/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(g.searchParams.has("cursor"))try{e=ho(JSON.parse(g.searchParams.get("cursor")||"{}"))}catch{e={}}if(o.writeHead(200,{"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive"}),o.write(`event: hello
|
|
45
45
|
data: ${JSON.stringify({cursor:Q.cursor(),count:Q.count(),version:ue})}
|
|
46
46
|
|
|
47
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
|
|
48
48
|
data: ${JSON.stringify(vt(s))}
|
|
49
49
|
|
|
50
|
-
`)}}return}if(
|
|
51
|
-
data: ${JSON.stringify({pending:
|
|
50
|
+
`)}}return}if(l==="/v1/link"&&n.method==="GET")return a(o,200,{...f?{enabled:!0,...f.status()}:{enabled:!1,devices:[],pairing:null},agentSessions:t.link?.agentSessions!==!1});if(l==="/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 k(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,ce())}catch(r){console.warn(`[link] could not persist the settings: ${r.message}`)}return a(o,200,{ok:!0,agentSessions:t.link.agentSessions})}if(l==="/v1/link/pair"&&n.method==="POST"){if(!f)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 k(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=f.previewPartner(r)}catch(i){return a(o,400,{error:{message:i?.message||String(i),type:"invalid_request",code:i?.code||"bad_partner"}})}if(e.confirm!==!0)return a(o,200,{confirmed:!1,preview:s});try{return a(o,200,{confirmed:!0,...await f.pairPartner(r)})}catch(i){return a(o,i?.code==="bad_partner"?400:502,{error:{message:i?.message||String(i),type:i?.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 f.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(l==="/v1/link/route"&&n.method==="POST"){if(!f)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 k(n,t.maxBodyBytes)).toString("utf8")||"{}")||{}}catch{e={}}let r;try{r=aa({id:String(e.route||"link"),url:String(e.url||"")})}catch(i){return a(o,400,{error:{message:i.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,ce())}catch(i){console.warn(`[link] could not persist the route: ${i.message}`)}return a(o,200,{enabled:!0,...await f.applySettings(s)})}if(l.startsWith("/v1/link/devices/")&&n.method==="DELETE"){if(!f)return a(o,404,{error:{message:"link is off",type:"disabled"}});const e=decodeURIComponent(l.slice(17));return await f.remove(e)?(b.cancelDevice(e),a(o,200,{ok:!0})):a(o,404,{error:{message:"no such device",type:"not_found"}})}if(l==="/v1/link/files"||l.startsWith("/v1/link/files/")){const e=He(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=f?.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=l.slice(14).replace(/^\//,"");let i=s;try{i=decodeURIComponent(s)}catch{}const d=n.method==="GET"&&(!s||/^(data|\.claude\/skills|\.claude\/agents|\.agents\/skills)\/?$/.test(i));let m;try{m=ua(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:ma(r,m.replace(/\/$/,""))});if(n.method==="GET"){const h=pa(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,ha(r,m,await k(n,t.maxBodyBytes))):n.method==="DELETE"?ya(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 y=h?.status||(h?.code===413?413:h?.code==="bad_partner"?400:500);return a(o,y,{error:{message:h?.message||String(h),type:y===404?"not_found":y===413?"too_large":"invalid_request"}})}}if(l==="/v1/link/approvals"||l.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(l==="/v1/link/approvals"&&n.method==="GET")return a(o,200,{pending:b.list()});if(l==="/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
|
|
51
|
+
data: ${JSON.stringify({pending:d})}
|
|
52
52
|
|
|
53
|
-
`);r(b.list());const s=b.subscribe(r),
|
|
53
|
+
`);r(b.list());const s=b.subscribe(r),i=setInterval(()=>o.write(`:
|
|
54
54
|
|
|
55
|
-
`),25e3);
|
|
55
|
+
`),25e3);i.unref?.(),o.on("close",()=>{s(),clearInterval(i)});return}const e=/^\/v1\/link\/approvals\/([A-Za-z0-9_-]{1,40})$/.exec(l);if(e&&n.method==="POST"){let r={};try{r=JSON.parse((await k(n,t.maxBodyBytes)).toString("utf8")||"{}")||{}}catch{r={}}return fo.some(s=>s.id===r.decision)?b.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: ${fo.map(s=>s.id).join(" | ")} }`,type:"invalid_request"}})}}if(l==="/v1/browser"&&n.method==="GET")return a(o,200,p.status());if(l==="/v1/browser/stream"&&n.method==="GET"){p.stream(n,o);return}if((l==="/v1/browser/call"||l==="/v1/browser/announce"||l==="/v1/browser/result")&&n.method==="POST"){let e;try{e=JSON.parse((await k(n,t.maxBodyBytes)).toString("utf8"))}catch{return a(o,400,{error:{message:"browser: body must be JSON",type:"invalid_request"}})}const r=l==="/v1/browser/call"?await p.call(e,n):l==="/v1/browser/announce"?p.announce(e):p.result(e);return a(o,r.status,r.body)}if(l==="/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
|
|
56
56
|
data: ${JSON.stringify({newest:e.newest,rev:e.rev,size:e.size,version:ue,prefsRevision:me.revision})}
|
|
57
57
|
|
|
58
|
-
`),xe.add(o),n.on("close",()=>xe.delete(o));return}if(i==="/v1/history/records"&&n.method==="GET"){const e=L.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,...L.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=L.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:io()});if(i==="/v1/history/key"&&n.method==="POST")try{const e=JSON.parse((await S(n,t.maxBodyBytes)).toString("utf8"))||{};e.passphrase?Vr(String(e.passphrase)):Fr();const r=e.passphrase?await kt(L,String(e.passphrase)):{ok:!0,ingested:0};return r.ok&&r.whole&&Ve(),a(o,200,{ok:!0,hasKey:!!e.passphrase,...r})}catch(e){return a(o,400,{error:{message:`key handoff failed: ${e.message}`,type:"key_error"}})}if(i==="/v1/history/ingest-backup"&&n.method==="POST")try{const e=await kt(L,ft());return e.ok&&e.whole&&Ve(),a(o,e.ok?200:409,e)}catch(e){return a(o,400,{error:{message:`backup ingest failed: ${e.message}`,type:"ingest_error"}})}if(i==="/ner"){if(n.method==="GET"){const e=await Vo(t);return a(o,e.ok?200:503,e)}if(n.method==="POST"){if(await nt(t),J.state()!=="off"){if(!J.isReady()){const r=J.health();return a(o,503,{error:{message:r.state==="error"?`NER model failed to load: ${r.error||"unknown error"}`:`NER model is ${r.state} — not ready yet`,type:r.state==="error"?"ner_error":"ner_loading"},state:r.state,model:r.model})}try{const r=await S(n,t.maxBodyBytes);let s="",l=!1;try{const m=JSON.parse(r.toString("utf8"));s=m?.text||"",l=m?.strict===!0}catch{}const c=await J.detect(s,{strict:l});return a(o,200,{entities:c})}catch(r){return a(o,500,{error:{message:`NER error: ${r.message}`,type:"ner_error"}})}}const e=Uo(t);if(!e){const r=J.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:J.state(),model:t.ner?.model||null})}try{const r=await S(n,t.maxBodyBytes),s=await tt(e,{method:"POST",headers:{"content-type":"application/json"},body:r,signal:AbortSignal.timeout(8e3)}),l=await s.text();return o.writeHead(s.status,{"content-type":"application/json"}),o.end(l)}catch(r){return a(o,502,{error:{message:`NER unreachable: ${r.message}`,type:"ner_unreachable"}})}}}if(i==="/redact"&&n.method==="POST"){let e="";try{e=String(JSON.parse((await S(n,t.maxBodyBytes)).toString("utf8"))?.text||"")}catch{e=""}if(!e)return a(o,200,{text:"",count:0,sanitized:0,entities:[],detector:Mt(t)});try{let r=e;const s=await ke(t.pro?.entitlementToken);await nt(t);const l=await qe([ht(()=>r,c=>{r=c})],t.redaction,{isPro:s});return a(o,200,{text:r,count:l.count||0,sanitized:l.sanitized||0,tier:t.redaction?.tier==="full"?"full":"basic",entities:Go(l.vault,"types")||[],detector:Mt(t)})}catch(r){return a(o,500,{error:{message:`redaction preview failed: ${r.message}`,type:"redact_error"}})}}if(i==="/ner/models"){if(n.method==="GET"){const e=J.health().model||t.ner?.model||null,r=Math.round(St.totalmem()/1048576),s=Ba(bo,{totalRamMB:r}).map(l=>({...l,installed:J.modelOnDisk(l.id)}));for(const l of[e,...J.modelsOnDisk()])!l||s.some(c=>c.id===l)||s.push({id:l,label:l,lang:"—",custom:!0,installed:J.modelOnDisk(l),note:"Custom model (from Hugging Face)."});return a(o,200,{active:e,companions:J.companions(),union:Array.isArray(t.ner?.union)?t.ner.union:[],machine:{totalRamMB:r},skipped:Hr(),recommendation:so(s,{totalRamMB:r},[]),state:J.state(),progress:J.progress(),available:s})}if(n.method==="POST"){let e=null;try{e=JSON.parse((await S(n,t.maxBodyBytes)).toString("utf8"))}catch{e=null}if(e&&e.recommended===!0){const s=Math.round(St.totalmem()/1048576),l=so(bo.map(c=>({...c,installed:J.modelOnDisk(c.id)})),{totalRamMB:s},[]);e={id:l.primary,union:l.union}}const r=e&&typeof e.id=="string"?e.id.trim():null;if(e&&Array.isArray(e.union)){const s=[...new Set(e.union.map(c=>String(c||"").trim()).filter(Boolean))];for(const c of s)if(!(vo(c)||ko(c)))return a(o,400,{error:{message:`unknown or invalid model id in union: ${c}`,type:"bad_model"}});const l=r||t.ner?.model||J.health().model;t.ner=t.ner||{allowDownload:!0,enableFullTier:!0},t.ner.union=s.filter(c=>c!==l),r&&Bo(t,r);try{be(t,ce())}catch{}return(async()=>{r&&await J.setModel(r,{onLog:m=>console.log(m)});const c=Gr(t.ner,{log:m=>console.log(m)});for(const m of J.companions())c.includes(m.model)||await J.removeCompanion(m.model);for(const m of c)await J.addCompanion(m,{onLog:h=>console.log(h),allowDownload:t.ner.allowDownload!==!1});J.setUnionOrder(c)})().catch(c=>console.log(`[ner] union update failed: ${c.message}`)),a(o,202,{accepted:!0,active:l,union:t.ner.union,companions:J.companions(),state:J.state()})}if(!r||!(vo(r)||ko(r)))return a(o,400,{error:{message:"unknown or invalid model id",type:"bad_model"}});Bo(t,r);try{be(t,ce())}catch{}return J.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:J.state(),progress:J.progress()})}}if(i==="/stt/models"){if(n.method==="GET"){const e=A.health().model||t.stt?.model||De,r={platform:process.platform,arch:process.arch,helper:!!bt()},s=Ma.map(l=>{const c=So(l,r);return{...l,installed:A.modelOnDisk(l.id),...c?{unavailable:c}:{}}});return e&&!s.some(l=>l.id===e)&&s.push({id:e,label:e,lang:"—",tier:"custom",custom:!0,installed:A.modelOnDisk(e),note:"Custom model (from Hugging Face)."}),a(o,200,{active:e,state:A.state(),progress:A.progress(),available:s,dtype:t.stt?.dtype||"auto",loadedDtype:A.health().dtype,runtime:A.health().runtime,dtypes:Ia,licenses:t.stt?.licenses||{}})}if(n.method==="POST"){let e=null;try{e=JSON.parse((await S(n,t.maxBodyBytes)).toString("utf8"))}catch{e=null}const r=e&&typeof e.id=="string"?e.id.trim():null;if(!r||!(Da(r)||Ca(r)))return a(o,400,{error:{message:"unknown or invalid model id",type:"bad_model"}});const s=So(at(r),{platform:process.platform,arch:process.arch,helper:!!bt()});if(s)return a(o,400,{error:{message:s,type:"bad_model"}});const l=at(r)?.license||null;if(l){const m=To(l),h=t.stt?.licenses?.[l.id]?.version===l.version;if(!h&&e.acceptLicense!==m)return a(o,409,{error:{message:`Accept the ${l.name} to use this model`,type:"license_required"},license:{...l,accept:m}});h||(t.stt||={enabled:!0,allowDownload:!0},t.stt.licenses={...t.stt.licenses||{},[l.id]:{version:l.version,acceptedAt:new Date().toISOString()}})}const c=typeof e.dtype=="string"&&Ra(e.dtype)?e.dtype:void 0;t.stt?t.stt.model=r:t.stt={enabled:!0,model:r,allowDownload:!0},c&&(t.stt.dtype=c==="auto"?null:c);try{be(t,ce())}catch{}return A.setModel(r,{onLog:m=>console.log(m),dtype:c||t.stt.dtype||"auto",warmMs:t.stt.warmMs,allowDownload:t.stt?.allowDownload!==!1,segment:t.stt?.segment,speaker:It(t,{installing:!0}),licenseAccepted:Ko(t,r)}),a(o,202,{accepted:!0,active:r,dtype:t.stt.dtype||"auto",state:A.state(),progress:A.progress(),speaker:{id:M.activeModel(),state:M.state(),installed:M.modelOnDisk()}})}}if(i==="/diarize/model"){if(n.method==="GET"){const e=M.activeModel(),r=Ea.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:Oa.health(),translate:$e.health(),indictrans:xa.health(),aec:xt.health(),progress:M.progress(),available:r})}if(n.method==="POST"){let e=null;try{e=JSON.parse((await S(n,t.maxBodyBytes)).toString("utf8")||"{}")}catch{e=null}const r=e&&typeof e.id=="string"?e.id.trim():null;if(r){if(!go(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,ce())}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(Ot()),r=Ot(),s=xo.find(c=>c.id===e)||null,l=xo.map(c=>({...c,installed:D.modelOnDisk(c.id),unavailable:c.requiresNative&&!r?"needs the npm gateway — the standalone binary cannot load this engine":void 0}));return e&&!l.some(c=>c.id===e)&&l.push({id:e,label:e,lang:"—",tier:"custom",custom:!0,installed: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||(lt(e)==="pocket-tts"?st: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()&<(e)==="pocket-tts"?(D.builtinVoices().length?D.builtinVoices():Ua).map(c=>({id:c,label:c[0].toUpperCase()+c.slice(1),lang:"en",installed:D.builtinVoices().includes(c)})):D.arch()&&D.arch()!=="style-tts2"?[]:Ja.map(c=>({...c,installed:D.voiceOnDisk(c.id,e)})),dtype:t.tts?.dtype||"auto",loadedDtype:D.health().dtype,runtime:D.health().runtime,dtypes:za})}if(n.method==="POST"){let e=null;try{e=JSON.parse((await S(n,t.maxBodyBytes)).toString("utf8"))}catch{e=null}const r=e&&typeof e.id=="string"?e.id.trim():null;if(r&&!(La(r)||ja(r)))return a(o,400,{error:{message:"unknown or invalid model id",type:"bad_model"}});const s=e&&typeof e.voice=="string"?e.voice.trim():null;if(s){const c=de.parseCustomVoice(s);if(!(c?!!de.getVoice(c):it(s)||_o(s)&&Oo(s)))return a(o,400,{error:{message:"unknown or invalid voice",type:"bad_voice"}})}const l=e&&typeof e.dtype=="string"&&Ga(e.dtype)?e.dtype:void 0;if(t.tts||(t.tts={enabled:!0,model:Eo,voice:Oe,allowDownload:!0}),r&&(t.tts.model=r),s&&(t.tts.voice=s),r&&!s){const c=Ha(r),m=de.parseCustomVoice(t.tts.voice||""),h=!!(m&&de.getVoice(m));if(c&&!h)if(lt(r)==="pocket-tts")t.tts.voice=st;else{const w=de.listVoices();t.tts.voice=w.length?`custom:${w[0].id}`:""}else!c&&h&&(t.tts.voice=Oe);const g=lt(r)==="pocket-tts";g&&!de.parseCustomVoice(t.tts.voice||"")&&!it(t.tts.voice)&&(t.tts.voice=st),!g&&it(t.tts.voice)&&(t.tts.voice=Oe)}l&&(t.tts.dtype=l==="auto"?null:l);try{be(t,ce())}catch{}return r&&D.setModel(r,{onLog:c=>console.log(c),dtype:l||t.tts.dtype||"auto"}),a(o,202,{accepted:!0,active:t.tts.model,voice:t.tts.voice,dtype:t.tts.dtype||"auto",state:D.state(),progress:D.progress()})}}if(i==="/tts/voices"){if(n.method==="GET")return a(o,200,{voices:de.listVoices(),usable:D.supportsCustomVoices(),embedder:M.activeModel(),embedderReady:M.isReady()});if(n.method==="POST"){let e=null;try{e=JSON.parse((await S(n,t.maxBodyBytes)).toString("utf8"))}catch{e=null}const r=e&&typeof e.name=="string"?e.name.trim():"",s=e&&Array.isArray(e.pcm)?e.pcm:null,l=e&&typeof e.id=="string"?e.id.trim():"";if(l){if(!de.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,{...de.renameVoice(l,r),usable:D.supportsCustomVoices()})}catch(c){return a(o,400,{error:{message:c.message,type:"rename_failed"}})}}if(s.length<16e3)return a(o,400,{error:{message:"need at least 1 second of 16 kHz mono audio",type:"sample_too_short"}})}else if(!r)return a(o,400,{error:{message:"a name is required",type:"bad_request"}});if(!s||s.length<16e3)return a(o,400,{error:{message:"need at least 1 second of 16 kHz mono audio",type:"sample_too_short"}});try{const c=$a(M.activeModel())?.dim===de.EMBED_DIM;if(c&&!M.isReady()){const O=M.download({onLog:q=>console.log(q)}),x=Symbol("timeout"),I=await Promise.race([O.then(()=>null).catch(q=>q),new Promise(q=>setTimeout(()=>q(x),$s))]);if(I===x||!M.isReady())return a(o,503,{error:{message:I===x?"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 m=Float32Array.from(s),h=c?await M.embed(m):null;let g=null;try{const O=await D.pocketForEncoding({allowDownload:t.tts?.allowDownload!==!1,log:x=>console.log(x)});O&&(g=await O.encodeVoice(As(m,16e3,24e3)))}catch(O){console.log(`[tts] pocket conditioning unavailable for this voice (${O.message})`)}const w=l?de.replaceVoice(l,{vec:h,pocket:g}):de.saveVoice({name:r,vec:h,pocket:g}),v=l&&r&&r!==w.name?de.renameVoice(l,r):w;return console.log(`[tts] ${l?"re-recorded":"saved"} custom voice "${v.name}" (${(w.kinds||[]).join(" + ")}, sample discarded)`),a(o,l?200:201,{...w,...v,usable:D.supportsCustomVoices()})}catch(c){return a(o,400,{error:{message:c.message,type:"save_failed"}})}}if(n.method==="DELETE"){const e=f.searchParams.get("id")||"",r=de.deleteVoice(e);if(r&&t.tts?.voice===`custom:${e}`){const s=de.listVoices();t.tts.voice=s.length?`custom:${s[0].id}`:Oe;try{be(t,ce())}catch{}}return a(o,200,{deleted:r,voice:t.tts?.voice})}}if((i==="/tts"||i==="/v1/audio/speech")&&n.method==="POST"){if(t.tts?.enabled===!1)return a(o,503,{error:{message:"tts is disabled in gateway config",type:"tts_disabled"}});let e=null;try{e=JSON.parse((await S(n,t.maxBodyBytes)).toString("utf8"))}catch{e=null}const r=e&&typeof(e.input??e.text)=="string"?String(e.input??e.text).trim():"";if(!r)return a(o,400,{error:{message:"text is required",type:"bad_request"}});if(r.length>Po)return a(o,413,{error:{message:`text too long (max ${Po} chars)`,type:"too_long"}});const s=Number.isFinite(e.speed)?Math.min(2,Math.max(.5,e.speed)):1,l=Va(t),c=e&&typeof e.voice=="string"&&e.voice.trim()?e.voice.trim():null,m=c||(l?l.voice:t.tts?.voice||Oe);if(l&&!Wa(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:ne,contentType:Te,redacted:U}=await Fa({dest:l,text:r,voice:m,speed:s,auth:n.headers.authorization||n.headers["xi-api-key"]||"",redaction:t.redaction,isPro:await ke(t.pro?.entitlementToken)});return o.writeHead(200,{"Content-Type":Te,"Content-Length":String(ne.length),"Cache-Control":"no-store","X-Tts-Provider":l.kind,"X-Tts-Redacted":String(U)}),o.end(ne)}if(!await D.ready({onLog:ne=>console.log(ne),allowDownload:t.tts?.allowDownload!==!1,model:t.tts?.model||$o(Ot()),dtype:t.tts?.dtype||"auto"}))return a(o,503,{error:{message:D.health().error||"tts model not ready",type:"tts_unavailable"}});const w=Ka({requested:c,configured:m,engine:D,voices:de,isPocketVoice:it,isKnownVoice:_o,isValidVoiceId:Oo,defaultVoice:Oe,defaultPocketVoice:st});if(!w.ok)return a(o,w.status,{error:{message:w.message,type:w.type}});const{voice:v,customId:O,speakerEmbedding:x}=w,I=await D.synth(r,{voice:v,speed:s,speakerEmbedding:x}),q=D.sampleRate(),we=h==="pcm"?Buffer.from(new Float32Array(I).buffer):D.toWav(I,q);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(q),...O||D.isPocket()||D.supportsVoices()?{"X-Tts-Voice":v}:{}}),o.end(we)}catch(g){return a(o,500,{error:{message:g.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=Aa(await S(n,Math.max(t.maxBodyBytes||0,64*1024*1024)),n.headers["content-type"])}catch(v){return a(o,v.code===413?413:415,{error:{message:v.message,type:"bad_request"}})}const r=v=>e.find(O=>O.name===v&&!O.filename)?.data.toString("utf8").trim()||"",s=e.find(v=>v.name==="file"&&v.filename)||e.find(v=>v.filename);if(!s?.data?.length)return a(o,400,{error:{message:"a `file` part is required",type:"bad_request"}});let l;try{l=await Na(s.data)}catch(v){return a(o,v.code===415?415:500,{error:{message:v.message,type:"unsupported_media"}})}const c=["json","text","verbose_json"].includes(r("response_format"))?r("response_format"):"json",m=_t(t,"stt");let h=null;if(m.kind==="remote"||m.kind==="container")try{h=wo(m,{fetchImpl:tt})}catch(v){return a(o,500,{error:{message:`stt provider: ${v.message}`,type:"bad_provider"}})}if(!h&&!A.isReady()&&await A.init({model:t.stt?.model||De,allowDownload:t.stt?.allowDownload!==!1,dtype:t.stt?.dtype||void 0,warmMs:t.stt?.warmMs,segment:t.stt?.segment,speaker:It(t),onLog:v=>console.log(v)}),!h&&!A.isReady())return a(o,503,{error:{message:`speech model not ready: ${A.health().error||A.state()}`,type:"stt_not_ready"}});const g=r("diarize")==="true"&&t.stt?.diarize!==!1;g&&!M.isReady()&&await M.init({allowDownload:t.stt?.allowDownload!==!1,warmMs:t.stt?.warmMs,onLog:v=>console.log(v)});const w=Date.now();try{const{id:v}=A.createSession({lang:r("language")||void 0,diarize:g,interims:!1,remote:h}),O=[],x=[];let I=null;A.subscribe(v,U=>{U.type==="final"&&U.text?O.push(U):U.type==="language"?I=U.lang:U.type==="error"&&x.push(U.message||U.code)});const q=16e3*5;for(let U=0;U<l.pcm.length;U+=q)A.pushAudio(v,l.pcm.subarray(U,Math.min(l.pcm.length,U+q))),await A.decodeNow(v);if(await A.endSession(v),!O.length&&x.length)return a(o,500,{error:{message:x[0],type:"decode_failed"}});let we=0;const ne=O.map((U,qo)=>{const Ft=typeof U.startMs=="number"?U.startMs/1e3:we,er=(U.durationMs||0)/1e3;return we=Ft+er,{id:qo,start:Math.round(Ft*100)/100,end:Math.round(we*100)/100,text:U.text,...U.speaker?{speaker:U.speaker}:{},...U.turns?{turns:U.turns.map(Ze=>({start:Math.round(Ze.startMs/10)/100,end:Math.round((Ze.startMs+Ze.durationMs)/10)/100,speaker:Ze.speaker}))}:{}}}),Te=ne.map(U=>U.text).join(" ").replace(/\s+/g," ").trim();return c==="text"?(o.writeHead(200,{"content-type":"text/plain; charset=utf-8"}),o.end(Te)):c==="verbose_json"?a(o,200,{task:"transcribe",language:I||r("language")||null,duration:Math.round(l.seconds*100)/100,text:Te,segments:ne,provider:m.kind,took_ms:Date.now()-w}):a(o,200,{text:Te})}catch(v){return a(o,v.code==="too_many_sessions"?429:500,{error:{message:v.message,type:v.code||"stt_error"}})}}if(i.startsWith("/v1/stt/sessions")&&(i=i.slice(3)),i==="/stt/sessions"&&n.method==="POST"){if(t.stt?.enabled===!1)return a(o,403,{error:{message:"STT disabled in gateway config",type:"stt_disabled"}});let e=null;try{e=JSON.parse((await S(n,t.maxBodyBytes)).toString("utf8")||"{}")}catch{e=null}const r=_t(t,"stt");let s=null;if(r.kind==="remote"||r.kind==="container")try{s=wo(r,{fetchImpl:tt})}catch(O){return a(o,500,{error:{message:`stt provider: ${O.message}`,type:"bad_provider"}})}!s&&!A.isReady()&&A.init({model:t.stt?.model||De,allowDownload:t.stt?.allowDownload!==!1,dtype:t.stt?.dtype||void 0,warmMs:t.stt?.warmMs,segment:t.stt?.segment,speaker:It(t),licenseAccepted:Ko(t,t.stt?.model||De),onLog:O=>console.log(O)});const l=e?.diarize===!0&&t.stt?.diarize!==!1;l&&!M.isReady()&&M.init({allowDownload:t.stt?.allowDownload!==!1,warmMs:t.stt?.warmMs,onLog:O=>console.log(O)});const c=typeof e?.translateTo=="string"&&t.stt?.translate!==!1?e.translateTo:null,m=c?{allowDownload:t.stt?.allowDownload!==!1,warmMs:t.stt?.warmMs,onLog:O=>console.log(O)}:null,h=e?.echo&&typeof e.echo=="object"&&typeof e.echo.group=="string"&&["mic","reference"].includes(e.echo.role)&&t.stt?.aec!==!1&&!s?{group:e.echo.group,role:e.echo.role}:null;h&&xt.state()==="off"&&xt.init({allowDownload:t.stt?.allowDownload!==!1,warmMs:t.stt?.warmMs,onLog:O=>console.log(O)});const g=Array.isArray(e?.langs)?e.langs.slice(0,12):null,w=t.stt?.model||De,v=g&&!s?_a(g,{engine:at(w)?.engine||"",englishOnly:/\.en$/.test(w)}).missing:[];try{const O=e?.poll===!0,x=e?.format==="pcm16"?"pcm16":"f32",{id:I}=A.createSession({lang:e?.lang,langs:g,translateTo:c,translateLoad:m,echo:h,redact:e?.redact===!0,diarize:l,speakerLabel:e?.speakerLabel,endSilenceMs:e?.endSilenceMs,interims:e?.interims!==!1,remote:s,poll:O,format:x});return a(o,201,{id:I,state:A.state(),format:x,...O?{poll:!0}:{},...v.length?{languagesMissing:v}:{},...c?{translate:$e.state()}:{}})}catch(O){return a(o,O.code==="too_many_sessions"?429:500,{error:{message:O.message,type:O.code||"stt_error"}})}}{const e=i.match(/^\/stt\/sessions\/([0-9a-f-]{36})(\/audio|\/events)?$/);if(e){const r=e[1],s=async(c,m,h)=>{if(m.type!=="final"&&m.type!=="translation"||!c.redact||!m.text)return m;try{let g=m.text;return await qe([ht(()=>g,w=>{g=w})],t.redaction,{isPro:h}),{...m,text:g}}catch{return m}},l=async c=>{const m=A.drainEvents(r);if(!m)return null;const h=[];if(c&&!c.closed){const w=c.remote?"ready":A.state();w==="downloading"||w==="loading"?h.push({type:"progress",state:w,...A.progress()||{}}):w==="error"?h.push({type:"error",code:"model_failed",message:A.health().error||"model failed to load",fatal:!0}):c.diarize&&["downloading","loading"].includes(M.state())?h.push({type:"diarize-progress",state:M.state(),...M.progress()||{}}):c.translateTo&&["downloading","loading"].includes($e.state())?h.push({type:"translate-progress",state:$e.state(),...$e.progress()||{}}):Wo.get(c)!==w&&(Wo.set(c,w),h.push({type:"state",state:w}))}const g=c?.redact?await ke(t.pro?.entitlementToken):!0;for(const w of m)c?h.push(await s(c,w,g)):w.type!=="final"&&w.type!=="interim"&&w.type!=="translation"&&h.push(w);return h};if(e[2]==="/audio"&&n.method==="POST"){const c=A.getSession(r)||A.endedSession(r);try{const m=await S(n,t.maxBodyBytes);A.pushAudio(r,A.toFloat32(m,c?.format));const h=await l(c);return a(o,200,{ok:!0,state:A.state(),...h?{events:h}:{}})}catch(m){const h=m.code==="no_session"?await l(c).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 c=A.getSession(r);if(!c)return a(o,404,{error:{message:"no such session",type:"no_session"}});o.writeHead(200,{"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive"});const m=x=>o.write(`data: ${JSON.stringify(x)}
|
|
58
|
+
`),xe.add(o),n.on("close",()=>xe.delete(o));return}if(l==="/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(g.searchParams.get("since"))||0,cursor:g.searchParams.get("cursor")||"",limit:Number(g.searchParams.get("limit"))||200,kind:g.searchParams.get("kind")||null,bytes:Number(g.searchParams.get("bytes"))||0,afterRev:g.searchParams.has("after_rev")?Number(g.searchParams.get("after_rev"))||0:null});return a(o,200,{ok:!0,...r,size:e.size,newest:e.newest})}if(l==="/v1/history/list"&&n.method==="GET"){const e=Math.min(500,Math.max(1,Number(g.searchParams.get("limit"))||50)),r=Math.max(0,Number(g.searchParams.get("offset"))||0),s=g.searchParams.get("type")||null;return a(o,200,{ok:!0,...J.list({limit:e,offset:r,type:s})})}if(l==="/v1/history/get"&&n.method==="GET"){const e=g.searchParams.get("maxChars")!=null?Math.max(1,Number(g.searchParams.get("maxChars"))||0):null,r=Math.max(0,Number(g.searchParams.get("offset"))||0),s=J.get(String(g.searchParams.get("id")||""),{maxChars:e,offset:r});return s?a(o,200,{ok:!0,record:s}):a(o,404,{error:{message:"no such record",type:"not_found"}})}if(l==="/v1/history/key"&&n.method==="GET")return a(o,200,{ok:!0,hasKey:lo()});if(l==="/v1/history/key"&&n.method==="POST")try{const e=JSON.parse((await k(n,t.maxBodyBytes)).toString("utf8"))||{};e.passphrase?Kr(String(e.passphrase)):Yr();const r=e.passphrase?await kt(J,String(e.passphrase)):{ok:!0,ingested:0};return r.ok&&r.whole&&Ve(),a(o,200,{ok:!0,hasKey:!!e.passphrase,...r})}catch(e){return a(o,400,{error:{message:`key handoff failed: ${e.message}`,type:"key_error"}})}if(l==="/v1/history/ingest-backup"&&n.method==="POST")try{const e=await kt(J,ft());return e.ok&&e.whole&&Ve(),a(o,e.ok?200:409,e)}catch(e){return a(o,400,{error:{message:`backup ingest failed: ${e.message}`,type:"ingest_error"}})}if(l==="/ner"){if(n.method==="GET"){const e=await Fo(t);return a(o,e.ok?200:503,e)}if(n.method==="POST"){if(await nt(t),L.state()!=="off"){if(!L.isReady()){const r=L.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 k(n,t.maxBodyBytes);let s="",i=!1;try{const m=JSON.parse(r.toString("utf8"));s=m?.text||"",i=m?.strict===!0}catch{}const d=await L.detect(s,{strict:i});return a(o,200,{entities:d})}catch(r){return a(o,500,{error:{message:`NER error: ${r.message}`,type:"ner_error"}})}}const e=Vo(t);if(!e){const r=L.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:L.state(),model:t.ner?.model||null})}try{const r=await k(n,t.maxBodyBytes),s=await tt(e,{method:"POST",headers:{"content-type":"application/json"},body:r,signal:AbortSignal.timeout(8e3)}),i=await s.text();return o.writeHead(s.status,{"content-type":"application/json"}),o.end(i)}catch(r){return a(o,502,{error:{message:`NER unreachable: ${r.message}`,type:"ner_unreachable"}})}}}if(l==="/redact"&&n.method==="POST"){let e="";try{e=String(JSON.parse((await k(n,t.maxBodyBytes)).toString("utf8"))?.text||"")}catch{e=""}if(!e)return a(o,200,{text:"",count:0,sanitized:0,entities:[],detector:Bt(t)});try{let r=e;const s=await ke(t.pro?.entitlementToken);await nt(t);const i=await qe([ht(()=>r,d=>{r=d})],t.redaction,{isPro:s});return a(o,200,{text:r,count:i.count||0,sanitized:i.sanitized||0,tier:t.redaction?.tier==="full"?"full":"basic",entities:Ho(i.vault,"types")||[],detector:Bt(t)})}catch(r){return a(o,500,{error:{message:`redaction preview failed: ${r.message}`,type:"redact_error"}})}}if(l==="/ner/models"){if(n.method==="GET"){const e=L.health().model||t.ner?.model||null,r=Math.round(St.totalmem()/1048576),s=Ca(vo,{totalRamMB:r}).map(i=>({...i,installed:L.modelOnDisk(i.id)}));for(const i of[e,...L.modelsOnDisk()])!i||s.some(d=>d.id===i)||s.push({id:i,label:i,lang:"—",custom:!0,installed:L.modelOnDisk(i),note:"Custom model (from Hugging Face)."});return a(o,200,{active:e,companions:L.companions(),union:Array.isArray(t.ner?.union)?t.ner.union:[],machine:{totalRamMB:r},skipped:Fr(),recommendation:io(s,{totalRamMB:r},[]),state:L.state(),progress:L.progress(),available:s})}if(n.method==="POST"){let e=null;try{e=JSON.parse((await k(n,t.maxBodyBytes)).toString("utf8"))}catch{e=null}if(e&&e.recommended===!0){const s=Math.round(St.totalmem()/1048576),i=io(vo.map(d=>({...d,installed:L.modelOnDisk(d.id)})),{totalRamMB:s},[]);e={id:i.primary,union:i.union}}const r=e&&typeof e.id=="string"?e.id.trim():null;if(e&&Array.isArray(e.union)){const s=[...new Set(e.union.map(d=>String(d||"").trim()).filter(Boolean))];for(const d of s)if(!(ko(d)||So(d)))return a(o,400,{error:{message:`unknown or invalid model id in union: ${d}`,type:"bad_model"}});const i=r||t.ner?.model||L.health().model;t.ner=t.ner||{allowDownload:!0,enableFullTier:!0},t.ner.union=s.filter(d=>d!==i),r&&Bo(t,r);try{be(t,ce())}catch{}return(async()=>{r&&await L.setModel(r,{onLog:m=>console.log(m)});const d=Vr(t.ner,{log:m=>console.log(m)});for(const m of L.companions())d.includes(m.model)||await L.removeCompanion(m.model);for(const m of d)await L.addCompanion(m,{onLog:h=>console.log(h),allowDownload:t.ner.allowDownload!==!1});L.setUnionOrder(d)})().catch(d=>console.log(`[ner] union update failed: ${d.message}`)),a(o,202,{accepted:!0,active:i,union:t.ner.union,companions:L.companions(),state:L.state()})}if(!r||!(ko(r)||So(r)))return a(o,400,{error:{message:"unknown or invalid model id",type:"bad_model"}});Bo(t,r);try{be(t,ce())}catch{}return L.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:L.state(),progress:L.progress()})}}if(l==="/stt/models"){if(n.method==="GET"){const e=N.health().model||t.stt?.model||De,r={platform:process.platform,arch:process.arch,helper:!!bt()},s=Ia.map(i=>{const d=To(i,r);return{...i,installed:N.modelOnDisk(i.id),...d?{unavailable:d}:{}}});return e&&!s.some(i=>i.id===e)&&s.push({id:e,label:e,lang:"—",tier:"custom",custom:!0,installed:N.modelOnDisk(e),note:"Custom model (from Hugging Face)."}),a(o,200,{active:e,state:N.state(),progress:N.progress(),available:s,dtype:t.stt?.dtype||"auto",loadedDtype:N.health().dtype,runtime:N.health().runtime,dtypes:Ja,licenses:t.stt?.licenses||{}})}if(n.method==="POST"){let e=null;try{e=JSON.parse((await k(n,t.maxBodyBytes)).toString("utf8"))}catch{e=null}const r=e&&typeof e.id=="string"?e.id.trim():null;if(!r||!(Ra(r)||La(r)))return a(o,400,{error:{message:"unknown or invalid model id",type:"bad_model"}});const s=To(at(r),{platform:process.platform,arch:process.arch,helper:!!bt()});if(s)return a(o,400,{error:{message:s,type:"bad_model"}});const i=at(r)?.license||null;if(i){const m=xo(i),h=t.stt?.licenses?.[i.id]?.version===i.version;if(!h&&e.acceptLicense!==m)return a(o,409,{error:{message:`Accept the ${i.name} to use this model`,type:"license_required"},license:{...i,accept:m}});h||(t.stt||={enabled:!0,allowDownload:!0},t.stt.licenses={...t.stt.licenses||{},[i.id]:{version:i.version,acceptedAt:new Date().toISOString()}})}const d=typeof e.dtype=="string"&&ja(e.dtype)?e.dtype:void 0;t.stt?t.stt.model=r:t.stt={enabled:!0,model:r,allowDownload:!0},d&&(t.stt.dtype=d==="auto"?null:d);try{be(t,ce())}catch{}return N.setModel(r,{onLog:m=>console.log(m),dtype:d||t.stt.dtype||"auto",warmMs:t.stt.warmMs,allowDownload:t.stt?.allowDownload!==!1,segment:t.stt?.segment,speaker:Rt(t,{installing:!0}),licenseAccepted:Xo(t,r)}),a(o,202,{accepted:!0,active:r,dtype:t.stt.dtype||"auto",state:N.state(),progress:N.progress(),speaker:{id:$.activeModel(),state:$.state(),installed:$.modelOnDisk()}})}}if(l==="/diarize/model"){if(n.method==="GET"){const e=$.activeModel(),r=Aa.map(s=>({...s,installed:$.modelOnDisk(s.id)})).sort((s,i)=>(i.id===e?1:0)-(s.id===e?1:0));return a(o,200,{active:e,state:$.state(),threshold:$.activeThreshold(),segment:$a.health(),translate:$e.health(),indictrans:Ea.health(),aec:xt.health(),progress:$.progress(),available:r})}if(n.method==="POST"){let e=null;try{e=JSON.parse((await k(n,t.maxBodyBytes)).toString("utf8")||"{}")}catch{e=null}const r=e&&typeof e.id=="string"?e.id.trim():null;if(r){if(!wo(r))return a(o,400,{error:{message:"unknown speaker model id",type:"bad_model"}});if(!await $.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,ce())}catch{}return $.init({allowDownload:t.stt?.allowDownload!==!1,warmMs:t.stt?.warmMs,onLog:s=>console.log(s)}),a(o,202,{accepted:!0,active:$.activeModel(),state:$.state(),threshold:$.activeThreshold(),progress:$.progress()})}return $.download({onLog:s=>console.log(s)}),a(o,202,{accepted:!0,active:$.activeModel(),state:$.state(),threshold:$.activeThreshold(),progress:$.progress()})}}if(l==="/tts/models"){if(n.method==="GET"){const e=C.health().model||t.tts?.model||Ao(Ot()),r=Ot(),s=_o.find(d=>d.id===e)||null,i=_o.map(d=>({...d,installed:C.modelOnDisk(d.id),unavailable:d.requiresNative&&!r?"needs the npm gateway — the standalone binary cannot load this engine":void 0}));return e&&!i.some(d=>d.id===e)&&i.push({id:e,label:e,lang:"—",tier:"custom",custom:!0,installed:C.modelOnDisk(e),note:"Custom model (from Hugging Face)."}),a(o,200,{active:e,state:C.state(),progress:C.progress(),available:i,voice:t.tts?.voice||(lt(e)==="pocket-tts"?st:Oe),arch:C.arch(),supportsVoices:C.arch()?C.supportsVoices():s?s.arch==="style-tts2"&&!!s.voices:!0,supportsCustomVoices:C.arch()?C.supportsCustomVoices():!!s?.customVoices,sampleRate:C.sampleRate(),voices:C.isPocket()||!C.arch()&<(e)==="pocket-tts"?(C.builtinVoices().length?C.builtinVoices():Wa).map(d=>({id:d,label:d[0].toUpperCase()+d.slice(1),lang:"en",installed:C.builtinVoices().includes(d)})):C.arch()&&C.arch()!=="style-tts2"?[]:za.map(d=>({...d,installed:C.voiceOnDisk(d.id,e)})),dtype:t.tts?.dtype||"auto",loadedDtype:C.health().dtype,runtime:C.health().runtime,dtypes:Ua})}if(n.method==="POST"){let e=null;try{e=JSON.parse((await k(n,t.maxBodyBytes)).toString("utf8"))}catch{e=null}const r=e&&typeof e.id=="string"?e.id.trim():null;if(r&&!(Ga(r)||Ha(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=de.parseCustomVoice(s);if(!(d?!!de.getVoice(d):it(s)||Oo(s)&&Eo(s)))return a(o,400,{error:{message:"unknown or invalid voice",type:"bad_voice"}})}const i=e&&typeof e.dtype=="string"&&Va(e.dtype)?e.dtype:void 0;if(t.tts||(t.tts={enabled:!0,model:Po,voice:Oe,allowDownload:!0}),r&&(t.tts.model=r),s&&(t.tts.voice=s),r&&!s){const d=Fa(r),m=de.parseCustomVoice(t.tts.voice||""),h=!!(m&&de.getVoice(m));if(d&&!h)if(lt(r)==="pocket-tts")t.tts.voice=st;else{const w=de.listVoices();t.tts.voice=w.length?`custom:${w[0].id}`:""}else!d&&h&&(t.tts.voice=Oe);const y=lt(r)==="pocket-tts";y&&!de.parseCustomVoice(t.tts.voice||"")&&!it(t.tts.voice)&&(t.tts.voice=st),!y&&it(t.tts.voice)&&(t.tts.voice=Oe)}i&&(t.tts.dtype=i==="auto"?null:i);try{be(t,ce())}catch{}return r&&C.setModel(r,{onLog:d=>console.log(d),dtype:i||t.tts.dtype||"auto"}),a(o,202,{accepted:!0,active:t.tts.model,voice:t.tts.voice,dtype:t.tts.dtype||"auto",state:C.state(),progress:C.progress()})}}if(l==="/tts/voices"){if(n.method==="GET")return a(o,200,{voices:de.listVoices(),usable:C.supportsCustomVoices(),embedder:$.activeModel(),embedderReady:$.isReady()});if(n.method==="POST"){let e=null;try{e=JSON.parse((await k(n,t.maxBodyBytes)).toString("utf8"))}catch{e=null}const r=e&&typeof e.name=="string"?e.name.trim():"",s=e&&Array.isArray(e.pcm)?e.pcm:null,i=e&&typeof e.id=="string"?e.id.trim():"";if(i){if(!de.getVoice(i))return a(o,404,{error:{message:"no such saved voice",type:"bad_voice"}});if(!s){if(!r)return a(o,400,{error:{message:"a name is required",type:"bad_request"}});try{return a(o,200,{...de.renameVoice(i,r),usable:C.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{const d=Ma($.activeModel())?.dim===de.EMBED_DIM;if(d&&!$.isReady()){const O=$.download({onLog:Y=>console.log(Y)}),x=Symbol("timeout"),D=await Promise.race([O.then(()=>null).catch(Y=>Y),new Promise(Y=>setTimeout(()=>Y(x),Ko))]);if(D===x||!$.isReady())return a(o,503,{error:{message:D===x?"the speaker model is still downloading (~100 MB) — your recording was kept, press Save again shortly":`the speaker model failed to load: ${$.health().error||"unknown error"}`,type:"embedder_not_ready"},progress:$.progress()})}const m=Float32Array.from(s),h=d?await $.embed(m):null;let y=null;try{const O=await C.pocketForEncoding({allowDownload:t.tts?.allowDownload!==!1,log:x=>console.log(x)});O&&(y=await O.encodeVoice(Bs(m,16e3,24e3)))}catch(O){console.log(`[tts] pocket conditioning unavailable for this voice (${O.message})`)}const w=i?de.replaceVoice(i,{vec:h,pocket:y}):de.saveVoice({name:r,vec:h,pocket:y}),v=i&&r&&r!==w.name?de.renameVoice(i,r):w;return console.log(`[tts] ${i?"re-recorded":"saved"} custom voice "${v.name}" (${(w.kinds||[]).join(" + ")}, sample discarded)`),a(o,i?200:201,{...w,...v,usable:C.supportsCustomVoices()})}catch(d){return a(o,400,{error:{message:d.message,type:"save_failed"}})}}if(n.method==="DELETE"){const e=g.searchParams.get("id")||"",r=de.deleteVoice(e);if(r&&t.tts?.voice===`custom:${e}`){const s=de.listVoices();t.tts.voice=s.length?`custom:${s[0].id}`:Oe;try{be(t,ce())}catch{}}return a(o,200,{deleted:r,voice:t.tts?.voice})}}if((l==="/tts"||l==="/v1/audio/speech")&&n.method==="POST"){if(t.tts?.enabled===!1)return a(o,503,{error:{message:"tts is disabled in gateway config",type:"tts_disabled"}});let e=null;try{e=JSON.parse((await k(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>$o)return a(o,413,{error:{message:`text too long (max ${$o} chars)`,type:"too_long"}});const s=Number.isFinite(e.speed)?Math.min(2,Math.max(.5,e.speed)):1,i=Ka(t),d=e&&typeof e.voice=="string"&&e.voice.trim()?e.voice.trim():null,m=d||(i?i.voice:t.tts?.voice||Oe);if(i&&!Qa(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(i){const{audio:ne,contentType:Te,redacted:U}=await Ya({dest:i,text:r,voice:m,speed:s,auth:n.headers.authorization||n.headers["xi-api-key"]||"",redaction:t.redaction,isPro:await ke(t.pro?.entitlementToken),format:h});return o.writeHead(200,{"Content-Type":Te,"Content-Length":String(ne.length),"Cache-Control":"no-store","X-Tts-Provider":i.kind,"X-Tts-Redacted":String(U)}),o.end(ne)}if(!await C.ready({onLog:ne=>console.log(ne),allowDownload:t.tts?.allowDownload!==!1,model:t.tts?.model||Ao(Ot()),dtype:t.tts?.dtype||"auto"}))return a(o,503,{error:{message:C.health().error||"tts model not ready",type:"tts_unavailable"}});const w=Xa({requested:d,configured:m,engine:C,voices:de,isPocketVoice:it,isKnownVoice:Oo,isValidVoiceId:Eo,defaultVoice:Oe,defaultPocketVoice:st});if(!w.ok)return a(o,w.status,{error:{message:w.message,type:w.type}});const{voice:v,customId:O,speakerEmbedding:x}=w,D=await C.synth(r,{voice:v,speed:s,speakerEmbedding:x}),Y=C.sampleRate(),we=h==="pcm"?Buffer.from(new Float32Array(D).buffer):C.toWav(D,Y);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(Y),...O||C.isPocket()||C.supportsVoices()?{"X-Tts-Voice":v}:{}}),o.end(we)}catch(y){return a(o,500,{error:{message:y.message,type:"tts_failed"}})}}if(l==="/v1/audio/transcriptions"&&n.method==="POST"){if(t.stt?.enabled===!1)return a(o,403,{error:{message:"STT disabled in gateway config",type:"stt_disabled"}});let e;try{e=Ba(await k(n,Math.max(t.maxBodyBytes||0,64*1024*1024)),n.headers["content-type"])}catch(v){return a(o,v.code===413?413:415,{error:{message:v.message,type:"bad_request"}})}const r=v=>e.find(O=>O.name===v&&!O.filename)?.data.toString("utf8").trim()||"",s=e.find(v=>v.name==="file"&&v.filename)||e.find(v=>v.filename);if(!s?.data?.length)return a(o,400,{error:{message:"a `file` part is required",type:"bad_request"}});let i;try{i=await Da(s.data)}catch(v){return a(o,v.code===415?415:500,{error:{message:v.message,type:"unsupported_media"}})}const d=["json","text","verbose_json"].includes(r("response_format"))?r("response_format"):"json",m=_t(t,"stt");let h=null;if(m.kind==="remote"||m.kind==="container")try{h=bo(m,{fetchImpl:tt})}catch(v){return a(o,500,{error:{message:`stt provider: ${v.message}`,type:"bad_provider"}})}if(!h&&!N.isReady()&&await N.init({model:t.stt?.model||De,allowDownload:t.stt?.allowDownload!==!1,dtype:t.stt?.dtype||void 0,warmMs:t.stt?.warmMs,segment:t.stt?.segment,speaker:Rt(t),onLog:v=>console.log(v)}),!h&&!N.isReady())return a(o,503,{error:{message:`speech model not ready: ${N.health().error||N.state()}`,type:"stt_not_ready"}});const y=r("diarize")==="true"&&t.stt?.diarize!==!1;y&&!$.isReady()&&await $.init({allowDownload:t.stt?.allowDownload!==!1,warmMs:t.stt?.warmMs,onLog:v=>console.log(v)});const w=Date.now();try{const{id:v}=N.createSession({lang:r("language")||void 0,diarize:y,interims:!1,remote:h}),O=[],x=[];let D=null;N.subscribe(v,U=>{U.type==="final"&&U.text?O.push(U):U.type==="language"?D=U.lang:U.type==="error"&&x.push(U.message||U.code)});const Y=16e3*5;for(let U=0;U<i.pcm.length;U+=Y)N.pushAudio(v,i.pcm.subarray(U,Math.min(i.pcm.length,U+Y))),await N.decodeNow(v);if(await N.endSession(v),!O.length&&x.length)return a(o,500,{error:{message:x[0],type:"decode_failed"}});let we=0;const ne=O.map((U,or)=>{const Wt=typeof U.startMs=="number"?U.startMs/1e3:we,rr=(U.durationMs||0)/1e3;return we=Wt+rr,{id:or,start:Math.round(Wt*100)/100,end:Math.round(we*100)/100,text:U.text,...U.speaker?{speaker:U.speaker}:{},...U.turns?{turns:U.turns.map(Ze=>({start:Math.round(Ze.startMs/10)/100,end:Math.round((Ze.startMs+Ze.durationMs)/10)/100,speaker:Ze.speaker}))}:{}}}),Te=ne.map(U=>U.text).join(" ").replace(/\s+/g," ").trim();return d==="text"?(o.writeHead(200,{"content-type":"text/plain; charset=utf-8"}),o.end(Te)):d==="verbose_json"?a(o,200,{task:"transcribe",language:D||r("language")||null,duration:Math.round(i.seconds*100)/100,text:Te,segments:ne,provider:m.kind,took_ms:Date.now()-w}):a(o,200,{text:Te})}catch(v){return a(o,v.code==="too_many_sessions"?429:500,{error:{message:v.message,type:v.code||"stt_error"}})}}if(l==="/v1/voice/embed"&&n.method==="POST"){if(t.stt?.enabled===!1)return a(o,403,{error:{message:"STT disabled in gateway config",type:"stt_disabled"}});if(t.stt?.diarize===!1)return a(o,403,{error:{message:"the speaker model is switched off in the gateway config (stt.diarize)",type:"speaker_disabled"}});const e=String(n.headers["content-type"]||"").split(";")[0].trim().toLowerCase();if(e&&e!=="audio/pcm"&&e!=="application/octet-stream")return a(o,415,{error:{message:"send raw 16 kHz mono Float32 little-endian samples as audio/pcm or application/octet-stream",type:"unsupported_media"}});if(Number(n.headers["content-length"])>Yo)return a(o,413,{error:{message:`at most ${It} s of audio`,type:"too_large"}});let r;try{r=await k(n,Yo)}catch(d){return a(o,d.code===413?413:400,{error:{message:d.code===413?`at most ${It} s of audio`:d.message,type:d.code===413?"too_large":"bad_request"}})}const s=N.toFloat32(r);if(s.length<Ms)return a(o,400,{error:{message:"too little audio to fingerprint (at least a quarter of a second)",type:"sample_too_short"}});if(!$.isReady()){const d=$.init({allowDownload:t.stt?.allowDownload!==!1,warmMs:t.stt?.warmMs,onLog:y=>console.log(y)}),m=Symbol("timeout"),h=await Promise.race([d.then(()=>null,()=>null),new Promise(y=>{setTimeout(()=>y(m),Ko).unref?.()})]);if(!$.isReady())return a(o,503,{error:{message:h===m?"the speaker model is still downloading — try again shortly":`the speaker model is not available: ${$.health().error||$.state()}`,type:"speaker_not_ready"},...$.progress()?{progress:$.progress()}:{}})}const i=await $.embed(s);return i?a(o,200,{vec:$.plainVector(i),seconds:Math.round(s.length/16e3*100)/100,model:$.activeModel()}):a(o,500,{error:{message:"the speaker model gave no fingerprint for this audio",type:"embed_failed"}})}if(l.startsWith("/v1/stt/sessions")&&(l=l.slice(3)),l==="/stt/sessions"&&n.method==="POST"){if(t.stt?.enabled===!1)return a(o,403,{error:{message:"STT disabled in gateway config",type:"stt_disabled"}});let e=null;try{e=JSON.parse((await k(n,t.maxBodyBytes)).toString("utf8")||"{}")}catch{e=null}const r=_t(t,"stt");let s=null;if(r.kind==="remote"||r.kind==="container")try{s=bo(r,{fetchImpl:tt})}catch(O){return a(o,500,{error:{message:`stt provider: ${O.message}`,type:"bad_provider"}})}!s&&!N.isReady()&&N.init({model:t.stt?.model||De,allowDownload:t.stt?.allowDownload!==!1,dtype:t.stt?.dtype||void 0,warmMs:t.stt?.warmMs,segment:t.stt?.segment,speaker:Rt(t),licenseAccepted:Xo(t,t.stt?.model||De),onLog:O=>console.log(O)});const i=e?.diarize===!0&&t.stt?.diarize!==!1;i&&!$.isReady()&&$.init({allowDownload:t.stt?.allowDownload!==!1,warmMs:t.stt?.warmMs,onLog:O=>console.log(O)});const d=typeof e?.translateTo=="string"&&t.stt?.translate!==!1?e.translateTo:null,m=d?{allowDownload:t.stt?.allowDownload!==!1,warmMs:t.stt?.warmMs,onLog:O=>console.log(O)}:null,h=e?.echo&&typeof e.echo=="object"&&typeof e.echo.group=="string"&&["mic","reference"].includes(e.echo.role)&&t.stt?.aec!==!1&&!s?{group:e.echo.group,role:e.echo.role}:null;h&&xt.state()==="off"&&xt.init({allowDownload:t.stt?.allowDownload!==!1,warmMs:t.stt?.warmMs,onLog:O=>console.log(O)});const y=Array.isArray(e?.langs)?e.langs.slice(0,12):null,w=t.stt?.model||De,v=y&&!s?Pa(y,{engine:at(w)?.engine||"",englishOnly:/\.en$/.test(w)}).missing:[];try{const O=e?.poll===!0,x=e?.format==="pcm16"?"pcm16":"f32",D=i&&e?.vectors===!0,{id:Y}=N.createSession({lang:e?.lang,langs:y,translateTo:d,translateLoad:m,echo:h,redact:e?.redact===!0,diarize:i,vectors:D,speakerLabel:e?.speakerLabel,endSilenceMs:e?.endSilenceMs,interims:e?.interims!==!1,remote:s,poll:O,format:x});return a(o,201,{id:Y,state:N.state(),format:x,...O?{poll:!0}:{},...D?{vectors:!0}:{},...v.length?{languagesMissing:v}:{},...d?{translate:$e.state()}:{}})}catch(O){return a(o,O.code==="too_many_sessions"?429:500,{error:{message:O.message,type:O.code||"stt_error"}})}}{const e=l.match(/^\/stt\/sessions\/([0-9a-f-]{36})(\/audio|\/events)?$/);if(e){const r=e[1],s=async(d,m,h)=>{if(m.type!=="final"&&m.type!=="translation"||!d.redact||!m.text)return m;try{let y=m.text;return await qe([ht(()=>y,w=>{y=w})],t.redaction,{isPro:h}),{...m,text:y}}catch{return m}},i=async d=>{const m=N.drainEvents(r);if(!m)return null;const h=[];if(d&&!d.closed){const w=d.remote?"ready":N.state();w==="downloading"||w==="loading"?h.push({type:"progress",state:w,...N.progress()||{}}):w==="error"?h.push({type:"error",code:"model_failed",message:N.health().error||"model failed to load",fatal:!0}):d.diarize&&["downloading","loading"].includes($.state())?h.push({type:"diarize-progress",state:$.state(),...$.progress()||{}}):d.translateTo&&["downloading","loading"].includes($e.state())?h.push({type:"translate-progress",state:$e.state(),...$e.progress()||{}}):Qo.get(d)!==w&&(Qo.set(d,w),h.push({type:"state",state:w}))}const y=d?.redact?await ke(t.pro?.entitlementToken):!0;for(const w of m)d?h.push(await s(d,w,y)):w.type!=="final"&&w.type!=="interim"&&w.type!=="translation"&&h.push(w);return h};if(e[2]==="/audio"&&n.method==="POST"){const d=N.getSession(r)||N.endedSession(r);try{const m=await k(n,t.maxBodyBytes);N.pushAudio(r,N.toFloat32(m,d?.format));const h=await i(d);return a(o,200,{ok:!0,state:N.state(),...h?{events:h}:{}})}catch(m){const h=m.code==="no_session"?await i(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=N.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=x=>o.write(`data: ${JSON.stringify(x)}
|
|
59
59
|
|
|
60
|
-
`),h=
|
|
61
|
-
data: ${JSON.stringify(
|
|
60
|
+
`),h=d.redact?await ke(t.pro?.entitlementToken):!0,y=x=>s(d,x,h);m({type:"state",state:d.remote?"ready":N.state()});const w=setInterval(()=>{const x=d.remote?"ready":N.state();if(x==="downloading"||x==="loading"){m({type:"progress",state:x,...N.progress()||{}});return}if(x==="error"){m({type:"error",code:"model_failed",message:N.health().error||"model failed to load",fatal:!0}),clearInterval(w);return}if(d.diarize){const D=$.state();if(D==="downloading"||D==="loading"){m({type:"diarize-progress",state:D,...$.progress()||{}});return}}if(d.translateTo){const D=$e.state();if(D==="downloading"||D==="loading"){m({type:"translate-progress",state:D,...$e.progress()||{}});return}}m({type:"state",state:x}),clearInterval(w)},500);w.unref?.();let v=Promise.resolve();const O=N.subscribe(r,x=>{v=v.then(async()=>{m(await y(x)),x.type==="end"&&(clearInterval(w),o.end())}).catch(()=>{})});n.on("close",()=>{clearInterval(w),O?.()});return}if(!e[2]&&n.method==="DELETE"){const d=N.getSession(r);await N.endSession(r);const m=d?.poll?await i(d).catch(()=>null):null;return a(o,200,{ok:!0,...m?{events:m}:{}})}}}if(l==="/logs"&&n.method==="GET")return a(o,200,{entries:[...I].reverse()});if(l==="/config"&&n.method==="GET"){const e=await ke(t.pro?.entitlementToken);return a(o,200,No(t,{proUnlocked:e,policy:et()}))}if(l==="/config"&&n.method==="POST"){let e=null;try{e=JSON.parse((await k(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);if(e.capabilities&&typeof e.capabilities=="object"){const h=JSON.parse(JSON.stringify({capabilities:t.capabilities||{},redaction:t.redaction||{}}));try{Mo(h,{capabilities:e.capabilities})}catch(w){if(w?.code==="SHAPE")return a(o,400,{error:w.message});throw w}const y=Object.keys(e.capabilities).map(w=>as(w,t.capabilities?.[w],h.capabilities?.[w])).find(Boolean);if(y&&!await ke(t.pro?.entitlementToken))return a(o,403,{error:y,needs:"pro"})}try{Mo(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&&Fe?.restart("sandbox settings changed");try{be(t,ce())}catch(h){return a(o,500,{error:`could not persist config: ${h.message}`})}const s=t.redaction?.detection,i=!s||!s.backend||s.backend==="off",d=L.state();t.ner?.autostart&&i&&d!=="ready"&&d!=="loading"&&d!=="downloading"&&L.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 ke(t.pro?.entitlementToken);return a(o,200,No(t,{proUnlocked:m,policy:et()}))}if(n.method==="GET"&&l==="/skills")return ve(n,o,t,`/skills${Re(g,t)}`,{pick:e=>({skills:Array.isArray(e?.skills)?e.skills:[]})});if(n.method==="POST"&&l==="/v1/threads/send"){if(!G(n))return a(o,403,{error:{message:"asking another chat: extension origin or gateway token required",type:"forbidden"}});if(n.headers["x-chatpanel-link-device"])return a(o,403,{error:{message:"asking another chat is not available from a linked phone yet",type:"forbidden"}});const e=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 k(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||""),i=String(r.message||"").trim();if(!i||i.length>mo)return a(o,400,{error:{message:`threads/send: a message of 1–${mo} 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=on(m,{cards:me.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 y=rn({fromTitle:d?.title,message:i}),w={thread:{id:h.thread,...m.title?{title:m.title}:{}},...h.workingDir?{workingDir:h.workingDir}:{}};let v="";try{const x=await fetch(`http://127.0.0.1:${n.socket.localPort}/v1/chat/completions`,{method:"POST",headers:{"content-type":"application/json","x-chatpanel-token":Be()||_e(),"x-chatpanel-run":encodeURIComponent(JSON.stringify(w))},body:JSON.stringify({model:h.model,messages:[...nn(m),{role:"user",content:y}],stream:!1}),signal:AbortSignal.timeout(6e5)}),D=await x.json().catch(()=>null);if(!x.ok)return a(o,502,{error:{message:`that chat's ${h.model} did not answer: ${D?.error?.message||`HTTP ${x.status}`}`,type:"upstream"}});v=String(D?.choices?.[0]?.message?.content||"")}catch(x){return a(o,502,{error:{message:`that chat's ${h.model} did not answer: ${x?.message||x}`,type:"upstream"}})}const O=an(e.get(s)||m,{question:y,reply:v,model:h.model,from:d});e.write([O],{host:"gateway",at:Date.now()});try{const x=yo(e.get(s));x&&J.bulk({upserts:[x],removes:[]})}catch{}return Ve({ids:[s]}),a(o,200,{ok:!0,title:m.title,model:h.model,reply:v})}const q=/^(?:\/v1)?(\/agent-sessions(?:\/read|\/adopt|\/catchup)?)$/.exec(l)?.[1];if(n.method==="POST"&&q)return G(n)?n.headers["x-chatpanel-link-device"]&&t.link?.agentSessions===!1?a(o,403,{error:{message:"this computer does not share its coding agents' sessions with a linked phone — Settings › Link › Phones",type:"forbidden"}}):ve(n,o,t,q,{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"&&l==="/skills-quarantined")return ve(n,o,t,`/skills-quarantined${Re(g,t)}`,{pick:e=>({quarantined:Array.isArray(e?.quarantined)?e.quarantined:[]})});if(l==="/skills"&&n.method==="POST")return G(n)?ve(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(l)&&n.method==="DELETE"){const e=decodeURIComponent(l.slice(8));return Lt(e)?a(o,400,{error:{message:"not a skill id",type:"invalid_request"}}):G(n)?ve(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(l)&&n.method==="PUT"){const e=/^\/skills\/([^/]+)\/file\/(.+)$/.exec(l),r=decodeURIComponent(e[1]);return Lt(r)||/(^|\/)\.\.(\/|$)/.test(decodeURIComponent(e[2]))?a(o,400,{error:{message:"not a skill file",type:"invalid_request"}}):G(n)?ve(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"&&l==="/agent-defs")return ve(n,o,t,`/agent-defs${Re(g,t)}`,{pick:e=>({agents:Array.isArray(e?.agents)?e.agents:[],...e?.quarantined?{quarantined:e.quarantined}:{},...e?.problems?{problems:e.problems}:{}})});if(n.method==="GET"&&/^\/agent-defs\/[^/]+$/.test(l)){const e=decodeURIComponent(l.slice(12));return Lt(e)?a(o,400,{error:{message:"not an agent id",type:"invalid_request"}}):ve(n,o,t,`/agent-defs/${encodeURIComponent(e)}${Re(g,t)}`)}if(l.startsWith("/a2a/")){if(!G(n))return a(o,403,{error:{message:"a2a: extension origin or gateway token required",type:"forbidden"}});try{if(n.method==="GET"&&l==="/a2a/agents")return a(o,200,{agents:Lr()});if(n.method==="POST"&&l==="/a2a/card"){const e=JSON.parse((await k(n,t.maxBodyBytes)).toString("utf8")||"{}");e.forget&&Br(e.url||"");const r=await ot(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"&&l==="/a2a/message"){const e=JSON.parse((await k(n,t.maxBodyBytes)).toString("utf8")||"{}"),r=e.card||(await ot(e.url,{auth:String(e.auth||"")})).card,s=await Dr({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"&&l==="/a2a/message/stream"){const e=JSON.parse((await k(n,t.maxBodyBytes)).toString("utf8")||"{}"),r=e.card||(await ot(e.url,{auth:String(e.auth||"")})).card;o.writeHead(200,{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"});const s=(i,d)=>o.write(`event: ${i}
|
|
61
|
+
data: ${JSON.stringify(d)}
|
|
62
62
|
|
|
63
|
-
`);try{const l=await Br({card:r,message:e.message||{messageId:`cp_${Date.now().toString(36)}`,role:"ROLE_USER",parts:[{text:String(e.text||"")}]},auth:String(e.auth||""),contextId:String(e.contextId||""),taskId:String(e.taskId||""),onEvent:c=>s(c.kind,{kind:c.kind,task:c.task,message:c.message})});s("done",l)}catch(l){s("error",{code:l.code||"ERROR",message:l.message})}return o.end()}if(n.method==="POST"&&i==="/a2a/task"){const e=JSON.parse((await S(n,t.maxBodyBytes)).toString("utf8")||"{}"),r=e.card||(await ot(e.url,{auth:String(e.auth||"")})).card,s=e.cancel?await Dr({card:r,id:String(e.id||""),auth:String(e.auth||"")}):await Mr({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 eo||e?.name==="A2AClientError"?e.code:"ERROR";return a(o,e instanceof eo&&e.code==="UNREACHABLE"?502:400,{error:{message:e.message,type:"a2a_error",code:r}})}}if(n.method==="POST"&&(i==="/agent-defs/export"||i==="/agent-defs/export-plan"))return G(n)?ve(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"}}):ve(n,o,t,`/skills/${encodeURIComponent(e)}${Re(f,t)}`,{pick:r=>({skill:r?.skill||null})})}if(i==="/channels"||/^\/channels\/(connect|pair|unpair|settings|disconnect)$/.test(i)){if(!G(n))return a(o,403,{error:{message:"channels: extension origin or gateway token required",type:"forbidden"}});if(!(i==="/channels"&&n.method==="GET"||i!=="/channels"&&n.method==="POST"))return a(o,405,{error:{message:"method not allowed",type:"invalid_request"}});const e=await je(t);if(!e)return a(o,503,{error:{message:"no bridge is configured",type:"no_bridge"}});const r=ze(t.bridge?.token);try{const s=n.method==="POST"?(await S(n,t.maxBodyBytes)).toString("utf8"):"",l=await fetch(`${e}${i}`,{method:n.method,headers:{Accept:"application/json",...n.method==="POST"?{"content-type":"application/json"}:{},...r?{Authorization:`Bearer ${r}`}:{}},...n.method==="POST"?{body:s||"{}"}:{},signal:AbortSignal.timeout(15e3)}),c=await l.json().catch(()=>({}));return a(o,l.status,c)}catch(s){return a(o,502,{error:{message:`bridge unreachable: ${s.message}`,type:"bridge_unreachable"}})}}if(n.method==="GET"&&/^\/skills\/[^/]+\/file\/.+/.test(i)){const e=/^\/skills\/([^/]+)\/file\/(.+)$/.exec(i),r=decodeURIComponent(e[1]),s=e[2];return!r||r==="."||r===".."||r.includes("/")||r.includes("\\")||/(^|\/)\.\.(\/|$)/.test(decodeURIComponent(s))?a(o,400,{error:{message:"not a skill file",type:"invalid_request"}}):ve(n,o,t,`/skills/${encodeURIComponent(r)}/file/${s}${Re(f,t)}`)}if(n.method==="GET"&&/\/models$/.test(i)){const e=await j(),r=e.sig!==void 0&&e.sig!==R;return R=e.sig,a(o,200,await rs(t,{serviceHealth:async()=>e,fresh:r,engineAt:d.engineAt}))}if(Ns.some(e=>i===e||i.startsWith(`${e}/`)))return a(o,404,{error:{message:`this gateway (${ue}) has no ${i} — update it to use this feature`,type:"unknown_endpoint"}});const H=vs(i,n.headers,t);let K;try{K=await S(n,t.maxBodyBytes)}catch(e){a(o,e.code===413?413:400,{error:e.code===413?"payload too large":"bad request"}),n.destroy();return}let W=null,k=null,ie=K,We=0,Ae=0,Lt=0,Se=!1,Pe=!1,jt="",Ne=!0;const ae=t.logRequests&&H.redactable&&n.method==="POST"?bs(ee):null,Qo=Date.now();if(H.redactable&&n.method==="POST"&&K.length){try{k=JSON.parse(K.toString("utf8"))}catch{k=null}if(k&&ks(k,H.kind))ie=K;else if(k){const e=t.tools||{};if(e.autoNarrow!==!1&&Array.isArray(k.tools)&&k.tools.length){const g=Number(e.maxPerTurn)>0?Number(e.maxPerTurn):us,w=e.narrowAll?null:O=>!ms.test(Jo(O)),v=k.tools.length;k.tools=dr(k.tools,hs(k,H.kind),{cap:g,keep:w,name:Jo,description:ps}),Lt=v-k.tools.length}if(Ne=await ke(t.pro?.entitlementToken),Se=String(n.headers["x-chatpanel-redaction"]||"").trim().toLowerCase()==="off"&&G(n),!Se){const g=dt(k?.model,t,H.kind,{destination:String(n.headers["x-chatpanel-destination"]||k?.chatpanel?.destination||"").trim(),down:()=>!1}),w=g?.type==="api"?await d.decide(g,k?.model).catch(()=>null):null;Pe=w?.redact===!1,jt=Pe?w.engine||"declared":""}if(!Se&&!Pe){const g=Qa(t,Ne);if(!g.allowed)return a(o,402,{error:{message:`ChatPanel Gateway free trial used up (${g.cap} redactions). Add a ChatPanel Pro entitlement token to unlock unlimited full-tier redaction (names/orgs).`,type:"free_limit_reached"}})}!Se&&!Pe&&await nt(t);const r=Se?[]:H.adapter.collectSegments(k,t.redaction,{skipPublic:G(n)}),s=new AbortController;o.on("close",()=>{o.writableFinished||s.abort()});const l=ae?ae.clock():0,{vault:c,count:m,sanitized:h}=Se?{vault:null,count:0,sanitized:0}:await qe(r,t.redaction,{signal:s.signal,isPro:Ne,sanitizeOnly:Pe,onEgress:g=>Nt.push(Do({ts:Date.now(),client:"redaction",tool:`detect:${g.backend}@${g.host||"local"}`,ok:g.ok,ms:g.ms,error:g.error}))});if(ae&&ae.lap("redact",l),H.adapter.joinTextParts?.(k),W=c,We=m,Ae=h||0,m>0&&o.setHeader("x-chatpanel-redacted",String(m)),!Ne&&m>0){Ya(t,Ne);try{be(t,ce())}catch{}}if(!Se&&!Pe&&Array.isArray(k.tools)&&k.tools.length&&typeof H.adapter.injectSystemNote=="function"){const g=dt(k?.model,t,H.kind,{destination:String(n.headers["x-chatpanel-destination"]||k?.chatpanel?.destination||"").trim(),down:v=>!!v.service&&_.fn(v.id)==="down"}),w=!(g&&g.type==="api");H.adapter.injectSystemNote(k,ur({toolData:t.tools?.toolData,ownTools:w}))}else!Se&&m>0&&typeof H.adapter.injectSystemNote=="function"&&H.adapter.injectSystemNote(k,mr());ie=Buffer.from(JSON.stringify(k),"utf8")}}const zt=cr({vault:W,toolData:t.tools?.toolData}),Ke=k&&typeof k.chatpanel=="object"&&k.chatpanel||null;if(Ke&&(delete k.chatpanel,ie=Buffer.from(JSON.stringify(k),"utf8")),typeof k?.model=="string"&&k.model.startsWith("fusion:")){const e=Bn(k.model,t,await j());if(e?.error)return ae?.commit(),a(o,400,{error:{message:e.error,type:"fusion"}});e&&(k.model=e.model,ie=Buffer.from(JSON.stringify(k),"utf8"),o.setHeader("x-chatpanel-fusion",`${e.fusion.id} -> ${e.model}`))}const se={destination:String(n.headers["x-chatpanel-destination"]||Ke?.destination||"").trim(),reach:String(n.headers["x-chatpanel-reach"]||Ke?.reach||"").trim(),run:Jt(n.headers["x-chatpanel-run"],Ke?.run)},Qe=await j(),Gt=e=>!!e.service&&Qe(e.id)==="down";let N=dt(k?.model,t,H.kind,{destination:se.destination,down:Gt});N?.type==="agent"&&k?.model&&!se.destination&&!ss(N,k.model)&&(await as(t,{serviceHealth:async()=>Qe,engineAt:d.engineAt}),N=dt(k?.model,t,H.kind,{destination:se.destination,down:Gt}));const Ht=N?.service&&Qe(N.id)==="down"?await P().revive(N.service).catch(()=>null):null;if(Ht?.ok&&(_.at=0),N?.service&&Qe(N.id)==="down"&&!Ht?.ok)return ae?.commit(),a(o,503,{error:{message:`${N.id} is not running — the model ${JSON.stringify(k?.model||"")} is served by an engine the Runtime has stopped; start it under Settings › Runtime`,type:"engine_down",service:N.service}});if(se.destination&&(!N||N.id!==se.destination))return ae?.commit(),a(o,404,{error:{message:`no destination "${se.destination}" is configured on this gateway`,type:"unknown_destination",known:ns(t).map(e=>e.id)}});const le=He(n.headers);if(le&&!aa(le,N?.type==="api"?"api":"agent"))return ae?.commit(),a(o,403,{error:{message:`link: partner "${le.partner}" may not use ${N?.type==="api"?"this model":"this computer’s coding agents"} — its scopes are ${le.scopes.join(", ")||"none"}; the owner grants agents at pairing`,type:"forbidden",code:"link_scope"}});const Ye=le&&H.redactable&&n.method==="POST"&&k?{caller:le,surface:xn(le,le.kind==="partner"?"":y?.deviceNameOf(le.device)),model:k.model||null,startedAt:Qo}:null;ae&&(ae.meta={t:Date.now(),model:k?.model||null,dest:N?N.id:null,type:N?N.type:null,redacted:We,sanitized:Ae,narrowed:Lt,detail:Go(W,t.logDetail),redaction:Se?"off":Pe?`on-device (${jt})`:t.redaction.tier||"basic",...le?.kind==="partner"?{via:sa(le)}:{}});const Xe=et();if(Xe&&N){const e=N.type==="api"?qt(Xe,{model:k?.model||"",endpoint:N.baseUrl||""}):Pr(Xe,N.agent||N.id)?qt(Xe,{model:k?.model||""}):{ok:!1,reason:`agent "${N.agent||N.id}" is not allowed by your organisation’s policy`};if(!e.ok)return ae?.commit(),a(o,403,{error:{message:e.reason,type:"policy",code:"org_policy"}})}if(N&&N.type==="api")return N.baseUrl?Ss(N.baseUrl,t)?(ae?.commit(),a(o,508,{error:{message:`destination "${N.id}" points back at the gateway (${N.baseUrl}) — refusing to forward (would loop).`,type:"loop_detected"}})):Bs(n,o,{...H,pathname:i,search:f.search,base:N.baseUrl,destKey:N.apiKey,destProtocol:N.protocol,harness:zt,trace:ae,link:Ye&&{...Ye,agentId:N.id,dest:{type:"api",id:N.id}}},ie,W):(ae?.commit(),a(o,502,{error:`destination "${N.id}" has no baseUrl`}));const mt=Je(n),Ut=mt==="local"&&t.bridge?.openAgentLane?"token":mt;if(Ut==="local")return ae?.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 Vt=Math.max(0,Math.min(8,Number(n.headers["x-chatpanel-ask-depth"])||0)),Yo=new Set(["thread","ephemeral","workingDir","worker"]),pt=le?.kind==="partner";if(mt==="token"&&n.headers["x-chatpanel-link-device"]&&!pt&&!(se.run&&Object.keys(se.run).some(e=>!Yo.has(e)))){const e=Jt(null,co(lo(me.get("agentTools").agentTools?.value,N?.agent||k?.model)));e&&(se.run={...e,...se.run||{}})}if(pt){const e=Jt(null,co(lo(me.get("agentTools").agentTools?.value,N?.agent||k?.model)));se.run={...e||{},...ia(se.run,le.device)};const r=y?.partnerFolderOf(le.device);if(!r)return ae?.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"}});se.run.workingDir=r,se.reach="",Array.isArray(k?.tools)&&(k.tools=k.tools.filter(s=>!fo(s?.function?.name??s?.name)))}const Be=hr({...se.run||{},...se.reach?{reach:se.reach}:{},...Vt?{askDepth:Vt}:{}},Ut);Be.reach&&o.setHeader("x-chatpanel-reach-used",Be.reach);const Xo=pt?{inbox:b,partner:le.partner,device:le.device,conversation:Be.thread?.id||null}:null,Zo=Ye&&{...Ye,dest:{type:"agent",id:N?.id||"bridge"},threadId:Be.thread?.id||null};return Es(n,o,{...H,pathname:i,agentOverride:N?.agent,harness:zt,trace:ae,run:Object.keys(Be).length?Be:null,owner:Xo,link:Zo},k,W,t,Ne)});return pe.on("close",()=>{E?.stop("closed"),Gn(),p.close(),y?.stop(),b.stop()}),pe.on("upgrade",(n,o,f)=>{o.on("error",()=>{});const i=String(n.url||"").split("?")[0];if(y&&i.startsWith(na)){y.acceptTunnel(n,o,f).catch(()=>{try{o.destroy()}catch{}});return}try{o.end(`HTTP/1.1 404 Not Found\r
|
|
63
|
+
`);try{const i=await Cr({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",i)}catch(i){s("error",{code:i.code||"ERROR",message:i.message})}return o.end()}if(n.method==="POST"&&l==="/a2a/task"){const e=JSON.parse((await k(n,t.maxBodyBytes)).toString("utf8")||"{}"),r=e.card||(await ot(e.url,{auth:String(e.auth||"")})).card,s=e.cancel?await Rr({card:r,id:String(e.id||""),auth:String(e.auth||"")}):await Ir({card:r,id:String(e.id||""),auth:String(e.auth||"")});return a(o,200,{ok:!0,...s})}return a(o,404,{error:{message:`no such a2a route: ${l}`,type:"invalid_request"}})}catch(e){const r=e instanceof to||e?.name==="A2AClientError"?e.code:"ERROR";return a(o,e instanceof to&&e.code==="UNREACHABLE"?502:400,{error:{message:e.message,type:"a2a_error",code:r}})}}if(n.method==="POST"&&(l==="/agent-defs/export"||l==="/agent-defs/export-plan"))return G(n)?ve(n,o,t,l,{method:"POST",timeoutMs:15e3}):a(o,403,{error:{message:"exporting an agent: extension origin or gateway token required",type:"forbidden"}});if(n.method==="GET"&&/^\/skills\/[^/]+$/.test(l)){const e=decodeURIComponent(l.slice(8));return!e||e==="."||e===".."||e.includes("/")||e.includes("\\")?a(o,400,{error:{message:"not a skill id",type:"invalid_request"}}):ve(n,o,t,`/skills/${encodeURIComponent(e)}${Re(g,t)}`,{pick:r=>({skill:r?.skill||null})})}if(l==="/channels"||/^\/channels\/(connect|pair|unpair|settings|disconnect)$/.test(l)){if(!G(n))return a(o,403,{error:{message:"channels: extension origin or gateway token required",type:"forbidden"}});if(!(l==="/channels"&&n.method==="GET"||l!=="/channels"&&n.method==="POST"))return a(o,405,{error:{message:"method not allowed",type:"invalid_request"}});const e=await je(t);if(!e)return a(o,503,{error:{message:"no bridge is configured",type:"no_bridge"}});const r=ze(t.bridge?.token);try{const s=n.method==="POST"?(await k(n,t.maxBodyBytes)).toString("utf8"):"",i=await fetch(`${e}${l}`,{method:n.method,headers:{Accept:"application/json",...n.method==="POST"?{"content-type":"application/json"}:{},...r?{Authorization:`Bearer ${r}`}:{}},...n.method==="POST"?{body:s||"{}"}:{},signal:AbortSignal.timeout(15e3)}),d=await i.json().catch(()=>({}));return a(o,i.status,d)}catch(s){return a(o,502,{error:{message:`bridge unreachable: ${s.message}`,type:"bridge_unreachable"}})}}if(n.method==="GET"&&/^\/skills\/[^/]+\/file\/.+/.test(l)){const e=/^\/skills\/([^/]+)\/file\/(.+)$/.exec(l),r=decodeURIComponent(e[1]),s=e[2];return!r||r==="."||r===".."||r.includes("/")||r.includes("\\")||/(^|\/)\.\.(\/|$)/.test(decodeURIComponent(s))?a(o,400,{error:{message:"not a skill file",type:"invalid_request"}}):ve(n,o,t,`/skills/${encodeURIComponent(r)}/file/${s}${Re(g,t)}`)}if(n.method==="GET"&&/\/models$/.test(l)){const e=await j(),r=e.sig!==void 0&&e.sig!==R;return R=e.sig,a(o,200,await ss(t,{serviceHealth:async()=>e,fresh:r,engineAt:c.engineAt}))}if(Ds.some(e=>l===e||l.startsWith(`${e}/`)))return a(o,404,{error:{message:`this gateway (${ue}) has no ${l} — update it to use this feature`,type:"unknown_endpoint"}});const H=Ts(l,n.headers,t);let K;try{K=await k(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,S=null,ie=K,We=0,Ae=0,jt=0,Se=!1,Pe=!1,zt="",Ne=!0;const ae=t.logRequests&&H.redactable&&n.method==="POST"?Ss(ee):null,Zo=Date.now();if(H.redactable&&n.method==="POST"&&K.length){try{S=JSON.parse(K.toString("utf8"))}catch{S=null}if(S&&xs(S,H.kind))ie=K;else if(S){const e=t.tools||{};if(e.autoNarrow!==!1&&Array.isArray(S.tools)&&S.tools.length){const y=Number(e.maxPerTurn)>0?Number(e.maxPerTurn):hs,w=e.narrowAll?null:O=>!ys.test(Jo(O)),v=S.tools.length;S.tools=mr(S.tools,gs(S,H.kind),{cap:y,keep:w,name:Jo,description:fs}),jt=v-S.tools.length}if(Ne=await ke(t.pro?.entitlementToken),Se=String(n.headers["x-chatpanel-redaction"]||"").trim().toLowerCase()==="off"&&G(n),!Se){const y=dt(S?.model,t,H.kind,{destination:String(n.headers["x-chatpanel-destination"]||S?.chatpanel?.destination||"").trim(),down:()=>!1}),w=y?.type==="api"?await c.decide(y,S?.model).catch(()=>null):null;Pe=w?.redact===!1,zt=Pe?w.engine||"declared":""}if(!Se&&!Pe){const y=Za(t,Ne);if(!y.allowed)return a(o,402,{error:{message:`ChatPanel Gateway free trial used up (${y.cap} redactions). Add a ChatPanel Pro entitlement token to unlock unlimited full-tier redaction (names/orgs).`,type:"free_limit_reached"}})}!Se&&!Pe&&await nt(t);const r=Se?[]:H.adapter.collectSegments(S,t.redaction,{skipPublic:G(n)}),s=new AbortController;o.on("close",()=>{o.writableFinished||s.abort()});const i=ae?ae.clock():0,{vault:d,count:m,sanitized:h}=Se?{vault:null,count:0,sanitized:0}:await qe(r,t.redaction,{signal:s.signal,isPro:Ne,sanitizeOnly:Pe,onEgress:y=>Nt.push(Co({ts:Date.now(),client:"redaction",tool:`detect:${y.backend}@${y.host||"local"}`,ok:y.ok,ms:y.ms,error:y.error}))});if(ae&&ae.lap("redact",i),H.adapter.joinTextParts?.(S),W=d,We=m,Ae=h||0,m>0&&o.setHeader("x-chatpanel-redacted",String(m)),!Ne&&m>0){qa(t,Ne);try{be(t,ce())}catch{}}if(!Se&&!Pe&&Array.isArray(S.tools)&&S.tools.length&&typeof H.adapter.injectSystemNote=="function"){const y=dt(S?.model,t,H.kind,{destination:String(n.headers["x-chatpanel-destination"]||S?.chatpanel?.destination||"").trim(),down:v=>!!v.service&&_.fn(v.id)==="down"}),w=!(y&&y.type==="api");H.adapter.injectSystemNote(S,hr({toolData:t.tools?.toolData,ownTools:w}))}else!Se&&m>0&&typeof H.adapter.injectSystemNote=="function"&&H.adapter.injectSystemNote(S,yr());ie=Buffer.from(JSON.stringify(S),"utf8")}}const Gt=pr({vault:W,toolData:t.tools?.toolData}),Ke=S&&typeof S.chatpanel=="object"&&S.chatpanel||null;if(Ke&&(delete S.chatpanel,ie=Buffer.from(JSON.stringify(S),"utf8")),typeof S?.model=="string"&&S.model.startsWith("fusion:")){const e=Cn(S.model,t,await j());if(e?.error)return ae?.commit(),a(o,400,{error:{message:e.error,type:"fusion"}});e&&(S.model=e.model,ie=Buffer.from(JSON.stringify(S),"utf8"),o.setHeader("x-chatpanel-fusion",`${e.fusion.id} -> ${e.model}`))}const se={destination:String(n.headers["x-chatpanel-destination"]||Ke?.destination||"").trim(),reach:String(n.headers["x-chatpanel-reach"]||Ke?.reach||"").trim(),run:Jt(n.headers["x-chatpanel-run"],Ke?.run)},Ye=await j(),Ht=e=>!!e.service&&Ye(e.id)==="down";let M=dt(S?.model,t,H.kind,{destination:se.destination,down:Ht});M?.type==="agent"&&S?.model&&!se.destination&&!ds(M,S.model)&&(await ls(t,{serviceHealth:async()=>Ye,engineAt:c.engineAt}),M=dt(S?.model,t,H.kind,{destination:se.destination,down:Ht}));const Ut=M?.service&&Ye(M.id)==="down"?await P().revive(M.service).catch(()=>null):null;if(Ut?.ok&&(_.at=0),M?.service&&Ye(M.id)==="down"&&!Ut?.ok)return ae?.commit(),a(o,503,{error:{message:`${M.id} is not running — the model ${JSON.stringify(S?.model||"")} is served by an engine the Runtime has stopped; start it under Settings › Runtime`,type:"engine_down",service:M.service}});if(se.destination&&(!M||M.id!==se.destination))return ae?.commit(),a(o,404,{error:{message:`no destination "${se.destination}" is configured on this gateway`,type:"unknown_destination",known:is(t).map(e=>e.id)}});const le=He(n.headers);if(le&&!la(le,M?.type==="api"?"api":"agent"))return ae?.commit(),a(o,403,{error:{message:`link: partner "${le.partner}" may not use ${M?.type==="api"?"this model":"this computer’s coding agents"} — its scopes are ${le.scopes.join(", ")||"none"}; the owner grants agents at pairing`,type:"forbidden",code:"link_scope"}});const Qe=le&&H.redactable&&n.method==="POST"&&S?{caller:le,surface:En(le,le.kind==="partner"?"":f?.deviceNameOf(le.device)),model:S.model||null,startedAt:Zo}:null;ae&&(ae.meta={t:Date.now(),model:S?.model||null,dest:M?M.id:null,type:M?M.type:null,redacted:We,sanitized:Ae,narrowed:jt,detail:Ho(W,t.logDetail),redaction:Se?"off":Pe?`on-device (${zt})`:t.redaction.tier||"basic",...le?.kind==="partner"?{via:da(le)}:{}});const Xe=et();if(Xe&&M){const e=M.type==="api"?eo(Xe,{model:S?.model||"",endpoint:M.baseUrl||""}):Nr(Xe,M.agent||M.id)?eo(Xe,{model:S?.model||""}):{ok:!1,reason:`agent "${M.agent||M.id}" is not allowed by your organisation’s policy`};if(!e.ok)return ae?.commit(),a(o,403,{error:{message:e.reason,type:"policy",code:"org_policy"}})}if(M&&M.type==="api")return M.baseUrl?_s(M.baseUrl,t)?(ae?.commit(),a(o,508,{error:{message:`destination "${M.id}" points back at the gateway (${M.baseUrl}) — refusing to forward (would loop).`,type:"loop_detected"}})):Cs(n,o,{...H,pathname:l,search:g.search,base:M.baseUrl,destKey:M.apiKey,destProtocol:M.protocol,harness:Gt,trace:ae,link:Qe&&{...Qe,agentId:M.id,dest:{type:"api",id:M.id}}},ie,W):(ae?.commit(),a(o,502,{error:`destination "${M.id}" has no baseUrl`}));const mt=Le(n),Vt=mt==="local"&&t.bridge?.openAgentLane?"token":mt;if(Vt==="local")return ae?.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 Ft=Math.max(0,Math.min(8,Number(n.headers["x-chatpanel-ask-depth"])||0)),qo=new Set(["thread","ephemeral","workingDir","worker"]),pt=le?.kind==="partner";if(mt==="token"&&n.headers["x-chatpanel-link-device"]&&!pt&&!(se.run&&Object.keys(se.run).some(e=>!qo.has(e)))){const e=Jt(null,uo(co(me.get("agentTools").agentTools?.value,M?.agent||S?.model)));e&&(se.run={...e,...se.run||{}})}if(pt){const e=Jt(null,uo(co(me.get("agentTools").agentTools?.value,M?.agent||S?.model)));se.run={...e||{},...ca(se.run,le.device)};const r=f?.partnerFolderOf(le.device);if(!r)return ae?.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"}});se.run.workingDir=r,se.reach="",Array.isArray(S?.tools)&&(S.tools=S.tools.filter(s=>!go(s?.function?.name??s?.name)))}const Me=gr({...se.run||{},...se.reach?{reach:se.reach}:{},...Ft?{askDepth:Ft}:{}},Vt);Me.reach&&o.setHeader("x-chatpanel-reach-used",Me.reach);const er=pt?{inbox:b,partner:le.partner,device:le.device,conversation:Me.thread?.id||null}:null,tr=Qe&&{...Qe,dest:{type:"agent",id:M?.id||"bridge"},threadId:Me.thread?.id||null};return As(n,o,{...H,pathname:l,agentOverride:M?.agent,harness:Gt,trace:ae,run:Object.keys(Me).length?Me:null,owner:er,link:tr},S,W,t,Ne)});return pe.on("close",()=>{E?.stop("closed"),Vn(),p.close(),f?.stop(),b.stop()}),pe.on("upgrade",(n,o,g)=>{o.on("error",()=>{});const l=String(n.url||"").split("?")[0];if(f&&l.startsWith(ia)){f.acceptTunnel(n,o,g).catch(()=>{try{o.destroy()}catch{}});return}try{o.end(`HTTP/1.1 404 Not Found\r
|
|
64
64
|
connection: close\r
|
|
65
65
|
content-length: 0\r
|
|
66
66
|
\r
|
|
67
|
-
`)}catch{}}),pe.once("listening",()=>{P()}),pe.linkHost=
|
|
67
|
+
`)}catch{}}),pe.once("listening",()=>{P()}),pe.linkHost=f,pe.runtimeDefaults=()=>P().ensureDefaults(),pe}function Jt(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(f=>String(f).slice(0,80)).slice(0,32)),u.workspace&&typeof u.workspace=="object"&&u.workspace.repo){const f=u.workspace;p.workspace={repo:String(f.repo).slice(0,400),projectId:String(f.projectId||"").slice(0,120),jobId:String(f.jobId||"").slice(0,120),...f.base?{base:String(f.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)),os.includes(u.permissionMode)&&u.permissionMode!=="default"&&(p.permissionMode=u.permissionMode),u.sandbox&&typeof u.sandbox=="object"){const f=(Array.isArray(u.sandbox.hosts)?u.sandbox.hosts:String(u.sandbox.hosts||"").split(/[\s,;]+/)).map(T=>String(T).trim().toLowerCase().slice(0,253)).filter(Boolean).slice(0,64),A=(Array.isArray(u.sandbox.write)?u.sandbox.write:[]).map(T=>String(T).slice(0,1024)).filter(Boolean).slice(0,32),B=u.sandbox.outside===!0,E=(Array.isArray(u.sandbox.signIn)?u.sandbox.signIn:[]).map(T=>String(T).trim().toLowerCase().slice(0,32)).filter(Boolean).slice(0,8);(f.length||A.length||B||E.length)&&(p.sandbox={...f.length?{hosts:f}:{},...A.length?{write:A}:{},...B?{outside:!0}:{},...E.length?{signIn:E}:{}})}const b=Zr(u.thread);return b&&(p.thread=b),u.ephemeral===!0&&(p.ephemeral=!0),u.worker===!0&&(p.worker=!0,p.ephemeral=!0),u.lean===!0&&(p.lean=!0,p.ephemeral=!0),Object.keys(p).length?p:null}let Fe=null,ut=null;async function Al(t=Kt()){Wr();let c=null;try{c=await $r()}catch(T){throw T instanceof Ar&&(console.error(`[chatpanel-gateway] org policy: ${T.message}`),process.exit(78)),T}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=Er({enabled:Zt(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}`}`),_r(globalThis,{allow:u?.egress?(T,{local:_})=>Mr(u,T,{local:_}):null}),_e();const b=Is(t),f=Ur(t),A=ar(t);let B=!1;b.on("error",T=>{if(T&&T.code==="EADDRINUSE"){const _=ct(t.host)?"127.0.0.1":t.host;fetch(`http://${_}:${t.port}/health`,{signal:AbortSignal.timeout(1500)}).then(R=>R.ok?R.json():null).catch(()=>null).then(R=>{const j=!!(R?.version&&typeof R.tier=="string"),F=qr({name:"gateway",self:ue,holder:j?{ours:j,version:R.version}:null,managedBy:en(process.env),port:t.port});if(F.action==="standby"||B&&!R){if(!B)for(const P of F.lines)console.error(P);B=!0,setTimeout(()=>b.listen(t.port,t.host),tn);return}if(j){const P=R.managedBy?` (run by ${R.managedBy})`:"";for(const[V,z]of F.lines.entries())console.error(V===0?z.replace(` on ${t.port}`,` at http://${_}:${t.port}${P}`):z)}else{const P=fn(t.port);console.error(`Port ${t.port} is held by ${P||"another program"}, which is not a ChatPanel gateway.`),console.error(`Fix: stop that program, or set a different port — edit "port" in ${ce()} (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: ${T?.message||T}`),process.exit(1)}),b.listen(t.port,t.host,()=>{B&&console.log(" standby : the other gateway is gone — this copy has the port now"),B=!1,console.log(`ChatPanel Privacy Gateway v${ue} on http://${t.host}:${t.port}`),b.linkHost?.start().catch(T=>console.log(` link : not started (${T?.message||T})`)),b.runtimeDefaults?.().then(T=>{for(const _ of T||[])console.log(` ${_.label.toLowerCase().padEnd(9).slice(0,9)}: ${_.ok?_.already?"running":_.adopted?"already running — adopted":"started":`not started (${_.skipped})`}`)}).catch(T=>console.log(` runtime : defaults not started (${T?.message||T})`)),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 T of ns(t))console.log(` ⚠ sandbox : ${T}`);console.log(` confined : ${Sn(wt({stateDir:Ue.dirname(ce())}))}`),ut={mode:"starting",version:null,pid:null,restarts:0,why:"deciding: adopt the bridge that answers, or start ours"},yn(t,{childEnv:()=>({...rs(t,process.env,et()),...ts(t)})}).then(T=>{Fe=T}).catch(T=>{ut={mode:"off",version:null,pid:null,restarts:0,why:`not supervised (${T?.message||T})`},console.log(` bridge : not supervised (${T?.message||T})`)}),console.log(` redaction: ${t.redaction.tier}`+(t.redaction.detection?.backend&&t.redaction.detection.backend!=="off"?` + ${t.redaction.detection.backend} detector`:t.ner?.autostart?" (+ NER starting…)":"")),ct(t.host)||console.error(`⚠ SECURITY: gateway bound to NON-LOOPBACK host ${t.host}. It is reachable off-machine, and the loopback Host-header check is spoofable from the LAN. Admin routes still need the token/extension, but prefer binding 127.0.0.1 unless you intend LAN exposure on a trusted network.`)}),lo()&&kt(J,ft()).then(T=>{T?.ok&&(console.log(` warm : seeded ${T.ingested} records from ${T.file}`),T.whole&&Ve())}).catch(()=>{});const E=()=>{f?.stop(),A.stop(),Fe?.stop(),ps(b)};return process.on("SIGINT",E),process.on("SIGTERM",E),b}export{Os as RECORDS_MAX_BYTES,Bl as VERSION,Is as createGateway,Ns as joinUpstream,Mt as parseAgentModel,Al as start};
|
package/src/stt-engine.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{join as Qe}from"node:path";import{deflateSync as Je}from"node:zlib";import Ne from"node:os";import{existsSync as Ze,readdirSync as et}from"node:fs";import{randomUUID as tt}from"node:crypto";import{ensureLib as Pe,modelRoot as Oe}from"./ner-engine.js";import{runtimeDtype as se,runtimeName as Re,DTYPE_SUFFIX as nt}from"./model-runtime.js";import{verifyModelWeights as ot}from"./model-integrity.js";import{DEFAULT_STT_MODEL as Fe,isEnglishOnly as me,sttModelDtype as he,isKnownSttModel as rt,sttModelEngine as G}from"./stt-models.js";import*as I from"./parakeet-engine.js";import*as _e from"./coreml-stt-engine.js";import*as te from"./indic-engine.js";import*as j from"./diarize-engine.js";import*as Y from"./segment-engine.js";import{turnsFromSpans as lt,mainLocal as at,timeByLocal as st,audioOfLocal as it}from"@chatpanel/events/speaker-turns.js";import{diarizeApproxMB as ct}from"./diarize-models.js";import*as ne from"./translate-engine.js";import*as Z from"./indictrans-engine.js";import{rawOrtAvailable as ut}from"./ort.js";import*as $ from"./vad-engine.js";import*as ee from"./echo-pair.js";import*as we from"./aec-engine.js";import{pickSegmentLanguage as ft,detectTextLanguage as dt,needsTranslation as gt,localTranslatable as pt,normalizeLanguages as mt,normalizeLanguage as ht,decodeLanguages as _t,lineLanguage as wt,autoCandidates as yt,AUTO_LEARN_CONFIDENCE as Mt,AUTO_LEARN_SECONDS as Et,ANY_LANGUAGE_CONFIDENCE as St,AUTO_LANGUAGES as Tt}from"@chatpanel/events/speech-language.js";import*as Lt from"@chatpanel/events/speech-language.js";import{makeWarmTimer as ye}from"./warm-timer.js";const p=16e3,$e=p,Ce=3*p,xt=2,At=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 kt(e,t){if(t>xt*p)return!1;const n=String(e||"").toLowerCase().replace(/[^\p{L}\p{N}\s]/gu,"").replace(/\s+/g," ").trim();return n?At.has(n)||/^(you ?){2,}$/.test(n)||/^(thank you\.? ?){2,}$/.test(n):!0}const bt=12,Me=3;function Dt(e){const t=String(e||"").split(/\s+/).filter(Boolean);if(t.length<Me)return{text:String(e||"").trim(),removed:0,total:t.length};const n=l=>l.toLowerCase().replace(/[^\p{L}\p{N}']/gu,""),o=[];let r=0;for(let l=0;l<t.length;){let f=0,c=0;for(let i=1;i<=bt&&l+i*Me<=t.length;i++){let s=1;for(;l+(s+1)*i<=t.length&&t.slice(l+s*i,l+(s+1)*i).every((u,d)=>n(u)===n(t[l+d]));)s++;s>=Me&&(s-1)*i>f&&(f=(s-1)*i,c=i)}f?(o.push(...t.slice(l,l+c)),r+=f,l+=c+f):(o.push(t[l]),l++)}return{text:o.join(" "),removed:r,total:t.length}}const vt=.6,He=2.4;function ze(e){const t=Buffer.from(String(e||""),"utf8");return t.length<40?1:t.length/Je(t).length}function Nt(e){return String(e||"").replace(/([^\d\s]{1,8}?)\1{4,}/gu,"$1")}function Pt({cores:e=Ne.availableParallelism?.()??Ne.cpus().length,env:t=process.env}={}){const n=Number(t.CHATPANEL_STT_THREADS);return Number.isFinite(n)&&n>0?Math.floor(n):Math.max(1,Math.min(4,Math.floor(e/2)))}function oe(e){return{intraOpNumThreads:Pt(e),interOpNumThreads:1,extra:{session:{intra_op:{allow_spinning:"0"}}}}}const Ot=.12,Ue=.8,Rt=.15,Ft=.5,$t=1.2,Ge=(e,t)=>e>=Ft||e>=Rt&&!(t<$t),Ct=.999,Ht=2.5;function ie(e={},t=1/0){return Ge(e.en??0,t)?"en":Object.entries(e).sort((n,o)=>o[1]-n[1])[0]?.[0]||null}function zt(e,t=[]){const n=[];return e.forEach((o,r)=>{const l=t[r]??o.lang,f=n[n.length-1];f&&f.lang===l?f.to=o.to:n.push({from:o.from,to:o.to,lang:l})}),n}function Ut(e,{base:t=null,rate:n=p}={}){const o=e||[],r=i=>{const[s,u]=Object.entries(i.scores||{}).sort((d,b)=>b[1]-d[1])[0]||[];return s&&s!=="en"&&u>=Ct?s:null},l=new Array(o.length).fill(null);for(let i=0;i<o.length;){const s=r(o[i]);let u=i+1;if(s)for(;u<o.length&&r(o[u])===s;)u++;if(s&&(o[u-1].to-o[i].from)/n>=Ht)for(let d=i;d<u;d++)l[d]=s;i=u}const f=[];let c=t;return o.forEach((i,s)=>{l[s]?c=l[s]:c!=="en"&&Ge(i.scores?.en??0,(i.to-i.from)/n)&&(c="en");const u=f[f.length-1];u&&u.lang===c?u.to=i.to:f.push({from:i.from,to:i.to,lang:c})}),f}async function Gt(e,t,n){const{spelledEnglish:o,isSpelledEnglish:r,SPELLED_ENGLISH_MIN:l,SPELLED_SHAPE_MIN:f}=Lt;if(typeof o!="function")return e;const c=[];let i=!1;for(const s of e){const u=o(s.text);if(!s.lang||s.lang==="en"||u.english<l&&!r(s.text)){c.push(s);continue}const d=u.words>=f&&u.shaped===u.words,b=[];for(let a=0;a+1<t.length;a++)t[a]>=s.from&&t[a+1]<=s.to&&b.push([t[a],t[a+1]]);if(b.length<2||d){const a=r(s.text)?await n(s.from,s.to,"en"):"";a?(c.push({...s,text:a,lang:"en"}),i=!0):c.push(s);continue}const h=[];for(const[a,S]of b){const A=await n(a,S,s.lang),z=o(A),ge=z.words>0&&z.words-z.shaped<=(z.english>=1&&z.words>=3?1:0);h.push({from:a,to:S,text:A,near:ge,lang:r(A)?"en":s.lang})}for(let a=!0;a;)a=!1,h.forEach((S,A)=>{S.lang!=="en"&&S.near&&(h[A-1]?.lang==="en"||h[A+1]?.lang==="en")&&(S.lang="en",a=!0)});if(!h.some(a=>a.lang==="en")){c.push(s);continue}const M=[];for(const a of h){const S=M[M.length-1];S&&S.lang===a.lang?(S.to=a.to,S.n++):M.push({from:a.from,to:a.to,lang:a.lang,n:1,text:a.text})}for(const a of M){const S=a.n===1&&a.lang===s.lang?a.text:await n(a.from,a.to,a.lang);S&&c.push({from:a.from,to:a.to,lang:a.lang,text:S})}i=!0}return i?c.reduce((s,u)=>{const d=s[s.length-1];return d&&d.lang===u.lang&&d.to===u.from?s[s.length-1]={...d,to:u.to,text:`${d.text} ${u.text}`}:s.push(u),s},[]):e}function jt(e,t,{frame:n=Math.round(.03*p),minPause:o=Ot*p,minPiece:r=Ue*p}={}){const l=[];let f=0,c=-1;for(let i=0;i+n<=e;i+=n){const s=t(i,i+n)===!1;if(s&&c<0&&(c=i),(!s||i+2*n>e)&&c>=0){const u=s?i+n:i,d=Math.round((c+u)/2);u-c>=o&&d-f>=r&&e-d>=r&&(l.push(d),f=d),c=-1}}return l}const Bt=.12;function It(e,t=Math.round(.03*p)){const n=Math.floor(e.length/t);if(n<3)return 0;const o=new Float32Array(n);for(let r=0;r<n;r++)o[r]=J(e,r*t,(r+1)*t);return o.sort(),Math.max(1e-4,o[Math.floor(n*.9)]*Bt)}let _="off",x=null,m=null,v=null,q=null,L=null,K=null,P=null;function Kt(e=x||Fe,t=he(e)||se()){if(G(e)==="parakeet-tdt")return I.parakeetOnDisk(e,I.parakeetDtype(t));if(G(e)==="coreml-tdt")return _e.coremlOnDisk(e);if(G(e)==="indic-canary")return te.indicOnDisk();const n=Qe(Oe(),...e.split("/"),"onnx");if(!Ze(n))return!1;const o=nt[t]??"";try{const r=et(n);return r.includes(`encoder_model${o}.onnx`)&&r.some(l=>l===`decoder_model_merged${o}.onnx`||l===`decoder_model${o}.onnx`)}catch{return!1}}function bn(){return _}function ce(){return _==="ready"&&!!m}function Dn(){return L}function vn(){return{configured:_!=="off",ok:ce(),state:_,model:x,dtype:K,runtime:Re(),error:v,warmMs:P?.warmMs??null,vad:$.state()}}function Nn(){return!!P?.pending()}function re(){return H.size>0||_==="loading"||_==="downloading"}async function Ee({log:e=()=>{}}={}){if(re())return!1;P?.disarm();const t=m;if(m=null,q=null,K=null,L=null,v=null,_="off",t)try{await t.dispose?.()}catch{}return t&&e(`[stt] idle for ${Math.round((P?.warmMs||0)/6e4)} min — model unloaded (reloads on next dictation)`),!0}function je(e){return e.then(t=>(t&&!re()&&P?.arm(),t))}async function Be(e,{log:t=()=>{},allowDownload:n=!0,dtype:o=null,licenseAccepted:r=null}={}){if(G(e)==="parakeet-tdt")return Wt(e,{log:t,allowDownload:n,dtype:o});if(G(e)==="coreml-tdt")return Yt(e,{log:t,allowDownload:n});if(G(e)==="indic-canary")return qt(e,{log:t,allowDownload:n,licenseAccepted:r});const l=m,f=x;let c;try{c=await Pe()}catch(h){return _="error",v=`engine load failed: ${h.message}`,t(`[stt] transformers.js not available (${h.message}) — dictation falls back to the browser engine`),!1}const s=(o&&o!=="auto"?o:null)||he(e)||se(),u=Kt(e,s);if(c.env.allowRemoteModels=u?!1:!!n,!u&&!n)return _="error",v="model not on disk and downloads disabled",t(`[stt] model ${e} not installed and downloads disabled`),!1;const d=c.env.remoteHost,b=!rt(e);if(!u&&b)try{c.env.remoteHost="https://huggingface.co/"}catch{}_=u?"loading":"downloading",u||(L={model:e,file:null,pct:0},t(`[stt] downloading model ${e} (one-time${b?", from Hugging Face":""})…`));try{const h=a=>{if(!a)return;const S=typeof a.progress=="number"?Math.round(a.progress):L?.pct??0;a.status==="progress"||a.status==="download"||a.status==="initiate"?L={model:e,file:a.file||L?.file||null,pct:S}:a.status==="done"&&a.file&&t(`[stt] fetched ${a.file}`)};let M;try{M=await c.pipeline("automatic-speech-recognition",e,{dtype:s,progress_callback:h,...globalThis.__CHATPANEL_WASM_PATHS__?{}:{session_options:oe()}})}catch(a){if(u||b||!n)throw a;t(`[stt] mirror fetch failed (${String(a.message).slice(0,80)}) — retrying from Hugging Face…`),c.env.remoteHost="https://huggingface.co/",c.env.allowRemoteModels=!0,M=await c.pipeline("automatic-speech-recognition",e,{dtype:s,progress_callback:h,...globalThis.__CHATPANEL_WASM_PATHS__?{}:{session_options:oe()}})}if(!u)try{ot(e,{modelsDir:Oe(),log:t})}catch(a){try{await M.dispose?.()}catch{}throw a}if(m=M,x=e,_="ready",v=null,L=null,K=s,l&&l!==M)try{await l.dispose?.()}catch{}return t(`[stt] ready — model ${e} @ ${s} (in-process, offline) — local dictation active`),!0}catch(h){return v=h.message,L=null,l?(m=l,x=f,_="ready"):_="error",t(`[stt] model load failed (${h.message})${l?" — keeping previous model":""}`),!1}finally{try{c.env.remoteHost=d}catch{}}}async function Wt(e,{log:t=()=>{},allowDownload:n=!0,dtype:o=null}={}){const r=m,l=x,f=I.parakeetDtype(o&&o!=="auto"?o:Xt()),c=I.parakeetOnDisk(e,f);if(!c&&!n)return _="error",v="model not on disk and downloads disabled",t(`[stt] model ${e} not installed and downloads disabled`),!1;_=c?"loading":"downloading",c||(L={model:e,file:null,pct:0},t(`[stt] downloading model ${e} (one-time, from Hugging Face)…`));try{const i=await I.loadRecognizer({modelId:e,dtype:f,allowDownload:n,log:t,sessionOptions:globalThis.__CHATPANEL_WASM_PATHS__?null:oe(),onProgress:u=>{L={model:e,file:u.file||null,pct:typeof u.pct=="number"?u.pct:L?.pct??0}}}),s=async u=>({text:await i.transcribe(u)});if(s.__transducer=!0,s.dispose=()=>i.dispose(),m=s,x=e,_="ready",v=null,L=null,K=f,r&&r!==s)try{await r.dispose?.()}catch{}return t(`[stt] ready — model ${e} @ ${f} (parakeet-tdt, in-process, offline) — local dictation active`),!0}catch(i){return v=i.message,L=null,r?(m=r,x=l,_="ready"):_="error",t(`[stt] model load failed (${i.message})${r?" — keeping previous model":""}`),!1}}function Xt(){return I.PARAKEET_DEFAULT_DTYPE}const Ie="fp16";async function Yt(e,{log:t=()=>{},allowDownload:n=!0}={}){const o=m,r=x,l=_e.coremlOnDisk(e);if(!l&&!n)return _="error",v="model not on disk and downloads disabled",t(`[stt] model ${e} not installed and downloads disabled`),!1;_=l?"loading":"downloading",l||(L={model:e,file:null,pct:0},t(`[stt] downloading model ${e} (one-time, from Hugging Face)…`));try{let f=null;const c=await _e.loadRecognizer({modelId:e,allowDownload:n,log:t,onProgress:i=>{L={model:e,file:i.file||null,pct:typeof i.pct=="number"?i.pct:L?.pct??0}},onExit:i=>{m===f&&(m=null,q=null,_="error",v=i,P?.disarm(),t(`[stt] ${i} — reloads on the next dictation`))}});if(f=async i=>({text:await c.transcribe(i)}),f.__transducer=!0,f.dispose=()=>c.dispose(),m=f,x=e,_="ready",v=null,L=null,K=Ie,o&&o!==f)try{await o.dispose?.()}catch{}return t(`[stt] ready — model ${e} (Core ML on the Neural Engine, helper ${c.version}, windows ${c.windows.join("/")} s, offline) — local dictation active`),!0}catch(f){return v=f.message,L=null,o?(m=o,x=r,_="ready"):_="error",t(`[stt] model load failed (${f.message})${o?" — keeping previous model":""}`),!1}}async function qt(e,{log:t=()=>{},allowDownload:n=!0,licenseAccepted:o=null}={}){const r=m,l=x,f=te.indicOnDisk();if(!f&&!n)return _="error",v="model not on disk and downloads disabled",!1;_=f?"loading":"downloading",f||(L={model:e,file:null,pct:0},t(`[stt] downloading ${e} (one-time, ~1.5 GB, from Hugging Face)…`));try{f||await te.ensureIndicFiles({licenseAccepted:o,log:t,onProgress:s=>{L={model:e,file:s.file,pct:s.pct}}});const c=await te.loadRecognizer({sessionOptions:globalThis.__CHATPANEL_WASM_PATHS__?null:oe(),log:t}),i=async(s,u={})=>c.transcribe(s,u);if(i.identify=(s,u)=>c.identify(s,u),i.__transducer=!0,i.__indic=!0,i.dispose=()=>c.dispose(),m=i,x=e,_="ready",v=null,L=null,K="int8",r&&r!==i)try{await r.dispose?.()}catch{}return t(`[stt] ready — ${e} (Indic-Transcribe, int8, in-process, offline) — ${te.INDIC_LICENSE.attribution}`),!0}catch(c){return v=c.message,L=null,r?(m=r,x=l,_="ready"):_="error",t(`[stt] model load failed (${c.message})${r?" — keeping previous model":""}`),!1}}const Vt=30;function Ke({mode:e="ondisk",onDisk:t=!1,ready:n=!1,approxMB:o=null}={}){return n||e==="off"?null:t?{allowDownload:!1}:typeof o=="number"&&o<=Vt||e==="download"?{allowDownload:!0}:null}function Se(e,{log:t=()=>{},warmMs:n,allowDownload:o=!0}={}){const r=Ke({mode:e,onDisk:j.modelOnDisk(),ready:j.isReady(),approxMB:ct(j.activeModel())});if(r&&j.init({allowDownload:r.allowDownload&&o!==!1,warmMs:n,onLog:t}),e==="off"||Te)return;const l=Ke({mode:e,onDisk:Y.modelOnDisk(),ready:Y.isReady(),approxMB:Y.SEGMENT_MODEL_APPROX_MB});l&&Y.init({allowDownload:l.allowDownload&&o!==!1,warmMs:n,onLog:t})}let Te=!1,Le=null;function xe(e={},{log:t=()=>{}}={}){e.vad!==!1&&(Le={vad:e.vad,allowDownload:e.allowDownload,warmMs:e.warmMs},($.state()==="off"||$.state()==="error")&&$.init({allowDownload:e.allowDownload!==!1,warmMs:e.warmMs,onLog:t}))}function Pn(e={}){if(q&&_!=="error")return q;const t=typeof e.onLog=="function"?e.onLog:()=>{};return x=e.model||Fe,Te=e.segment===!1,_="loading",P=ye({warmMs:e.warmMs,busy:re,log:t,unload:()=>Ee({log:t})}),q=je(Be(x,{log:t,allowDownload:e.allowDownload!==!1,dtype:e.dtype,licenseAccepted:e.licenseAccepted||null})).then(n=>(n&&(Se(e.speaker,{log:t,warmMs:e.warmMs,allowDownload:e.allowDownload!==!1}),xe(e,{log:t})),n)),q}async function On(e,t={}){const n=typeof t.onLog=="function"?t.onLog:()=>{};if(!e)return!1;t.segment!==void 0&&(Te=t.segment===!1);const o=G(e)==="parakeet-tdt"?I.parakeetDtype(t.dtype&&t.dtype!=="auto"?t.dtype:I.PARAKEET_DEFAULT_DTYPE):G(e)==="coreml-tdt"?Ie:G(e)==="indic-canary"?"int8":t.dtype&&t.dtype!=="auto"?t.dtype:he(e)||se();if(e===x&&ce()&&K===o)return Se(t.speaker,{log:n,warmMs:t.warmMs,allowDownload:t.allowDownload!==!1}),!0;P??=ye({warmMs:t.warmMs,busy:re,log:n,unload:()=>Ee({log:n})});const r=await je(Be(e,{log:n,allowDownload:t.allowDownload!==!1,dtype:t.dtype,licenseAccepted:t.licenseAccepted||null}));return r&&(Se(t.speaker,{log:n,warmMs:t.warmMs,allowDownload:t.allowDownload!==!1}),xe(t,{log:n})),r}const Qt=8,Jt=12e4,Zt=6e4,en=1200,ue=12,Ae=700,ke=.008,tn=.002,nn=4;function on(e){return e>0?Math.min(ke,Math.max(tn,e*nn)):ke}function rn(e){const t=Math.round(.1*p),n=Math.floor(e.length/t);if(n<5)return null;const o=new Float32Array(n);for(let r=0;r<n;r++)o[r]=J(e,r*t,(r+1)*t);return o.sort(),o[Math.floor(n*.1)]}const We=30,ln=15e3,H=new Map,V=new Map;let Q=Promise.resolve();function Rn(){return H.size}const an=300,sn=3e3;function cn(e){const t=Number(e);return Number.isFinite(t)?Math.min(sn,Math.max(an,Math.round(t))):Ae}function Fn({lang:e,langs:t=null,translateTo:n=null,translateLoad:o=null,echo:r=null,redact:l=!1,diarize:f=!1,speakerLabel:c=null,endSilenceMs:i=Ae,interims:s=!0,remote:u=null,poll:d=!1,format:b="f32"}={}){if(H.size>=Qt){const S=new Error("too many concurrent dictation sessions");throw S.code="too_many_sessions",S}const h=Array.isArray(t)?mt(t):null,M=typeof e=="string"&&e?e.slice(0,12):null,a={id:tt(),format:b==="pcm16"?"pcm16":"f32",endSilenceMs:cn(i),lang:h?h.length===1?h[0]:h.length?null:M:M,langs:h,lastLang:null,lastDecoded:null,learned:new Set,translateTo:ht(n)||null,translateLoad:o||{},translations:Promise.resolve(),echo:r&&typeof r=="object"?ee.join(r.group,r.role):null,langTried:!1,pushed:0,noiseFloor:null,redact:!!l,diarize:!!f,speakerLabel:typeof c=="string"&&c?c.slice(0,40):null,diarizer:f?new j.Diarizer:null,remote:u||null,interims:s!==!1&&!u,chunks:[],samples:0,listeners:new Set,poll:d?[]:null,lastDecodeAt:0,decodeTimer:null,lastInterim:"",closed:!1,idleTimer:null};return H.set(a.id,a),P?.disarm(),a.diarizer&&(j.retain(),Y.retain()),a.translateTo&&(ne.retain(),Z.retain()),a.echo&&we.retain(),$.retain(),Le&&($.state()==="off"||$.state()==="error")&&xe(Le),Xe(a),{id:a.id}}function fe(e){return H.get(String(e||""))||null}function $n(e,t){const n=fe(e);return n?(n.listeners.add(t),()=>n.listeners.delete(t)):null}function W(e,t){e.poll&&e.poll.push(t);for(const n of e.listeners)try{n(t)}catch{}}function Cn(e){const t=String(e||""),n=H.get(t);if(n)return n.poll?n.poll.splice(0):null;const o=V.get(t);return o?(clearTimeout(o.timer),V.delete(t),o.session.poll.splice(0)):null}function Hn(e){return V.get(String(e||""))?.session||null}function Xe(e){e.idleTimer&&clearTimeout(e.idleTimer),e.idleTimer=setTimeout(()=>gn(e.id).catch(()=>{}),Zt),e.idleTimer.unref?.()}function zn(e,t){const n=fe(e);if(!n||n.closed){const o=new Error("no such session");throw o.code="no_session",o}if(!(!(t instanceof Float32Array)||!t.length)){if(Xe(n),n.echo?.role==="mic"){ee.pushMic(n.echo,t),Ye(n);return}n.echo?.role==="reference"&&ee.pushReference(n.echo,t),n.chunks.push(t),n.samples+=t.length,n.pushed+=t.length,Ye(n)}}function Un(e){const t=fe(e);return!t||t.closed?Promise.resolve():(t.decodeTimer&&(clearTimeout(t.decodeTimer),t.decodeTimer=null),Q=Q.then(()=>be(t).catch(()=>{})),Q)}function Gn(e,t="f32"){if(t==="pcm16"){const r=new Float32Array(Math.floor(e.length/2));for(let l=0;l<r.length;l++)r[l]=e.readInt16LE(l*2)/32768;return r}const n=e.length-e.length%4,o=new Float32Array(n/4);for(let r=0;r<o.length;r++)o[r]=e.readFloatLE(r*4);return o}function Ye(e){if(e.closed||e.decodeTimer)return;const t=Math.max(0,e.lastDecodeAt+en-Date.now());e.decodeTimer=setTimeout(()=>{e.decodeTimer=null,Q=Q.then(()=>be(e).catch(()=>{}))},t),e.decodeTimer.unref?.()}function de(e,t,n){const o=e.samples-t,r=[];n&&r.push(n),o>0&&r.push(qe(e).subarray(t)),e.chunks=r,e.samples=r.reduce((l,f)=>l+f.length,0),e.lastInterim=""}function qe(e){const t=new Float32Array(e.samples);let n=0;for(const o of e.chunks)t.set(o,n),n+=o.length;return t}function un(e,t,n){const o=p/100,r=Math.max(0,e.length-t),l=Math.floor((e.length-r)/o),f=Math.max(1,Math.round(n/o));if(l<=f)return 0;const c=new Float32Array(l);for(let d=0;d<l;d++){let b=0;const h=r+d*o;for(let M=0;M<o;M++)b+=e[h+M]*e[h+M];c[d]=b/o}let i=-1,s=1/0,u=0;for(let d=0;d<f;d++)u+=c[d];for(let d=0;d+f<=l;d++)d>0&&(u+=c[d+f-1]-c[d-1]),u<s&&(s=u,i=d);return i<0?0:r+Math.round((i+f/2)*o)}function J(e,t=0,n=e.length){let o=0;const r=Math.max(1,n-t);for(let l=t;l<n;l++)o+=e[l]*e[l];return Math.sqrt(o/r)}function fn(e,t=ke){const n=Math.round(.02*p);let o=0,r=e.length;for(let l=0;l+n<=e.length;l+=n)if(J(e,l,l+n)>=t){o=l;break}for(let l=e.length-n;l>=0;l-=n)if(J(e,l,l+n)>=t){r=l+n;break}return r>o?e.subarray(o,r):e}async function Ve(e){try{const t=await Pe(),n=m?.model?.generation_config;if(!n?.lang_to_id||!n.decoder_start_token_id||!t.Tensor)return null;const o=e.length>p*8?e.subarray(0,p*8):e,r=await m.processor(o),l=new t.Tensor("int64",new BigInt64Array([BigInt(n.decoder_start_token_id)]),[1,1]),f=await m.model({...r,decoder_input_ids:l}),c={};for(const[i,s]of Object.entries(n.lang_to_id))c[i.slice(2,-2)]=Number(f.logits.data[s]);return c}catch{return null}}async function dn(e){const t=await Ve(e);if(!t)return null;let n=null,o=-1/0;for(const[r,l]of Object.entries(t))l>o&&(o=l,n=r);return n}async function be(e,{flush:t=!1}={}){if(e.closed&&!t)return;if(e.echo?.role==="mic"){const g=await ee.drain(e.echo,{force:t});g.length&&(e.chunks.push(g),e.samples+=g.length,e.pushed+=g.length)}if(!e.remote&&!ce()||!e.samples)return;e.lastDecodeAt=Date.now();let n=qe(e);const o=n.length,r=Math.max(0,(e.pushed||0)-e.samples),l=Math.round((e.endSilenceMs||Ae)/1e3*p),f=rn(n);f!==null&&(e.noiseFloor==null||f<e.noiseFloor)&&(e.noiseFloor=f);const c=on(e.noiseFloor);let i=null,s=null;$.isReady()&&(e.vad||=$.createStream(),await e.vad.advance(n,r)&&(i=e.vad.speechIn(r,r+n.length,$.ONSET),n.length>l&&(s=e.vad.speechIn(r+n.length-l,r+n.length,$.OFFSET))));const u=n.length>l&&(s!==null?!s:J(n,n.length-l)<c);if(i===!1||i===null&&J(n)<c){n.length>p*5&&(e.chunks=[n.subarray(n.length-p)],e.samples=p);return}if(!e.interims&&!t&&!u&&n.length<ue*p)return;let d=null;if(!t&&!u&&o>=ue*p&&o<We*p){const g=un(n,3*p,Math.round(.2*p));g>0&&g<n.length&&(d=n.subarray(g),n=n.subarray(0,g))}const b=!e.remote&&!me(x)&&!m?.__transducer;if(b&&!e.langs&&!e.lang&&!e.langTried&&n.length>=p){e.langTried=!0;const g=await dn(n);g&&(e.lang=g,W(e,{type:"language",lang:g}))}const h=t||u||o>=ue*p;let M=e.lang;if(b&&e.langs&&!e.lang){const g=e.langs.length>0,O=g?_t(e.langs):yt([...e.learned]);if(O.length===1)M=O[0];else if(M=O.includes(e.lastDecoded)?e.lastDecoded:null,(h||!M)&&n.length>=p/2){const R=await Ve(n);if(R){const T=ft({scores:R,allowed:O,seconds:n.length/p,last:e.lastDecoded});M=!g&&!T.inherited&&T.confidence<St?e.lastDecoded||"en":T.lang,!g&&h&&!T.inherited&&T.confidence>=Mt&&n.length>=Et*p&&e.learned.add(T.lang)}}h&&M&&(e.lastDecoded=M)}let a="",S=null,A=null,z=null;try{if(e.remote){const g=await e.remote.transcribe(n,{lang:e.lang,langs:e.langs});a=g.text,z=g.lang||null}else{const g=m.__indic?e.langs?.length?{langs:[...new Set([...e.langs,"en"])],last:e.lastLang,choose:ie}:e.lang?{lang:e.lang}:{langs:[...Tt],last:e.lastLang,choose:ie}:me(x)?{}:{language:M||void 0,task:"transcribe"},O=m.__indic&&m.identify&&h&&g.langs&&n.length>=2*Ue*p?jt(n.length,(E=>(y,k)=>J(n,y,k)>=E)(It(n))):[],R=[0,...O,n.length];let T=null;if(O.length){const E=await m.identify(n,{langs:g.langs}),y=[];for(let k=0;k+1<R.length;k++){const N=await m.identify(n.subarray(R[k],R[k+1]),{langs:g.langs});y.push({from:R[k],to:R[k+1],scores:N?.scores||{}})}if(T=Ut(y,{base:E?.scores?ie(E.scores,n.length/p):null}),T.length>1){const k=[];for(let N=0;N<T.length;N++){const w=T[N],D=w.lang&&w.lang!=="en"&&(T[N-1]?.lang==="en"||T[N+1]?.lang==="en");k.push(D?ie((await m.identify(n.subarray(w.from,w.to),{langs:g.langs}))?.scores||{},(w.to-w.from)/p):w.lang)}T=zt(T,k)}T.length<2&&(T=null)}if(T){A=[];for(const E of T){const y=await m(n.subarray(E.from,E.to),E.lang?{lang:E.lang}:{...g}),k=String(y?.text||"").trim(),N=y?.lang||E.lang||null;k&&A.push({text:k,lang:N,from:E.from,to:E.to}),N&&(g.last=N)}}else{const E=await m(n,g);a=String(E?.text||"").trim(),m.__indic&&(S=E?.lang||null),m.__indic&&a&&(A=[{text:a,lang:S,from:0,to:n.length}])}if(A&&h&&g.langs&&(A=await Gt(A,R,async(E,y,k)=>String((await m(n.subarray(E,y),{lang:k}))?.text||"").trim())),A){a=A.map(y=>y.text).join(" ");const E=new Map;for(const y of A)y.lang&&E.set(y.lang,(E.get(y.lang)||0)+(y.to-y.from));S=[...E].sort((y,k)=>k[1]-y[1])[0]?.[0]||null,(A.length<2||E.size<2)&&(A=null)}}}catch(g){W(e,{type:"error",code:"decode_failed",message:g.message,fatal:!1}),h&&de(e,o,d);return}if(!a){h&&de(e,o,d);return}{const g=Dt(a);if(g.removed&&g.removed/g.total>=vt&&g.total>=12?a="":a=g.text,a&&ze(a)>He){const O=Nt(a);a=O.replace(/[\s\p{P}]/gu,"").length<12||ze(O)>He?"":O}if(!a){h&&de(e,o,d);return}}const ge=o>=ue*p,De=o>=We*p;if(t||u||ge||De){const g=t?"flush":u?"silence":De?"overflow":"length",O=g==="flush"||g==="silence";de(e,o,d);const R=fn(n,c);if(kt(a,R?R.length:0)||e.echo?.role==="mic"&&we.mostlyEcho(ee.verdict(e.echo,r,r+n.length)))return;let T=null,E=null;if(e.diarizer)try{const w=e.speakerLabel?null:await Y.spans(n),D=w?lt(w):[];if(D.length){const F=new Map;for(const{local:C}of st(D)){const U=it(n,D,C),le=U.length?await j.embed(U):null,ae=U.length<$e,X=U.length<Ce;F.set(C,e.diarizer.assign(le,{pinnedLabel:null,weak:ae,thin:X}))}const B=Math.round(r/p*1e3);E=D.map(C=>({startMs:B+Math.round(C.start*1e3),durationMs:Math.round((C.end-C.start)*1e3),speaker:F.get(C.local)})).filter(C=>C.speaker),T=F.get(at(D))||null}}catch{}if(e.diarizer&&!T)try{const w=R,D=w?await j.embed(w):null,F=!!w&&w.length<$e,B=!!w&&w.length<Ce;T=e.diarizer.assign(D,{pinnedLabel:e.speakerLabel,weak:F,thin:B})}catch{}let y=null;(e.langs||e.translateTo)&&(S?y=S:z?y=z:me(x)&&!e.remote?y="en":b?y=wt(a,M||e.lang)||null:y=e.lang||dt(a,{allowed:e.langs||[],last:e.lastLang}).lang,y&&y!==e.lastLang&&(e.lastLang=y,W(e,{type:"language",lang:y})));const k=Math.round(r/p*1e3),N=A&&(e.langs||e.translateTo)?A.map((w,D)=>({text:w.text,lang:w.lang,startMs:k+Math.round(w.from/p*1e3),durationMs:Math.round((w.to-w.from)/p*1e3),last:D===A.length-1})):[{text:a,lang:y,startMs:k,durationMs:Math.round(n.length/p*1e3),last:!0}];for(const w of N){N.length>1&&w.lang&&w.lang!==e.lastLang&&(e.lastLang=w.lang,W(e,{type:"language",lang:w.lang}));const{text:D,lang:F,startMs:B}=w,C=(D.match(new RegExp("\\p{Script=Latin}","gu"))||[]).length/Math.max(1,(D.match(new RegExp("\\p{L}","gu"))||[]).length),U=Z.indictransLanguage(F)&&C<.5&&Z.state()!=="error"&&ut(),le=!!e.translateTo&>(F,e.translateTo)&&(U||pt(D,F)&&ne.state()!=="error"),ae=N.length>1&&E?E.filter(X=>X.startMs<B+w.durationMs&&X.startMs+X.durationMs>B):E;if(W(e,{type:"final",text:D,reason:g,endOfTurn:w.last?O:!1,durationMs:w.durationMs,startMs:B,...F?{lang:F}:{},...le?{translating:!0}:{},...T?{speaker:T}:{},...ae?.length?{turns:ae}:{}}),le){const X=e.translateTo,pe=U?Z:ne;pe.state()==="off"&&pe.init({...e.translateLoad,...U?{sessionOptions:oe()}:{}}),e.translations=e.translations.then(async()=>{await pe.ready();const ve=U?await Z.translate(D,F):await ne.translate(D);W(e,{type:"translation",startMs:B,lang:F,to:X,text:ve||null,...ve?{}:{failed:!0}})}).catch(()=>{})}}}else a!==e.lastInterim&&(e.lastInterim=a,W(e,{type:"interim",text:a}))}async function gn(e){const t=fe(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(Q=Q.then(()=>be(t,{flush:!0}).catch(()=>{}))),await Promise.race([t.translations,new Promise(n=>setTimeout(n,ln).unref?.())])}finally{if(W(t,{type:"end"}),t.listeners.clear(),H.delete(t.id),t.poll){const n=setTimeout(()=>V.delete(t.id),Jt);n.unref?.(),V.set(t.id,{session:t,timer:n})}t.diarizer&&(j.release(),Y.release()),t.translateTo&&(ne.release(),Z.release()),t.echo&&we.release(),$.release(),ee.leave(t.echo),H.size===0&&ce()&&P?.arm()}return!0}function jn(){for(const e of H.values())e.idleTimer&&clearTimeout(e.idleTimer),e.decodeTimer&&clearTimeout(e.decodeTimer);H.clear();for(const e of V.values())clearTimeout(e.timer);V.clear(),P?.disarm(),P=null,_="off",x=null,m=null,v=null,q=null,L=null}function Bn(e,t="test/fake",{warmMs:n=null,dtype:o=null}={}){m=e,x=t,_=e?"ready":"off",K=o,n!==null&&(P=ye({warmMs:n,busy:re,unload:()=>Ee()}),e&&P.arm())}export{Vt as AUTO_FETCH_MAX_MB,He as COMPRESSION_LIMIT,Ct as FROM_ENGLISH,Ht as FROM_ENGLISH_RUN_S,vt as LOOP_DROP,Bt as PAUSE_SHARE,Ue as PIECE_MIN_S,Ot as PIECE_PAUSE_S,p as SAMPLE_RATE,Ft as SURE_ENGLISH,Ce as THIN_SPEAKER_SAMPLES,Rt as TO_ENGLISH,$t as WEAK_ENGLISH_MIN_S,$e as WEAK_SPEAKER_SAMPLES,jn as _reset,Bn as _setPipeForTest,cn as clampEndSilence,Dt as collapseLoops,Nt as collapseRuns,ze as compressionRatio,Fn as createSession,Un as decodeNow,Cn as drainEvents,gn as endSession,Hn as endedSession,fe as getSession,vn as health,Pn as init,ce as isReady,Ut as languageGroups,kt as looksHallucinated,Kt as modelOnDisk,rn as noiseFloorOf,jt as pauseCuts,It as pauseLevel,Dn as progress,zn as pushAudio,un as quietestCut,zt as relabelGroups,Gt as respellEnglish,se as runtimeDtype,Re as runtimeName,ie as segmentLanguage,Rn as sessionCount,On as setModel,on as silenceGate,Ke as speakerPlan,bn as state,oe as sttSessionOptions,Pt as sttThreads,$n as subscribe,Gn as toFloat32,Ee as unload,Nn as warmPending};
|
|
1
|
+
import{join as et}from"node:path";import{deflateSync as tt}from"node:zlib";import Oe from"node:os";import{existsSync as nt,readdirSync as ot}from"node:fs";import{randomUUID as rt}from"node:crypto";import{ensureLib as Re,modelRoot as Fe}from"./ner-engine.js";import{runtimeDtype as ce,runtimeName as $e,DTYPE_SUFFIX as lt}from"./model-runtime.js";import{verifyModelWeights as at}from"./model-integrity.js";import{DEFAULT_STT_MODEL as Ce,isEnglishOnly as we,sttModelDtype as _e,isKnownSttModel as st,sttModelEngine as B}from"./stt-models.js";import*as K from"./parakeet-engine.js";import*as ye from"./coreml-stt-engine.js";import*as le from"./indic-engine.js";import*as H from"./diarize-engine.js";import*as q from"./segment-engine.js";import{turnsFromSpans as it,mainLocal as He,timeByLocal as ct,audioOfLocal as ut}from"@chatpanel/events/speaker-turns.js";import{diarizeApproxMB as ft}from"./diarize-models.js";import*as ae from"./translate-engine.js";import*as te from"./indictrans-engine.js";import{rawOrtAvailable as dt}from"./ort.js";import*as C from"./vad-engine.js";import*as ne from"./echo-pair.js";import*as Me from"./aec-engine.js";import{pickSegmentLanguage as gt,detectTextLanguage as pt,needsTranslation as mt,localTranslatable as ht,normalizeLanguages as wt,normalizeLanguage as _t,decodeLanguages as yt,lineLanguage as Mt,autoCandidates as Et,AUTO_LEARN_CONFIDENCE as St,AUTO_LEARN_SECONDS as Tt,ANY_LANGUAGE_CONFIDENCE as Lt,AUTO_LANGUAGES as xt}from"@chatpanel/events/speech-language.js";import*as At from"@chatpanel/events/speech-language.js";import{makeWarmTimer as Ee}from"./warm-timer.js";const p=16e3,ze=p,Ue=3*p,kt=2,vt=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 bt(e,t){if(t>kt*p)return!1;const n=String(e||"").toLowerCase().replace(/[^\p{L}\p{N}\s]/gu,"").replace(/\s+/g," ").trim();return n?vt.has(n)||/^(you ?){2,}$/.test(n)||/^(thank you\.? ?){2,}$/.test(n):!0}const Dt=12,Se=3;function Nt(e){const t=String(e||"").split(/\s+/).filter(Boolean);if(t.length<Se)return{text:String(e||"").trim(),removed:0,total:t.length};const n=l=>l.toLowerCase().replace(/[^\p{L}\p{N}']/gu,""),o=[];let r=0;for(let l=0;l<t.length;){let u=0,c=0;for(let i=1;i<=Dt&&l+i*Se<=t.length;i++){let a=1;for(;l+(a+1)*i<=t.length&&t.slice(l+a*i,l+(a+1)*i).every((f,d)=>n(f)===n(t[l+d]));)a++;a>=Se&&(a-1)*i>u&&(u=(a-1)*i,c=i)}u?(o.push(...t.slice(l,l+c)),r+=u,l+=c+u):(o.push(t[l]),l++)}return{text:o.join(" "),removed:r,total:t.length}}const Pt=.6,Ge=2.4;function je(e){const t=Buffer.from(String(e||""),"utf8");return t.length<40?1:t.length/tt(t).length}function Ot(e){return String(e||"").replace(/([^\d\s]{1,8}?)\1{4,}/gu,"$1")}function Rt({cores:e=Oe.availableParallelism?.()??Oe.cpus().length,env:t=process.env}={}){const n=Number(t.CHATPANEL_STT_THREADS);return Number.isFinite(n)&&n>0?Math.floor(n):Math.max(1,Math.min(4,Math.floor(e/2)))}function se(e){return{intraOpNumThreads:Rt(e),interOpNumThreads:1,extra:{session:{intra_op:{allow_spinning:"0"}}}}}const Ft=.12,Be=.8,$t=.15,Ct=.5,Ht=1.2,Ie=(e,t)=>e>=Ct||e>=$t&&!(t<Ht),zt=.999,Ut=2.5;function ue(e={},t=1/0){return Ie(e.en??0,t)?"en":Object.entries(e).sort((n,o)=>o[1]-n[1])[0]?.[0]||null}function Gt(e,t=[]){const n=[];return e.forEach((o,r)=>{const l=t[r]??o.lang,u=n[n.length-1];u&&u.lang===l?u.to=o.to:n.push({from:o.from,to:o.to,lang:l})}),n}function jt(e,{base:t=null,rate:n=p}={}){const o=e||[],r=i=>{const[a,f]=Object.entries(i.scores||{}).sort((d,b)=>b[1]-d[1])[0]||[];return a&&a!=="en"&&f>=zt?a:null},l=new Array(o.length).fill(null);for(let i=0;i<o.length;){const a=r(o[i]);let f=i+1;if(a)for(;f<o.length&&r(o[f])===a;)f++;if(a&&(o[f-1].to-o[i].from)/n>=Ut)for(let d=i;d<f;d++)l[d]=a;i=f}const u=[];let c=t;return o.forEach((i,a)=>{l[a]?c=l[a]:c!=="en"&&Ie(i.scores?.en??0,(i.to-i.from)/n)&&(c="en");const f=u[u.length-1];f&&f.lang===c?f.to=i.to:u.push({from:i.from,to:i.to,lang:c})}),u}async function Bt(e,t,n){const{spelledEnglish:o,isSpelledEnglish:r,SPELLED_ENGLISH_MIN:l,SPELLED_SHAPE_MIN:u}=At;if(typeof o!="function")return e;const c=[];let i=!1;for(const a of e){const f=o(a.text);if(!a.lang||a.lang==="en"||f.english<l&&!r(a.text)){c.push(a);continue}const d=f.words>=u&&f.shaped===f.words,b=[];for(let s=0;s+1<t.length;s++)t[s]>=a.from&&t[s+1]<=a.to&&b.push([t[s],t[s+1]]);if(b.length<2||d){const s=r(a.text)?await n(a.from,a.to,"en"):"";s?(c.push({...a,text:s,lang:"en"}),i=!0):c.push(a);continue}const y=[];for(const[s,_]of b){const x=await n(s,_,a.lang),G=o(x),me=G.words>0&&G.words-G.shaped<=(G.english>=1&&G.words>=3?1:0);y.push({from:s,to:_,text:x,near:me,lang:r(x)?"en":a.lang})}for(let s=!0;s;)s=!1,y.forEach((_,x)=>{_.lang!=="en"&&_.near&&(y[x-1]?.lang==="en"||y[x+1]?.lang==="en")&&(_.lang="en",s=!0)});if(!y.some(s=>s.lang==="en")){c.push(a);continue}const w=[];for(const s of y){const _=w[w.length-1];_&&_.lang===s.lang?(_.to=s.to,_.n++):w.push({from:s.from,to:s.to,lang:s.lang,n:1,text:s.text})}for(const s of w){const _=s.n===1&&s.lang===a.lang?s.text:await n(s.from,s.to,s.lang);_&&c.push({from:s.from,to:s.to,lang:s.lang,text:_})}i=!0}return i?c.reduce((a,f)=>{const d=a[a.length-1];return d&&d.lang===f.lang&&d.to===f.from?a[a.length-1]={...d,to:f.to,text:`${d.text} ${f.text}`}:a.push(f),a},[]):e}function It(e,t,{frame:n=Math.round(.03*p),minPause:o=Ft*p,minPiece:r=Be*p}={}){const l=[];let u=0,c=-1;for(let i=0;i+n<=e;i+=n){const a=t(i,i+n)===!1;if(a&&c<0&&(c=i),(!a||i+2*n>e)&&c>=0){const f=a?i+n:i,d=Math.round((c+f)/2);f-c>=o&&d-u>=r&&e-d>=r&&(l.push(d),u=d),c=-1}}return l}const Kt=.12;function Wt(e,t=Math.round(.03*p)){const n=Math.floor(e.length/t);if(n<3)return 0;const o=new Float32Array(n);for(let r=0;r<n;r++)o[r]=Z(e,r*t,(r+1)*t);return o.sort(),Math.max(1e-4,o[Math.floor(n*.9)]*Kt)}let h="off",k=null,m=null,D=null,V=null,A=null,W=null,P=null;function Xt(e=k||Ce,t=_e(e)||ce()){if(B(e)==="parakeet-tdt")return K.parakeetOnDisk(e,K.parakeetDtype(t));if(B(e)==="coreml-tdt")return ye.coremlOnDisk(e);if(B(e)==="indic-canary")return le.indicOnDisk();const n=et(Fe(),...e.split("/"),"onnx");if(!nt(n))return!1;const o=lt[t]??"";try{const r=ot(n);return r.includes(`encoder_model${o}.onnx`)&&r.some(l=>l===`decoder_model_merged${o}.onnx`||l===`decoder_model${o}.onnx`)}catch{return!1}}function Dn(){return h}function fe(){return h==="ready"&&!!m}function Nn(){return A}function Pn(){return{configured:h!=="off",ok:fe(),state:h,model:k,dtype:W,runtime:$e(),error:D,warmMs:P?.warmMs??null,vad:C.state()}}function On(){return!!P?.pending()}function ie(){return U.size>0||h==="loading"||h==="downloading"}async function Te({log:e=()=>{}}={}){if(ie())return!1;P?.disarm();const t=m;if(m=null,V=null,W=null,A=null,D=null,h="off",t)try{await t.dispose?.()}catch{}return t&&e(`[stt] idle for ${Math.round((P?.warmMs||0)/6e4)} min — model unloaded (reloads on next dictation)`),!0}function Ke(e){return e.then(t=>(t&&!ie()&&P?.arm(),t))}async function We(e,{log:t=()=>{},allowDownload:n=!0,dtype:o=null,licenseAccepted:r=null}={}){if(B(e)==="parakeet-tdt")return Yt(e,{log:t,allowDownload:n,dtype:o});if(B(e)==="coreml-tdt")return Vt(e,{log:t,allowDownload:n});if(B(e)==="indic-canary")return Qt(e,{log:t,allowDownload:n,licenseAccepted:r});const l=m,u=k;let c;try{c=await Re()}catch(y){return h="error",D=`engine load failed: ${y.message}`,t(`[stt] transformers.js not available (${y.message}) — dictation falls back to the browser engine`),!1}const a=(o&&o!=="auto"?o:null)||_e(e)||ce(),f=Xt(e,a);if(c.env.allowRemoteModels=f?!1:!!n,!f&&!n)return h="error",D="model not on disk and downloads disabled",t(`[stt] model ${e} not installed and downloads disabled`),!1;const d=c.env.remoteHost,b=!st(e);if(!f&&b)try{c.env.remoteHost="https://huggingface.co/"}catch{}h=f?"loading":"downloading",f||(A={model:e,file:null,pct:0},t(`[stt] downloading model ${e} (one-time${b?", from Hugging Face":""})…`));try{const y=s=>{if(!s)return;const _=typeof s.progress=="number"?Math.round(s.progress):A?.pct??0;s.status==="progress"||s.status==="download"||s.status==="initiate"?A={model:e,file:s.file||A?.file||null,pct:_}:s.status==="done"&&s.file&&t(`[stt] fetched ${s.file}`)};let w;try{w=await c.pipeline("automatic-speech-recognition",e,{dtype:a,progress_callback:y,...globalThis.__CHATPANEL_WASM_PATHS__?{}:{session_options:se()}})}catch(s){if(f||b||!n)throw s;t(`[stt] mirror fetch failed (${String(s.message).slice(0,80)}) — retrying from Hugging Face…`),c.env.remoteHost="https://huggingface.co/",c.env.allowRemoteModels=!0,w=await c.pipeline("automatic-speech-recognition",e,{dtype:a,progress_callback:y,...globalThis.__CHATPANEL_WASM_PATHS__?{}:{session_options:se()}})}if(!f)try{at(e,{modelsDir:Fe(),log:t})}catch(s){try{await w.dispose?.()}catch{}throw s}if(m=w,k=e,h="ready",D=null,A=null,W=a,l&&l!==w)try{await l.dispose?.()}catch{}return t(`[stt] ready — model ${e} @ ${a} (in-process, offline) — local dictation active`),!0}catch(y){return D=y.message,A=null,l?(m=l,k=u,h="ready"):h="error",t(`[stt] model load failed (${y.message})${l?" — keeping previous model":""}`),!1}finally{try{c.env.remoteHost=d}catch{}}}async function Yt(e,{log:t=()=>{},allowDownload:n=!0,dtype:o=null}={}){const r=m,l=k,u=K.parakeetDtype(o&&o!=="auto"?o:qt()),c=K.parakeetOnDisk(e,u);if(!c&&!n)return h="error",D="model not on disk and downloads disabled",t(`[stt] model ${e} not installed and downloads disabled`),!1;h=c?"loading":"downloading",c||(A={model:e,file:null,pct:0},t(`[stt] downloading model ${e} (one-time, from Hugging Face)…`));try{const i=await K.loadRecognizer({modelId:e,dtype:u,allowDownload:n,log:t,sessionOptions:globalThis.__CHATPANEL_WASM_PATHS__?null:se(),onProgress:f=>{A={model:e,file:f.file||null,pct:typeof f.pct=="number"?f.pct:A?.pct??0}}}),a=async f=>({text:await i.transcribe(f)});if(a.__transducer=!0,a.dispose=()=>i.dispose(),m=a,k=e,h="ready",D=null,A=null,W=u,r&&r!==a)try{await r.dispose?.()}catch{}return t(`[stt] ready — model ${e} @ ${u} (parakeet-tdt, in-process, offline) — local dictation active`),!0}catch(i){return D=i.message,A=null,r?(m=r,k=l,h="ready"):h="error",t(`[stt] model load failed (${i.message})${r?" — keeping previous model":""}`),!1}}function qt(){return K.PARAKEET_DEFAULT_DTYPE}const Xe="fp16";async function Vt(e,{log:t=()=>{},allowDownload:n=!0}={}){const o=m,r=k,l=ye.coremlOnDisk(e);if(!l&&!n)return h="error",D="model not on disk and downloads disabled",t(`[stt] model ${e} not installed and downloads disabled`),!1;h=l?"loading":"downloading",l||(A={model:e,file:null,pct:0},t(`[stt] downloading model ${e} (one-time, from Hugging Face)…`));try{let u=null;const c=await ye.loadRecognizer({modelId:e,allowDownload:n,log:t,onProgress:i=>{A={model:e,file:i.file||null,pct:typeof i.pct=="number"?i.pct:A?.pct??0}},onExit:i=>{m===u&&(m=null,V=null,h="error",D=i,P?.disarm(),t(`[stt] ${i} — reloads on the next dictation`))}});if(u=async i=>({text:await c.transcribe(i)}),u.__transducer=!0,u.dispose=()=>c.dispose(),m=u,k=e,h="ready",D=null,A=null,W=Xe,o&&o!==u)try{await o.dispose?.()}catch{}return t(`[stt] ready — model ${e} (Core ML on the Neural Engine, helper ${c.version}, windows ${c.windows.join("/")} s, offline) — local dictation active`),!0}catch(u){return D=u.message,A=null,o?(m=o,k=r,h="ready"):h="error",t(`[stt] model load failed (${u.message})${o?" — keeping previous model":""}`),!1}}async function Qt(e,{log:t=()=>{},allowDownload:n=!0,licenseAccepted:o=null}={}){const r=m,l=k,u=le.indicOnDisk();if(!u&&!n)return h="error",D="model not on disk and downloads disabled",!1;h=u?"loading":"downloading",u||(A={model:e,file:null,pct:0},t(`[stt] downloading ${e} (one-time, ~1.5 GB, from Hugging Face)…`));try{u||await le.ensureIndicFiles({licenseAccepted:o,log:t,onProgress:a=>{A={model:e,file:a.file,pct:a.pct}}});const c=await le.loadRecognizer({sessionOptions:globalThis.__CHATPANEL_WASM_PATHS__?null:se(),log:t}),i=async(a,f={})=>c.transcribe(a,f);if(i.identify=(a,f)=>c.identify(a,f),i.__transducer=!0,i.__indic=!0,i.dispose=()=>c.dispose(),m=i,k=e,h="ready",D=null,A=null,W="int8",r&&r!==i)try{await r.dispose?.()}catch{}return t(`[stt] ready — ${e} (Indic-Transcribe, int8, in-process, offline) — ${le.INDIC_LICENSE.attribution}`),!0}catch(c){return D=c.message,A=null,r?(m=r,k=l,h="ready"):h="error",t(`[stt] model load failed (${c.message})${r?" — keeping previous model":""}`),!1}}const Jt=30;function Ye({mode:e="ondisk",onDisk:t=!1,ready:n=!1,approxMB:o=null}={}){return n||e==="off"?null:t?{allowDownload:!1}:typeof o=="number"&&o<=Jt||e==="download"?{allowDownload:!0}:null}function Le(e,{log:t=()=>{},warmMs:n,allowDownload:o=!0}={}){const r=Ye({mode:e,onDisk:H.modelOnDisk(),ready:H.isReady(),approxMB:ft(H.activeModel())});if(r&&H.init({allowDownload:r.allowDownload&&o!==!1,warmMs:n,onLog:t}),e==="off"||xe)return;const l=Ye({mode:e,onDisk:q.modelOnDisk(),ready:q.isReady(),approxMB:q.SEGMENT_MODEL_APPROX_MB});l&&q.init({allowDownload:l.allowDownload&&o!==!1,warmMs:n,onLog:t})}let xe=!1,Ae=null;function ke(e={},{log:t=()=>{}}={}){e.vad!==!1&&(Ae={vad:e.vad,allowDownload:e.allowDownload,warmMs:e.warmMs},(C.state()==="off"||C.state()==="error")&&C.init({allowDownload:e.allowDownload!==!1,warmMs:e.warmMs,onLog:t}))}function Rn(e={}){if(V&&h!=="error")return V;const t=typeof e.onLog=="function"?e.onLog:()=>{};return k=e.model||Ce,xe=e.segment===!1,h="loading",P=Ee({warmMs:e.warmMs,busy:ie,log:t,unload:()=>Te({log:t})}),V=Ke(We(k,{log:t,allowDownload:e.allowDownload!==!1,dtype:e.dtype,licenseAccepted:e.licenseAccepted||null})).then(n=>(n&&(Le(e.speaker,{log:t,warmMs:e.warmMs,allowDownload:e.allowDownload!==!1}),ke(e,{log:t})),n)),V}async function Fn(e,t={}){const n=typeof t.onLog=="function"?t.onLog:()=>{};if(!e)return!1;t.segment!==void 0&&(xe=t.segment===!1);const o=B(e)==="parakeet-tdt"?K.parakeetDtype(t.dtype&&t.dtype!=="auto"?t.dtype:K.PARAKEET_DEFAULT_DTYPE):B(e)==="coreml-tdt"?Xe:B(e)==="indic-canary"?"int8":t.dtype&&t.dtype!=="auto"?t.dtype:_e(e)||ce();if(e===k&&fe()&&W===o)return Le(t.speaker,{log:n,warmMs:t.warmMs,allowDownload:t.allowDownload!==!1}),!0;P??=Ee({warmMs:t.warmMs,busy:ie,log:n,unload:()=>Te({log:n})});const r=await Ke(We(e,{log:n,allowDownload:t.allowDownload!==!1,dtype:t.dtype,licenseAccepted:t.licenseAccepted||null}));return r&&(Le(t.speaker,{log:n,warmMs:t.warmMs,allowDownload:t.allowDownload!==!1}),ke(t,{log:n})),r}const Zt=8,en=12e4,tn=6e4,nn=1200,de=12,ve=700,be=.008,on=.002,rn=4;function ln(e){return e>0?Math.min(be,Math.max(on,e*rn)):be}function an(e){const t=Math.round(.1*p),n=Math.floor(e.length/t);if(n<5)return null;const o=new Float32Array(n);for(let r=0;r<n;r++)o[r]=Z(e,r*t,(r+1)*t);return o.sort(),o[Math.floor(n*.1)]}const qe=30,sn=15e3,U=new Map,Q=new Map;let J=Promise.resolve();function $n(){return U.size}const cn=300,un=3e3;function fn(e){const t=Number(e);return Number.isFinite(t)?Math.min(un,Math.max(cn,Math.round(t))):ve}function Cn({lang:e,langs:t=null,translateTo:n=null,translateLoad:o=null,echo:r=null,redact:l=!1,diarize:u=!1,vectors:c=!1,speakerLabel:i=null,endSilenceMs:a=ve,interims:f=!0,remote:d=null,poll:b=!1,format:y="f32"}={}){if(U.size>=Zt){const x=new Error("too many concurrent dictation sessions");throw x.code="too_many_sessions",x}const w=Array.isArray(t)?wt(t):null,s=typeof e=="string"&&e?e.slice(0,12):null,_={id:rt(),format:y==="pcm16"?"pcm16":"f32",endSilenceMs:fn(a),lang:w?w.length===1?w[0]:w.length?null:s:s,langs:w,lastLang:null,lastDecoded:null,learned:new Set,translateTo:_t(n)||null,translateLoad:o||{},translations:Promise.resolve(),echo:r&&typeof r=="object"?ne.join(r.group,r.role):null,langTried:!1,pushed:0,noiseFloor:null,redact:!!l,diarize:!!u,speakerLabel:typeof i=="string"&&i?i.slice(0,40):null,diarizer:u?new H.Diarizer:null,vectors:!!u&&c===!0,remote:d||null,interims:f!==!1&&!d,chunks:[],samples:0,listeners:new Set,poll:b?[]:null,lastDecodeAt:0,decodeTimer:null,lastInterim:"",closed:!1,idleTimer:null};return U.set(_.id,_),P?.disarm(),_.diarizer&&(H.retain(),q.retain()),_.translateTo&&(ae.retain(),te.retain()),_.echo&&Me.retain(),C.retain(),Ae&&(C.state()==="off"||C.state()==="error")&&ke(Ae),Ve(_),{id:_.id}}function ge(e){return U.get(String(e||""))||null}function Hn(e,t){const n=ge(e);return n?(n.listeners.add(t),()=>n.listeners.delete(t)):null}function X(e,t){e.poll&&e.poll.push(t);for(const n of e.listeners)try{n(t)}catch{}}function zn(e){const t=String(e||""),n=U.get(t);if(n)return n.poll?n.poll.splice(0):null;const o=Q.get(t);return o?(clearTimeout(o.timer),Q.delete(t),o.session.poll.splice(0)):null}function Un(e){return Q.get(String(e||""))?.session||null}function Ve(e){e.idleTimer&&clearTimeout(e.idleTimer),e.idleTimer=setTimeout(()=>mn(e.id).catch(()=>{}),tn),e.idleTimer.unref?.()}function Gn(e,t){const n=ge(e);if(!n||n.closed){const o=new Error("no such session");throw o.code="no_session",o}if(!(!(t instanceof Float32Array)||!t.length)){if(Ve(n),n.echo?.role==="mic"){ne.pushMic(n.echo,t),Qe(n);return}n.echo?.role==="reference"&&ne.pushReference(n.echo,t),n.chunks.push(t),n.samples+=t.length,n.pushed+=t.length,Qe(n)}}function jn(e){const t=ge(e);return!t||t.closed?Promise.resolve():(t.decodeTimer&&(clearTimeout(t.decodeTimer),t.decodeTimer=null),J=J.then(()=>De(t).catch(()=>{})),J)}function Bn(e,t="f32"){if(t==="pcm16"){const r=new Float32Array(Math.floor(e.length/2));for(let l=0;l<r.length;l++)r[l]=e.readInt16LE(l*2)/32768;return r}const n=e.length-e.length%4,o=new Float32Array(n/4);for(let r=0;r<o.length;r++)o[r]=e.readFloatLE(r*4);return o}function Qe(e){if(e.closed||e.decodeTimer)return;const t=Math.max(0,e.lastDecodeAt+nn-Date.now());e.decodeTimer=setTimeout(()=>{e.decodeTimer=null,J=J.then(()=>De(e).catch(()=>{}))},t),e.decodeTimer.unref?.()}function pe(e,t,n){const o=e.samples-t,r=[];n&&r.push(n),o>0&&r.push(Je(e).subarray(t)),e.chunks=r,e.samples=r.reduce((l,u)=>l+u.length,0),e.lastInterim=""}function Je(e){const t=new Float32Array(e.samples);let n=0;for(const o of e.chunks)t.set(o,n),n+=o.length;return t}function dn(e,t,n){const o=p/100,r=Math.max(0,e.length-t),l=Math.floor((e.length-r)/o),u=Math.max(1,Math.round(n/o));if(l<=u)return 0;const c=new Float32Array(l);for(let d=0;d<l;d++){let b=0;const y=r+d*o;for(let w=0;w<o;w++)b+=e[y+w]*e[y+w];c[d]=b/o}let i=-1,a=1/0,f=0;for(let d=0;d<u;d++)f+=c[d];for(let d=0;d+u<=l;d++)d>0&&(f+=c[d+u-1]-c[d-1]),f<a&&(a=f,i=d);return i<0?0:r+Math.round((i+u/2)*o)}function Z(e,t=0,n=e.length){let o=0;const r=Math.max(1,n-t);for(let l=t;l<n;l++)o+=e[l]*e[l];return Math.sqrt(o/r)}function gn(e,t=be){const n=Math.round(.02*p);let o=0,r=e.length;for(let l=0;l+n<=e.length;l+=n)if(Z(e,l,l+n)>=t){o=l;break}for(let l=e.length-n;l>=0;l-=n)if(Z(e,l,l+n)>=t){r=l+n;break}return r>o?e.subarray(o,r):e}async function Ze(e){try{const t=await Re(),n=m?.model?.generation_config;if(!n?.lang_to_id||!n.decoder_start_token_id||!t.Tensor)return null;const o=e.length>p*8?e.subarray(0,p*8):e,r=await m.processor(o),l=new t.Tensor("int64",new BigInt64Array([BigInt(n.decoder_start_token_id)]),[1,1]),u=await m.model({...r,decoder_input_ids:l}),c={};for(const[i,a]of Object.entries(n.lang_to_id))c[i.slice(2,-2)]=Number(u.logits.data[a]);return c}catch{return null}}async function pn(e){const t=await Ze(e);if(!t)return null;let n=null,o=-1/0;for(const[r,l]of Object.entries(t))l>o&&(o=l,n=r);return n}async function De(e,{flush:t=!1}={}){if(e.closed&&!t)return;if(e.echo?.role==="mic"){const g=await ne.drain(e.echo,{force:t});g.length&&(e.chunks.push(g),e.samples+=g.length,e.pushed+=g.length)}if(!e.remote&&!fe()||!e.samples)return;e.lastDecodeAt=Date.now();let n=Je(e);const o=n.length,r=Math.max(0,(e.pushed||0)-e.samples),l=Math.round((e.endSilenceMs||ve)/1e3*p),u=an(n);u!==null&&(e.noiseFloor==null||u<e.noiseFloor)&&(e.noiseFloor=u);const c=ln(e.noiseFloor);let i=null,a=null;C.isReady()&&(e.vad||=C.createStream(),await e.vad.advance(n,r)&&(i=e.vad.speechIn(r,r+n.length,C.ONSET),n.length>l&&(a=e.vad.speechIn(r+n.length-l,r+n.length,C.OFFSET))));const f=n.length>l&&(a!==null?!a:Z(n,n.length-l)<c);if(i===!1||i===null&&Z(n)<c){n.length>p*5&&(e.chunks=[n.subarray(n.length-p)],e.samples=p);return}if(!e.interims&&!t&&!f&&n.length<de*p)return;let d=null;if(!t&&!f&&o>=de*p&&o<qe*p){const g=dn(n,3*p,Math.round(.2*p));g>0&&g<n.length&&(d=n.subarray(g),n=n.subarray(0,g))}const b=!e.remote&&!we(k)&&!m?.__transducer;if(b&&!e.langs&&!e.lang&&!e.langTried&&n.length>=p){e.langTried=!0;const g=await pn(n);g&&(e.lang=g,X(e,{type:"language",lang:g}))}const y=t||f||o>=de*p;let w=e.lang;if(b&&e.langs&&!e.lang){const g=e.langs.length>0,O=g?yt(e.langs):Et([...e.learned]);if(O.length===1)w=O[0];else if(w=O.includes(e.lastDecoded)?e.lastDecoded:null,(y||!w)&&n.length>=p/2){const R=await Ze(n);if(R){const S=gt({scores:R,allowed:O,seconds:n.length/p,last:e.lastDecoded});w=!g&&!S.inherited&&S.confidence<Lt?e.lastDecoded||"en":S.lang,!g&&y&&!S.inherited&&S.confidence>=St&&n.length>=Tt*p&&e.learned.add(S.lang)}}y&&w&&(e.lastDecoded=w)}let s="",_=null,x=null,G=null;try{if(e.remote){const g=await e.remote.transcribe(n,{lang:e.lang,langs:e.langs});s=g.text,G=g.lang||null}else{const g=m.__indic?e.langs?.length?{langs:[...new Set([...e.langs,"en"])],last:e.lastLang,choose:ue}:e.lang?{lang:e.lang}:{langs:[...xt],last:e.lastLang,choose:ue}:we(k)?{}:{language:w||void 0,task:"transcribe"},O=m.__indic&&m.identify&&y&&g.langs&&n.length>=2*Be*p?It(n.length,(E=>(T,M)=>Z(n,T,M)>=E)(Wt(n))):[],R=[0,...O,n.length];let S=null;if(O.length){const E=await m.identify(n,{langs:g.langs}),T=[];for(let M=0;M+1<R.length;M++){const F=await m.identify(n.subarray(R[M],R[M+1]),{langs:g.langs});T.push({from:R[M],to:R[M+1],scores:F?.scores||{}})}if(S=jt(T,{base:E?.scores?ue(E.scores,n.length/p):null}),S.length>1){const M=[];for(let F=0;F<S.length;F++){const z=S[F],oe=z.lang&&z.lang!=="en"&&(S[F-1]?.lang==="en"||S[F+1]?.lang==="en");M.push(oe?ue((await m.identify(n.subarray(z.from,z.to),{langs:g.langs}))?.scores||{},(z.to-z.from)/p):z.lang)}S=Gt(S,M)}S.length<2&&(S=null)}if(S){x=[];for(const E of S){const T=await m(n.subarray(E.from,E.to),E.lang?{lang:E.lang}:{...g}),M=String(T?.text||"").trim(),F=T?.lang||E.lang||null;M&&x.push({text:M,lang:F,from:E.from,to:E.to}),F&&(g.last=F)}}else{const E=await m(n,g);s=String(E?.text||"").trim(),m.__indic&&(_=E?.lang||null),m.__indic&&s&&(x=[{text:s,lang:_,from:0,to:n.length}])}if(x&&y&&g.langs&&(x=await Bt(x,R,async(E,T,M)=>String((await m(n.subarray(E,T),{lang:M}))?.text||"").trim())),x){s=x.map(T=>T.text).join(" ");const E=new Map;for(const T of x)T.lang&&E.set(T.lang,(E.get(T.lang)||0)+(T.to-T.from));_=[...E].sort((T,M)=>M[1]-T[1])[0]?.[0]||null,(x.length<2||E.size<2)&&(x=null)}}}catch(g){X(e,{type:"error",code:"decode_failed",message:g.message,fatal:!1}),y&&pe(e,o,d);return}if(!s){y&&pe(e,o,d);return}{const g=Nt(s);if(g.removed&&g.removed/g.total>=Pt&&g.total>=12?s="":s=g.text,s&&je(s)>Ge){const O=Ot(s);s=O.replace(/[\s\p{P}]/gu,"").length<12||je(O)>Ge?"":O}if(!s){y&&pe(e,o,d);return}}const me=o>=de*p,Ne=o>=qe*p;if(t||f||me||Ne){const g=t?"flush":f?"silence":Ne?"overflow":"length",O=g==="flush"||g==="silence";pe(e,o,d);const R=gn(n,c);if(bt(s,R?R.length:0)||e.echo?.role==="mic"&&Me.mostlyEcho(ne.verdict(e.echo,r,r+n.length)))return;let S=null,E=null,T=null;if(e.diarizer)try{const L=e.speakerLabel?null:await q.spans(n),v=L?it(L):[];if(v.length){const $=new Map,j=new Map;for(const{local:N}of ct(v)){const I=ut(n,v,N),ee=I.length?await H.embed(I):null;ee&&j.set(N,{vec:ee,samples:I.length});const Y=I.length<ze,re=I.length<Ue;$.set(N,e.diarizer.assign(ee,{pinnedLabel:null,weak:Y,thin:re}))}const he=Math.round(r/p*1e3);E=v.map(N=>({startMs:he+Math.round(N.start*1e3),durationMs:Math.round((N.end-N.start)*1e3),speaker:$.get(N.local)})).filter(N=>N.speaker),S=$.get(He(v))||null,S&&(T=j.get(He(v))||null)}}catch{}if(e.diarizer&&!S)try{const L=R,v=L?await H.embed(L):null,$=!!L&&L.length<ze,j=!!L&&L.length<Ue;v&&(T={vec:v,samples:L.length}),S=e.diarizer.assign(v,{pinnedLabel:e.speakerLabel,weak:$,thin:j})}catch{}let M=null;(e.langs||e.translateTo)&&(_?M=_:G?M=G:we(k)&&!e.remote?M="en":b?M=Mt(s,w||e.lang)||null:M=e.lang||pt(s,{allowed:e.langs||[],last:e.lastLang}).lang,M&&M!==e.lastLang&&(e.lastLang=M,X(e,{type:"language",lang:M})));const F=e.vectors&&T?{vec:H.plainVector(T.vec),seconds:Math.round(T.samples/p*100)/100,speakerModel:H.activeModel()}:null,z=Math.round(r/p*1e3),oe=x&&(e.langs||e.translateTo)?x.map((L,v)=>({text:L.text,lang:L.lang,startMs:z+Math.round(L.from/p*1e3),durationMs:Math.round((L.to-L.from)/p*1e3),last:v===x.length-1})):[{text:s,lang:M,startMs:z,durationMs:Math.round(n.length/p*1e3),last:!0}];for(const L of oe){oe.length>1&&L.lang&&L.lang!==e.lastLang&&(e.lastLang=L.lang,X(e,{type:"language",lang:L.lang}));const{text:v,lang:$,startMs:j}=L,he=(v.match(new RegExp("\\p{Script=Latin}","gu"))||[]).length/Math.max(1,(v.match(new RegExp("\\p{L}","gu"))||[]).length),N=te.indictransLanguage($)&&he<.5&&te.state()!=="error"&&dt(),I=!!e.translateTo&&mt($,e.translateTo)&&(N||ht(v,$)&&ae.state()!=="error"),ee=oe.length>1&&E?E.filter(Y=>Y.startMs<j+L.durationMs&&Y.startMs+Y.durationMs>j):E;if(X(e,{type:"final",text:v,reason:g,endOfTurn:L.last?O:!1,durationMs:L.durationMs,startMs:j,...$?{lang:$}:{},...I?{translating:!0}:{},...S?{speaker:S}:{},...ee?.length?{turns:ee}:{},...F||{}}),I){const Y=e.translateTo,re=N?te:ae;re.state()==="off"&&re.init({...e.translateLoad,...N?{sessionOptions:se()}:{}}),e.translations=e.translations.then(async()=>{await re.ready();const Pe=N?await te.translate(v,$):await ae.translate(v);X(e,{type:"translation",startMs:j,lang:$,to:Y,text:Pe||null,...Pe?{}:{failed:!0}})}).catch(()=>{})}}}else s!==e.lastInterim&&(e.lastInterim=s,X(e,{type:"interim",text:s}))}async function mn(e){const t=ge(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(J=J.then(()=>De(t,{flush:!0}).catch(()=>{}))),await Promise.race([t.translations,new Promise(n=>setTimeout(n,sn).unref?.())])}finally{if(X(t,{type:"end"}),t.listeners.clear(),U.delete(t.id),t.poll){const n=setTimeout(()=>Q.delete(t.id),en);n.unref?.(),Q.set(t.id,{session:t,timer:n})}t.diarizer&&(H.release(),q.release()),t.translateTo&&(ae.release(),te.release()),t.echo&&Me.release(),C.release(),ne.leave(t.echo),U.size===0&&fe()&&P?.arm()}return!0}function In(){for(const e of U.values())e.idleTimer&&clearTimeout(e.idleTimer),e.decodeTimer&&clearTimeout(e.decodeTimer);U.clear();for(const e of Q.values())clearTimeout(e.timer);Q.clear(),P?.disarm(),P=null,h="off",k=null,m=null,D=null,V=null,A=null}function Kn(e,t="test/fake",{warmMs:n=null,dtype:o=null}={}){m=e,k=t,h=e?"ready":"off",W=o,n!==null&&(P=Ee({warmMs:n,busy:ie,unload:()=>Te()}),e&&P.arm())}export{Jt as AUTO_FETCH_MAX_MB,Ge as COMPRESSION_LIMIT,zt as FROM_ENGLISH,Ut as FROM_ENGLISH_RUN_S,Pt as LOOP_DROP,Kt as PAUSE_SHARE,Be as PIECE_MIN_S,Ft as PIECE_PAUSE_S,p as SAMPLE_RATE,Ct as SURE_ENGLISH,Ue as THIN_SPEAKER_SAMPLES,$t as TO_ENGLISH,Ht as WEAK_ENGLISH_MIN_S,ze as WEAK_SPEAKER_SAMPLES,In as _reset,Kn as _setPipeForTest,fn as clampEndSilence,Nt as collapseLoops,Ot as collapseRuns,je as compressionRatio,Cn as createSession,jn as decodeNow,zn as drainEvents,mn as endSession,Un as endedSession,ge as getSession,Pn as health,Rn as init,fe as isReady,jt as languageGroups,bt as looksHallucinated,Xt as modelOnDisk,an as noiseFloorOf,It as pauseCuts,Wt as pauseLevel,Nn as progress,Gn as pushAudio,dn as quietestCut,Gt as relabelGroups,Bt as respellEnglish,ce as runtimeDtype,$e as runtimeName,ue as segmentLanguage,$n as sessionCount,Fn as setModel,ln as silenceGate,Ye as speakerPlan,Dn as state,se as sttSessionOptions,Rt as sttThreads,Hn as subscribe,Bn as toFloat32,Te as unload,On as warmPending};
|
package/src/tts-remote.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{secureFetch as g}from"./secure-fetch.js";import{redactSegments as
|
|
1
|
+
import{secureFetch as g}from"./secure-fetch.js";import{redactSegments as U,segment as I}from"./redact.js";import{primaryProvider as _}from"./capability-config.js";const L=["local","openai","elevenlabs"];function h(e){return L.includes(String(e||""))}function O(e={}){const r=e.tts||{},t=_(e.capabilities?.tts,"tts",{destinations:e.destinations||[]});if(t&&typeof t=="object"){if(t.provider==="embedded")return null;const i=t.adapter||"openai";if(t.url&&h(i)){const s=r.remote||{};return{kind:i,baseUrl:String(t.url).replace(/\/+$/,""),model:t.model||s.model||(i==="elevenlabs"?"eleven_multilingual_v2":"tts-1"),voice:t.voice||s.voice||(i==="elevenlabs"?"21m00Tcm4TlvDq8ikWAM":"alloy"),redact:t.redact!==!1,token:t.token||"",...t.endpoint?{endpoint:t.endpoint}:{}}}}const n=r.provider||"local";if(n==="local"||!h(n))return null;const a=r.remote||{};return{kind:n,baseUrl:String(a.baseUrl||(n==="elevenlabs"?"https://api.elevenlabs.io/v1":"https://api.openai.com/v1")).replace(/\/+$/,""),model:a.model||(n==="elevenlabs"?"eleven_multilingual_v2":"tts-1"),voice:a.voice||(n==="elevenlabs"?"21m00Tcm4TlvDq8ikWAM":"alloy"),redact:a.redact!==!1}}function $(e){return/^[A-Za-z0-9_-]{1,64}$/.test(String(e||""))}const A=new Set(["alloy","ash","ballad","coral","echo","fable","nova","onyx","sage","shimmer","verse"]);function B(e,r){const t=String(r||"");return t?e.endpoint?e.kind==="elevenlabs"?/^[A-Za-z0-9]{20}$/.test(t)?t:e.voice:A.has(t)?t:e.voice:t:e.voice}async function z({dest:e,text:r,voice:t,speed:n=1,auth:a,redaction:i,isPro:s=!0,onEgress:E=null,fetchImpl:T=null,format:u=null}={}){if(!e)throw new Error("no remote TTS destination configured");const l=e.endpoint&&e.token?e.token:a||e.token||"",p=B(e,t);if(!$(p))throw new Error(`invalid remote voice id: ${p}`);let d=String(r),m=0;if(e.redact&&i){const o={text:d},x=await U([I(()=>o.text,S=>{o.text=S})],i,{isPro:s,onEgress:E});d=o.text,m=x?.count||0}const k=T||g,v={"Content-Type":"application/json"};let f,w;if(e.kind==="elevenlabs"){f=`${e.baseUrl}/text-to-speech/${encodeURIComponent(p)}`,(u==="wav"||u==="pcm")&&(f+=`?output_format=pcm_${y}`),w={text:d,model_id:e.model};const o=P(l);o&&(v["xi-api-key"]=o)}else f=`${e.baseUrl}/audio/speech`,w={model:e.model,input:d,voice:p,response_format:"wav",speed:n},l&&(v.Authorization=l.startsWith("Bearer ")?l:`Bearer ${l}`);const c=await k(f,{method:"POST",headers:v,body:JSON.stringify(w)});if(!c.ok){let o=`HTTP ${c.status}`;try{o=(await c.text()).slice(0,300)||o}catch{}throw new Error(`remote tts failed: ${o}`)}const b=Buffer.from(await c.arrayBuffer());return e.kind==="elevenlabs"&&u==="pcm"?{audio:b,contentType:"audio/pcm",redacted:m}:e.kind==="elevenlabs"&&u==="wav"?{audio:V(b,y),contentType:"audio/wav",redacted:m}:{audio:b,contentType:c.headers.get("content-type")||"audio/mpeg",redacted:m}}const y=24e3;function V(e,r){const t=e.length&-2,n=Buffer.alloc(44);return n.write("RIFF",0),n.writeUInt32LE(36+t,4),n.write("WAVE",8),n.write("fmt ",12),n.writeUInt32LE(16,16),n.writeUInt16LE(1,20),n.writeUInt16LE(1,22),n.writeUInt32LE(r,24),n.writeUInt32LE(r*2,28),n.writeUInt16LE(2,32),n.writeUInt16LE(16,34),n.write("data",36),n.writeUInt32LE(t,40),Buffer.concat([n,e.subarray(0,t)])}function P(e){const r=String(e||"").trim();return r.toLowerCase().startsWith("bearer ")?r.slice(7).trim():r}export{L as TTS_PROVIDERS,$ as isValidRemoteVoice,h as isValidTtsProvider,V as pcm16ToWav,B as remoteVoiceFor,z as synthesizeRemote,O as ttsDestination};
|
package/src/version.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
const o="0.
|
|
1
|
+
const o="0.140.0";export{o as VERSION};
|