@chatpanel/gateway 0.9.4 → 0.11.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@chatpanel/gateway",
3
- "version": "0.9.4",
3
+ "version": "0.11.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": {
@@ -1 +1 @@
1
- import{ensureLib as S,modelRoot as k}from"./ner-engine.js";import{join as $}from"node:path";import{existsSync as z,readdirSync as D}from"node:fs";const f="Xenova/wavlm-base-plus-sv";let i="off",d=null,m=null,h=null,a=null,u=null;function p(){return globalThis.__CHATPANEL_WASM_PATHS__?"fp32":"q8"}function T(){return i}function w(){return i==="ready"&&!!d&&!!m}function E(){return u}function L(){return{configured:i!=="off",ok:w(),state:i,model:d,error:h}}function q(r=f,t=p()){const n=$(k(),...r.split("/"),"onnx");if(!z(n))return!1;const e=t==="fp32"?"":t==="q8"?"_quantized":`_${t}`;try{return D(n).some(l=>l===`model${e}.onnx`)}catch{return!1}}async function x({log:r=()=>{},allowDownload:t=!0}={}){let n;try{n=await S()}catch(o){return i="error",h=o.message,r(`[diarize] engine unavailable (${o.message})`),!1}const e=q();if(n.env.allowRemoteModels=e?!1:!!t,!e&&!t)return i="error",h="model not on disk and downloads disabled",!1;const l=n.env.remoteHost;if(!e)try{n.env.remoteHost="https://huggingface.co/"}catch{}i=e?"loading":"downloading",e||(u={model:f,file:null,pct:0},r(`[diarize] downloading ${f} (one-time)…`));try{const{AutoModel:o,AutoProcessor:s}=n,y=c=>{if(!c)return;const M=typeof c.progress=="number"?Math.round(c.progress):u?.pct??0;(c.status==="progress"||c.status==="download"||c.status==="initiate")&&(u={model:f,file:c.file||u?.file||null,pct:M})},v=await s.from_pretrained(f,{progress_callback:y}),A=await o.from_pretrained(f,{dtype:p(),progress_callback:y});return m=v,d=A,i="ready",h=null,u=null,r(`[diarize] ready — ${f} @ ${p()}`),!0}catch(o){return h=o.message,u=null,i="error",r(`[diarize] load failed (${o.message}) — diarization off`),!1}finally{try{n.env.remoteHost=l}catch{}}}function O(r={}){return a&&i!=="error"||(i="loading",a=x({log:r.onLog,allowDownload:r.allowDownload!==!1})),a}function I({onLog:r}={}){return a=null,i="loading",a=x({log:r,allowDownload:!0}),a}const b=16e3;function g(r){let t=0;for(const e of r)t+=e*e;t=Math.sqrt(t)||1;const n=new Float32Array(r.length);for(let e=0;e<r.length;e++)n[e]=r[e]/t;return n}async function _(r){try{const t=await m(r),n=await d(t),e=n.embeddings??n.logits??n.last_hidden_state;return e?.data?Float32Array.from(e.data):null}catch{return null}}async function j(r){if(!w()||!(r instanceof Float32Array)||!r.length)return null;const t=2*b,n=Math.round(1.3*b);if(r.length<=Math.round(t*1.4)){const o=await _(r);return o?g(o):null}const e=[];for(let o=0;o+t<=r.length;o+=n){const s=await _(r.subarray(o,o+t));s&&e.push(g(s))}if(!e.length){const o=await _(r);return o?g(o):null}const l=new Float32Array(e[0].length);for(const o of e)for(let s=0;s<l.length;s++)l[s]+=o[s];return g(l)}function C(){i="off",d=null,m=null,h=null,a=null,u=null}function N(r,t){d=r,m=t,i=r?"ready":"off"}function F(r,t){let n=0,e=0,l=0;for(let s=0;s<r.length;s++)n+=r[s]*t[s],e+=r[s]*r[s],l+=t[s]*t[s];const o=Math.sqrt(e)*Math.sqrt(l);return o?n/o:0}class W{constructor({threshold:t=.75,maxSpeakers:n=12}={}){this.threshold=t,this.maxSpeakers=n,this.centroids=[]}assign(t,{pinnedLabel:n=null}={}){if(!t)return null;if(n)return this._merge(this._find(n)||this._create(n),t);let e=null,l=-1;for(const o of this.centroids){const s=F(t,o.vec);s>l&&(l=s,e=o)}return e&&l>=this.threshold?this._merge(e,t):this.centroids.length>=this.maxSpeakers&&e?this._merge(e,t):this._merge(this._create(`Speaker ${this.centroids.length+1}`),t)}_find(t){return this.centroids.find(n=>n.label===t)||null}_create(t){const n={id:this.centroids.length+1,label:t,vec:null,n:0};return this.centroids.push(n),n}_merge(t,n){if(!t.vec)t.vec=Float32Array.from(n);else for(let e=0;e<t.vec.length;e++)t.vec[e]=(t.vec[e]*t.n+n[e])/(t.n+1);return t.n+=1,{id:t.id,label:t.label}}}export{f as DIARIZE_MODEL,W as Diarizer,C as _reset,N as _setForTest,I as download,j as embed,L as health,O as init,w as isReady,q as modelOnDisk,E as progress,T as state};
1
+ import{ensureLib as k,modelRoot as S}from"./ner-engine.js";import{join as $}from"node:path";import{existsSync as z,readdirSync as D}from"node:fs";const c="Xenova/wavlm-base-plus-sv";let i="off",h=null,p=null,m=null,a=null,u=null;function y(){return globalThis.__CHATPANEL_WASM_PATHS__?"fp32":"q8"}function T(){return i}function x(){return i==="ready"&&!!h&&!!p}function E(){return u}function L(){return{configured:i!=="off",ok:x(),state:i,model:h,error:m}}function q(e=c,t=y()){const r=$(S(),...e.split("/"),"onnx");if(!z(r))return!1;const n=t==="fp32"?"":t==="q8"?"_quantized":`_${t}`;try{return D(r).some(s=>s===`model${n}.onnx`)}catch{return!1}}async function b({log:e=()=>{},allowDownload:t=!0}={}){let r;try{r=await k()}catch(o){return i="error",m=o.message,e(`[diarize] engine unavailable (${o.message})`),!1}const n=q();if(r.env.allowRemoteModels=n?!1:!!t,!n&&!t)return i="error",m="model not on disk and downloads disabled",!1;const s=r.env.remoteHost;if(!n)try{r.env.remoteHost="https://huggingface.co/"}catch{}i=n?"loading":"downloading",n||(u={model:c,file:null,pct:0},e(`[diarize] downloading ${c} (one-time)…`));try{const{AutoModel:o,AutoProcessor:l}=r,d=f=>{if(!f)return;const M=typeof f.progress=="number"?Math.round(f.progress):u?.pct??0;(f.status==="progress"||f.status==="download"||f.status==="initiate")&&(u={model:c,file:f.file||u?.file||null,pct:M})},g=await l.from_pretrained(c,{progress_callback:d}),A=await o.from_pretrained(c,{dtype:y(),progress_callback:d});return p=g,h=A,i="ready",m=null,u=null,e(`[diarize] ready — ${c} @ ${y()}`),!0}catch(o){return m=o.message,u=null,i="error",e(`[diarize] load failed (${o.message}) — diarization off`),!1}finally{try{r.env.remoteHost=s}catch{}}}function O(e={}){return a&&i!=="error"||(i="loading",a=b({log:e.onLog,allowDownload:e.allowDownload!==!1})),a}function I({onLog:e}={}){return a=null,i="loading",a=b({log:e,allowDownload:!0}),a}const v=16e3;function _(e){let t=0;for(const n of e)t+=n*n;t=Math.sqrt(t)||1;const r=new Float32Array(e.length);for(let n=0;n<e.length;n++)r[n]=e[n]/t;return r}async function w(e){try{const t=await p(e),r=await h(t),n=r.embeddings??r.logits??r.last_hidden_state;return n?.data?Float32Array.from(n.data):null}catch{return null}}async function j(e){if(!x()||!(e instanceof Float32Array)||!e.length)return null;const t=2*v,r=Math.round(1.3*v);if(e.length<=Math.round(t*1.4)){const o=await w(e);return o?_(o):null}const n=[];for(let o=0;o+t<=e.length;o+=r){const l=await w(e.subarray(o,o+t));l&&n.push(_(l))}if(!n.length){const o=await w(e);return o?_(o):null}const s=new Float32Array(n[0].length);for(const o of n)for(let l=0;l<s.length;l++)s[l]+=o[l];return _(s)}function C(){i="off",h=null,p=null,m=null,a=null,u=null}function N(e,t){h=e,p=t,i=e?"ready":"off"}function F(e,t){let r=0,n=0,s=0;for(let l=0;l<e.length;l++)r+=e[l]*t[l],n+=e[l]*e[l],s+=t[l]*t[l];const o=Math.sqrt(n)*Math.sqrt(s);return o?r/o:0}class W{constructor({threshold:t=.75,maxSpeakers:r=12}={}){this.threshold=t,this.maxSpeakers=r,this.centroids=[]}assign(t,{pinnedLabel:r=null,weak:n=!1}={}){if(!t)return null;if(r)return this._merge(this._find(r)||this._create(r),t);let s=null,o=-1;const l={};for(const d of this.centroids){const g=F(t,d.vec);l[d.label]=Math.round(g*1e3)/1e3,g>o&&(o=g,s=d)}return n&&s?{...this._merge(s,t,{update:!1}),scores:l,weak:!0}:s&&o>=this.threshold?{...this._merge(s,t),scores:l}:this.centroids.length>=this.maxSpeakers&&s?{...this._merge(s,t),scores:l}:{...this._merge(this._create(`Speaker ${this.centroids.length+1}`),t),scores:l,...n?{weak:!0}:{}}}_find(t){return this.centroids.find(r=>r.label===t)||null}_create(t){const r={id:this.centroids.length+1,label:t,vec:null,n:0};return this.centroids.push(r),r}_merge(t,r,{update:n=!0}={}){if(!t.vec)t.vec=Float32Array.from(r),t.n=1;else if(n){for(let s=0;s<t.vec.length;s++)t.vec[s]=(t.vec[s]*t.n+r[s])/(t.n+1);t.n+=1}return{id:t.id,label:t.label}}}export{c as DIARIZE_MODEL,W as Diarizer,C as _reset,N as _setForTest,I as download,j as embed,L as health,O as init,x as isReady,q as modelOnDisk,E as progress,T as state};
package/src/server.js CHANGED
@@ -1,19 +1,27 @@
1
- import{createServer as ht}from"node:http";import{loadConfig as Ce}from"./config.js";import{startEntitlementRefresh as ft,maybeRevalidate as gt}from"./entitlement-refresh.js";import{redactSegments as ge,segment as De}from"./redact.js";import{pipeRestoredStream as bt,pipeRestoredOpenAIStream as wt,makeTokenRestorer as je,restoreDeep as kt}from"./stream.js";import{restoreText as St,gatedDictionary as vt,narrowSpecs as Tt,makeToolHarness as _t,placeholderToolNote as Ot,placeholderNote as Pt,assertEndpointUrl as Et,capRunOptions as At,isPaired as xt}from"@chatpanel/pii";import{ensureGatewayToken as be,currentGatewayToken as $t,isAdminAuthorized as F,callerTrustOf as de,setPinnedExtensionIds as Nt,issuePairingCode as Bt,claimPairingCode as Ct}from"./gateway-token.js";import{installEgressLedger as Dt,egressAudit as jt}from"./egress.js";import{initPolicy as It,activePolicy as Mt,applyPolicyToConfig as Ie,managedSummary as ae,PolicyLoadError as Rt}from"./policy.js";import{routeAllowed as Me,agentAllowed as Lt,egressAllowed as zt}from"@chatpanel/events/policy.js";import{resolveBridgeUrl as ue}from"./bridge.js";import{secureFetch as Re}from"./secure-fetch.js";import{streamBridgeChat as Le,readBridgeToken as ie,openBridgeChat as Gt}from"./bridge.js";import{createRelaySession as Vt,getRelaySession as ze,endRelaySession as me,pumpBridgeStream as Jt,deliverToolResult as Ht,toolsToSpecs as Ut,parseToolCallId as Ge,touchRelaySession as we}from"./toolrelay.js";import{shaperFor as ke}from"./shape.js";import{startNer as Ft,ensureNer as Se}from"./ner.js";import{installTimestampedConsole as Wt}from"./log.js";import{saveBackupSecret as Kt,clearBackupSecret as Zt,loadBackupSecret as ve,hasBackupSecret as Ve}from"./history-store.js";import{createMemoryStore as Yt}from"./memory-store.js";import{createPrefsStore as Qt}from"./prefs-store.js";import{createTeamStore as Xt,loadOrCreateKey as Te}from"./team-store.js";import{createScorecardStore as qt}from"./scorecard-store.js";import{createEngineLedgerStore as eo}from"./engine-ledger-store.js";import{createProjectStore as to}from"./project-store.js";import{applicationsFor as oo,recruitPass as ro}from"./recruiting.js";import{ensureBridge as no}from"./bridge-supervisor.js";import{checkForUpdate as so,updateStatus as ao,startUpdate as io,updateJob as lo}from"./update.js";import{createHistoryStore as co}from"./sqlite-store.js";import{ingestBackups as _e}from"./backup-ingest.js";import{toSearchRecord as uo}from"@chatpanel/events/library.js";import{deriveBackupKey as mo,openRecord as po,keyCache as yo,nodeCodec as ho}from"@chatpanel/events/backup-envelope.js";import fo from"node:zlib";import*as C from"./ner-engine.js";import*as A from"./stt-engine.js";import*as B from"./diarize-engine.js";import{MODEL_CATALOG as go,isKnownModel as bo,isValidCustomModelId as wo}from"./models.js";import{STT_MODEL_CATALOG as ko,isKnownSttModel as So,isValidCustomSttId as vo,DEFAULT_STT_MODEL as Oe,STT_DTYPES as To,isValidDtype as _o}from"./stt-models.js";import*as S from"./tts-engine.js";import{TTS_MODEL_CATALOG as Je,TTS_VOICES as Oo,isKnownTtsModel as Po,isValidCustomTtsId as Eo,isKnownVoice as He,isValidVoiceId as Ue,DEFAULT_TTS_MODEL as Fe,DEFAULT_TTS_VOICE as Q,TTS_DTYPES as Ao,isValidTtsDtype as xo,MAX_TTS_CHARS as We,ttsModelHasCustomVoices as $o,resolveDefaultModel as Ke,POCKET_VOICES as No,DEFAULT_POCKET_VOICE as pe,isPocketVoice as ye,ttsModelEngine as he}from"./tts-models.js";import{ttsDestination as Bo,synthesizeRemote as Co,isValidRemoteVoice as Do}from"./tts-remote.js";import{rawOrtAvailable as Pe}from"./ort.js";import*as G from"./tts-voices.js";import{resolveTtsVoice as jo}from"./tts-voice-resolve.js";import{resolvePro as q,checkQuota as Io,consume as Mo,usage as Ro}from"./freegate.js";import{publicConfig as Ze,applyConfigPatch as Lo,applyNerModelSelection as zo,persistConfig as te,configPath as ee,bridgeAgentOptions as Ye}from"./configstore.js";import{resolveDestination as Qe,aggregateModelsAsync as Go,listDestinations as Vo}from"./router.js";import{makeAccessEvent as Xe}from"./observability.js";import{createPersistentAccessLog as Jo}from"./access-log-store.js";import{planQueries as Ho,multiSearch as Uo}from"./rrf.js";import*as Ee from"./openai.js";import*as qe from"./responses.js";import*as Ae from"./anthropic.js";const K="0.9.4",P=await co(),H=await Yt(),Z=Qt(),oe=qt({key:Te()}),re=eo({key:Te()}),V=to({key:Te()}),D=Xt({scorecards:oe,engines:re}),xe=new Set,et=(t,i)=>{for(const d of xe)try{d({applied:t,by:i,revision:Z.revision})}catch{}},$e=Jo(),tt=new Set(["codex","claude","opencode","pi","kiro","antigravity","hermes"]),Fo=16,Wo=/^mcp[_-]/i,ot=t=>t&&t.function&&t.function.name||t&&t.name||"",Ko=t=>t&&t.function&&t.function.description||t&&t.description||"";function rt(t){return typeof t=="string"?t:Array.isArray(t)?t.map(i=>typeof i=="string"?i:i&&(i.text||i.content)||"").join(" "):""}function Zo(t,i){if(!t)return"";if(i==="responses"){const r=t.input;return typeof r=="string"?r:Array.isArray(r)?r.map(o=>rt(o&&(o.content??o))).join(" "):""}const d=Array.isArray(t.messages)?t.messages:[];for(let r=d.length-1;r>=0;r--)if(d[r]&&d[r].role==="user")return rt(d[r].content);return""}const nt=new Set(["host","connection","content-length","transfer-encoding","accept-encoding","content-encoding","keep-alive"]);function st(t){if(!t)return!1;const i=t.replace(/:\d+$/,"").replace(/^\[|\]$/g,"");return i==="localhost"||i==="127.0.0.1"||i==="::1"}function Yo(t,i){return!t||/^chrome-extension:\/\//.test(t)||/^moz-extension:\/\//.test(t)||/^http:\/\/(localhost|127\.0\.0\.1|\[::1\])(:\d+)?$/.test(t)?!0:Array.isArray(i.allowedOrigins)&&i.allowedOrigins.includes(t)}function Qo(t,i){t.setHeader("Access-Control-Allow-Origin",i||"*"),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 at=Date.now();function Xo(t){if(!t)return"";const i={redact:"redact",upstream:"model",stream:"stream",restore:"restore",total:"total"};return Object.keys(t).map(d=>`${i[d]||d} ${t[d]}ms`).join(" · ")}function qo(t){const i=/^(model|harness):([^/]+)(?:\/(.+))?$/.exec(String(t||""));return i?{kind:i[1],id:i[2],...i[3]?{model:i[3]}:{}}:null}function er(t){const i=performance.now(),d={};let r=!1;const o=(u,c)=>{d[u]=Math.round(c*10)/10};return{meta:{},timings:d,mark:o,lap(u,c){o(u,performance.now()-c)},clock(){return performance.now()},commit(){if(r)return;r=!0,o("total",performance.now()-i);const u={...this.meta,timings:d};setImmediate(()=>{t(u),console.log(`[gateway] model=${u.model||"-"} → ${u.dest?`${u.dest}(${u.type})`:"none"} · ${u.redaction==="off"?"redaction OFF (client request)":`redacted ${u.redacted||0}`}${u.sanitized?` · scrubbed ${u.sanitized} hidden`:""}${u.narrowed?` · narrowed -${u.narrowed}`:""} · ${Xo(d)}`)})}}}function it(t,i){if(!t||!t.byToken||i!=="types"&&i!=="values")return;const d=[];for(const[r,o]of t.byToken){const u=/^\[\[([A-Z][A-Z0-9]*)_\d+\]\]$/.exec(r),c=u?u[1]:"PII",g=r.replace(/^\[\[|\]\]$/g,"");d.push(i==="values"?{token:g,type:c,value:o}:{token:g,type:c})}return d}function tr(t,i,d){return Ae.matches(t)||"anthropic-version"in i?{kind:"anthropic",adapter:Ae,redactable:Ae.matches(t),base:d.upstreams?.anthropic?.baseUrl}:qe.matches(t)?{kind:"responses",adapter:qe,redactable:!0,base:d.upstreams?.openai?.baseUrl}:{kind:"openai",adapter:Ee,redactable:Ee.matches(t),base:d.upstreams?.openai?.baseUrl}}function Ne(t,i){const d=String(t||"");if(tt.has(d))return{agent:d,agentModel:""};const r=d.indexOf("/");if(r>0){const o=d.slice(0,r);if(tt.has(o))return{agent:o,agentModel:d.slice(r+1)}}return{agent:i.bridge.agent,agentModel:""}}function lt(t,i){return Ne(t,i).agent}function or(t,i){if(i!=="openai"||!t)return!1;const d=Ee.extractLatestToolResult(t);if(!d)return!1;const r=Ge(d.tool_call_id);return!!(r&&ze(r.gwId))}function rr(t,i){try{const d=new URL(t),r=d.hostname.replace(/^\[|\]$/g,""),o=r==="127.0.0.1"||r==="localhost"||r==="::1",u=d.port||(d.protocol==="https:"?"443":"80");return o&&String(u)===String(i.port)}catch{return!1}}async function v(t,i){const d=[];let r=0;for await(const o of t){if(r+=o.length,i&&r>i){const u=new Error("payload too large");throw u.code=413,u}d.push(o)}return Buffer.concat(d)}function s(t,i,d){t.writeHead(i,{"content-type":"application/json"}),t.end(JSON.stringify(d))}function ct(t){const i=t.redaction?.detection?.url;return!i||t.redaction?.detection?.backend==="off"?null:i}function Be(t){const i=t?.redaction?.detection,d=t?.redaction?.tier==="full"?"full":"basic";if(i&&i.backend&&i.backend!=="off")return{source:"external",backend:i.backend,state:"external",model:i.model||null,ready:!0,tier:d,coverage:d==="full"?"names":"patterns"};const r=C.health(),o=r.ok&&d==="full";return{source:"bundled",state:r.state,model:r.model||t?.ner?.model||null,installed:C.modelOnDisk(t?.ner?.model||void 0),error:r.error||null,ready:o,tier:d,coverage:o?"names":"patterns"}}async function dt(t){if(C.state()!=="off"){const d=C.health();return{configured:d.configured,ok:d.ok,state:d.state,model:d.model,error:d.error||null,url:d.configured?`http://${t.host}:${t.port}/ner`:null}}const i=ct(t);if(!i)return{configured:!1,ok:!1,url:null,model:null};try{const d=await Re(i.replace(/\/ner\/?$/,"")+"/health",{signal:AbortSignal.timeout(2e3)});if(!d.ok)return{configured:!0,ok:!1,url:i,model:null};const r=await d.json().catch(()=>({}));return{configured:!0,ok:!0,url:i,model:r.model||null}}catch{return{configured:!0,ok:!1,url:i,model:null}}}function nr(t,i){const d={};for(const[r,o]of Object.entries(t)){const u=r.toLowerCase();u.startsWith("x-chatpanel-")||nt.has(u)||(d[r]=o)}d["accept-encoding"]="identity";try{d.host=new URL(i).host}catch{}return d}async function ut(t,i,d,r){const o=je(i.vault),u=r?r.clock():0;let c=u,g=!0;const b=()=>{r&&g&&(r.lap("upstream",u),c=r.clock(),g=!1)};await Jt(i,{onText:E=>{b(),we(i.id);const p=o.push(E);p&&t.write(d.sseDelta(p))},onToolRequest:({name:E,restoredArgs:p,toolId:L})=>{b(),we(i.id);const $=o.flush();$&&t.write(d.sseDelta($)),t.write(d.sseToolCalls([{id:L,name:E,arguments:JSON.stringify(p)}])),t.write(d.sseToolFinish()),r&&r.lap("stream",c),t.end(),r?.commit()},onDone:()=>{const E=o.flush();E&&t.write(d.sseDelta(E)),t.write(d.sseTail()),r&&r.lap("stream",c),t.end(),me(i.id),r?.commit()},onError:E=>{t.write(`data: ${JSON.stringify({error:{message:E.message,type:"bridge_error"}})}
1
+ import{createServer as gt}from"node:http";import{loadConfig as Ie}from"./config.js";import{startEntitlementRefresh as bt,maybeRevalidate as wt}from"./entitlement-refresh.js";import{redactSegments as we,segment as je}from"./redact.js";import{pipeRestoredStream as kt,pipeRestoredOpenAIStream as St,makeTokenRestorer as Me,restoreDeep as vt}from"./stream.js";import{restoreText as Tt,gatedDictionary as _t,narrowSpecs as Ot,makeToolHarness as Pt,placeholderToolNote as Et,placeholderNote as xt,assertEndpointUrl as At,capRunOptions as $t,isPaired as Nt}from"@chatpanel/pii";import{ensureGatewayToken as ke,currentGatewayToken as Bt,isAdminAuthorized as F,callerTrustOf as ue,setPinnedExtensionIds as Ct,issuePairingCode as Dt,claimPairingCode as It}from"./gateway-token.js";import{installEgressLedger as jt,egressAudit as Mt}from"./egress.js";import{initPolicy as Rt,activePolicy as Lt,applyPolicyToConfig as Re,managedSummary as ie,PolicyLoadError as zt}from"./policy.js";import{routeAllowed as Le,agentAllowed as Gt,egressAllowed as Vt}from"@chatpanel/events/policy.js";import{resolveBridgeUrl as me}from"./bridge.js";import{secureFetch as ze}from"./secure-fetch.js";import{streamBridgeChat as Ge,readBridgeToken as le,openBridgeChat as Jt}from"./bridge.js";import{createRelaySession as Ht,getRelaySession as Ve,endRelaySession as pe,pumpBridgeStream as Ut,deliverToolResult as Ft,toolsToSpecs as Wt,parseToolCallId as Je,touchRelaySession as Se}from"./toolrelay.js";import{shaperFor as ve}from"./shape.js";import{startNer as Kt,ensureNer as Te}from"./ner.js";import{installTimestampedConsole as Zt}from"./log.js";import{saveBackupSecret as Yt,clearBackupSecret as Qt,loadBackupSecret as _e,hasBackupSecret as He}from"./history-store.js";import{createMemoryStore as Xt}from"./memory-store.js";import{createPrefsStore as qt}from"./prefs-store.js";import{createTeamStore as eo,loadOrCreateKey as Oe}from"./team-store.js";import{createScorecardStore as to}from"./scorecard-store.js";import{createEngineLedgerStore as oo}from"./engine-ledger-store.js";import{createProjectStore as ro}from"./project-store.js";import{applicationsFor as no,recruitPass as so}from"./recruiting.js";import{ensureBridge as ao}from"./bridge-supervisor.js";import{checkForUpdate as io,updateStatus as lo,startUpdate as co,updateJob as uo}from"./update.js";import{createHistoryStore as mo}from"./sqlite-store.js";import{ingestBackups as Pe}from"./backup-ingest.js";import{toSearchRecord as po}from"@chatpanel/events/library.js";import{deriveBackupKey as yo,openRecord as ho,keyCache as fo,nodeCodec as go}from"@chatpanel/events/backup-envelope.js";import bo from"node:zlib";import*as C from"./ner-engine.js";import*as x from"./stt-engine.js";import*as B from"./diarize-engine.js";import{MODEL_CATALOG as wo,isKnownModel as ko,isValidCustomModelId as So}from"./models.js";import{STT_MODEL_CATALOG as vo,isKnownSttModel as To,isValidCustomSttId as _o,DEFAULT_STT_MODEL as Ee,STT_DTYPES as Oo,isValidDtype as Po}from"./stt-models.js";import*as S from"./tts-engine.js";import{TTS_MODEL_CATALOG as Ue,TTS_VOICES as Eo,isKnownTtsModel as xo,isValidCustomTtsId as Ao,isKnownVoice as Fe,isValidVoiceId as We,DEFAULT_TTS_MODEL as Ke,DEFAULT_TTS_VOICE as Q,TTS_DTYPES as $o,isValidTtsDtype as No,MAX_TTS_CHARS as Ze,ttsModelHasCustomVoices as Bo,resolveDefaultModel as Ye,POCKET_VOICES as Co,DEFAULT_POCKET_VOICE as ye,isPocketVoice as he,ttsModelEngine as fe}from"./tts-models.js";import{ttsDestination as Do,synthesizeRemote as Io,isValidRemoteVoice as jo}from"./tts-remote.js";import{rawOrtAvailable as xe}from"./ort.js";import*as G from"./tts-voices.js";import{resolveTtsVoice as Mo}from"./tts-voice-resolve.js";import{resolvePro as q,checkQuota as Ro,consume as Lo,usage as zo}from"./freegate.js";import{publicConfig as Qe,applyConfigPatch as Go,applyNerModelSelection as Vo,persistConfig as oe,configPath as ee,bridgeAgentOptions as Xe}from"./configstore.js";import{resolveDestination as qe,aggregateModelsAsync as Jo,listDestinations as Ho}from"./router.js";import{makeAccessEvent as et}from"./observability.js";import{createPersistentAccessLog as Uo}from"./access-log-store.js";import{planQueries as Fo,multiSearch as Wo}from"./rrf.js";import*as Ae from"./openai.js";import*as tt from"./responses.js";import*as $e from"./anthropic.js";const W="0.11.0",O=await mo(),te=new Set;function ge({ids:t=[]}={}){const i=O.lossless;if(!i||!te.size)return;const d=JSON.stringify({newest:i.newest,size:i.size,ids:t.slice(0,50),at:Date.now()});for(const r of te)try{r.write(`event: records
2
+ data: ${d}
2
3
 
3
- `),t.end(),me(i.id),r?.commit()}})}async function sr(t,i,{kind:d,adapter:r,agent:o,run:u=null},c,g,b,E,p,L=null,$=null){const{messages:j,system:Y}=r.toTurn(c),{agentModel:z}=Ne(c?.model,b),R=Ye(b,{...z?{model:z}:{},...u||{}}),N=ie(b.bridge.token),O=ke(d,c?.model||o),I={tier:b.redaction.tier==="full"?"full":"basic",dictionary:vt(b.redaction,E),entities:[]},J=await ue(b),T=Vt({vault:g,redactOpts:I,bridgeUrl:J,token:N,harness:L});let W;try{W=await Gt({bridgeUrl:J,agent:o,token:N,messages:j,system:Y,specs:Ut(p),options:R,signal:void 0})}catch(X){return me(T.id),$?.commit(),s(i,502,{error:{message:`bridge: ${X.message}`,type:"bridge_error"}})}return T.reader=W.body.getReader(),i.writeHead(200,{"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive"}),i.write(O.sseHead()),ut(i,T,O,$)}async function ar(t,i,d,r,o=null){we(i.id),i.rounds=(i.rounds||0)+1;try{const c=o?o.clock():0;await Ht(i,d),o&&o.lap("redact",c)}catch(c){return me(i.id),o?.commit(),s(t,502,{error:{message:`tool-result: ${c.message}`,type:"bridge_error"}})}const u=ke("openai",r||"codex");return t.writeHead(200,{"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive"}),t.write(u.sseHead()),ut(t,i,u,o)}async function ir(t,i,{kind:d,adapter:r,redactable:o,pathname:u,agentOverride:c,harness:g,trace:b,run:E=null},p,L,$,j){if(!o)return b?.commit(),s(i,404,{error:`endpoint ${u} not supported by the bridge backend`});if(d==="openai"){const e=r.extractLatestToolResult(p);if(e){const a=Ge(e.tool_call_id),l=a&&ze(a.gwId);if(l)return ar(i,l,e.content,p?.model,b)}const n=r.extractTools(p);if(n.length&&p?.stream===!0)return sr(t,i,{kind:d,adapter:r,agent:c||lt(p?.model,$),run:E},p,L,$,j,n,g,b)}const{messages:Y,system:z}=r.toTurn(p),R=c||lt(p?.model,$),N=p?.stream===!0,O=ke(d,p?.model||R),I=ie($.bridge.token),J=new AbortController;i.on("close",()=>{i.writableFinished||J.abort()});const{agentModel:T}=Ne(p?.model,$),W={bridgeUrl:await ue($),agent:R,token:I,messages:Y,system:z,signal:J.signal,options:Ye($,{...T?{model:T}:{},...E||{}})};if(!N)try{let e="";const n=b?b.clock():0;await Le(W,m=>{e+=m}),b&&b.lap("upstream",n);const a=b?b.clock():0,l=O.full(St(e,L));return b&&b.lap("restore",a),i.writeHead(200,{"content-type":O.contentType}),i.end(l),b?.commit()}catch(e){return b?.commit(),s(i,502,{error:{message:`bridge backend failed: ${e.message}`,type:"bridge_error"}})}i.writeHead(200,{"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive"}),i.write(O.sseHead());const X=je(L),ne=b?b.clock():0;let se=ne;try{let e=!0;await Le(W,a=>{b&&e&&(b.lap("upstream",ne),se=b.clock(),e=!1);const l=X.push(a);l&&i.write(O.sseDelta(l))},O.sseActivity?a=>{try{i.write(O.sseActivity(kt(a,L)))}catch{}}:null);const n=X.flush();n&&i.write(O.sseDelta(n)),i.write(O.sseTail())}catch(e){i.write(`data: ${JSON.stringify({error:{message:e.message,type:"bridge_error"}})}
4
+ `)}catch{te.delete(r)}}setInterval(()=>{for(const t of te)try{t.write(`: ping
4
5
 
5
- `)}b&&b.lap("stream",se),i.end(),b?.commit()}function lr(t,i,d=""){const r=String(t||"").replace(/\/+$/,""),o=String(i||"").split("/")[1];return o&&r.endsWith(`/${o}`)?r.slice(0,-(o.length+1))+i+d:r+i+d}const cr=9e4;function dr(t,i,d){if(i===d)return t;const r=i/d,o=new Float32Array(Math.floor(t.length/r));for(let u=0;u<o.length;u++){const c=u*r,g=Math.floor(c),b=Math.min(t.length-1,g+1),E=c-g;o[u]=t[g]*(1-E)+t[b]*E}return o}const ur=["/tts","/stt","/ner","/diarize","/skills","/redact","/config","/logs","/status","/admin"];function mt(t,i){const d=new URLSearchParams;for(const u of t.searchParams.getAll("dir"))u&&d.append("dir",u);const r=t.searchParams.get("workdir")||String(i?.bridge?.workingDir||"").trim();r&&d.set("workdir",r);const o=d.toString();return o?`?${o}`:""}async function mr(t,i,{adapter:d,kind:r,pathname:o,search:u,base:c,destKey:g,destProtocol:b,harness:E,trace:p},L,$){let j;const Y=p?p.clock():0;try{const O=nr(t.headers,c);g&&(b==="anthropic"?(O["x-api-key"]=g,delete O.authorization):O.authorization=`Bearer ${g}`);const I=Et(lr(c,o,u)).toString();j=await fetch(I,{method:t.method,headers:O,body:["GET","HEAD"].includes(t.method)?void 0:L})}catch(O){return p?.commit(),s(i,502,{error:`upstream fetch failed: ${O.message}`})}const z=j.headers.get("content-type")||"",R={};if(j.headers.forEach((O,I)=>{nt.has(I.toLowerCase())||(R[I]=O)}),z.includes("text/event-stream")&&j.body){p&&p.lap("upstream",Y);const O=p?p.clock():0;i.writeHead(j.status,R);const I=r==="openai"?wt(j.body,i,$,E):bt(j.body,i,$);return Promise.resolve(I).finally(()=>{p&&p.lap("stream",O),p?.commit()})}const N=Buffer.from(await j.arrayBuffer());if(p&&p.lap("upstream",Y),$&&z.includes("application/json"))try{const O=p?p.clock():0,I=d.restoreResponse(JSON.parse(N.toString("utf8")),$,E);return p&&p.lap("restore",O),i.writeHead(j.status,{...R,"content-type":"application/json"}),i.end(Buffer.from(JSON.stringify(I),"utf8")),p?.commit()}catch{}i.writeHead(j.status,R),i.end(N),p?.commit()}function pr(t=Ce()){Nt(t.allowedExtensionIds||[]);const i=[],d=r=>{i.push(r),i.length>50&&i.shift()};return ht(async(r,o)=>{const u=new URL(r.url,"http://127.0.0.1"),c=u.pathname;if(!st(r.headers.host))return s(o,403,{error:"loopback only"});if(!Yo(r.headers.origin,t))return s(o,403,{error:"origin not allowed"});if(r.headers.origin&&Qo(o,r.headers.origin),r.method==="OPTIONS")return o.writeHead(204),o.end();if(c==="/admin/token"&&r.method==="POST")return F(r)?s(o,200,{token:be()}):s(o,403,{error:"admin: extension origin or gateway token required"});if(c==="/pair/code"&&r.method==="POST"){if(!F(r))return s(o,403,{error:"pair/code: extension origin or gateway token required"});const e=Bt();return console.log("[gateway] pairing code issued — valid for 5 minutes, one use"),s(o,200,{ok:!0,...e})}if(c==="/pair"&&r.method==="POST"){let e=null;try{e=JSON.parse((await v(r,t.maxBodyBytes)).toString("utf8"))}catch{e=null}const n=Ct(e?.code);if(!n.ok)return console.log(`[gateway] pairing refused (${n.reason}) from ${de(r)} caller`),s(o,403,{error:n.reason});console.log(`[gateway] paired a ${de(r)} client${r.headers.origin?` (${r.headers.origin})`:""}`);const a=ie(t.bridge?.token);return s(o,200,{ok:!0,token:$t()||be(),...a?{bridgeToken:a}:{}})}if(c==="/whoami"&&r.method==="POST"){const e=de(r);return s(o,200,{ok:!0,trust:e,paired:xt(e),version:K})}if(c==="/audit"&&r.method==="GET")return F(r)?s(o,200,jt(t,{version:K,startedAt:at,managed:ae()})):s(o,403,{error:"audit: extension origin or gateway token required"});if((c==="/config"||c==="/logs"||c==="/update"&&r.method!=="GET")&&!F(r))return s(o,403,{error:"admin route: extension origin or gateway token required"});if(c==="/update"&&r.method==="GET"){const e=await so(K,{force:u.searchParams.get("force")==="1"}).catch(n=>({current:K,updateAvailable:!1,error:String(n?.message||n)}));return s(o,200,{ok:!0,update:e,job:lo()})}if(c==="/update"&&r.method==="POST"){const e=io(K);return s(o,e.already?409:202,{ok:!0,job:e})}if((c==="/v1/history/key"||c==="/v1/history/ingest-backup")&&r.method==="POST"&&!F(r))return s(o,403,{error:{message:"history key route: extension origin or gateway token required",type:"forbidden"}});if(c==="/v1/history/records"&&r.method==="PUT"&&!F(r))return s(o,403,{error:{message:"history write — extension origin or gateway token required",type:"forbidden"}});if((c==="/v1/history/ingest"||c==="/v1/history/clear")&&r.method==="POST"&&!F(r))return s(o,403,{error:{message:"history write — extension origin or gateway token required",type:"forbidden"}});if((c==="/v1/memory/remember"||c==="/v1/memory/forget"||c==="/v1/memory/sync"||c==="/v1/memory/clear")&&r.method==="POST"&&!F(r))return s(o,403,{error:{message:"memory write — extension origin or gateway token required",type:"forbidden"}});if((c==="/v1/prefs"||c.startsWith("/v1/prefs/")||c.startsWith("/v1/teams")||c.startsWith("/v1/agents")||c.startsWith("/v1/projects"))&&!F(r))return s(o,403,{error:{message:"prefs: extension origin or gateway token required",type:"forbidden"}});if(c.startsWith("/v1/observability")&&!F(r))return s(o,403,{error:{message:"observability: extension origin or gateway token required",type:"forbidden"}});if(r.method==="GET"&&c==="/health"){const e=A.health(),n=S.health();return s(o,200,{ok:!0,version:K,backend:t.backend,tier:t.redaction.tier,pairing:!0,...ae()?{managed:ae()}:{},...process.env.CHATPANEL_MANAGED_BY?{managedBy:String(process.env.CHATPANEL_MANAGED_BY).slice(0,32)}:{},...fe?{bridge:fe.status()}:{},stt:{enabled:t.stt?.enabled!==!1,state:e.state,ready:e.ok,model:e.model||t.stt?.model||Oe,runtime:e.runtime,dtype:e.dtype},tts:{enabled:t.tts?.enabled!==!1,state:n.state,ready:n.ok,model:n.model||t.tts?.model||Fe,voice:t.tts?.voice||Q,runtime:n.runtime,dtype:n.dtype}})}if(c==="/status"&&r.method==="GET"){gt(t);const e=await q(t.pro?.entitlementToken),n=await dt(t);return s(o,200,{ok:!0,version:K,backend:t.backend,tier:t.redaction.tier,...ae()?{managed:ae()}:{},...process.env.CHATPANEL_MANAGED_BY?{managedBy:String(process.env.CHATPANEL_MANAGED_BY).slice(0,32)}:{},ner:{autostart:!!t.ner?.autostart,configured:n.configured,ready:n.ok,model:n.model,url:n.url},detector:Be(t),pro:{unlocked:e},usage:Ro(t),uptimeSeconds:Math.floor((Date.now()-at)/1e3),update:ao(K)})}if(c==="/v1/history/ingest"&&r.method==="POST")try{const e=JSON.parse((await v(r,t.maxBodyBytes)).toString("utf8"))||{},n=P.bulk({upserts:Array.isArray(e.upserts)?e.upserts:[],removes:Array.isArray(e.removes)?e.removes:[]});return s(o,200,{ok:!0,size:n})}catch(e){return s(o,400,{error:{message:`ingest failed: ${e.message}`,type:"ingest_error"}})}if(c==="/v1/prefs"&&r.method==="GET"){const e=String(u.searchParams.get("section")||"");return u.searchParams.get("stamps")?s(o,200,{ok:!0,revision:Z.revision,stamps:Z.stamps()}):s(o,200,{ok:!0,revision:Z.revision,sections:Z.get(e)})}if(c==="/v1/prefs"&&(r.method==="POST"||r.method==="PUT"))try{const e=JSON.parse((await v(r,t.maxBodyBytes)).toString("utf8"))||{},n=Z.put(e.sections||{},{by:e.by||""});return n.applied.length&&et(n.applied,e.by||""),s(o,200,{ok:!0,...n})}catch(e){return s(o,400,{error:{message:`prefs write failed: ${e.message}`,type:"prefs_error"}})}if(c==="/v1/prefs"&&r.method==="DELETE"){const e=String(u.searchParams.get("section")||""),n=e?Z.remove(e):!1;return n&&et([e],""),s(o,200,{ok:!0,removed:n})}if(c==="/v1/prefs/events"&&r.method==="GET"){o.writeHead(200,{"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive"});const e=l=>o.write(`data: ${JSON.stringify(l)}
6
+ `)}catch{te.delete(t)}},25e3).unref?.();const H=await Xt(),Z=qt(),re=to({key:Oe()}),ne=oo({key:Oe()}),V=ro({key:Oe()}),D=eo({scorecards:re,engines:ne}),Ne=new Set,ot=(t,i)=>{for(const d of Ne)try{d({applied:t,by:i,revision:Z.revision})}catch{}},Be=Uo(),rt=new Set(["codex","claude","opencode","pi","kiro","antigravity","hermes"]),Ko=16,Zo=/^mcp[_-]/i,nt=t=>t&&t.function&&t.function.name||t&&t.name||"",Yo=t=>t&&t.function&&t.function.description||t&&t.description||"";function st(t){return typeof t=="string"?t:Array.isArray(t)?t.map(i=>typeof i=="string"?i:i&&(i.text||i.content)||"").join(" "):""}function Qo(t,i){if(!t)return"";if(i==="responses"){const r=t.input;return typeof r=="string"?r:Array.isArray(r)?r.map(o=>st(o&&(o.content??o))).join(" "):""}const d=Array.isArray(t.messages)?t.messages:[];for(let r=d.length-1;r>=0;r--)if(d[r]&&d[r].role==="user")return st(d[r].content);return""}const at=new Set(["host","connection","content-length","transfer-encoding","accept-encoding","content-encoding","keep-alive"]);function it(t){if(!t)return!1;const i=t.replace(/:\d+$/,"").replace(/^\[|\]$/g,"");return i==="localhost"||i==="127.0.0.1"||i==="::1"}function Xo(t,i){return!t||/^chrome-extension:\/\//.test(t)||/^moz-extension:\/\//.test(t)||/^http:\/\/(localhost|127\.0\.0\.1|\[::1\])(:\d+)?$/.test(t)?!0:Array.isArray(i.allowedOrigins)&&i.allowedOrigins.includes(t)}function qo(t,i){t.setHeader("Access-Control-Allow-Origin",i||"*"),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 lt=Date.now();function er(t){if(!t)return"";const i={redact:"redact",upstream:"model",stream:"stream",restore:"restore",total:"total"};return Object.keys(t).map(d=>`${i[d]||d} ${t[d]}ms`).join(" · ")}function tr(t){const i=/^(model|harness):([^/]+)(?:\/(.+))?$/.exec(String(t||""));return i?{kind:i[1],id:i[2],...i[3]?{model:i[3]}:{}}:null}function or(t){const i=performance.now(),d={};let r=!1;const o=(u,c)=>{d[u]=Math.round(c*10)/10};return{meta:{},timings:d,mark:o,lap(u,c){o(u,performance.now()-c)},clock(){return performance.now()},commit(){if(r)return;r=!0,o("total",performance.now()-i);const u={...this.meta,timings:d};setImmediate(()=>{t(u),console.log(`[gateway] model=${u.model||"-"} → ${u.dest?`${u.dest}(${u.type})`:"none"} · ${u.redaction==="off"?"redaction OFF (client request)":`redacted ${u.redacted||0}`}${u.sanitized?` · scrubbed ${u.sanitized} hidden`:""}${u.narrowed?` · narrowed -${u.narrowed}`:""} · ${er(d)}`)})}}}function ct(t,i){if(!t||!t.byToken||i!=="types"&&i!=="values")return;const d=[];for(const[r,o]of t.byToken){const u=/^\[\[([A-Z][A-Z0-9]*)_\d+\]\]$/.exec(r),c=u?u[1]:"PII",g=r.replace(/^\[\[|\]\]$/g,"");d.push(i==="values"?{token:g,type:c,value:o}:{token:g,type:c})}return d}function rr(t,i,d){return $e.matches(t)||"anthropic-version"in i?{kind:"anthropic",adapter:$e,redactable:$e.matches(t),base:d.upstreams?.anthropic?.baseUrl}:tt.matches(t)?{kind:"responses",adapter:tt,redactable:!0,base:d.upstreams?.openai?.baseUrl}:{kind:"openai",adapter:Ae,redactable:Ae.matches(t),base:d.upstreams?.openai?.baseUrl}}function Ce(t,i){const d=String(t||"");if(rt.has(d))return{agent:d,agentModel:""};const r=d.indexOf("/");if(r>0){const o=d.slice(0,r);if(rt.has(o))return{agent:o,agentModel:d.slice(r+1)}}return{agent:i.bridge.agent,agentModel:""}}function dt(t,i){return Ce(t,i).agent}function nr(t,i){if(i!=="openai"||!t)return!1;const d=Ae.extractLatestToolResult(t);if(!d)return!1;const r=Je(d.tool_call_id);return!!(r&&Ve(r.gwId))}function sr(t,i){try{const d=new URL(t),r=d.hostname.replace(/^\[|\]$/g,""),o=r==="127.0.0.1"||r==="localhost"||r==="::1",u=d.port||(d.protocol==="https:"?"443":"80");return o&&String(u)===String(i.port)}catch{return!1}}async function v(t,i){const d=[];let r=0;for await(const o of t){if(r+=o.length,i&&r>i){const u=new Error("payload too large");throw u.code=413,u}d.push(o)}return Buffer.concat(d)}function s(t,i,d){t.writeHead(i,{"content-type":"application/json"}),t.end(JSON.stringify(d))}function ut(t){const i=t.redaction?.detection?.url;return!i||t.redaction?.detection?.backend==="off"?null:i}function De(t){const i=t?.redaction?.detection,d=t?.redaction?.tier==="full"?"full":"basic";if(i&&i.backend&&i.backend!=="off")return{source:"external",backend:i.backend,state:"external",model:i.model||null,ready:!0,tier:d,coverage:d==="full"?"names":"patterns"};const r=C.health(),o=r.ok&&d==="full";return{source:"bundled",state:r.state,model:r.model||t?.ner?.model||null,installed:C.modelOnDisk(t?.ner?.model||void 0),error:r.error||null,ready:o,tier:d,coverage:o?"names":"patterns"}}async function mt(t){if(C.state()!=="off"){const d=C.health();return{configured:d.configured,ok:d.ok,state:d.state,model:d.model,error:d.error||null,url:d.configured?`http://${t.host}:${t.port}/ner`:null}}const i=ut(t);if(!i)return{configured:!1,ok:!1,url:null,model:null};try{const d=await ze(i.replace(/\/ner\/?$/,"")+"/health",{signal:AbortSignal.timeout(2e3)});if(!d.ok)return{configured:!0,ok:!1,url:i,model:null};const r=await d.json().catch(()=>({}));return{configured:!0,ok:!0,url:i,model:r.model||null}}catch{return{configured:!0,ok:!1,url:i,model:null}}}function ar(t,i){const d={};for(const[r,o]of Object.entries(t)){const u=r.toLowerCase();u.startsWith("x-chatpanel-")||at.has(u)||(d[r]=o)}d["accept-encoding"]="identity";try{d.host=new URL(i).host}catch{}return d}async function pt(t,i,d,r){const o=Me(i.vault),u=r?r.clock():0;let c=u,g=!0;const b=()=>{r&&g&&(r.lap("upstream",u),c=r.clock(),g=!1)};await Ut(i,{onText:E=>{b(),Se(i.id);const p=o.push(E);p&&t.write(d.sseDelta(p))},onToolRequest:({name:E,restoredArgs:p,toolId:L})=>{b(),Se(i.id);const $=o.flush();$&&t.write(d.sseDelta($)),t.write(d.sseToolCalls([{id:L,name:E,arguments:JSON.stringify(p)}])),t.write(d.sseToolFinish()),r&&r.lap("stream",c),t.end(),r?.commit()},onDone:()=>{const E=o.flush();E&&t.write(d.sseDelta(E)),t.write(d.sseTail()),r&&r.lap("stream",c),t.end(),pe(i.id),r?.commit()},onError:E=>{t.write(`data: ${JSON.stringify({error:{message:E.message,type:"bridge_error"}})}
6
7
 
7
- `);e({type:"hello",revision:Z.revision,stamps:Z.stamps()});const n=l=>e({type:"changed",...l});xe.add(n);const a=setInterval(()=>{try{o.write(`: keep-alive
8
+ `),t.end(),pe(i.id),r?.commit()}})}async function ir(t,i,{kind:d,adapter:r,agent:o,run:u=null},c,g,b,E,p,L=null,$=null){const{messages:I,system:Y}=r.toTurn(c),{agentModel:z}=Ce(c?.model,b),R=Xe(b,{...z?{model:z}:{},...u||{}}),N=le(b.bridge.token),P=ve(d,c?.model||o),j={tier:b.redaction.tier==="full"?"full":"basic",dictionary:_t(b.redaction,E),entities:[]},J=await me(b),T=Ht({vault:g,redactOpts:j,bridgeUrl:J,token:N,harness:L});let K;try{K=await Jt({bridgeUrl:J,agent:o,token:N,messages:I,system:Y,specs:Wt(p),options:R,signal:void 0})}catch(X){return pe(T.id),$?.commit(),s(i,502,{error:{message:`bridge: ${X.message}`,type:"bridge_error"}})}return T.reader=K.body.getReader(),i.writeHead(200,{"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive"}),i.write(P.sseHead()),pt(i,T,P,$)}async function lr(t,i,d,r,o=null){Se(i.id),i.rounds=(i.rounds||0)+1;try{const c=o?o.clock():0;await Ft(i,d),o&&o.lap("redact",c)}catch(c){return pe(i.id),o?.commit(),s(t,502,{error:{message:`tool-result: ${c.message}`,type:"bridge_error"}})}const u=ve("openai",r||"codex");return t.writeHead(200,{"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive"}),t.write(u.sseHead()),pt(t,i,u,o)}async function cr(t,i,{kind:d,adapter:r,redactable:o,pathname:u,agentOverride:c,harness:g,trace:b,run:E=null},p,L,$,I){if(!o)return b?.commit(),s(i,404,{error:`endpoint ${u} not supported by the bridge backend`});if(d==="openai"){const e=r.extractLatestToolResult(p);if(e){const a=Je(e.tool_call_id),l=a&&Ve(a.gwId);if(l)return lr(i,l,e.content,p?.model,b)}const n=r.extractTools(p);if(n.length&&p?.stream===!0)return ir(t,i,{kind:d,adapter:r,agent:c||dt(p?.model,$),run:E},p,L,$,I,n,g,b)}const{messages:Y,system:z}=r.toTurn(p),R=c||dt(p?.model,$),N=p?.stream===!0,P=ve(d,p?.model||R),j=le($.bridge.token),J=new AbortController;i.on("close",()=>{i.writableFinished||J.abort()});const{agentModel:T}=Ce(p?.model,$),K={bridgeUrl:await me($),agent:R,token:j,messages:Y,system:z,signal:J.signal,options:Xe($,{...T?{model:T}:{},...E||{}})};if(!N)try{let e="";const n=b?b.clock():0;await Ge(K,m=>{e+=m}),b&&b.lap("upstream",n);const a=b?b.clock():0,l=P.full(Tt(e,L));return b&&b.lap("restore",a),i.writeHead(200,{"content-type":P.contentType}),i.end(l),b?.commit()}catch(e){return b?.commit(),s(i,502,{error:{message:`bridge backend failed: ${e.message}`,type:"bridge_error"}})}i.writeHead(200,{"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive"}),i.write(P.sseHead());const X=Me(L),se=b?b.clock():0;let ae=se;try{let e=!0;await Ge(K,a=>{b&&e&&(b.lap("upstream",se),ae=b.clock(),e=!1);const l=X.push(a);l&&i.write(P.sseDelta(l))},P.sseActivity?a=>{try{i.write(P.sseActivity(vt(a,L)))}catch{}}:null);const n=X.flush();n&&i.write(P.sseDelta(n)),i.write(P.sseTail())}catch(e){i.write(`data: ${JSON.stringify({error:{message:e.message,type:"bridge_error"}})}
8
9
 
9
- `)}catch{}},25e3);o.on("close",()=>{xe.delete(n),clearInterval(a)});return}if(c==="/v1/projects"&&r.method==="GET")return s(o,200,{ok:!0,projects:V.list({limit:u.searchParams.get("limit")||50,status:u.searchParams.get("status")||""})});if(c==="/v1/projects/jobs"&&r.method==="GET")return s(o,200,{ok:!0,jobs:V.openJobs()});if(c==="/v1/projects"&&r.method==="POST")try{const e=JSON.parse((await v(r,t.maxBodyBytes)).toString("utf8"))||{};return s(o,200,{ok:!0,project:V.create({id:e.id||e.project?.id,project:e.project||null,by:e.by})})}catch(e){return s(o,400,{error:{message:`project: ${e.message}`,type:"project_error"}})}{const e=/^\/v1\/projects\/([a-zA-Z0-9_-]{1,64})(\/events|\/jobs(?:\/([a-zA-Z0-9_-]{1,64})(\/applications|\/recruit)?)?)?$/.exec(c);if(e){const n=e[1],a=e[2]||"",l=e[3]||"",m=e[4]||"",k=()=>s(o,404,{error:{message:`no project ${n}`,type:"not_found"}});if(m){const h=V.get(n);if(!h)return k();const w=h.jobs.find(f=>f.id===l);if(!w)return s(o,404,{error:{message:`no job ${l}`,type:"not_found"}});const y={cfg:t,prefsStore:Z,scorecards:oe,engines:re};if(m==="/applications"&&r.method==="GET"){const f=await oo(w,{...y,reach:u.searchParams.get("reach")||"any",chatModel:u.searchParams.get("chatModel")||null});return s(o,200,{ok:!0,job:w,...f})}if(m==="/recruit"&&r.method==="POST"){if(!["open","evaluating"].includes(w.status))return s(o,400,{error:{message:`job ${l} is ${w.status}; only an open job is recruited`,type:"project_error"}});try{const f=JSON.parse((await v(r,t.maxBodyBytes)).toString("utf8"))||{},_=String(f.by||"evaluator").slice(0,80),M=await ro(w,{...y,record:h,reach:f.reach||"any",chatModel:f.chatModel||null,evaluation:f.evaluation||null,text:f.text??null,by:_});let x=null;for(const U of M.events)U.type==="job.updated"?x=V.updateJob(n,l,U.job,{by:U.by||_}):x=V.append(n,[U]);return s(o,200,{ok:!0,project:x,decision:M.decision,applications:M.applications,evaluation:M.evaluation})}catch(f){return s(o,400,{error:{message:`recruit: ${f.message}`,type:"project_error"}})}}return s(o,405,{error:{message:"method not allowed",type:"project_error"}})}if(!a&&r.method==="GET"){const h=V.get(n,{events:u.searchParams.get("events")==="1"});return h?s(o,200,{ok:!0,project:h}):k()}if(!a&&r.method==="DELETE")return s(o,200,{ok:!0,removed:V.remove(n)});if(r.method==="POST"&&(a==="/events"||a.startsWith("/jobs")))try{const h=JSON.parse((await v(r,t.maxBodyBytes)).toString("utf8"))||{},w=String(h.by||"person").slice(0,80),y=a==="/events"?V.append(n,h.events||[]):l?V.updateJob(n,l,h.patch||h,{by:w}):V.postJob(n,h.job||h,{by:w});return s(o,200,{ok:!0,project:y})}catch(h){return s(o,h.message.startsWith("no ")?404:400,{error:{message:`project: ${h.message}`,type:"project_error"}})}if(a==="/events"&&r.method==="GET"){if(!V.get(n))return k();o.writeHead(200,{"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive"});const h=_=>o.write(`data: ${JSON.stringify(_)}
10
+ `)}b&&b.lap("stream",ae),i.end(),b?.commit()}function dr(t,i,d=""){const r=String(t||"").replace(/\/+$/,""),o=String(i||"").split("/")[1];return o&&r.endsWith(`/${o}`)?r.slice(0,-(o.length+1))+i+d:r+i+d}const ur=9e4;function mr(t,i,d){if(i===d)return t;const r=i/d,o=new Float32Array(Math.floor(t.length/r));for(let u=0;u<o.length;u++){const c=u*r,g=Math.floor(c),b=Math.min(t.length-1,g+1),E=c-g;o[u]=t[g]*(1-E)+t[b]*E}return o}const pr=["/tts","/stt","/ner","/diarize","/skills","/redact","/config","/logs","/status","/admin"];function yt(t,i){const d=new URLSearchParams;for(const u of t.searchParams.getAll("dir"))u&&d.append("dir",u);const r=t.searchParams.get("workdir")||String(i?.bridge?.workingDir||"").trim();r&&d.set("workdir",r);const o=d.toString();return o?`?${o}`:""}async function yr(t,i,{adapter:d,kind:r,pathname:o,search:u,base:c,destKey:g,destProtocol:b,harness:E,trace:p},L,$){let I;const Y=p?p.clock():0;try{const P=ar(t.headers,c);g&&(b==="anthropic"?(P["x-api-key"]=g,delete P.authorization):P.authorization=`Bearer ${g}`);const j=At(dr(c,o,u)).toString();I=await fetch(j,{method:t.method,headers:P,body:["GET","HEAD"].includes(t.method)?void 0:L})}catch(P){return p?.commit(),s(i,502,{error:`upstream fetch failed: ${P.message}`})}const z=I.headers.get("content-type")||"",R={};if(I.headers.forEach((P,j)=>{at.has(j.toLowerCase())||(R[j]=P)}),z.includes("text/event-stream")&&I.body){p&&p.lap("upstream",Y);const P=p?p.clock():0;i.writeHead(I.status,R);const j=r==="openai"?St(I.body,i,$,E):kt(I.body,i,$);return Promise.resolve(j).finally(()=>{p&&p.lap("stream",P),p?.commit()})}const N=Buffer.from(await I.arrayBuffer());if(p&&p.lap("upstream",Y),$&&z.includes("application/json"))try{const P=p?p.clock():0,j=d.restoreResponse(JSON.parse(N.toString("utf8")),$,E);return p&&p.lap("restore",P),i.writeHead(I.status,{...R,"content-type":"application/json"}),i.end(Buffer.from(JSON.stringify(j),"utf8")),p?.commit()}catch{}i.writeHead(I.status,R),i.end(N),p?.commit()}function hr(t=Ie()){Ct(t.allowedExtensionIds||[]);const i=[],d=r=>{i.push(r),i.length>50&&i.shift()};return gt(async(r,o)=>{const u=new URL(r.url,"http://127.0.0.1"),c=u.pathname;if(!it(r.headers.host))return s(o,403,{error:"loopback only"});if(!Xo(r.headers.origin,t))return s(o,403,{error:"origin not allowed"});if(r.headers.origin&&qo(o,r.headers.origin),r.method==="OPTIONS")return o.writeHead(204),o.end();if(c==="/admin/token"&&r.method==="POST")return F(r)?s(o,200,{token:ke()}):s(o,403,{error:"admin: extension origin or gateway token required"});if(c==="/pair/code"&&r.method==="POST"){if(!F(r))return s(o,403,{error:"pair/code: extension origin or gateway token required"});const e=Dt();return console.log("[gateway] pairing code issued — valid for 5 minutes, one use"),s(o,200,{ok:!0,...e})}if(c==="/pair"&&r.method==="POST"){let e=null;try{e=JSON.parse((await v(r,t.maxBodyBytes)).toString("utf8"))}catch{e=null}const n=It(e?.code);if(!n.ok)return console.log(`[gateway] pairing refused (${n.reason}) from ${ue(r)} caller`),s(o,403,{error:n.reason});console.log(`[gateway] paired a ${ue(r)} client${r.headers.origin?` (${r.headers.origin})`:""}`);const a=le(t.bridge?.token);return s(o,200,{ok:!0,token:Bt()||ke(),...a?{bridgeToken:a}:{}})}if(c==="/whoami"&&r.method==="POST"){const e=ue(r);return s(o,200,{ok:!0,trust:e,paired:Nt(e),version:W})}if(c==="/audit"&&r.method==="GET")return F(r)?s(o,200,Mt(t,{version:W,startedAt:lt,managed:ie()})):s(o,403,{error:"audit: extension origin or gateway token required"});if((c==="/config"||c==="/logs"||c==="/update"&&r.method!=="GET")&&!F(r))return s(o,403,{error:"admin route: extension origin or gateway token required"});if(c==="/update"&&r.method==="GET"){const e=await io(W,{force:u.searchParams.get("force")==="1"}).catch(n=>({current:W,updateAvailable:!1,error:String(n?.message||n)}));return s(o,200,{ok:!0,update:e,job:uo()})}if(c==="/update"&&r.method==="POST"){const e=co(W);return s(o,e.already?409:202,{ok:!0,job:e})}if((c==="/v1/history/key"||c==="/v1/history/ingest-backup")&&r.method==="POST"&&!F(r))return s(o,403,{error:{message:"history key route: extension origin or gateway token required",type:"forbidden"}});if(c==="/v1/history/records"&&r.method==="PUT"&&!F(r))return s(o,403,{error:{message:"history write — extension origin or gateway token required",type:"forbidden"}});if((c==="/v1/history/ingest"||c==="/v1/history/clear")&&r.method==="POST"&&!F(r))return s(o,403,{error:{message:"history write — extension origin or gateway token required",type:"forbidden"}});if((c==="/v1/memory/remember"||c==="/v1/memory/forget"||c==="/v1/memory/sync"||c==="/v1/memory/clear")&&r.method==="POST"&&!F(r))return s(o,403,{error:{message:"memory write — extension origin or gateway token required",type:"forbidden"}});if((c==="/v1/prefs"||c.startsWith("/v1/prefs/")||c.startsWith("/v1/teams")||c.startsWith("/v1/agents")||c.startsWith("/v1/projects"))&&!F(r))return s(o,403,{error:{message:"prefs: extension origin or gateway token required",type:"forbidden"}});if(c.startsWith("/v1/observability")&&!F(r))return s(o,403,{error:{message:"observability: extension origin or gateway token required",type:"forbidden"}});if(r.method==="GET"&&c==="/health"){const e=x.health(),n=S.health();return s(o,200,{ok:!0,version:W,backend:t.backend,tier:t.redaction.tier,pairing:!0,...ie()?{managed:ie()}:{},...process.env.CHATPANEL_MANAGED_BY?{managedBy:String(process.env.CHATPANEL_MANAGED_BY).slice(0,32)}:{},...be?{bridge:be.status()}:{},stt:{enabled:t.stt?.enabled!==!1,state:e.state,ready:e.ok,model:e.model||t.stt?.model||Ee,runtime:e.runtime,dtype:e.dtype},tts:{enabled:t.tts?.enabled!==!1,state:n.state,ready:n.ok,model:n.model||t.tts?.model||Ke,voice:t.tts?.voice||Q,runtime:n.runtime,dtype:n.dtype}})}if(c==="/status"&&r.method==="GET"){wt(t);const e=await q(t.pro?.entitlementToken),n=await mt(t);return s(o,200,{ok:!0,version:W,backend:t.backend,tier:t.redaction.tier,...ie()?{managed:ie()}:{},...process.env.CHATPANEL_MANAGED_BY?{managedBy:String(process.env.CHATPANEL_MANAGED_BY).slice(0,32)}:{},ner:{autostart:!!t.ner?.autostart,configured:n.configured,ready:n.ok,model:n.model,url:n.url},detector:De(t),pro:{unlocked:e},usage:zo(t),uptimeSeconds:Math.floor((Date.now()-lt)/1e3),update:lo(W)})}if(c==="/v1/history/ingest"&&r.method==="POST")try{const e=JSON.parse((await v(r,t.maxBodyBytes)).toString("utf8"))||{},n=O.bulk({upserts:Array.isArray(e.upserts)?e.upserts:[],removes:Array.isArray(e.removes)?e.removes:[]});return s(o,200,{ok:!0,size:n})}catch(e){return s(o,400,{error:{message:`ingest failed: ${e.message}`,type:"ingest_error"}})}if(c==="/v1/prefs"&&r.method==="GET"){const e=String(u.searchParams.get("section")||"");return u.searchParams.get("stamps")?s(o,200,{ok:!0,revision:Z.revision,stamps:Z.stamps()}):s(o,200,{ok:!0,revision:Z.revision,sections:Z.get(e)})}if(c==="/v1/prefs"&&(r.method==="POST"||r.method==="PUT"))try{const e=JSON.parse((await v(r,t.maxBodyBytes)).toString("utf8"))||{},n=Z.put(e.sections||{},{by:e.by||""});return n.applied.length&&ot(n.applied,e.by||""),s(o,200,{ok:!0,...n})}catch(e){return s(o,400,{error:{message:`prefs write failed: ${e.message}`,type:"prefs_error"}})}if(c==="/v1/prefs"&&r.method==="DELETE"){const e=String(u.searchParams.get("section")||""),n=e?Z.remove(e):!1;return n&&ot([e],""),s(o,200,{ok:!0,removed:n})}if(c==="/v1/prefs/events"&&r.method==="GET"){o.writeHead(200,{"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive"});const e=l=>o.write(`data: ${JSON.stringify(l)}
11
+
12
+ `);e({type:"hello",revision:Z.revision,stamps:Z.stamps()});const n=l=>e({type:"changed",...l});Ne.add(n);const a=setInterval(()=>{try{o.write(`: keep-alive
13
+
14
+ `)}catch{}},25e3);o.on("close",()=>{Ne.delete(n),clearInterval(a)});return}if(c==="/v1/projects"&&r.method==="GET")return s(o,200,{ok:!0,projects:V.list({limit:u.searchParams.get("limit")||50,status:u.searchParams.get("status")||""})});if(c==="/v1/projects/jobs"&&r.method==="GET")return s(o,200,{ok:!0,jobs:V.openJobs()});if(c==="/v1/projects"&&r.method==="POST")try{const e=JSON.parse((await v(r,t.maxBodyBytes)).toString("utf8"))||{};return s(o,200,{ok:!0,project:V.create({id:e.id||e.project?.id,project:e.project||null,by:e.by})})}catch(e){return s(o,400,{error:{message:`project: ${e.message}`,type:"project_error"}})}{const e=/^\/v1\/projects\/([a-zA-Z0-9_-]{1,64})(\/events|\/jobs(?:\/([a-zA-Z0-9_-]{1,64})(\/applications|\/recruit)?)?)?$/.exec(c);if(e){const n=e[1],a=e[2]||"",l=e[3]||"",m=e[4]||"",k=()=>s(o,404,{error:{message:`no project ${n}`,type:"not_found"}});if(m){const h=V.get(n);if(!h)return k();const w=h.jobs.find(f=>f.id===l);if(!w)return s(o,404,{error:{message:`no job ${l}`,type:"not_found"}});const y={cfg:t,prefsStore:Z,scorecards:re,engines:ne};if(m==="/applications"&&r.method==="GET"){const f=await no(w,{...y,reach:u.searchParams.get("reach")||"any",chatModel:u.searchParams.get("chatModel")||null});return s(o,200,{ok:!0,job:w,...f})}if(m==="/recruit"&&r.method==="POST"){if(!["open","evaluating"].includes(w.status))return s(o,400,{error:{message:`job ${l} is ${w.status}; only an open job is recruited`,type:"project_error"}});try{const f=JSON.parse((await v(r,t.maxBodyBytes)).toString("utf8"))||{},_=String(f.by||"evaluator").slice(0,80),M=await so(w,{...y,record:h,reach:f.reach||"any",chatModel:f.chatModel||null,evaluation:f.evaluation||null,text:f.text??null,by:_});let A=null;for(const U of M.events)U.type==="job.updated"?A=V.updateJob(n,l,U.job,{by:U.by||_}):A=V.append(n,[U]);return s(o,200,{ok:!0,project:A,decision:M.decision,applications:M.applications,evaluation:M.evaluation})}catch(f){return s(o,400,{error:{message:`recruit: ${f.message}`,type:"project_error"}})}}return s(o,405,{error:{message:"method not allowed",type:"project_error"}})}if(!a&&r.method==="GET"){const h=V.get(n,{events:u.searchParams.get("events")==="1"});return h?s(o,200,{ok:!0,project:h}):k()}if(!a&&r.method==="DELETE")return s(o,200,{ok:!0,removed:V.remove(n)});if(r.method==="POST"&&(a==="/events"||a.startsWith("/jobs")))try{const h=JSON.parse((await v(r,t.maxBodyBytes)).toString("utf8"))||{},w=String(h.by||"person").slice(0,80),y=a==="/events"?V.append(n,h.events||[]):l?V.updateJob(n,l,h.patch||h,{by:w}):V.postJob(n,h.job||h,{by:w});return s(o,200,{ok:!0,project:y})}catch(h){return s(o,h.message.startsWith("no ")?404:400,{error:{message:`project: ${h.message}`,type:"project_error"}})}if(a==="/events"&&r.method==="GET"){if(!V.get(n))return k();o.writeHead(200,{"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive"});const h=_=>o.write(`data: ${JSON.stringify(_)}
10
15
 
11
16
  `);let w=u.searchParams.has("after")?Number(u.searchParams.get("after")):-1;h({seq:-1,type:"hello",at:Date.now(),payload:{project:V.get(n),after:w}});const y=V.watch(n,_=>{_.seq>w&&(w=_.seq,h(_))});for(const _ of V.eventsSince(n,w))w=_.seq,h(_);const f=setInterval(()=>{try{o.write(`: keep
12
17
 
13
- `)}catch{}},25e3);r.on("close",()=>{clearInterval(f),y()});return}}}if(c==="/v1/agents/scorecards"&&r.method==="GET")return s(o,200,{ok:!0,agents:oe.list()});{const e=/^\/v1\/agents\/([a-zA-Z0-9_.:@+-]{1,120})\/scorecard$/.exec(c);if(e){const n=decodeURIComponent(e[1]);if(r.method==="GET")return s(o,200,{ok:!0,...await oe.get(n)});if(r.method==="POST")try{const a=JSON.parse((await v(r,t.maxBodyBytes)).toString("utf8"))||{},l=await oe.append({agentId:n,kind:"rating",runId:a.runId,taskId:a.taskId,jobId:a.jobId,rating:{by:String(a.by||"person").slice(0,40),score:a.score,note:a.note,about:a.about},refs:a.refs});return re.fromRating(oe.chains.get(n)||[],{...l,jobKind:a.jobKind?String(a.jobKind).slice(0,60):void 0}),s(o,200,{ok:!0,entry:l})}catch(a){return s(o,400,{error:{message:`scorecard: ${a.message}`,type:"scorecard_error"}})}}}if(c==="/v1/engines"&&r.method==="GET"){const e=Number(u.searchParams.get("minCalls"))||void 0;return s(o,200,{ok:!0,engines:re.list({minCalls:e})})}{const e=/^\/v1\/engines\/(.+)\/(card|entries)$/.exec(c);if(e){const n=decodeURIComponent(e[1]).slice(0,300);if(e[2]==="card"&&r.method==="GET"){const a=Number(u.searchParams.get("minCalls"))||void 0;return s(o,200,{ok:!0,...await re.get(n,{entries:u.searchParams.get("entries")==="1",minCalls:a})})}if(e[2]==="entries"&&r.method==="POST")try{const a=JSON.parse((await v(r,t.maxBodyBytes)).toString("utf8"))||{},l=a.engine||qo(n);if(!l)return s(o,400,{error:{message:"model-ledger: engine required",type:"model_ledger_error"}});const m=await re.append({...a,engine:l,kind:a.kind||"call"});return m.key!==n?s(o,400,{error:{message:`model-ledger: entry is for ${m.key}, not ${n}`,type:"model_ledger_error"}}):s(o,200,{ok:!0,entry:m})}catch(a){return s(o,400,{error:{message:`model-ledger: ${a.message}`,type:"model_ledger_error"}})}}}if(c==="/v1/teams/runs"&&r.method==="GET")return s(o,200,{ok:!0,runs:D.list({limit:u.searchParams.get("limit")||50,team:u.searchParams.get("team")||""})});if(c==="/v1/teams/runs"&&r.method==="POST")try{const e=JSON.parse((await v(r,t.maxBodyBytes)).toString("utf8"))||{};return s(o,200,{ok:!0,run:D.create({id:e.id,client:e.client,team:e.team,request:e.request})})}catch(e){return s(o,400,{error:{message:`team run: ${e.message}`,type:"team_error"}})}{const e=/^\/v1\/teams\/runs\/([a-zA-Z0-9_-]{4,64})(\/events|\/stop|\/answer|\/decide|\/post|\/handoff|\/checkpoint|\/claim|\/threads\/[a-zA-Z0-9_:-]{1,80})?$/.exec(c);if(e){const n=e[1],a=e[2]||"";if(!a&&r.method==="GET"){const l=D.get(n,{events:u.searchParams.get("events")==="1"});return l?s(o,200,{ok:!0,run:l}):s(o,404,{error:{message:`no run ${n}`,type:"not_found"}})}if(!a&&r.method==="DELETE")return D.stop(n),s(o,200,{ok:!0,removed:D.remove(n)});if(a==="/stop"&&r.method==="POST"){const l=D.stop(n);return l?s(o,200,{ok:!0,run:l}):s(o,404,{error:{message:`no run ${n}`,type:"not_found"}})}if(a==="/checkpoint"&&r.method==="GET")try{return s(o,200,{ok:!0,checkpoint:D.checkpoint(n)})}catch(l){return s(o,404,{error:{message:`team run: ${l.message}`,type:"team_error"}})}if((a==="/handoff"||a==="/claim")&&r.method==="POST")try{const l=JSON.parse((await v(r,t.maxBodyBytes)).toString("utf8"))||{},m=a==="/handoff"?D.handoff(n,{taskId:l.taskId,model:l.model,by:l.by,reason:l.reason}):D.claim(n,{client:l.client});return s(o,200,{ok:!0,run:m})}catch(l){return s(o,l.message.startsWith("no ")?404:400,{error:{message:`team run: ${l.message}`,type:"team_error"}})}if(a.startsWith("/threads/")&&r.method==="DELETE")try{return s(o,200,{ok:!0,run:D.removeThread(n,{threadId:a.slice(9),by:"person"})})}catch(l){return s(o,l.message.startsWith("no ")?404:400,{error:{message:`team run: ${l.message}`,type:"team_error"}})}if((a==="/answer"||a==="/decide"||a==="/post")&&r.method==="POST")try{const l=JSON.parse((await v(r,t.maxBodyBytes)).toString("utf8"))||{},m=String(l.by||"person").slice(0,40),k=a==="/answer"?D.answer(n,{threadId:l.threadId,text:l.text,by:m}):a==="/decide"?D.decide(n,{postId:l.postId,status:l.status,by:m}):D.post(n,{threadId:l.threadId,text:l.text,by:m,kind:l.kind,replyTo:l.replyTo});return s(o,200,{ok:!0,run:k})}catch(l){return s(o,l.message.startsWith("no ")?404:400,{error:{message:`team run: ${l.message}`,type:"team_error"}})}if(a==="/events"&&r.method==="POST")try{const l=JSON.parse((await v(r,t.maxBodyBytes)).toString("utf8"))||{};return s(o,200,{ok:!0,run:D.append(n,l.events||[])})}catch(l){return s(o,l.message.startsWith("no run")?404:400,{error:{message:`team run: ${l.message}`,type:"team_error"}})}if(a==="/events"&&r.method==="GET"){if(!D.get(n))return s(o,404,{error:{message:`no run ${n}`,type:"not_found"}});o.writeHead(200,{"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive"});const l=y=>o.write(`data: ${JSON.stringify(y)}
18
+ `)}catch{}},25e3);r.on("close",()=>{clearInterval(f),y()});return}}}if(c==="/v1/agents/scorecards"&&r.method==="GET")return s(o,200,{ok:!0,agents:re.list()});{const e=/^\/v1\/agents\/([a-zA-Z0-9_.:@+-]{1,120})\/scorecard$/.exec(c);if(e){const n=decodeURIComponent(e[1]);if(r.method==="GET")return s(o,200,{ok:!0,...await re.get(n)});if(r.method==="POST")try{const a=JSON.parse((await v(r,t.maxBodyBytes)).toString("utf8"))||{},l=await re.append({agentId:n,kind:"rating",runId:a.runId,taskId:a.taskId,jobId:a.jobId,rating:{by:String(a.by||"person").slice(0,40),score:a.score,note:a.note,about:a.about},refs:a.refs});return ne.fromRating(re.chains.get(n)||[],{...l,jobKind:a.jobKind?String(a.jobKind).slice(0,60):void 0}),s(o,200,{ok:!0,entry:l})}catch(a){return s(o,400,{error:{message:`scorecard: ${a.message}`,type:"scorecard_error"}})}}}if(c==="/v1/engines"&&r.method==="GET"){const e=Number(u.searchParams.get("minCalls"))||void 0;return s(o,200,{ok:!0,engines:ne.list({minCalls:e})})}{const e=/^\/v1\/engines\/(.+)\/(card|entries)$/.exec(c);if(e){const n=decodeURIComponent(e[1]).slice(0,300);if(e[2]==="card"&&r.method==="GET"){const a=Number(u.searchParams.get("minCalls"))||void 0;return s(o,200,{ok:!0,...await ne.get(n,{entries:u.searchParams.get("entries")==="1",minCalls:a})})}if(e[2]==="entries"&&r.method==="POST")try{const a=JSON.parse((await v(r,t.maxBodyBytes)).toString("utf8"))||{},l=a.engine||tr(n);if(!l)return s(o,400,{error:{message:"model-ledger: engine required",type:"model_ledger_error"}});const m=await ne.append({...a,engine:l,kind:a.kind||"call"});return m.key!==n?s(o,400,{error:{message:`model-ledger: entry is for ${m.key}, not ${n}`,type:"model_ledger_error"}}):s(o,200,{ok:!0,entry:m})}catch(a){return s(o,400,{error:{message:`model-ledger: ${a.message}`,type:"model_ledger_error"}})}}}if(c==="/v1/teams/runs"&&r.method==="GET")return s(o,200,{ok:!0,runs:D.list({limit:u.searchParams.get("limit")||50,team:u.searchParams.get("team")||""})});if(c==="/v1/teams/runs"&&r.method==="POST")try{const e=JSON.parse((await v(r,t.maxBodyBytes)).toString("utf8"))||{};return s(o,200,{ok:!0,run:D.create({id:e.id,client:e.client,team:e.team,request:e.request})})}catch(e){return s(o,400,{error:{message:`team run: ${e.message}`,type:"team_error"}})}{const e=/^\/v1\/teams\/runs\/([a-zA-Z0-9_-]{4,64})(\/events|\/stop|\/answer|\/decide|\/post|\/handoff|\/checkpoint|\/claim|\/threads\/[a-zA-Z0-9_:-]{1,80})?$/.exec(c);if(e){const n=e[1],a=e[2]||"";if(!a&&r.method==="GET"){const l=D.get(n,{events:u.searchParams.get("events")==="1"});return l?s(o,200,{ok:!0,run:l}):s(o,404,{error:{message:`no run ${n}`,type:"not_found"}})}if(!a&&r.method==="DELETE")return D.stop(n),s(o,200,{ok:!0,removed:D.remove(n)});if(a==="/stop"&&r.method==="POST"){const l=D.stop(n);return l?s(o,200,{ok:!0,run:l}):s(o,404,{error:{message:`no run ${n}`,type:"not_found"}})}if(a==="/checkpoint"&&r.method==="GET")try{return s(o,200,{ok:!0,checkpoint:D.checkpoint(n)})}catch(l){return s(o,404,{error:{message:`team run: ${l.message}`,type:"team_error"}})}if((a==="/handoff"||a==="/claim")&&r.method==="POST")try{const l=JSON.parse((await v(r,t.maxBodyBytes)).toString("utf8"))||{},m=a==="/handoff"?D.handoff(n,{taskId:l.taskId,model:l.model,by:l.by,reason:l.reason}):D.claim(n,{client:l.client});return s(o,200,{ok:!0,run:m})}catch(l){return s(o,l.message.startsWith("no ")?404:400,{error:{message:`team run: ${l.message}`,type:"team_error"}})}if(a.startsWith("/threads/")&&r.method==="DELETE")try{return s(o,200,{ok:!0,run:D.removeThread(n,{threadId:a.slice(9),by:"person"})})}catch(l){return s(o,l.message.startsWith("no ")?404:400,{error:{message:`team run: ${l.message}`,type:"team_error"}})}if((a==="/answer"||a==="/decide"||a==="/post")&&r.method==="POST")try{const l=JSON.parse((await v(r,t.maxBodyBytes)).toString("utf8"))||{},m=String(l.by||"person").slice(0,40),k=a==="/answer"?D.answer(n,{threadId:l.threadId,text:l.text,by:m}):a==="/decide"?D.decide(n,{postId:l.postId,status:l.status,by:m}):D.post(n,{threadId:l.threadId,text:l.text,by:m,kind:l.kind,replyTo:l.replyTo});return s(o,200,{ok:!0,run:k})}catch(l){return s(o,l.message.startsWith("no ")?404:400,{error:{message:`team run: ${l.message}`,type:"team_error"}})}if(a==="/events"&&r.method==="POST")try{const l=JSON.parse((await v(r,t.maxBodyBytes)).toString("utf8"))||{};return s(o,200,{ok:!0,run:D.append(n,l.events||[])})}catch(l){return s(o,l.message.startsWith("no run")?404:400,{error:{message:`team run: ${l.message}`,type:"team_error"}})}if(a==="/events"&&r.method==="GET"){if(!D.get(n))return s(o,404,{error:{message:`no run ${n}`,type:"not_found"}});o.writeHead(200,{"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive"});const l=y=>o.write(`data: ${JSON.stringify(y)}
14
19
 
15
20
  `),m=u.searchParams.has("after")?Number(u.searchParams.get("after")):NaN;let k=Number.isFinite(m)?m:-1;l({seq:-1,type:"hello",at:Date.now(),payload:{run:D.get(n),after:k}});const h=D.watch(n,y=>{y.seq==null?l(y):y.seq>k&&(k=y.seq,l(y))});for(const y of D.eventsSince(n,k))k=y.seq,l(y);const w=setInterval(()=>{try{o.write(`: keep-alive
16
21
 
17
- `)}catch{}},25e3);o.on("close",()=>{h(),clearInterval(w)});return}}}if(c==="/v1/memory/list"&&r.method==="GET")return s(o,200,{ok:!0,size:H.size,memories:H.list()});if(c==="/v1/memory/recall"&&r.method==="POST")try{const e=JSON.parse((await v(r,t.maxBodyBytes)).toString("utf8"))||{},n=H.recall({text:String(e.text||""),scopes:Array.isArray(e.scopes)&&e.scopes.length?e.scopes.map(String):["global"],limit:Number(e.limit)||0,maxChars:Number(e.maxChars)||0});return s(o,200,{ok:!0,size:H.size,...n})}catch(e){return s(o,400,{error:{message:`recall failed: ${e.message}`,type:"memory_error"}})}if(c==="/v1/memory/remember"&&r.method==="POST")try{const e=JSON.parse((await v(r,t.maxBodyBytes)).toString("utf8"))||{},n=H.remember({text:String(e.text||""),kind:e.kind?String(e.kind):"fact",scope:e.scope?String(e.scope):"global",tags:Array.isArray(e.tags)?e.tags.map(String):[],source:{via:String(e.source?.via||"mcp"),surface:String(e.source?.surface||"mcp"),agent:String(e.source?.agent||""),ref:String(e.source?.ref||"")}});return s(o,200,{ok:!0,action:n.action,record:n.record,replaced:n.replaces||null,size:H.size})}catch(e){return s(o,400,{error:{message:e.message,type:"memory_error"}})}if(c==="/v1/memory/forget"&&r.method==="POST")try{const e=JSON.parse((await v(r,t.maxBodyBytes)).toString("utf8"))||{},{removed:n}=H.forget(String(e.query||""));return s(o,200,{ok:!0,removed:n,size:H.size})}catch(e){return s(o,400,{error:{message:e.message,type:"memory_error"}})}if(c==="/v1/memory/sync"&&r.method==="POST")try{const e=JSON.parse((await v(r,t.maxBodyBytes)).toString("utf8"))||{},n=H.bulk({upserts:Array.isArray(e.upserts)?e.upserts:[],removes:Array.isArray(e.removes)?e.removes:[]});return s(o,200,{ok:!0,...n,memories:H.list()})}catch(e){return s(o,400,{error:{message:`memory sync failed: ${e.message}`,type:"memory_error"}})}if(c==="/v1/memory/clear"&&r.method==="POST")return s(o,200,{ok:!0,dropped:H.clear(),size:H.size});if(c==="/v1/history/clear"&&r.method==="POST"){const e=P.clear();return s(o,200,{ok:!0,dropped:e,size:P.size})}if(c==="/v1/history/search"&&r.method==="POST")try{const e=JSON.parse((await v(r,t.maxBodyBytes)).toString("utf8"))||{},n=P.search(String(e.query||""),{limit:Number(e.limit)||10,offset:Math.max(0,Number(e.offset)||0),type:e.type?String(e.type):null,since:e.since!=null?Number(e.since):null,before:e.before!=null?Number(e.before):null});return s(o,200,{ok:!0,size:P.size,newest:P.newest,results:n})}catch(e){return s(o,400,{error:{message:`search failed: ${e.message}`,type:"search_error"}})}if(c==="/v1/history/smart-search"&&r.method==="POST")try{const e=JSON.parse((await v(r,t.maxBodyBytes)).toString("utf8"))||{},n=String(e.question||e.query||""),a=Ho(n,{extra:Array.isArray(e.queries)?e.queries.map(String):[],max:Math.min(6,Math.max(1,Number(e.maxQueries)||4))}),l={type:e.type?String(e.type):null,since:e.since!=null?Number(e.since):null,before:e.before!=null?Number(e.before):null},m=Math.min(30,Math.max(5,Number(e.limit)||10)*2),k=await Uo(a,w=>P.search(w,{limit:m,...l}),{limit:Math.min(50,Math.max(1,Number(e.limit)||10))}),h=l.type?k:[...k.filter(w=>w.type==="brief"),...k.filter(w=>w.type!=="brief")];return s(o,200,{ok:!0,size:P.size,newest:P.newest,queries:a,results:h})}catch(e){return s(o,400,{error:{message:`smart search failed: ${e.message}`,type:"search_error"}})}if(c==="/v1/history/related"&&r.method==="GET"){const e=String(u.searchParams.get("id")||""),n=Math.min(30,Math.max(1,Number(u.searchParams.get("limit"))||5));return s(o,200,{ok:!0,results:P.related(e,{limit:n})})}if(c==="/v1/history/status"&&r.method==="GET")return s(o,200,{ok:!0,size:P.size,newest:P.newest,bytes:P.bytes,lossless:P.lossless?{records:P.lossless.size,newest:P.lossless.newest}:null});if(c==="/v1/observability"&&r.method==="GET"){const e=Math.min(500,Math.max(1,Number(u.searchParams.get("limit"))||200));return s(o,200,{ok:!0,storage:{warm:{records:P.size,bytes:P.bytes,newest:P.newest}},access:$e.snapshot(e)})}if(c==="/v1/observability/access"&&r.method==="POST")try{const e=JSON.parse((await v(r,t.maxBodyBytes)).toString("utf8"))||{},n=$e.push(Xe({ts:Date.now(),...e}));return s(o,200,{ok:!0,event:n})}catch(e){return s(o,400,{error:{message:`access log failed: ${e.message}`,type:"observability_error"}})}if(c==="/v1/history/records"&&r.method==="PUT"){const e=P.lossless;if(!e)return s(o,501,{error:{message:"lossless records need the SQLite warm store",type:"unavailable"}});try{const n=JSON.parse((await v(r,t.maxBodyBytes)).toString("utf8"))||{},a=String(n.host||"").slice(0,80),l=Number(n.at)||Date.now(),m=[];let k=0;const h={upserts:[],removes:[]},w=y=>{if(!y||y.deletedAt){y?.id&&h.removes.push(y.id);return}try{const f=uo(y);f&&h.upserts.push(f)}catch{}};if(Array.isArray(n.records)){const y=e.upsert(n.records,{host:a,at:l});m.push(...y);for(const f of n.records)y.includes(f?.id)&&w(f)}if(Array.isArray(n.entries)){const y=ve(),f=y?yo((x,U)=>mo(y,{salt:x,iterations:U})):null,_=async x=>{if(!f||!x.blob)return null;const U=await f(x.blob),le=x.blob.compression&&x.blob.compression!=="none"?ho(fo,x.blob.compression):null;return po(x.blob,U,{codec:le})},M=await e.upsertEntries(n.entries,{open:_});m.push(...M.written),k+=M.sealed;for(const x of M.written)w(e.get(x))}return(h.upserts.length||h.removes.length)&&P.bulk(h),s(o,200,{ok:!0,written:m.length,ids:m,sealed:k,size:e.size})}catch(n){return s(o,400,{error:{message:`records failed: ${n.message}`,type:"ingest_error"}})}}if(c==="/v1/history/records"&&r.method==="GET"){const e=P.lossless;if(!e)return s(o,501,{error:{message:"lossless records need the SQLite warm store",type:"unavailable"}});const n=e.since({since:Number(u.searchParams.get("since"))||0,cursor:u.searchParams.get("cursor")||"",limit:Number(u.searchParams.get("limit"))||200,kind:u.searchParams.get("kind")||null});return s(o,200,{ok:!0,...n,size:e.size,newest:e.newest})}if(c==="/v1/history/list"&&r.method==="GET"){const e=Math.min(500,Math.max(1,Number(u.searchParams.get("limit"))||50)),n=Math.max(0,Number(u.searchParams.get("offset"))||0),a=u.searchParams.get("type")||null;return s(o,200,{ok:!0,...P.list({limit:e,offset:n,type:a})})}if(c==="/v1/history/get"&&r.method==="GET"){const e=u.searchParams.get("maxChars")!=null?Math.max(1,Number(u.searchParams.get("maxChars"))||0):null,n=Math.max(0,Number(u.searchParams.get("offset"))||0),a=P.get(String(u.searchParams.get("id")||""),{maxChars:e,offset:n});return a?s(o,200,{ok:!0,record:a}):s(o,404,{error:{message:"no such record",type:"not_found"}})}if(c==="/v1/history/key"&&r.method==="GET")return s(o,200,{ok:!0,hasKey:Ve()});if(c==="/v1/history/key"&&r.method==="POST")try{const e=JSON.parse((await v(r,t.maxBodyBytes)).toString("utf8"))||{};e.passphrase?Kt(String(e.passphrase)):Zt();const n=e.passphrase?await _e(P,String(e.passphrase)):{ok:!0,ingested:0};return s(o,200,{ok:!0,hasKey:!!e.passphrase,...n})}catch(e){return s(o,400,{error:{message:`key handoff failed: ${e.message}`,type:"key_error"}})}if(c==="/v1/history/ingest-backup"&&r.method==="POST")try{const e=await _e(P,ve());return s(o,e.ok?200:409,e)}catch(e){return s(o,400,{error:{message:`backup ingest failed: ${e.message}`,type:"ingest_error"}})}if(c==="/ner"){if(r.method==="GET"){const e=await dt(t);return s(o,e.ok?200:503,e)}if(r.method==="POST"){if(await Se(t),C.state()!=="off"){if(!C.isReady()){const n=C.health();return s(o,503,{error:{message:n.state==="error"?`NER model failed to load: ${n.error||"unknown error"}`:`NER model is ${n.state} — not ready yet`,type:n.state==="error"?"ner_error":"ner_loading"},state:n.state,model:n.model})}try{const n=await v(r,t.maxBodyBytes);let a="";try{a=JSON.parse(n.toString("utf8"))?.text||""}catch{}const l=await C.detect(a);return s(o,200,{entities:l})}catch(n){return s(o,500,{error:{message:`NER error: ${n.message}`,type:"ner_error"}})}}const e=ct(t);if(!e){const n=C.modelOnDisk(t.ner?.model||void 0);return s(o,503,{error:{message:n?"the bundled detector could not start — deterministic-only redaction":"no entity detector is installed — deterministic-only redaction (install one from Gateway settings)",type:n?"ner_error":"ner_not_installed"},state:C.state(),model:t.ner?.model||null})}try{const n=await v(r,t.maxBodyBytes),a=await Re(e,{method:"POST",headers:{"content-type":"application/json"},body:n,signal:AbortSignal.timeout(8e3)}),l=await a.text();return o.writeHead(a.status,{"content-type":"application/json"}),o.end(l)}catch(n){return s(o,502,{error:{message:`NER unreachable: ${n.message}`,type:"ner_unreachable"}})}}}if(c==="/redact"&&r.method==="POST"){let e="";try{e=String(JSON.parse((await v(r,t.maxBodyBytes)).toString("utf8"))?.text||"")}catch{e=""}if(!e)return s(o,200,{text:"",count:0,sanitized:0,entities:[],detector:Be(t)});try{let n=e;const a=await q(t.pro?.entitlementToken);await Se(t);const l=await ge([De(()=>n,m=>{n=m})],t.redaction,{isPro:a});return s(o,200,{text:n,count:l.count||0,sanitized:l.sanitized||0,tier:t.redaction?.tier==="full"?"full":"basic",entities:it(l.vault,"types")||[],detector:Be(t)})}catch(n){return s(o,500,{error:{message:`redaction preview failed: ${n.message}`,type:"redact_error"}})}}if(c==="/ner/models"){if(r.method==="GET"){const e=C.health().model||t.ner?.model||null,n=go.map(a=>({...a,installed:C.modelOnDisk(a.id)}));return e&&!n.some(a=>a.id===e)&&n.push({id:e,label:e,lang:"—",custom:!0,installed:C.modelOnDisk(e),note:"Custom model (from Hugging Face)."}),s(o,200,{active:e,state:C.state(),progress:C.progress(),available:n})}if(r.method==="POST"){let e=null;try{e=JSON.parse((await v(r,t.maxBodyBytes)).toString("utf8"))}catch{e=null}const n=e&&typeof e.id=="string"?e.id.trim():null;if(!n||!(bo(n)||wo(n)))return s(o,400,{error:{message:"unknown or invalid model id",type:"bad_model"}});zo(t,n);try{te(t,ee())}catch{}return C.setModel(n,{onLog:a=>console.log(a)}).then(a=>{a&&t.ner?.enableFullTier&&t.redaction.tier!=="full"&&(t.redaction.tier="full")}),s(o,202,{accepted:!0,active:n,state:C.state(),progress:C.progress()})}}if(c==="/stt/models"){if(r.method==="GET"){const e=A.health().model||t.stt?.model||Oe,n=ko.map(a=>({...a,installed:A.modelOnDisk(a.id)}));return e&&!n.some(a=>a.id===e)&&n.push({id:e,label:e,lang:"—",tier:"custom",custom:!0,installed:A.modelOnDisk(e),note:"Custom model (from Hugging Face)."}),s(o,200,{active:e,state:A.state(),progress:A.progress(),available:n,dtype:t.stt?.dtype||"auto",loadedDtype:A.health().dtype,runtime:A.health().runtime,dtypes:To})}if(r.method==="POST"){let e=null;try{e=JSON.parse((await v(r,t.maxBodyBytes)).toString("utf8"))}catch{e=null}const n=e&&typeof e.id=="string"?e.id.trim():null;if(!n||!(So(n)||vo(n)))return s(o,400,{error:{message:"unknown or invalid model id",type:"bad_model"}});const a=typeof e.dtype=="string"&&_o(e.dtype)?e.dtype:void 0;t.stt?t.stt.model=n:t.stt={enabled:!0,model:n,allowDownload:!0},a&&(t.stt.dtype=a==="auto"?null:a);try{te(t,ee())}catch{}return A.setModel(n,{onLog:l=>console.log(l),dtype:a||t.stt.dtype||"auto"}),s(o,202,{accepted:!0,active:n,dtype:t.stt.dtype||"auto",state:A.state(),progress:A.progress()})}}if(c==="/diarize/model"){if(r.method==="GET"){const e=B.health();return s(o,200,{active:B.DIARIZE_MODEL,state:e.state,progress:B.progress(),available:[{id:B.DIARIZE_MODEL,label:"Speaker embeddings (wavlm)",lang:"any",approxMB:100,note:"Tells voices apart for meeting transcription (who said what).",installed:B.modelOnDisk()}]})}if(r.method==="POST")return B.download({onLog:e=>console.log(e)}),s(o,202,{accepted:!0,active:B.DIARIZE_MODEL,state:B.state(),progress:B.progress()})}if(c==="/tts/models"){if(r.method==="GET"){const e=S.health().model||t.tts?.model||Ke(Pe()),n=Pe(),a=Je.find(m=>m.id===e)||null,l=Je.map(m=>({...m,installed:S.modelOnDisk(m.id),unavailable:m.requiresNative&&!n?"needs the npm gateway — the standalone binary cannot load this engine":void 0}));return e&&!l.some(m=>m.id===e)&&l.push({id:e,label:e,lang:"—",tier:"custom",custom:!0,installed:S.modelOnDisk(e),note:"Custom model (from Hugging Face)."}),s(o,200,{active:e,state:S.state(),progress:S.progress(),available:l,voice:t.tts?.voice||(he(e)==="pocket-tts"?pe:Q),arch:S.arch(),supportsVoices:S.arch()?S.supportsVoices():a?a.arch==="style-tts2"&&!!a.voices:!0,supportsCustomVoices:S.arch()?S.supportsCustomVoices():!!a?.customVoices,sampleRate:S.sampleRate(),voices:S.isPocket()||!S.arch()&&he(e)==="pocket-tts"?(S.builtinVoices().length?S.builtinVoices():No).map(m=>({id:m,label:m[0].toUpperCase()+m.slice(1),lang:"en",installed:S.builtinVoices().includes(m)})):S.arch()&&S.arch()!=="style-tts2"?[]:Oo.map(m=>({...m,installed:S.voiceOnDisk(m.id,e)})),dtype:t.tts?.dtype||"auto",loadedDtype:S.health().dtype,runtime:S.health().runtime,dtypes:Ao})}if(r.method==="POST"){let e=null;try{e=JSON.parse((await v(r,t.maxBodyBytes)).toString("utf8"))}catch{e=null}const n=e&&typeof e.id=="string"?e.id.trim():null;if(n&&!(Po(n)||Eo(n)))return s(o,400,{error:{message:"unknown or invalid model id",type:"bad_model"}});const a=e&&typeof e.voice=="string"?e.voice.trim():null;if(a){const m=G.parseCustomVoice(a);if(!(m?!!G.getVoice(m):ye(a)||He(a)&&Ue(a)))return s(o,400,{error:{message:"unknown or invalid voice",type:"bad_voice"}})}const l=e&&typeof e.dtype=="string"&&xo(e.dtype)?e.dtype:void 0;if(t.tts||(t.tts={enabled:!0,model:Fe,voice:Q,allowDownload:!0}),n&&(t.tts.model=n),a&&(t.tts.voice=a),n&&!a){const m=$o(n),k=G.parseCustomVoice(t.tts.voice||""),h=!!(k&&G.getVoice(k));if(m&&!h)if(he(n)==="pocket-tts")t.tts.voice=pe;else{const y=G.listVoices();t.tts.voice=y.length?`custom:${y[0].id}`:""}else!m&&h&&(t.tts.voice=Q);const w=he(n)==="pocket-tts";w&&!G.parseCustomVoice(t.tts.voice||"")&&!ye(t.tts.voice)&&(t.tts.voice=pe),!w&&ye(t.tts.voice)&&(t.tts.voice=Q)}l&&(t.tts.dtype=l==="auto"?null:l);try{te(t,ee())}catch{}return n&&S.setModel(n,{onLog:m=>console.log(m),dtype:l||t.tts.dtype||"auto"}),s(o,202,{accepted:!0,active:t.tts.model,voice:t.tts.voice,dtype:t.tts.dtype||"auto",state:S.state(),progress:S.progress()})}}if(c==="/tts/voices"){if(r.method==="GET")return s(o,200,{voices:G.listVoices(),usable:S.supportsCustomVoices(),embedder:B.DIARIZE_MODEL,embedderReady:B.isReady()});if(r.method==="POST"){let e=null;try{e=JSON.parse((await v(r,t.maxBodyBytes)).toString("utf8"))}catch{e=null}const n=e&&typeof e.name=="string"?e.name.trim():"",a=e&&Array.isArray(e.pcm)?e.pcm:null,l=e&&typeof e.id=="string"?e.id.trim():"";if(l){if(!G.getVoice(l))return s(o,404,{error:{message:"no such saved voice",type:"bad_voice"}});if(!a){if(!n)return s(o,400,{error:{message:"a name is required",type:"bad_request"}});try{return s(o,200,{...G.renameVoice(l,n),usable:S.supportsCustomVoices()})}catch(m){return s(o,400,{error:{message:m.message,type:"rename_failed"}})}}if(a.length<16e3)return s(o,400,{error:{message:"need at least 1 second of 16 kHz mono audio",type:"sample_too_short"}})}else if(!n)return s(o,400,{error:{message:"a name is required",type:"bad_request"}});if(!a||a.length<16e3)return s(o,400,{error:{message:"need at least 1 second of 16 kHz mono audio",type:"sample_too_short"}});try{if(!B.isReady()){const f=B.download({onLog:x=>console.log(x)}),_=Symbol("timeout"),M=await Promise.race([f.then(()=>null).catch(x=>x),new Promise(x=>setTimeout(()=>x(_),cr))]);if(M===_||!B.isReady())return s(o,503,{error:{message:M===_?"the speaker model is still downloading (~100 MB) — your recording was kept, press Save again shortly":`the speaker model failed to load: ${B.health().error||"unknown error"}`,type:"embedder_not_ready"},progress:B.progress()})}const m=Float32Array.from(a),k=await B.embed(m);let h=null;try{const f=await S.pocketForEncoding({allowDownload:t.tts?.allowDownload!==!1,log:_=>console.log(_)});f&&(h=await f.encodeVoice(dr(m,16e3,24e3)))}catch(f){console.log(`[tts] pocket conditioning unavailable for this voice (${f.message})`)}const w=l?G.replaceVoice(l,{vec:k,pocket:h}):G.saveVoice({name:n,vec:k,pocket:h}),y=l&&n&&n!==w.name?G.renameVoice(l,n):w;return console.log(`[tts] ${l?"re-recorded":"saved"} custom voice "${y.name}" (${(w.kinds||[]).join(" + ")}, sample discarded)`),s(o,l?200:201,{...w,...y,usable:S.supportsCustomVoices()})}catch(m){return s(o,400,{error:{message:m.message,type:"save_failed"}})}}if(r.method==="DELETE"){const e=u.searchParams.get("id")||"",n=G.deleteVoice(e);if(n&&t.tts?.voice===`custom:${e}`){const a=G.listVoices();t.tts.voice=a.length?`custom:${a[0].id}`:Q;try{te(t,ee())}catch{}}return s(o,200,{deleted:n,voice:t.tts?.voice})}}if((c==="/tts"||c==="/v1/audio/speech")&&r.method==="POST"){if(t.tts?.enabled===!1)return s(o,503,{error:{message:"tts is disabled in gateway config",type:"tts_disabled"}});let e=null;try{e=JSON.parse((await v(r,t.maxBodyBytes)).toString("utf8"))}catch{e=null}const n=e&&typeof(e.input??e.text)=="string"?String(e.input??e.text).trim():"";if(!n)return s(o,400,{error:{message:"text is required",type:"bad_request"}});if(n.length>We)return s(o,413,{error:{message:`text too long (max ${We} chars)`,type:"too_long"}});const a=Number.isFinite(e.speed)?Math.min(2,Math.max(.5,e.speed)):1,l=Bo(t),m=e&&typeof e.voice=="string"&&e.voice.trim()?e.voice.trim():null,k=m||(l?l.voice:t.tts?.voice||Q);if(l&&!Do(k))return s(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 s(o,400,{error:{message:`unsupported response_format "${h}" — this gateway synthesizes wav`,type:"bad_format"}});try{if(l){const{audio:ce,contentType:pt,redacted:yt}=await Co({dest:l,text:n,voice:k,speed:a,auth:r.headers.authorization||r.headers["xi-api-key"]||"",redaction:t.redaction,isPro:await q(t.pro?.entitlementToken)});return o.writeHead(200,{"Content-Type":pt,"Content-Length":String(ce.length),"Cache-Control":"no-store","X-Tts-Provider":l.kind,"X-Tts-Redacted":String(yt)}),o.end(ce)}if(!await S.ready({onLog:ce=>console.log(ce),allowDownload:t.tts?.allowDownload!==!1,model:t.tts?.model||Ke(Pe()),dtype:t.tts?.dtype||"auto"}))return s(o,503,{error:{message:S.health().error||"tts model not ready",type:"tts_unavailable"}});const y=jo({requested:m,configured:k,engine:S,voices:G,isPocketVoice:ye,isKnownVoice:He,isValidVoiceId:Ue,defaultVoice:Q,defaultPocketVoice:pe});if(!y.ok)return s(o,y.status,{error:{message:y.message,type:y.type}});const{voice:f,customId:_,speakerEmbedding:M}=y,x=await S.synth(n,{voice:f,speed:a,speakerEmbedding:M}),U=S.sampleRate(),le=h==="pcm"?Buffer.from(new Float32Array(x).buffer):S.toWav(x,U);return o.writeHead(200,{"Content-Type":h==="pcm"?"application/octet-stream":"audio/wav","Content-Length":String(le.length),"Cache-Control":"no-store","X-Tts-Sample-Rate":String(U),..._||S.isPocket()||S.supportsVoices()?{"X-Tts-Voice":f}:{}}),o.end(le)}catch(w){return s(o,500,{error:{message:w.message,type:"tts_failed"}})}}if(c==="/stt/sessions"&&r.method==="POST"){if(t.stt?.enabled===!1)return s(o,403,{error:{message:"STT disabled in gateway config",type:"stt_disabled"}});let e=null;try{e=JSON.parse((await v(r,t.maxBodyBytes)).toString("utf8")||"{}")}catch{e=null}A.isReady()||A.init({model:t.stt?.model||Oe,allowDownload:t.stt?.allowDownload!==!1,dtype:t.stt?.dtype||void 0,onLog:a=>console.log(a)});const n=e?.diarize===!0&&t.stt?.diarize!==!1;n&&!B.isReady()&&B.init({allowDownload:t.stt?.allowDownload!==!1,onLog:a=>console.log(a)});try{const{id:a}=A.createSession({lang:e?.lang,redact:e?.redact===!0,diarize:n,speakerLabel:e?.speakerLabel,endSilenceMs:e?.endSilenceMs});return s(o,201,{id:a,state:A.state()})}catch(a){return s(o,a.code==="too_many_sessions"?429:500,{error:{message:a.message,type:a.code||"stt_error"}})}}{const e=c.match(/^\/stt\/sessions\/([0-9a-f-]{36})(\/audio|\/events)?$/);if(e){const n=e[1];if(e[2]==="/audio"&&r.method==="POST")try{const a=await v(r,t.maxBodyBytes);return A.pushAudio(n,A.toFloat32(a)),s(o,200,{ok:!0,state:A.state()})}catch(a){return s(o,a.code==="no_session"?404:400,{error:{message:a.message,type:a.code||"stt_error"}})}if(e[2]==="/events"&&r.method==="GET"){const a=A.getSession(n);if(!a)return s(o,404,{error:{message:"no such session",type:"no_session"}});o.writeHead(200,{"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive"});const l=f=>o.write(`data: ${JSON.stringify(f)}
22
+ `)}catch{}},25e3);o.on("close",()=>{h(),clearInterval(w)});return}}}if(c==="/v1/memory/list"&&r.method==="GET")return s(o,200,{ok:!0,size:H.size,memories:H.list()});if(c==="/v1/memory/recall"&&r.method==="POST")try{const e=JSON.parse((await v(r,t.maxBodyBytes)).toString("utf8"))||{},n=H.recall({text:String(e.text||""),scopes:Array.isArray(e.scopes)&&e.scopes.length?e.scopes.map(String):["global"],limit:Number(e.limit)||0,maxChars:Number(e.maxChars)||0});return s(o,200,{ok:!0,size:H.size,...n})}catch(e){return s(o,400,{error:{message:`recall failed: ${e.message}`,type:"memory_error"}})}if(c==="/v1/memory/remember"&&r.method==="POST")try{const e=JSON.parse((await v(r,t.maxBodyBytes)).toString("utf8"))||{},n=H.remember({text:String(e.text||""),kind:e.kind?String(e.kind):"fact",scope:e.scope?String(e.scope):"global",tags:Array.isArray(e.tags)?e.tags.map(String):[],source:{via:String(e.source?.via||"mcp"),surface:String(e.source?.surface||"mcp"),agent:String(e.source?.agent||""),ref:String(e.source?.ref||"")}});return s(o,200,{ok:!0,action:n.action,record:n.record,replaced:n.replaces||null,size:H.size})}catch(e){return s(o,400,{error:{message:e.message,type:"memory_error"}})}if(c==="/v1/memory/forget"&&r.method==="POST")try{const e=JSON.parse((await v(r,t.maxBodyBytes)).toString("utf8"))||{},{removed:n}=H.forget(String(e.query||""));return s(o,200,{ok:!0,removed:n,size:H.size})}catch(e){return s(o,400,{error:{message:e.message,type:"memory_error"}})}if(c==="/v1/memory/sync"&&r.method==="POST")try{const e=JSON.parse((await v(r,t.maxBodyBytes)).toString("utf8"))||{},n=H.bulk({upserts:Array.isArray(e.upserts)?e.upserts:[],removes:Array.isArray(e.removes)?e.removes:[]});return s(o,200,{ok:!0,...n,memories:H.list()})}catch(e){return s(o,400,{error:{message:`memory sync failed: ${e.message}`,type:"memory_error"}})}if(c==="/v1/memory/clear"&&r.method==="POST")return s(o,200,{ok:!0,dropped:H.clear(),size:H.size});if(c==="/v1/history/clear"&&r.method==="POST"){const e=O.clear();return s(o,200,{ok:!0,dropped:e,size:O.size})}if(c==="/v1/history/search"&&r.method==="POST")try{const e=JSON.parse((await v(r,t.maxBodyBytes)).toString("utf8"))||{},n=O.search(String(e.query||""),{limit:Number(e.limit)||10,offset:Math.max(0,Number(e.offset)||0),type:e.type?String(e.type):null,since:e.since!=null?Number(e.since):null,before:e.before!=null?Number(e.before):null});return s(o,200,{ok:!0,size:O.size,newest:O.newest,results:n})}catch(e){return s(o,400,{error:{message:`search failed: ${e.message}`,type:"search_error"}})}if(c==="/v1/history/smart-search"&&r.method==="POST")try{const e=JSON.parse((await v(r,t.maxBodyBytes)).toString("utf8"))||{},n=String(e.question||e.query||""),a=Fo(n,{extra:Array.isArray(e.queries)?e.queries.map(String):[],max:Math.min(6,Math.max(1,Number(e.maxQueries)||4))}),l={type:e.type?String(e.type):null,since:e.since!=null?Number(e.since):null,before:e.before!=null?Number(e.before):null},m=Math.min(30,Math.max(5,Number(e.limit)||10)*2),k=await Wo(a,w=>O.search(w,{limit:m,...l}),{limit:Math.min(50,Math.max(1,Number(e.limit)||10))}),h=l.type?k:[...k.filter(w=>w.type==="brief"),...k.filter(w=>w.type!=="brief")];return s(o,200,{ok:!0,size:O.size,newest:O.newest,queries:a,results:h})}catch(e){return s(o,400,{error:{message:`smart search failed: ${e.message}`,type:"search_error"}})}if(c==="/v1/history/related"&&r.method==="GET"){const e=String(u.searchParams.get("id")||""),n=Math.min(30,Math.max(1,Number(u.searchParams.get("limit"))||5));return s(o,200,{ok:!0,results:O.related(e,{limit:n})})}if(c==="/v1/history/status"&&r.method==="GET")return s(o,200,{ok:!0,size:O.size,newest:O.newest,bytes:O.bytes,lossless:O.lossless?{records:O.lossless.size,newest:O.lossless.newest}:null});if(c==="/v1/observability"&&r.method==="GET"){const e=Math.min(500,Math.max(1,Number(u.searchParams.get("limit"))||200));return s(o,200,{ok:!0,storage:{warm:{records:O.size,bytes:O.bytes,newest:O.newest}},access:Be.snapshot(e)})}if(c==="/v1/observability/access"&&r.method==="POST")try{const e=JSON.parse((await v(r,t.maxBodyBytes)).toString("utf8"))||{},n=Be.push(et({ts:Date.now(),...e}));return s(o,200,{ok:!0,event:n})}catch(e){return s(o,400,{error:{message:`access log failed: ${e.message}`,type:"observability_error"}})}if(c==="/v1/history/records"&&r.method==="PUT"){const e=O.lossless;if(!e)return s(o,501,{error:{message:"lossless records need the SQLite warm store",type:"unavailable"}});try{const n=JSON.parse((await v(r,t.maxBodyBytes)).toString("utf8"))||{},a=String(n.host||"").slice(0,80),l=Number(n.at)||Date.now(),m=[];let k=0;const h={upserts:[],removes:[]},w=y=>{if(!y||y.deletedAt){y?.id&&h.removes.push(y.id);return}try{const f=po(y);f&&h.upserts.push(f)}catch{}};if(Array.isArray(n.records)){const y=e.upsert(n.records,{host:a,at:l});m.push(...y);for(const f of n.records)y.includes(f?.id)&&w(f)}if(Array.isArray(n.entries)){const y=_e(),f=y?fo((A,U)=>yo(y,{salt:A,iterations:U})):null,_=async A=>{if(!f||!A.blob)return null;const U=await f(A.blob),ce=A.blob.compression&&A.blob.compression!=="none"?go(bo,A.blob.compression):null;return ho(A.blob,U,{codec:ce})},M=await e.upsertEntries(n.entries,{open:_});m.push(...M.written),k+=M.sealed;for(const A of M.written)w(e.get(A))}return(h.upserts.length||h.removes.length)&&O.bulk(h),m.length&&ge({ids:m}),s(o,200,{ok:!0,written:m.length,ids:m,sealed:k,size:e.size})}catch(n){return s(o,400,{error:{message:`records failed: ${n.message}`,type:"ingest_error"}})}}if(c==="/v1/history/stream"&&r.method==="GET"){const e=O.lossless;if(!e)return s(o,501,{error:{message:"lossless records need the SQLite warm store",type:"unavailable"}});o.writeHead(200,{"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive"}),o.write(`event: hello
23
+ data: ${JSON.stringify({newest:e.newest,size:e.size,version:W})}
24
+
25
+ `),te.add(o),r.on("close",()=>te.delete(o));return}if(c==="/v1/history/records"&&r.method==="GET"){const e=O.lossless;if(!e)return s(o,501,{error:{message:"lossless records need the SQLite warm store",type:"unavailable"}});const n=e.since({since:Number(u.searchParams.get("since"))||0,cursor:u.searchParams.get("cursor")||"",limit:Number(u.searchParams.get("limit"))||200,kind:u.searchParams.get("kind")||null});return s(o,200,{ok:!0,...n,size:e.size,newest:e.newest})}if(c==="/v1/history/list"&&r.method==="GET"){const e=Math.min(500,Math.max(1,Number(u.searchParams.get("limit"))||50)),n=Math.max(0,Number(u.searchParams.get("offset"))||0),a=u.searchParams.get("type")||null;return s(o,200,{ok:!0,...O.list({limit:e,offset:n,type:a})})}if(c==="/v1/history/get"&&r.method==="GET"){const e=u.searchParams.get("maxChars")!=null?Math.max(1,Number(u.searchParams.get("maxChars"))||0):null,n=Math.max(0,Number(u.searchParams.get("offset"))||0),a=O.get(String(u.searchParams.get("id")||""),{maxChars:e,offset:n});return a?s(o,200,{ok:!0,record:a}):s(o,404,{error:{message:"no such record",type:"not_found"}})}if(c==="/v1/history/key"&&r.method==="GET")return s(o,200,{ok:!0,hasKey:He()});if(c==="/v1/history/key"&&r.method==="POST")try{const e=JSON.parse((await v(r,t.maxBodyBytes)).toString("utf8"))||{};e.passphrase?Yt(String(e.passphrase)):Qt();const n=e.passphrase?await Pe(O,String(e.passphrase)):{ok:!0,ingested:0};return n.ok&&n.whole&&ge(),s(o,200,{ok:!0,hasKey:!!e.passphrase,...n})}catch(e){return s(o,400,{error:{message:`key handoff failed: ${e.message}`,type:"key_error"}})}if(c==="/v1/history/ingest-backup"&&r.method==="POST")try{const e=await Pe(O,_e());return e.ok&&e.whole&&ge(),s(o,e.ok?200:409,e)}catch(e){return s(o,400,{error:{message:`backup ingest failed: ${e.message}`,type:"ingest_error"}})}if(c==="/ner"){if(r.method==="GET"){const e=await mt(t);return s(o,e.ok?200:503,e)}if(r.method==="POST"){if(await Te(t),C.state()!=="off"){if(!C.isReady()){const n=C.health();return s(o,503,{error:{message:n.state==="error"?`NER model failed to load: ${n.error||"unknown error"}`:`NER model is ${n.state} — not ready yet`,type:n.state==="error"?"ner_error":"ner_loading"},state:n.state,model:n.model})}try{const n=await v(r,t.maxBodyBytes);let a="";try{a=JSON.parse(n.toString("utf8"))?.text||""}catch{}const l=await C.detect(a);return s(o,200,{entities:l})}catch(n){return s(o,500,{error:{message:`NER error: ${n.message}`,type:"ner_error"}})}}const e=ut(t);if(!e){const n=C.modelOnDisk(t.ner?.model||void 0);return s(o,503,{error:{message:n?"the bundled detector could not start — deterministic-only redaction":"no entity detector is installed — deterministic-only redaction (install one from Gateway settings)",type:n?"ner_error":"ner_not_installed"},state:C.state(),model:t.ner?.model||null})}try{const n=await v(r,t.maxBodyBytes),a=await ze(e,{method:"POST",headers:{"content-type":"application/json"},body:n,signal:AbortSignal.timeout(8e3)}),l=await a.text();return o.writeHead(a.status,{"content-type":"application/json"}),o.end(l)}catch(n){return s(o,502,{error:{message:`NER unreachable: ${n.message}`,type:"ner_unreachable"}})}}}if(c==="/redact"&&r.method==="POST"){let e="";try{e=String(JSON.parse((await v(r,t.maxBodyBytes)).toString("utf8"))?.text||"")}catch{e=""}if(!e)return s(o,200,{text:"",count:0,sanitized:0,entities:[],detector:De(t)});try{let n=e;const a=await q(t.pro?.entitlementToken);await Te(t);const l=await we([je(()=>n,m=>{n=m})],t.redaction,{isPro:a});return s(o,200,{text:n,count:l.count||0,sanitized:l.sanitized||0,tier:t.redaction?.tier==="full"?"full":"basic",entities:ct(l.vault,"types")||[],detector:De(t)})}catch(n){return s(o,500,{error:{message:`redaction preview failed: ${n.message}`,type:"redact_error"}})}}if(c==="/ner/models"){if(r.method==="GET"){const e=C.health().model||t.ner?.model||null,n=wo.map(a=>({...a,installed:C.modelOnDisk(a.id)}));return e&&!n.some(a=>a.id===e)&&n.push({id:e,label:e,lang:"—",custom:!0,installed:C.modelOnDisk(e),note:"Custom model (from Hugging Face)."}),s(o,200,{active:e,state:C.state(),progress:C.progress(),available:n})}if(r.method==="POST"){let e=null;try{e=JSON.parse((await v(r,t.maxBodyBytes)).toString("utf8"))}catch{e=null}const n=e&&typeof e.id=="string"?e.id.trim():null;if(!n||!(ko(n)||So(n)))return s(o,400,{error:{message:"unknown or invalid model id",type:"bad_model"}});Vo(t,n);try{oe(t,ee())}catch{}return C.setModel(n,{onLog:a=>console.log(a)}).then(a=>{a&&t.ner?.enableFullTier&&t.redaction.tier!=="full"&&(t.redaction.tier="full")}),s(o,202,{accepted:!0,active:n,state:C.state(),progress:C.progress()})}}if(c==="/stt/models"){if(r.method==="GET"){const e=x.health().model||t.stt?.model||Ee,n=vo.map(a=>({...a,installed:x.modelOnDisk(a.id)}));return e&&!n.some(a=>a.id===e)&&n.push({id:e,label:e,lang:"—",tier:"custom",custom:!0,installed:x.modelOnDisk(e),note:"Custom model (from Hugging Face)."}),s(o,200,{active:e,state:x.state(),progress:x.progress(),available:n,dtype:t.stt?.dtype||"auto",loadedDtype:x.health().dtype,runtime:x.health().runtime,dtypes:Oo})}if(r.method==="POST"){let e=null;try{e=JSON.parse((await v(r,t.maxBodyBytes)).toString("utf8"))}catch{e=null}const n=e&&typeof e.id=="string"?e.id.trim():null;if(!n||!(To(n)||_o(n)))return s(o,400,{error:{message:"unknown or invalid model id",type:"bad_model"}});const a=typeof e.dtype=="string"&&Po(e.dtype)?e.dtype:void 0;t.stt?t.stt.model=n:t.stt={enabled:!0,model:n,allowDownload:!0},a&&(t.stt.dtype=a==="auto"?null:a);try{oe(t,ee())}catch{}return x.setModel(n,{onLog:l=>console.log(l),dtype:a||t.stt.dtype||"auto"}),s(o,202,{accepted:!0,active:n,dtype:t.stt.dtype||"auto",state:x.state(),progress:x.progress()})}}if(c==="/diarize/model"){if(r.method==="GET"){const e=B.health();return s(o,200,{active:B.DIARIZE_MODEL,state:e.state,progress:B.progress(),available:[{id:B.DIARIZE_MODEL,label:"Speaker embeddings (wavlm)",lang:"any",approxMB:100,note:"Tells voices apart for meeting transcription (who said what).",installed:B.modelOnDisk()}]})}if(r.method==="POST")return B.download({onLog:e=>console.log(e)}),s(o,202,{accepted:!0,active:B.DIARIZE_MODEL,state:B.state(),progress:B.progress()})}if(c==="/tts/models"){if(r.method==="GET"){const e=S.health().model||t.tts?.model||Ye(xe()),n=xe(),a=Ue.find(m=>m.id===e)||null,l=Ue.map(m=>({...m,installed:S.modelOnDisk(m.id),unavailable:m.requiresNative&&!n?"needs the npm gateway — the standalone binary cannot load this engine":void 0}));return e&&!l.some(m=>m.id===e)&&l.push({id:e,label:e,lang:"—",tier:"custom",custom:!0,installed:S.modelOnDisk(e),note:"Custom model (from Hugging Face)."}),s(o,200,{active:e,state:S.state(),progress:S.progress(),available:l,voice:t.tts?.voice||(fe(e)==="pocket-tts"?ye:Q),arch:S.arch(),supportsVoices:S.arch()?S.supportsVoices():a?a.arch==="style-tts2"&&!!a.voices:!0,supportsCustomVoices:S.arch()?S.supportsCustomVoices():!!a?.customVoices,sampleRate:S.sampleRate(),voices:S.isPocket()||!S.arch()&&fe(e)==="pocket-tts"?(S.builtinVoices().length?S.builtinVoices():Co).map(m=>({id:m,label:m[0].toUpperCase()+m.slice(1),lang:"en",installed:S.builtinVoices().includes(m)})):S.arch()&&S.arch()!=="style-tts2"?[]:Eo.map(m=>({...m,installed:S.voiceOnDisk(m.id,e)})),dtype:t.tts?.dtype||"auto",loadedDtype:S.health().dtype,runtime:S.health().runtime,dtypes:$o})}if(r.method==="POST"){let e=null;try{e=JSON.parse((await v(r,t.maxBodyBytes)).toString("utf8"))}catch{e=null}const n=e&&typeof e.id=="string"?e.id.trim():null;if(n&&!(xo(n)||Ao(n)))return s(o,400,{error:{message:"unknown or invalid model id",type:"bad_model"}});const a=e&&typeof e.voice=="string"?e.voice.trim():null;if(a){const m=G.parseCustomVoice(a);if(!(m?!!G.getVoice(m):he(a)||Fe(a)&&We(a)))return s(o,400,{error:{message:"unknown or invalid voice",type:"bad_voice"}})}const l=e&&typeof e.dtype=="string"&&No(e.dtype)?e.dtype:void 0;if(t.tts||(t.tts={enabled:!0,model:Ke,voice:Q,allowDownload:!0}),n&&(t.tts.model=n),a&&(t.tts.voice=a),n&&!a){const m=Bo(n),k=G.parseCustomVoice(t.tts.voice||""),h=!!(k&&G.getVoice(k));if(m&&!h)if(fe(n)==="pocket-tts")t.tts.voice=ye;else{const y=G.listVoices();t.tts.voice=y.length?`custom:${y[0].id}`:""}else!m&&h&&(t.tts.voice=Q);const w=fe(n)==="pocket-tts";w&&!G.parseCustomVoice(t.tts.voice||"")&&!he(t.tts.voice)&&(t.tts.voice=ye),!w&&he(t.tts.voice)&&(t.tts.voice=Q)}l&&(t.tts.dtype=l==="auto"?null:l);try{oe(t,ee())}catch{}return n&&S.setModel(n,{onLog:m=>console.log(m),dtype:l||t.tts.dtype||"auto"}),s(o,202,{accepted:!0,active:t.tts.model,voice:t.tts.voice,dtype:t.tts.dtype||"auto",state:S.state(),progress:S.progress()})}}if(c==="/tts/voices"){if(r.method==="GET")return s(o,200,{voices:G.listVoices(),usable:S.supportsCustomVoices(),embedder:B.DIARIZE_MODEL,embedderReady:B.isReady()});if(r.method==="POST"){let e=null;try{e=JSON.parse((await v(r,t.maxBodyBytes)).toString("utf8"))}catch{e=null}const n=e&&typeof e.name=="string"?e.name.trim():"",a=e&&Array.isArray(e.pcm)?e.pcm:null,l=e&&typeof e.id=="string"?e.id.trim():"";if(l){if(!G.getVoice(l))return s(o,404,{error:{message:"no such saved voice",type:"bad_voice"}});if(!a){if(!n)return s(o,400,{error:{message:"a name is required",type:"bad_request"}});try{return s(o,200,{...G.renameVoice(l,n),usable:S.supportsCustomVoices()})}catch(m){return s(o,400,{error:{message:m.message,type:"rename_failed"}})}}if(a.length<16e3)return s(o,400,{error:{message:"need at least 1 second of 16 kHz mono audio",type:"sample_too_short"}})}else if(!n)return s(o,400,{error:{message:"a name is required",type:"bad_request"}});if(!a||a.length<16e3)return s(o,400,{error:{message:"need at least 1 second of 16 kHz mono audio",type:"sample_too_short"}});try{if(!B.isReady()){const f=B.download({onLog:A=>console.log(A)}),_=Symbol("timeout"),M=await Promise.race([f.then(()=>null).catch(A=>A),new Promise(A=>setTimeout(()=>A(_),ur))]);if(M===_||!B.isReady())return s(o,503,{error:{message:M===_?"the speaker model is still downloading (~100 MB) — your recording was kept, press Save again shortly":`the speaker model failed to load: ${B.health().error||"unknown error"}`,type:"embedder_not_ready"},progress:B.progress()})}const m=Float32Array.from(a),k=await B.embed(m);let h=null;try{const f=await S.pocketForEncoding({allowDownload:t.tts?.allowDownload!==!1,log:_=>console.log(_)});f&&(h=await f.encodeVoice(mr(m,16e3,24e3)))}catch(f){console.log(`[tts] pocket conditioning unavailable for this voice (${f.message})`)}const w=l?G.replaceVoice(l,{vec:k,pocket:h}):G.saveVoice({name:n,vec:k,pocket:h}),y=l&&n&&n!==w.name?G.renameVoice(l,n):w;return console.log(`[tts] ${l?"re-recorded":"saved"} custom voice "${y.name}" (${(w.kinds||[]).join(" + ")}, sample discarded)`),s(o,l?200:201,{...w,...y,usable:S.supportsCustomVoices()})}catch(m){return s(o,400,{error:{message:m.message,type:"save_failed"}})}}if(r.method==="DELETE"){const e=u.searchParams.get("id")||"",n=G.deleteVoice(e);if(n&&t.tts?.voice===`custom:${e}`){const a=G.listVoices();t.tts.voice=a.length?`custom:${a[0].id}`:Q;try{oe(t,ee())}catch{}}return s(o,200,{deleted:n,voice:t.tts?.voice})}}if((c==="/tts"||c==="/v1/audio/speech")&&r.method==="POST"){if(t.tts?.enabled===!1)return s(o,503,{error:{message:"tts is disabled in gateway config",type:"tts_disabled"}});let e=null;try{e=JSON.parse((await v(r,t.maxBodyBytes)).toString("utf8"))}catch{e=null}const n=e&&typeof(e.input??e.text)=="string"?String(e.input??e.text).trim():"";if(!n)return s(o,400,{error:{message:"text is required",type:"bad_request"}});if(n.length>Ze)return s(o,413,{error:{message:`text too long (max ${Ze} chars)`,type:"too_long"}});const a=Number.isFinite(e.speed)?Math.min(2,Math.max(.5,e.speed)):1,l=Do(t),m=e&&typeof e.voice=="string"&&e.voice.trim()?e.voice.trim():null,k=m||(l?l.voice:t.tts?.voice||Q);if(l&&!jo(k))return s(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 s(o,400,{error:{message:`unsupported response_format "${h}" — this gateway synthesizes wav`,type:"bad_format"}});try{if(l){const{audio:de,contentType:ht,redacted:ft}=await Io({dest:l,text:n,voice:k,speed:a,auth:r.headers.authorization||r.headers["xi-api-key"]||"",redaction:t.redaction,isPro:await q(t.pro?.entitlementToken)});return o.writeHead(200,{"Content-Type":ht,"Content-Length":String(de.length),"Cache-Control":"no-store","X-Tts-Provider":l.kind,"X-Tts-Redacted":String(ft)}),o.end(de)}if(!await S.ready({onLog:de=>console.log(de),allowDownload:t.tts?.allowDownload!==!1,model:t.tts?.model||Ye(xe()),dtype:t.tts?.dtype||"auto"}))return s(o,503,{error:{message:S.health().error||"tts model not ready",type:"tts_unavailable"}});const y=Mo({requested:m,configured:k,engine:S,voices:G,isPocketVoice:he,isKnownVoice:Fe,isValidVoiceId:We,defaultVoice:Q,defaultPocketVoice:ye});if(!y.ok)return s(o,y.status,{error:{message:y.message,type:y.type}});const{voice:f,customId:_,speakerEmbedding:M}=y,A=await S.synth(n,{voice:f,speed:a,speakerEmbedding:M}),U=S.sampleRate(),ce=h==="pcm"?Buffer.from(new Float32Array(A).buffer):S.toWav(A,U);return o.writeHead(200,{"Content-Type":h==="pcm"?"application/octet-stream":"audio/wav","Content-Length":String(ce.length),"Cache-Control":"no-store","X-Tts-Sample-Rate":String(U),..._||S.isPocket()||S.supportsVoices()?{"X-Tts-Voice":f}:{}}),o.end(ce)}catch(w){return s(o,500,{error:{message:w.message,type:"tts_failed"}})}}if(c==="/stt/sessions"&&r.method==="POST"){if(t.stt?.enabled===!1)return s(o,403,{error:{message:"STT disabled in gateway config",type:"stt_disabled"}});let e=null;try{e=JSON.parse((await v(r,t.maxBodyBytes)).toString("utf8")||"{}")}catch{e=null}x.isReady()||x.init({model:t.stt?.model||Ee,allowDownload:t.stt?.allowDownload!==!1,dtype:t.stt?.dtype||void 0,onLog:a=>console.log(a)});const n=e?.diarize===!0&&t.stt?.diarize!==!1;n&&!B.isReady()&&B.init({allowDownload:t.stt?.allowDownload!==!1,onLog:a=>console.log(a)});try{const{id:a}=x.createSession({lang:e?.lang,redact:e?.redact===!0,diarize:n,speakerLabel:e?.speakerLabel,endSilenceMs:e?.endSilenceMs});return s(o,201,{id:a,state:x.state()})}catch(a){return s(o,a.code==="too_many_sessions"?429:500,{error:{message:a.message,type:a.code||"stt_error"}})}}{const e=c.match(/^\/stt\/sessions\/([0-9a-f-]{36})(\/audio|\/events)?$/);if(e){const n=e[1];if(e[2]==="/audio"&&r.method==="POST")try{const a=await v(r,t.maxBodyBytes);return x.pushAudio(n,x.toFloat32(a)),s(o,200,{ok:!0,state:x.state()})}catch(a){return s(o,a.code==="no_session"?404:400,{error:{message:a.message,type:a.code||"stt_error"}})}if(e[2]==="/events"&&r.method==="GET"){const a=x.getSession(n);if(!a)return s(o,404,{error:{message:"no such session",type:"no_session"}});o.writeHead(200,{"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive"});const l=f=>o.write(`data: ${JSON.stringify(f)}
18
26
 
19
- `),m=a.redact?await q(t.pro?.entitlementToken):!0,k=async f=>{if(f.type!=="final"||!a.redact)return f;try{let _=f.text;return await ge([De(()=>_,M=>{_=M})],t.redaction,{isPro:m}),{...f,text:_}}catch{return f}};l({type:"state",state:A.state()});const h=setInterval(()=>{const f=A.state();if(f==="downloading"||f==="loading"){l({type:"progress",state:f,...A.progress()||{}});return}if(f==="error"){l({type:"error",code:"model_failed",message:A.health().error||"model failed to load",fatal:!0}),clearInterval(h);return}if(a.diarize){const _=B.state();if(_==="downloading"||_==="loading"){l({type:"diarize-progress",state:_,...B.progress()||{}});return}}l({type:"state",state:f}),clearInterval(h)},500);h.unref?.();let w=Promise.resolve();const y=A.subscribe(n,f=>{w=w.then(async()=>{l(await k(f)),f.type==="end"&&(clearInterval(h),o.end())}).catch(()=>{})});r.on("close",()=>{clearInterval(h),y?.()});return}if(!e[2]&&r.method==="DELETE")return await A.endSession(n),s(o,200,{ok:!0})}}if(c==="/logs"&&r.method==="GET")return s(o,200,{entries:[...i].reverse()});if(c==="/config"&&r.method==="GET"){const e=await q(t.pro?.entitlementToken);return s(o,200,Ze(t,{proUnlocked:e}))}if(c==="/config"&&r.method==="POST"){let e=null;try{e=JSON.parse((await v(r,t.maxBodyBytes)).toString("utf8"))}catch{e=null}if(!e||typeof e!="object")return s(o,400,{error:"invalid config patch"});Lo(t,e),Ie(t);try{te(t,ee())}catch(k){return s(o,500,{error:`could not persist config: ${k.message}`})}const n=t.redaction?.detection,a=!n||!n.backend||n.backend==="off",l=C.state();t.ner?.autostart&&a&&l!=="ready"&&l!=="loading"&&l!=="downloading"&&C.setModel(t.ner.model,{onLog:k=>console.log(k)}).then(k=>{k&&t.ner?.enableFullTier&&t.redaction.tier!=="full"&&(t.redaction.tier="full")});const m=await q(t.pro?.entitlementToken);return s(o,200,Ze(t,{proUnlocked:m}))}if(r.method==="GET"&&c==="/skills"){const e=await ue(t);if(!e)return s(o,503,{error:{message:"no bridge is configured",type:"no_bridge"}});const n=ie(t.bridge?.token);try{const a=await fetch(`${e}/skills${mt(u,t)}`,{headers:{Accept:"application/json",...n?{Authorization:`Bearer ${n}`}:{}},signal:AbortSignal.timeout(8e3)}),l=await a.json().catch(()=>({}));return a.ok?s(o,200,{skills:Array.isArray(l?.skills)?l.skills:[]}):s(o,a.status,{error:{message:l?.error||`bridge ${a.status}`,type:"bridge_error"}})}catch(a){return s(o,502,{error:{message:`bridge unreachable: ${a.message}`,type:"bridge_unreachable"}})}}if(r.method==="GET"&&/^\/skills\/[^/]+$/.test(c)){const e=decodeURIComponent(c.slice(8));if(!e||e==="."||e===".."||e.includes("/")||e.includes("\\"))return s(o,400,{error:{message:"not a skill id",type:"invalid_request"}});const n=await ue(t);if(!n)return s(o,503,{error:{message:"no bridge is configured",type:"no_bridge"}});const a=ie(t.bridge?.token);try{const l=await fetch(`${n}/skills/${encodeURIComponent(e)}${mt(u,t)}`,{headers:{Accept:"application/json",...a?{Authorization:`Bearer ${a}`}:{}},signal:AbortSignal.timeout(8e3)}),m=await l.json().catch(()=>({}));return l.ok?s(o,200,{skill:m?.skill||null}):s(o,l.status,{error:{message:m?.error||`bridge ${l.status}`,type:"bridge_error"}})}catch(l){return s(o,502,{error:{message:`bridge unreachable: ${l.message}`,type:"bridge_unreachable"}})}}if(r.method==="GET"&&/\/models$/.test(c))return s(o,200,await Go(t));if(ur.some(e=>c===e||c.startsWith(`${e}/`)))return s(o,404,{error:{message:`this gateway (${K}) has no ${c} — update it to use this feature`,type:"unknown_endpoint"}});const g=tr(c,r.headers,t);let b;try{b=await v(r,t.maxBodyBytes)}catch(e){s(o,e.code===413?413:400,{error:e.code===413?"payload too large":"bad request"}),r.destroy();return}let E=null,p=null,L=b,$=0,j=0,Y=0,z=!1,R=!0;const N=t.logRequests&&g.redactable&&r.method==="POST"?er(d):null;if(g.redactable&&r.method==="POST"&&b.length){try{p=JSON.parse(b.toString("utf8"))}catch{p=null}if(p&&or(p,g.kind))L=b;else if(p){const e=t.tools||{};if(e.autoNarrow!==!1&&Array.isArray(p.tools)&&p.tools.length){const y=Number(e.maxPerTurn)>0?Number(e.maxPerTurn):Fo,f=e.narrowAll?null:M=>!Wo.test(ot(M)),_=p.tools.length;p.tools=Tt(p.tools,Zo(p,g.kind),{cap:y,keep:f,name:ot,description:Ko}),Y=_-p.tools.length}R=await q(t.pro?.entitlementToken);const n=Io(t,R);if(!n.allowed)return s(o,402,{error:{message:`ChatPanel Gateway free trial used up (${n.cap} redactions). Add a ChatPanel Pro entitlement token to unlock unlimited full-tier redaction (names/orgs).`,type:"free_limit_reached"}});z=String(r.headers["x-chatpanel-redaction"]||"").trim().toLowerCase()==="off"&&F(r),z||await Se(t);const a=z?[]:g.adapter.collectSegments(p,t.redaction),l=new AbortController;o.on("close",()=>{o.writableFinished||l.abort()});const m=N?N.clock():0,{vault:k,count:h,sanitized:w}=z?{vault:null,count:0,sanitized:0}:await ge(a,t.redaction,{signal:l.signal,isPro:R,onEgress:y=>$e.push(Xe({ts:Date.now(),client:"redaction",tool:`detect:${y.backend}@${y.host||"local"}`,ok:y.ok,ms:y.ms,error:y.error}))});if(N&&N.lap("redact",m),E=k,$=h,j=w||0,!R&&h>0){Mo(t,R);try{te(t,ee())}catch{}}if(!z&&Array.isArray(p.tools)&&p.tools.length&&typeof g.adapter.injectSystemNote=="function"){const y=Qe(p?.model,t,g.kind,{destination:String(r.headers["x-chatpanel-destination"]||p?.chatpanel?.destination||"").trim()}),f=!(y&&y.type==="api");g.adapter.injectSystemNote(p,Ot({toolData:t.tools?.toolData,ownTools:f}))}else!z&&h>0&&typeof g.adapter.injectSystemNote=="function"&&g.adapter.injectSystemNote(p,Pt());L=Buffer.from(JSON.stringify(p),"utf8")}}const O=_t({vault:E,toolData:t.tools?.toolData}),I=p&&typeof p.chatpanel=="object"&&p.chatpanel||null;I&&(delete p.chatpanel,L=Buffer.from(JSON.stringify(p),"utf8"));const J={destination:String(r.headers["x-chatpanel-destination"]||I?.destination||"").trim(),reach:String(r.headers["x-chatpanel-reach"]||I?.reach||"").trim(),run:yr(r.headers["x-chatpanel-run"],I?.run)},T=Qe(p?.model,t,g.kind,{destination:J.destination});if(J.destination&&(!T||T.id!==J.destination))return N?.commit(),s(o,404,{error:{message:`no destination "${J.destination}" is configured on this gateway`,type:"unknown_destination",known:Vo(t).map(e=>e.id)}});N&&(N.meta={t:Date.now(),model:p?.model||null,dest:T?T.id:null,type:T?T.type:null,redacted:$,sanitized:j,narrowed:Y,detail:it(E,t.logDetail),redaction:z?"off":t.redaction.tier||"basic"});const W=Mt();if(W&&T){const e=T.type==="api"?Me(W,{model:p?.model||"",endpoint:T.baseUrl||""}):Lt(W,T.agent||T.id)?Me(W,{model:p?.model||""}):{ok:!1,reason:`agent "${T.agent||T.id}" is not allowed by your organisation’s policy`};if(!e.ok)return N?.commit(),s(o,403,{error:{message:e.reason,type:"policy",code:"org_policy"}})}if(T&&T.type==="api")return T.baseUrl?rr(T.baseUrl,t)?(N?.commit(),s(o,508,{error:{message:`destination "${T.id}" points back at the gateway (${T.baseUrl}) — refusing to forward (would loop).`,type:"loop_detected"}})):mr(r,o,{...g,pathname:c,search:u.search,base:T.baseUrl,destKey:T.apiKey,destProtocol:T.protocol,harness:O,trace:N},L,E):(N?.commit(),s(o,502,{error:`destination "${T.id}" has no baseUrl`}));const X=de(r),ne=X==="local"&&t.bridge?.openAgentLane?"token":X;if(ne==="local")return N?.commit(),s(o,401,{error:{message:"agent destinations require the gateway token: send `Authorization: Bearer $(cat ~/.chatpanel/gateway-token)`, or pair this client with `chatpanel-gateway pair`",type:"auth",code:"agent_lane_token_required"}});const se=At({...J.run||{},...J.reach?{reach:J.reach}:{}},ne);return ir(r,o,{...g,pathname:c,agentOverride:T?.agent,harness:O,trace:N,run:Object.keys(se).length?se:null},p,E,t,R)})}function yr(t,i){let d=i&&typeof i=="object"?i:null;if(!d&&t)try{d=JSON.parse(decodeURIComponent(String(t)))}catch{d=null}if(!d||typeof d!="object")return null;const r={};if(Array.isArray(d.grants)&&(r.grants=d.grants.map(o=>String(o).slice(0,80)).slice(0,32)),d.workspace&&typeof d.workspace=="object"&&d.workspace.repo){const o=d.workspace;r.workspace={repo:String(o.repo).slice(0,400),projectId:String(o.projectId||"").slice(0,120),jobId:String(o.jobId||"").slice(0,120),...o.base?{base:String(o.base).slice(0,120)}:{}}}return d.connectionId&&(r.connectionId=String(d.connectionId).slice(0,64)),Object.keys(r).length?r:null}let fe=null;async function an(t=Ce()){Wt();let i=null;try{i=await It()}catch(g){throw g instanceof Rt&&(console.error(`[chatpanel-gateway] org policy: ${g.message}`),process.exit(78)),g}const d=i?.policy||null;d&&(Ie(t,d),console.log(`[chatpanel-gateway] ${i.label} — ${i.signed?"signed":"unsigned"} policy from ${i.source}`)),Dt(globalThis,{allow:d?.egress?(g,{local:b})=>zt(d,g,{local:b}):null}),be();const r=pr(t),o=Ft(t),u=ft(t);r.on("error",g=>{g&&g.code==="EADDRINUSE"&&(console.error(`Port ${t.port} is already in use — another app (or a second gateway) has it.`),console.error(`Fix: free the port, or set a different one — edit "port" in ${ee()} (or the extension's Gateway tab) and restart. The extension must point at the same port.`),process.exit(1)),console.error(`Gateway server error: ${g?.message||g}`),process.exit(1)}),r.listen(t.port,t.host,()=>{console.log(`ChatPanel Privacy Gateway v${K} on http://${t.host}:${t.port}`),console.log(` backend : ${t.backend}`+(t.backend==="bridge"?` (agent: ${t.bridge.agent}, via ${t.bridge.url})`:"")),t.bridge?.openAgentLane&&console.log(" ⚠ agents : bridge.openAgentLane is ON — any local process may drive a CLI agent through this gateway without a token"),no(t).then(g=>{fe=g}).catch(g=>console.log(` bridge : not supervised (${g?.message||g})`)),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…)":"")),st(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.`)}),Ve()&&_e(P,ve()).then(g=>{g?.ok&&console.log(` warm : seeded ${g.ingested} records from ${g.file}`)}).catch(()=>{});const c=()=>{o?.stop(),u.stop(),fe?.stop(),r.close(()=>process.exit(0))};return process.on("SIGINT",c),process.on("SIGTERM",c),r}export{K as VERSION,pr as createGateway,lr as joinUpstream,Ne as parseAgentModel,an as start};
27
+ `),m=a.redact?await q(t.pro?.entitlementToken):!0,k=async f=>{if(f.type!=="final"||!a.redact)return f;try{let _=f.text;return await we([je(()=>_,M=>{_=M})],t.redaction,{isPro:m}),{...f,text:_}}catch{return f}};l({type:"state",state:x.state()});const h=setInterval(()=>{const f=x.state();if(f==="downloading"||f==="loading"){l({type:"progress",state:f,...x.progress()||{}});return}if(f==="error"){l({type:"error",code:"model_failed",message:x.health().error||"model failed to load",fatal:!0}),clearInterval(h);return}if(a.diarize){const _=B.state();if(_==="downloading"||_==="loading"){l({type:"diarize-progress",state:_,...B.progress()||{}});return}}l({type:"state",state:f}),clearInterval(h)},500);h.unref?.();let w=Promise.resolve();const y=x.subscribe(n,f=>{w=w.then(async()=>{l(await k(f)),f.type==="end"&&(clearInterval(h),o.end())}).catch(()=>{})});r.on("close",()=>{clearInterval(h),y?.()});return}if(!e[2]&&r.method==="DELETE")return await x.endSession(n),s(o,200,{ok:!0})}}if(c==="/logs"&&r.method==="GET")return s(o,200,{entries:[...i].reverse()});if(c==="/config"&&r.method==="GET"){const e=await q(t.pro?.entitlementToken);return s(o,200,Qe(t,{proUnlocked:e}))}if(c==="/config"&&r.method==="POST"){let e=null;try{e=JSON.parse((await v(r,t.maxBodyBytes)).toString("utf8"))}catch{e=null}if(!e||typeof e!="object")return s(o,400,{error:"invalid config patch"});Go(t,e),Re(t);try{oe(t,ee())}catch(k){return s(o,500,{error:`could not persist config: ${k.message}`})}const n=t.redaction?.detection,a=!n||!n.backend||n.backend==="off",l=C.state();t.ner?.autostart&&a&&l!=="ready"&&l!=="loading"&&l!=="downloading"&&C.setModel(t.ner.model,{onLog:k=>console.log(k)}).then(k=>{k&&t.ner?.enableFullTier&&t.redaction.tier!=="full"&&(t.redaction.tier="full")});const m=await q(t.pro?.entitlementToken);return s(o,200,Qe(t,{proUnlocked:m}))}if(r.method==="GET"&&c==="/skills"){const e=await me(t);if(!e)return s(o,503,{error:{message:"no bridge is configured",type:"no_bridge"}});const n=le(t.bridge?.token);try{const a=await fetch(`${e}/skills${yt(u,t)}`,{headers:{Accept:"application/json",...n?{Authorization:`Bearer ${n}`}:{}},signal:AbortSignal.timeout(8e3)}),l=await a.json().catch(()=>({}));return a.ok?s(o,200,{skills:Array.isArray(l?.skills)?l.skills:[]}):s(o,a.status,{error:{message:l?.error||`bridge ${a.status}`,type:"bridge_error"}})}catch(a){return s(o,502,{error:{message:`bridge unreachable: ${a.message}`,type:"bridge_unreachable"}})}}if(r.method==="GET"&&/^\/skills\/[^/]+$/.test(c)){const e=decodeURIComponent(c.slice(8));if(!e||e==="."||e===".."||e.includes("/")||e.includes("\\"))return s(o,400,{error:{message:"not a skill id",type:"invalid_request"}});const n=await me(t);if(!n)return s(o,503,{error:{message:"no bridge is configured",type:"no_bridge"}});const a=le(t.bridge?.token);try{const l=await fetch(`${n}/skills/${encodeURIComponent(e)}${yt(u,t)}`,{headers:{Accept:"application/json",...a?{Authorization:`Bearer ${a}`}:{}},signal:AbortSignal.timeout(8e3)}),m=await l.json().catch(()=>({}));return l.ok?s(o,200,{skill:m?.skill||null}):s(o,l.status,{error:{message:m?.error||`bridge ${l.status}`,type:"bridge_error"}})}catch(l){return s(o,502,{error:{message:`bridge unreachable: ${l.message}`,type:"bridge_unreachable"}})}}if(r.method==="GET"&&/\/models$/.test(c))return s(o,200,await Jo(t));if(pr.some(e=>c===e||c.startsWith(`${e}/`)))return s(o,404,{error:{message:`this gateway (${W}) has no ${c} — update it to use this feature`,type:"unknown_endpoint"}});const g=rr(c,r.headers,t);let b;try{b=await v(r,t.maxBodyBytes)}catch(e){s(o,e.code===413?413:400,{error:e.code===413?"payload too large":"bad request"}),r.destroy();return}let E=null,p=null,L=b,$=0,I=0,Y=0,z=!1,R=!0;const N=t.logRequests&&g.redactable&&r.method==="POST"?or(d):null;if(g.redactable&&r.method==="POST"&&b.length){try{p=JSON.parse(b.toString("utf8"))}catch{p=null}if(p&&nr(p,g.kind))L=b;else if(p){const e=t.tools||{};if(e.autoNarrow!==!1&&Array.isArray(p.tools)&&p.tools.length){const y=Number(e.maxPerTurn)>0?Number(e.maxPerTurn):Ko,f=e.narrowAll?null:M=>!Zo.test(nt(M)),_=p.tools.length;p.tools=Ot(p.tools,Qo(p,g.kind),{cap:y,keep:f,name:nt,description:Yo}),Y=_-p.tools.length}R=await q(t.pro?.entitlementToken);const n=Ro(t,R);if(!n.allowed)return s(o,402,{error:{message:`ChatPanel Gateway free trial used up (${n.cap} redactions). Add a ChatPanel Pro entitlement token to unlock unlimited full-tier redaction (names/orgs).`,type:"free_limit_reached"}});z=String(r.headers["x-chatpanel-redaction"]||"").trim().toLowerCase()==="off"&&F(r),z||await Te(t);const a=z?[]:g.adapter.collectSegments(p,t.redaction),l=new AbortController;o.on("close",()=>{o.writableFinished||l.abort()});const m=N?N.clock():0,{vault:k,count:h,sanitized:w}=z?{vault:null,count:0,sanitized:0}:await we(a,t.redaction,{signal:l.signal,isPro:R,onEgress:y=>Be.push(et({ts:Date.now(),client:"redaction",tool:`detect:${y.backend}@${y.host||"local"}`,ok:y.ok,ms:y.ms,error:y.error}))});if(N&&N.lap("redact",m),E=k,$=h,I=w||0,!R&&h>0){Lo(t,R);try{oe(t,ee())}catch{}}if(!z&&Array.isArray(p.tools)&&p.tools.length&&typeof g.adapter.injectSystemNote=="function"){const y=qe(p?.model,t,g.kind,{destination:String(r.headers["x-chatpanel-destination"]||p?.chatpanel?.destination||"").trim()}),f=!(y&&y.type==="api");g.adapter.injectSystemNote(p,Et({toolData:t.tools?.toolData,ownTools:f}))}else!z&&h>0&&typeof g.adapter.injectSystemNote=="function"&&g.adapter.injectSystemNote(p,xt());L=Buffer.from(JSON.stringify(p),"utf8")}}const P=Pt({vault:E,toolData:t.tools?.toolData}),j=p&&typeof p.chatpanel=="object"&&p.chatpanel||null;j&&(delete p.chatpanel,L=Buffer.from(JSON.stringify(p),"utf8"));const J={destination:String(r.headers["x-chatpanel-destination"]||j?.destination||"").trim(),reach:String(r.headers["x-chatpanel-reach"]||j?.reach||"").trim(),run:fr(r.headers["x-chatpanel-run"],j?.run)},T=qe(p?.model,t,g.kind,{destination:J.destination});if(J.destination&&(!T||T.id!==J.destination))return N?.commit(),s(o,404,{error:{message:`no destination "${J.destination}" is configured on this gateway`,type:"unknown_destination",known:Ho(t).map(e=>e.id)}});N&&(N.meta={t:Date.now(),model:p?.model||null,dest:T?T.id:null,type:T?T.type:null,redacted:$,sanitized:I,narrowed:Y,detail:ct(E,t.logDetail),redaction:z?"off":t.redaction.tier||"basic"});const K=Lt();if(K&&T){const e=T.type==="api"?Le(K,{model:p?.model||"",endpoint:T.baseUrl||""}):Gt(K,T.agent||T.id)?Le(K,{model:p?.model||""}):{ok:!1,reason:`agent "${T.agent||T.id}" is not allowed by your organisation’s policy`};if(!e.ok)return N?.commit(),s(o,403,{error:{message:e.reason,type:"policy",code:"org_policy"}})}if(T&&T.type==="api")return T.baseUrl?sr(T.baseUrl,t)?(N?.commit(),s(o,508,{error:{message:`destination "${T.id}" points back at the gateway (${T.baseUrl}) — refusing to forward (would loop).`,type:"loop_detected"}})):yr(r,o,{...g,pathname:c,search:u.search,base:T.baseUrl,destKey:T.apiKey,destProtocol:T.protocol,harness:P,trace:N},L,E):(N?.commit(),s(o,502,{error:`destination "${T.id}" has no baseUrl`}));const X=ue(r),se=X==="local"&&t.bridge?.openAgentLane?"token":X;if(se==="local")return N?.commit(),s(o,401,{error:{message:"agent destinations require the gateway token: send `Authorization: Bearer $(cat ~/.chatpanel/gateway-token)`, or pair this client with `chatpanel-gateway pair`",type:"auth",code:"agent_lane_token_required"}});const ae=$t({...J.run||{},...J.reach?{reach:J.reach}:{}},se);return cr(r,o,{...g,pathname:c,agentOverride:T?.agent,harness:P,trace:N,run:Object.keys(ae).length?ae:null},p,E,t,R)})}function fr(t,i){let d=i&&typeof i=="object"?i:null;if(!d&&t)try{d=JSON.parse(decodeURIComponent(String(t)))}catch{d=null}if(!d||typeof d!="object")return null;const r={};if(Array.isArray(d.grants)&&(r.grants=d.grants.map(o=>String(o).slice(0,80)).slice(0,32)),d.workspace&&typeof d.workspace=="object"&&d.workspace.repo){const o=d.workspace;r.workspace={repo:String(o.repo).slice(0,400),projectId:String(o.projectId||"").slice(0,120),jobId:String(o.jobId||"").slice(0,120),...o.base?{base:String(o.base).slice(0,120)}:{}}}return d.connectionId&&(r.connectionId=String(d.connectionId).slice(0,64)),Object.keys(r).length?r:null}let be=null;async function cn(t=Ie()){Zt();let i=null;try{i=await Rt()}catch(g){throw g instanceof zt&&(console.error(`[chatpanel-gateway] org policy: ${g.message}`),process.exit(78)),g}const d=i?.policy||null;d&&(Re(t,d),console.log(`[chatpanel-gateway] ${i.label} — ${i.signed?"signed":"unsigned"} policy from ${i.source}`)),jt(globalThis,{allow:d?.egress?(g,{local:b})=>Vt(d,g,{local:b}):null}),ke();const r=hr(t),o=Kt(t),u=bt(t);r.on("error",g=>{g&&g.code==="EADDRINUSE"&&(console.error(`Port ${t.port} is already in use — another app (or a second gateway) has it.`),console.error(`Fix: free the port, or set a different one — edit "port" in ${ee()} (or the extension's Gateway tab) and restart. The extension must point at the same port.`),process.exit(1)),console.error(`Gateway server error: ${g?.message||g}`),process.exit(1)}),r.listen(t.port,t.host,()=>{console.log(`ChatPanel Privacy Gateway v${W} on http://${t.host}:${t.port}`),console.log(` backend : ${t.backend}`+(t.backend==="bridge"?` (agent: ${t.bridge.agent}, via ${t.bridge.url})`:"")),t.bridge?.openAgentLane&&console.log(" ⚠ agents : bridge.openAgentLane is ON — any local process may drive a CLI agent through this gateway without a token"),ao(t).then(g=>{be=g}).catch(g=>console.log(` bridge : not supervised (${g?.message||g})`)),console.log(` redaction: ${t.redaction.tier}`+(t.redaction.detection?.backend&&t.redaction.detection.backend!=="off"?` + ${t.redaction.detection.backend} detector`:t.ner?.autostart?" (+ NER starting…)":"")),it(t.host)||console.error(`⚠ SECURITY: gateway bound to NON-LOOPBACK host ${t.host}. It is reachable off-machine, and the loopback Host-header check is spoofable from the LAN. Admin routes still need the token/extension, but prefer binding 127.0.0.1 unless you intend LAN exposure on a trusted network.`)}),He()&&Pe(O,_e()).then(g=>{g?.ok&&(console.log(` warm : seeded ${g.ingested} records from ${g.file}`),g.whole&&ge())}).catch(()=>{});const c=()=>{o?.stop(),u.stop(),be?.stop(),r.close(()=>process.exit(0))};return process.on("SIGINT",c),process.on("SIGTERM",c),r}export{W as VERSION,hr as createGateway,dr as joinUpstream,Ce as parseAgentModel,cn as start};
package/src/stt-engine.js CHANGED
@@ -1 +1 @@
1
- import{join as O}from"node:path";import{existsSync as G,readdirSync as q}from"node:fs";import{randomUUID as Q}from"node:crypto";import{ensureLib as R,modelRoot as z}from"./ner-engine.js";import{runtimeDtype as x,runtimeName as C,DTYPE_SUFFIX as V}from"./model-runtime.js";import{verifyModelWeights as W}from"./model-integrity.js";import{DEFAULT_STT_MODEL as H,isEnglishOnly as U,sttModelDtype as v,isKnownSttModel as J,sttModelEngine as $}from"./stt-models.js";import*as T from"./parakeet-engine.js";import*as X from"./diarize-engine.js";const h=16e3;let c="off",f=null,d=null,y=null,M=null,m=null,D=null;function Z(e=f||H,t=v(e)||x()){if($(e)==="parakeet-tdt")return T.parakeetOnDisk(e,T.parakeetDtype(t));const n=O(z(),...e.split("/"),"onnx");if(!G(n))return!1;const r=V[t]??"";try{const o=q(n);return o.includes(`encoder_model${r}.onnx`)&&o.some(s=>s===`decoder_model_merged${r}.onnx`||s===`decoder_model${r}.onnx`)}catch{return!1}}function Ee(){return c}function F(){return c==="ready"&&!!d}function ke(){return m}function Me(){return{configured:c!=="off",ok:F(),state:c,model:f,dtype:D,runtime:C(),error:y}}async function B(e,{log:t=()=>{},allowDownload:n=!0,dtype:r=null}={}){if($(e)==="parakeet-tdt")return I(e,{log:t,allowDownload:n,dtype:r});const o=d,s=f;let a;try{a=await R()}catch(w){return c="error",y=`engine load failed: ${w.message}`,t(`[stt] transformers.js not available (${w.message}) — dictation falls back to the browser engine`),!1}const i=(r&&r!=="auto"?r:null)||v(e)||x(),l=Z(e,i);if(a.env.allowRemoteModels=l?!1:!!n,!l&&!n)return c="error",y="model not on disk and downloads disabled",t(`[stt] model ${e} not installed and downloads disabled`),!1;const p=a.env.remoteHost,_=!J(e);if(!l&&_)try{a.env.remoteHost="https://huggingface.co/"}catch{}c=l?"loading":"downloading",l||(m={model:e,file:null,pct:0},t(`[stt] downloading model ${e} (one-time${_?", from Hugging Face":""})…`));try{const w=u=>{if(!u)return;const j=typeof u.progress=="number"?Math.round(u.progress):m?.pct??0;u.status==="progress"||u.status==="download"||u.status==="initiate"?m={model:e,file:u.file||m?.file||null,pct:j}:u.status==="done"&&u.file&&t(`[stt] fetched ${u.file}`)};let k;try{k=await a.pipeline("automatic-speech-recognition",e,{dtype:i,progress_callback:w})}catch(u){if(l||_||!n)throw u;t(`[stt] mirror fetch failed (${String(u.message).slice(0,80)}) — retrying from Hugging Face…`),a.env.remoteHost="https://huggingface.co/",a.env.allowRemoteModels=!0,k=await a.pipeline("automatic-speech-recognition",e,{dtype:i,progress_callback:w})}if(!l)try{W(e,{modelsDir:z(),log:t})}catch(u){try{await k.dispose?.()}catch{}throw u}if(d=k,f=e,c="ready",y=null,m=null,D=i,o&&o!==k)try{await o.dispose?.()}catch{}return t(`[stt] ready — model ${e} @ ${i} (in-process, offline) — local dictation active`),!0}catch(w){return y=w.message,m=null,o?(d=o,f=s,c="ready"):c="error",t(`[stt] model load failed (${w.message})${o?" — keeping previous model":""}`),!1}finally{try{a.env.remoteHost=p}catch{}}}async function I(e,{log:t=()=>{},allowDownload:n=!0,dtype:r=null}={}){const o=d,s=f,a=T.parakeetDtype(r&&r!=="auto"?r:ee()),g=T.parakeetOnDisk(e,a);if(!g&&!n)return c="error",y="model not on disk and downloads disabled",t(`[stt] model ${e} not installed and downloads disabled`),!1;c=g?"loading":"downloading",g||(m={model:e,file:null,pct:0},t(`[stt] downloading model ${e} (one-time, from Hugging Face)…`));try{const i=await T.loadRecognizer({modelId:e,dtype:a,allowDownload:n,log:t,onProgress:p=>{m={model:e,file:p.file||null,pct:typeof p.pct=="number"?p.pct:m?.pct??0}}}),l=async p=>({text:await i.transcribe(p)});if(l.__parakeet=!0,l.dispose=()=>i.dispose(),d=l,f=e,c="ready",y=null,m=null,D=a,o&&o!==l)try{await o.dispose?.()}catch{}return t(`[stt] ready — model ${e} @ ${a} (parakeet-tdt, in-process, offline) — local dictation active`),!0}catch(i){return y=i.message,m=null,o?(d=o,f=s,c="ready"):c="error",t(`[stt] model load failed (${i.message})${o?" — keeping previous model":""}`),!1}}function ee(){return T.PARAKEET_DEFAULT_DTYPE}function Se(e={}){if(M)return M;const t=typeof e.onLog=="function"?e.onLog:()=>{};return f=e.model||H,c="loading",M=B(f,{log:t,allowDownload:e.allowDownload!==!1,dtype:e.dtype}),M}async function xe(e,t={}){const n=typeof t.onLog=="function"?t.onLog:()=>{};if(!e)return!1;const r=$(e)==="parakeet-tdt"?T.parakeetDtype(t.dtype&&t.dtype!=="auto"?t.dtype:T.PARAKEET_DEFAULT_DTYPE):t.dtype&&t.dtype!=="auto"?t.dtype:v(e)||x();return e===f&&F()&&D===r?!0:B(e,{log:n,allowDownload:t.allowDownload!==!1,dtype:t.dtype})}const te=4,ne=6e4,re=1200,oe=12,P=700,b=.008,ie=30,E=new Map;let A=Promise.resolve();function De(){return E.size}const se=300,ae=3e3;function le(e){const t=Number(e);return Number.isFinite(t)?Math.min(ae,Math.max(se,Math.round(t))):P}function be({lang:e,redact:t=!1,diarize:n=!1,speakerLabel:r=null,endSilenceMs:o=P}={}){if(E.size>=te){const a=new Error("too many concurrent dictation sessions");throw a.code="too_many_sessions",a}const s={id:Q(),endSilenceMs:le(o),lang:typeof e=="string"&&e?e.slice(0,12):null,langTried:!1,redact:!!t,diarize:!!n,speakerLabel:typeof r=="string"&&r?r.slice(0,40):null,diarizer:n?new X.Diarizer:null,chunks:[],samples:0,listeners:new Set,lastDecodeAt:0,decodeTimer:null,lastInterim:"",closed:!1,idleTimer:null};return E.set(s.id,s),K(s),{id:s.id}}function N(e){return E.get(String(e||""))||null}function Ae(e,t){const n=N(e);return n?(n.listeners.add(t),()=>n.listeners.delete(t)):null}function S(e,t){for(const n of e.listeners)try{n(t)}catch{}}function K(e){e.idleTimer&&clearTimeout(e.idleTimer),e.idleTimer=setTimeout(()=>pe(e.id).catch(()=>{}),ne),e.idleTimer.unref?.()}function Le(e,t){const n=N(e);if(!n||n.closed){const r=new Error("no such session");throw r.code="no_session",r}!(t instanceof Float32Array)||!t.length||(n.chunks.push(t),n.samples+=t.length,K(n),ce(n))}function ve(e){const t=e.length-e.length%4,n=new Float32Array(t/4);for(let r=0;r<n.length;r++)n[r]=e.readFloatLE(r*4);return n}function ce(e){if(e.closed||e.decodeTimer)return;const t=Math.max(0,e.lastDecodeAt+re-Date.now());e.decodeTimer=setTimeout(()=>{e.decodeTimer=null,A=A.then(()=>Y(e).catch(()=>{}))},t),e.decodeTimer.unref?.()}function ue(e){const t=new Float32Array(e.samples);let n=0;for(const r of e.chunks)t.set(r,n),n+=r.length;return t}function L(e,t=0,n=e.length){let r=0;const o=Math.max(1,n-t);for(let s=t;s<n;s++)r+=e[s]*e[s];return Math.sqrt(r/o)}function fe(e){const t=Math.round(.02*h);let n=0,r=e.length;for(let o=0;o+t<=e.length;o+=t)if(L(e,o,o+t)>=b){n=o;break}for(let o=e.length-t;o>=0;o-=t)if(L(e,o,o+t)>=b){r=o+t;break}return r>n?e.subarray(n,r):e}async function de(e){try{const t=await R(),n=d?.model?.generation_config;if(!n?.lang_to_id||!n.decoder_start_token_id||!t.Tensor)return null;const r=e.length>h*8?e.subarray(0,h*8):e,o=await d.processor(r),s=new t.Tensor("int64",new BigInt64Array([BigInt(n.decoder_start_token_id)]),[1,1]),a=await d.model({...o,decoder_input_ids:s});let g=null,i=-1/0;for(const[l,p]of Object.entries(n.lang_to_id)){const _=Number(a.logits.data[p]);_>i&&(i=_,g=l)}return g?g.slice(2,-2):null}catch{return null}}async function Y(e,{flush:t=!1}={}){if(e.closed&&!t||!F()||!e.samples)return;e.lastDecodeAt=Date.now();const n=ue(e),r=Math.round((e.endSilenceMs||P)/1e3*h),o=n.length>r&&L(n,n.length-r)<b;if(L(n)<b){n.length>h*5&&(e.chunks=[n.subarray(n.length-h)],e.samples=h);return}if(!e.lang&&!e.langTried&&!U(f)&&!d?.__parakeet&&n.length>=h){e.langTried=!0;const i=await de(n);i&&(e.lang=i,S(e,{type:"language",lang:i}))}let s="";try{const i=U(f)?{}:{language:e.lang||void 0,task:"transcribe"},l=await d(n,i);s=String(l?.text||"").trim()}catch(i){S(e,{type:"error",code:"decode_failed",message:i.message,fatal:!1});return}if(!s)return;const a=n.length>=oe*h,g=n.length>=ie*h;if(t||o||a||g){const i=t?"flush":o?"silence":g?"overflow":"length",l=i==="flush"||i==="silence";e.chunks=[],e.samples=0,e.lastInterim="";let p=null;if(e.diarizer)try{const _=e.speakerLabel?null:await X.embed(fe(n));p=e.diarizer.assign(_,{pinnedLabel:e.speakerLabel})}catch{}S(e,{type:"final",text:s,reason:i,endOfTurn:l,...p?{speaker:p}:{}})}else s!==e.lastInterim&&(e.lastInterim=s,S(e,{type:"interim",text:s}))}async function pe(e){const t=N(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(A=A.then(()=>Y(t,{flush:!0}).catch(()=>{})))}finally{S(t,{type:"end"}),t.listeners.clear(),E.delete(t.id)}return!0}function $e(){for(const e of E.values())e.idleTimer&&clearTimeout(e.idleTimer),e.decodeTimer&&clearTimeout(e.decodeTimer);E.clear(),c="off",f=null,d=null,y=null,M=null,m=null}function Fe(e,t="test/fake"){d=e,f=t,c=e?"ready":"off"}export{h as SAMPLE_RATE,$e as _reset,Fe as _setPipeForTest,le as clampEndSilence,be as createSession,pe as endSession,N as getSession,Me as health,Se as init,F as isReady,Z as modelOnDisk,ke as progress,Le as pushAudio,x as runtimeDtype,C as runtimeName,De as sessionCount,xe as setModel,Ee as state,Ae as subscribe,ve as toFloat32};
1
+ import{join as O}from"node:path";import{existsSync as G,readdirSync as W}from"node:fs";import{randomUUID as q}from"node:crypto";import{ensureLib as R,modelRoot as z}from"./ner-engine.js";import{runtimeDtype as x,runtimeName as C,DTYPE_SUFFIX as Q}from"./model-runtime.js";import{verifyModelWeights as V}from"./model-integrity.js";import{DEFAULT_STT_MODEL as H,isEnglishOnly as U,sttModelDtype as v,isKnownSttModel as J,sttModelEngine as $}from"./stt-models.js";import*as T from"./parakeet-engine.js";import*as K from"./diarize-engine.js";const y=16e3,Z=y;let c="off",d=null,f=null,w=null,M=null,m=null,D=null;function I(e=d||H,t=v(e)||x()){if($(e)==="parakeet-tdt")return T.parakeetOnDisk(e,T.parakeetDtype(t));const n=O(z(),...e.split("/"),"onnx");if(!G(n))return!1;const r=Q[t]??"";try{const o=W(n);return o.includes(`encoder_model${r}.onnx`)&&o.some(s=>s===`decoder_model_merged${r}.onnx`||s===`decoder_model${r}.onnx`)}catch{return!1}}function ke(){return c}function F(){return c==="ready"&&!!f}function Me(){return m}function Se(){return{configured:c!=="off",ok:F(),state:c,model:d,dtype:D,runtime:C(),error:w}}async function X(e,{log:t=()=>{},allowDownload:n=!0,dtype:r=null}={}){if($(e)==="parakeet-tdt")return ee(e,{log:t,allowDownload:n,dtype:r});const o=f,s=d;let a;try{a=await R()}catch(_){return c="error",w=`engine load failed: ${_.message}`,t(`[stt] transformers.js not available (${_.message}) — dictation falls back to the browser engine`),!1}const i=(r&&r!=="auto"?r:null)||v(e)||x(),l=I(e,i);if(a.env.allowRemoteModels=l?!1:!!n,!l&&!n)return c="error",w="model not on disk and downloads disabled",t(`[stt] model ${e} not installed and downloads disabled`),!1;const p=a.env.remoteHost,h=!J(e);if(!l&&h)try{a.env.remoteHost="https://huggingface.co/"}catch{}c=l?"loading":"downloading",l||(m={model:e,file:null,pct:0},t(`[stt] downloading model ${e} (one-time${h?", from Hugging Face":""})…`));try{const _=u=>{if(!u)return;const j=typeof u.progress=="number"?Math.round(u.progress):m?.pct??0;u.status==="progress"||u.status==="download"||u.status==="initiate"?m={model:e,file:u.file||m?.file||null,pct:j}:u.status==="done"&&u.file&&t(`[stt] fetched ${u.file}`)};let E;try{E=await a.pipeline("automatic-speech-recognition",e,{dtype:i,progress_callback:_})}catch(u){if(l||h||!n)throw u;t(`[stt] mirror fetch failed (${String(u.message).slice(0,80)}) — retrying from Hugging Face…`),a.env.remoteHost="https://huggingface.co/",a.env.allowRemoteModels=!0,E=await a.pipeline("automatic-speech-recognition",e,{dtype:i,progress_callback:_})}if(!l)try{V(e,{modelsDir:z(),log:t})}catch(u){try{await E.dispose?.()}catch{}throw u}if(f=E,d=e,c="ready",w=null,m=null,D=i,o&&o!==E)try{await o.dispose?.()}catch{}return t(`[stt] ready — model ${e} @ ${i} (in-process, offline) — local dictation active`),!0}catch(_){return w=_.message,m=null,o?(f=o,d=s,c="ready"):c="error",t(`[stt] model load failed (${_.message})${o?" — keeping previous model":""}`),!1}finally{try{a.env.remoteHost=p}catch{}}}async function ee(e,{log:t=()=>{},allowDownload:n=!0,dtype:r=null}={}){const o=f,s=d,a=T.parakeetDtype(r&&r!=="auto"?r:te()),g=T.parakeetOnDisk(e,a);if(!g&&!n)return c="error",w="model not on disk and downloads disabled",t(`[stt] model ${e} not installed and downloads disabled`),!1;c=g?"loading":"downloading",g||(m={model:e,file:null,pct:0},t(`[stt] downloading model ${e} (one-time, from Hugging Face)…`));try{const i=await T.loadRecognizer({modelId:e,dtype:a,allowDownload:n,log:t,onProgress:p=>{m={model:e,file:p.file||null,pct:typeof p.pct=="number"?p.pct:m?.pct??0}}}),l=async p=>({text:await i.transcribe(p)});if(l.__parakeet=!0,l.dispose=()=>i.dispose(),f=l,d=e,c="ready",w=null,m=null,D=a,o&&o!==l)try{await o.dispose?.()}catch{}return t(`[stt] ready — model ${e} @ ${a} (parakeet-tdt, in-process, offline) — local dictation active`),!0}catch(i){return w=i.message,m=null,o?(f=o,d=s,c="ready"):c="error",t(`[stt] model load failed (${i.message})${o?" — keeping previous model":""}`),!1}}function te(){return T.PARAKEET_DEFAULT_DTYPE}function xe(e={}){if(M)return M;const t=typeof e.onLog=="function"?e.onLog:()=>{};return d=e.model||H,c="loading",M=X(d,{log:t,allowDownload:e.allowDownload!==!1,dtype:e.dtype}),M}async function De(e,t={}){const n=typeof t.onLog=="function"?t.onLog:()=>{};if(!e)return!1;const r=$(e)==="parakeet-tdt"?T.parakeetDtype(t.dtype&&t.dtype!=="auto"?t.dtype:T.PARAKEET_DEFAULT_DTYPE):t.dtype&&t.dtype!=="auto"?t.dtype:v(e)||x();return e===d&&F()&&D===r?!0:X(e,{log:n,allowDownload:t.allowDownload!==!1,dtype:t.dtype})}const ne=4,re=6e4,oe=1200,ie=12,P=700,b=.008,se=30,k=new Map;let A=Promise.resolve();function be(){return k.size}const ae=300,le=3e3;function ce(e){const t=Number(e);return Number.isFinite(t)?Math.min(le,Math.max(ae,Math.round(t))):P}function Ae({lang:e,redact:t=!1,diarize:n=!1,speakerLabel:r=null,endSilenceMs:o=P}={}){if(k.size>=ne){const a=new Error("too many concurrent dictation sessions");throw a.code="too_many_sessions",a}const s={id:q(),endSilenceMs:ce(o),lang:typeof e=="string"&&e?e.slice(0,12):null,langTried:!1,redact:!!t,diarize:!!n,speakerLabel:typeof r=="string"&&r?r.slice(0,40):null,diarizer:n?new K.Diarizer:null,chunks:[],samples:0,listeners:new Set,lastDecodeAt:0,decodeTimer:null,lastInterim:"",closed:!1,idleTimer:null};return k.set(s.id,s),B(s),{id:s.id}}function N(e){return k.get(String(e||""))||null}function Le(e,t){const n=N(e);return n?(n.listeners.add(t),()=>n.listeners.delete(t)):null}function S(e,t){for(const n of e.listeners)try{n(t)}catch{}}function B(e){e.idleTimer&&clearTimeout(e.idleTimer),e.idleTimer=setTimeout(()=>me(e.id).catch(()=>{}),re),e.idleTimer.unref?.()}function ve(e,t){const n=N(e);if(!n||n.closed){const r=new Error("no such session");throw r.code="no_session",r}!(t instanceof Float32Array)||!t.length||(n.chunks.push(t),n.samples+=t.length,B(n),ue(n))}function $e(e){const t=e.length-e.length%4,n=new Float32Array(t/4);for(let r=0;r<n.length;r++)n[r]=e.readFloatLE(r*4);return n}function ue(e){if(e.closed||e.decodeTimer)return;const t=Math.max(0,e.lastDecodeAt+oe-Date.now());e.decodeTimer=setTimeout(()=>{e.decodeTimer=null,A=A.then(()=>Y(e).catch(()=>{}))},t),e.decodeTimer.unref?.()}function de(e){const t=new Float32Array(e.samples);let n=0;for(const r of e.chunks)t.set(r,n),n+=r.length;return t}function L(e,t=0,n=e.length){let r=0;const o=Math.max(1,n-t);for(let s=t;s<n;s++)r+=e[s]*e[s];return Math.sqrt(r/o)}function fe(e){const t=Math.round(.02*y);let n=0,r=e.length;for(let o=0;o+t<=e.length;o+=t)if(L(e,o,o+t)>=b){n=o;break}for(let o=e.length-t;o>=0;o-=t)if(L(e,o,o+t)>=b){r=o+t;break}return r>n?e.subarray(n,r):e}async function pe(e){try{const t=await R(),n=f?.model?.generation_config;if(!n?.lang_to_id||!n.decoder_start_token_id||!t.Tensor)return null;const r=e.length>y*8?e.subarray(0,y*8):e,o=await f.processor(r),s=new t.Tensor("int64",new BigInt64Array([BigInt(n.decoder_start_token_id)]),[1,1]),a=await f.model({...o,decoder_input_ids:s});let g=null,i=-1/0;for(const[l,p]of Object.entries(n.lang_to_id)){const h=Number(a.logits.data[p]);h>i&&(i=h,g=l)}return g?g.slice(2,-2):null}catch{return null}}async function Y(e,{flush:t=!1}={}){if(e.closed&&!t||!F()||!e.samples)return;e.lastDecodeAt=Date.now();const n=de(e),r=Math.round((e.endSilenceMs||P)/1e3*y),o=n.length>r&&L(n,n.length-r)<b;if(L(n)<b){n.length>y*5&&(e.chunks=[n.subarray(n.length-y)],e.samples=y);return}if(!e.lang&&!e.langTried&&!U(d)&&!f?.__parakeet&&n.length>=y){e.langTried=!0;const i=await pe(n);i&&(e.lang=i,S(e,{type:"language",lang:i}))}let s="";try{const i=U(d)?{}:{language:e.lang||void 0,task:"transcribe"},l=await f(n,i);s=String(l?.text||"").trim()}catch(i){S(e,{type:"error",code:"decode_failed",message:i.message,fatal:!1});return}if(!s)return;const a=n.length>=ie*y,g=n.length>=se*y;if(t||o||a||g){const i=t?"flush":o?"silence":g?"overflow":"length",l=i==="flush"||i==="silence";e.chunks=[],e.samples=0,e.lastInterim="";let p=null;if(e.diarizer)try{const h=e.speakerLabel?null:fe(n),_=h?await K.embed(h):null,E=!!h&&h.length<Z;p=e.diarizer.assign(_,{pinnedLabel:e.speakerLabel,weak:E})}catch{}S(e,{type:"final",text:s,reason:i,endOfTurn:l,...p?{speaker:p}:{}})}else s!==e.lastInterim&&(e.lastInterim=s,S(e,{type:"interim",text:s}))}async function me(e){const t=N(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(A=A.then(()=>Y(t,{flush:!0}).catch(()=>{})))}finally{S(t,{type:"end"}),t.listeners.clear(),k.delete(t.id)}return!0}function Fe(){for(const e of k.values())e.idleTimer&&clearTimeout(e.idleTimer),e.decodeTimer&&clearTimeout(e.decodeTimer);k.clear(),c="off",d=null,f=null,w=null,M=null,m=null}function Pe(e,t="test/fake"){f=e,d=t,c=e?"ready":"off"}export{y as SAMPLE_RATE,Z as WEAK_SPEAKER_SAMPLES,Fe as _reset,Pe as _setPipeForTest,ce as clampEndSilence,Ae as createSession,me as endSession,N as getSession,Se as health,xe as init,F as isReady,I as modelOnDisk,Me as progress,ve as pushAudio,x as runtimeDtype,C as runtimeName,be as sessionCount,De as setModel,ke as state,Le as subscribe,$e as toFloat32};