@chatpanel/gateway 0.9.3 → 0.9.4

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.3",
3
+ "version": "0.9.4",
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": {
@@ -22,7 +22,7 @@
22
22
  },
23
23
  "dependencies": {
24
24
  "@chatpanel/bridge": "^0.13.3",
25
- "@chatpanel/events": "^0.108.0",
25
+ "@chatpanel/events": "^0.117.0",
26
26
  "@chatpanel/pii": "^0.8.0",
27
27
  "@huggingface/transformers": "^4.2.0",
28
28
  "onnxruntime-web": "1.26.0-dev.20260416-b7804b056c",
@@ -1,9 +1,9 @@
1
- import{readFileSync as d,existsSync as A,readdirSync as m,statSync as h}from"node:fs";import{join as f}from"node:path";import S from"node:os";import{decryptBackupEnvelope as g}from"./backup-decrypt.js";const l=process.env.CHATPANEL_BACKUP_DIR||f(S.homedir(),"Downloads","ChatPanel Backups"),k=/^chatpanel-backup-(?:[a-z0-9]{12,16}-)?(?:Sun|Mon|Tue|Wed|Thu|Fri|Sat)\.encrypted\.json$/;function $(o=l){try{let e=null;for(const t of m(o)){if(!k.test(t))continue;const n=f(o,t),s=h(n).mtimeMs;(!e||s>e.mtime)&&(e={path:n,mtime:s})}return e?.path||null}catch{return null}}function b(o=l){try{return m(o).filter(e=>k.test(e)).map(e=>({path:f(o,e),mtime:h(f(o,e)).mtimeMs})).sort((e,t)=>e.mtime-t.mtime).map(e=>e.path)}catch{return[]}}function y(o){const e=[];for(const t of o?.conversations||[]){if(!t?.id)continue;const n=t.title||"Chat",s=t.updatedAt||t.createdAt||0,i=(t.messages||[]).filter(r=>r&&r.content).map(r=>`${r.role==="assistant"?"Assistant":r.role==="system"?"System":"You"}: ${r.content}`).join(`
1
+ import{readFileSync as h,existsSync as $,readdirSync as k,statSync as l}from"node:fs";import{join as f}from"node:path";import b from"node:os";import{decryptBackupEnvelope as g}from"./backup-decrypt.js";import{recordsFromBackup as x}from"@chatpanel/events/backup-records.js";const d=process.env.CHATPANEL_BACKUP_DIR||f(b.homedir(),"Downloads","ChatPanel Backups"),y=/^chatpanel-backup-(?:[a-z0-9]{12,16}-)?(?:Sun|Mon|Tue|Wed|Thu|Fri|Sat)\.encrypted\.json$/;function B(s=d){try{let n=null;for(const t of k(s)){if(!y.test(t))continue;const e=f(s,t),o=l(e).mtimeMs;(!n||o>n.mtime)&&(n={path:e,mtime:o})}return n?.path||null}catch{return null}}function M(s=d){try{return k(s).filter(n=>y.test(n)).map(n=>({path:f(s,n),mtime:l(f(s,n)).mtimeMs})).sort((n,t)=>n.mtime-t.mtime).map(n=>n.path)}catch{return[]}}function A(s){const n=[];for(const t of s?.conversations||[]){if(!t?.id)continue;const e=t.title||"Chat",o=t.updatedAt||t.createdAt||0,r=(t.messages||[]).filter(c=>c&&c.content).map(c=>`${c.role==="assistant"?"Assistant":c.role==="system"?"System":"You"}: ${c.content}`).join(`
2
2
 
3
- `);e.push({id:`chat:${t.id}`,type:"chat",title:n,date:s,text:`CHAT: ${n}
3
+ `);n.push({id:`chat:${t.id}`,type:"chat",title:e,date:o,text:`CHAT: ${e}
4
4
 
5
- ${i}`.trim()})}for(const t of o?.meetings||[]){const n=t?.record||t,s=n?.id;if(!s)continue;const i=n.title||"Meeting",r=n.startedAt||n.date||0,p=typeof t?.notes=="string"?t.notes:"",a=(n.segments||[]).map(u=>`${u.speaker||"?"}: ${u.text||""}`).join(`
6
- `),c=[`MEETING: ${i}`];n.platform&&c.push(`Platform: ${n.platform}`),p&&c.push("","SUMMARY:",p),a&&c.push("","TRANSCRIPT:",a),e.push({id:`meeting:${s}`,type:"meeting",title:i,date:r,text:c.join(`
7
- `).trim()})}for(const t of o?.notes||[]){if(!t?.id)continue;const n=t.title||"Note",s=t.updatedAt||t.createdAt||0;e.push({id:`note:${t.id}`,type:"note",title:n,date:s,text:`NOTE: ${n}
5
+ ${r}`.trim()})}for(const t of s?.meetings||[]){const e=t?.record||t,o=e?.id;if(!o)continue;const r=e.title||"Meeting",c=e.startedAt||e.date||0,a=typeof t?.notes=="string"?t.notes:"",u=(e.segments||[]).map(p=>`${p.speaker||"?"}: ${p.text||""}`).join(`
6
+ `),i=[`MEETING: ${r}`];e.platform&&i.push(`Platform: ${e.platform}`),a&&i.push("","SUMMARY:",a),u&&i.push("","TRANSCRIPT:",u),n.push({id:`meeting:${o}`,type:"meeting",title:r,date:c,text:i.join(`
7
+ `).trim()})}for(const t of s?.notes||[]){if(!t?.id)continue;const e=t.title||"Note",o=t.updatedAt||t.createdAt||0;n.push({id:`note:${t.id}`,type:"note",title:e,date:o,text:`NOTE: ${e}
8
8
 
9
- ${String(t.body||"")}`.trim()})}return e}async function M(o,e,{path:t=""}={}){const n=t||$();if(!n||!A(n))return{ok:!1,reason:"no-backup"};if(!e)return{ok:!1,reason:"no-passphrase"};let s;try{s=await g(JSON.parse(d(n,"utf8")),e)}catch(r){return{ok:!1,reason:"decrypt",error:String(r?.message||r)}}const i=y(s);return o.bulk({upserts:i}),{ok:!0,file:n,ingested:i.length,size:o.size}}async function N(o,e,{dir:t=l}={}){if(!e)return{ok:!1,reason:"no-passphrase"};const n=b(t);if(!n.length)return{ok:!1,reason:"no-backup"};const s=new Map,i=[],r=[];for(const a of n)try{const c=await g(JSON.parse(d(a,"utf8")),e);for(const u of y(c))s.set(u.id,u);i.push(a)}catch(c){r.push({file:a,error:String(c?.message||c)})}if(!i.length)return{ok:!1,reason:"decrypt",error:r[0]?.error||"no backup matched the stored passphrase"};const p=[...s.values()];return o.bulk({upserts:p}),{ok:!0,file:i.at(-1),files:i.length,skippedFiles:r.length,ingested:p.length,size:o.size}}export{y as backupToRecords,b as findBackups,$ as findLatestBackup,M as ingestBackup,N as ingestBackups};
9
+ ${String(t.body||"")}`.trim()})}return n}async function R(s,n,{path:t=""}={}){const e=t||B();if(!e||!$(e))return{ok:!1,reason:"no-backup"};if(!n)return{ok:!1,reason:"no-passphrase"};let o;try{o=await g(JSON.parse(h(e,"utf8")),n)}catch(a){return{ok:!1,reason:"decrypt",error:String(a?.message||a)}}const r=A(o);s.bulk({upserts:r});const c=S(s,o,e);return{ok:!0,file:e,ingested:r.length,size:s.size,whole:c}}async function E(s,n,{dir:t=d}={}){if(!n)return{ok:!1,reason:"no-passphrase"};const e=M(t);if(!e.length)return{ok:!1,reason:"no-backup"};const o=new Map,r=[],c=[];let a=0;for(const i of e)try{const p=await g(JSON.parse(h(i,"utf8")),n);for(const m of A(p))o.set(m.id,m);a+=S(s,p,i),r.push(i)}catch(p){c.push({file:i,error:String(p?.message||p)})}if(!r.length)return{ok:!1,reason:"decrypt",error:c[0]?.error||"no backup matched the stored passphrase"};const u=[...o.values()];return s.bulk({upserts:u}),{ok:!0,file:r.at(-1),files:r.length,skippedFiles:c.length,ingested:u.length,size:s.size,whole:a}}function S(s,n,t){const e=s?.lossless;if(!e)return 0;let o=0;try{o=l(t).mtimeMs}catch{o=0}const r=x(n,{now:o});return e.upsert(r,{host:"backup",at:o}).length}export{A as backupToRecords,M as findBackups,B as findLatestBackup,R as ingestBackup,E as ingestBackups};
@@ -0,0 +1,9 @@
1
+ const s=d=>Number.isFinite(Number(d))?Number(d):0,A=d=>Math.max(s(d?.updatedAt),s(d?.deletedAt));class N{constructor(i){this.db=i}init(){return this.db.exec(`CREATE TABLE IF NOT EXISTS library(
2
+ id TEXT PRIMARY KEY, kind TEXT NOT NULL, title TEXT NOT NULL DEFAULT '',
3
+ updated_at INTEGER NOT NULL DEFAULT 0, deleted_at INTEGER NOT NULL DEFAULT 0,
4
+ host TEXT NOT NULL DEFAULT '', seq INTEGER NOT NULL DEFAULT 0, at INTEGER NOT NULL DEFAULT 0,
5
+ record TEXT, sealed TEXT, bytes INTEGER NOT NULL DEFAULT 0,
6
+ stamp INTEGER NOT NULL DEFAULT 0
7
+ )`),this.db.exec("CREATE INDEX IF NOT EXISTS library_since ON library(stamp, id)"),this}get size(){return this.db.get("SELECT COUNT(*) c FROM library WHERE deleted_at = 0")?.c||0}get newest(){return this.db.get("SELECT MAX(stamp) m FROM library")?.m||0}stamp(i){const a=this.db.get("SELECT id, updated_at, deleted_at, at FROM library WHERE id = ?",[i]);return a?{id:a.id,updatedAt:a.updated_at,deletedAt:a.deleted_at,at:a.at}:null}_wins(i,a,u,r){const t=this.stamp(i);if(!t)return!0;const e=Math.max(s(a),s(u)),n=Math.max(s(t.updatedAt),s(t.deletedAt));return e!==n?e>n:s(r)>s(t.at)}upsert(i,{host:a="",seq:u=0,at:r=Date.now()}={}){const t=[];this.db.exec("BEGIN");try{for(const e of i||[]){if(!e||typeof e.id!="string"||!e.id.includes(":"))continue;const n=s(e.updatedAt),l=s(e.deletedAt);if(!n&&!l||!this._wins(e.id,n,l,r))continue;const E=l?null:JSON.stringify(e);this.db.run(`INSERT OR REPLACE INTO library(id, kind, title, updated_at, deleted_at, host, seq, at, record, sealed, bytes, stamp)
8
+ VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, NULL, ?, ?)`,[e.id,e.kind||e.id.split(":")[0],String(e.title||""),n,l,String(a||""),s(u),s(r),E,E?E.length:0,Math.max(n,l)]),t.push(e.id)}this.db.exec("COMMIT")}catch(e){throw this.db.exec("ROLLBACK"),e}return t}async upsertEntries(i,{open:a=async()=>null}={}){const u=[];let r=0;for(const t of i||[]){if(!t||typeof t.id!="string"||!t.stamp)continue;const e=s(t.stamp.updatedAt),n=s(t.stamp.deletedAt);if(!e&&!n||!this._wins(t.id,e,n,t.at))continue;if(n){this.upsert([{id:t.id,kind:t.id.split(":")[0],updatedAt:e,deletedAt:n}],{host:t.host,seq:t.seq,at:t.at}),u.push(t.id);continue}let l=null;try{l=await a(t)}catch{l=null}if(l&&typeof l=="object")this.upsert([{...l,id:t.id,updatedAt:s(l.updatedAt)||e,deletedAt:0}],{host:t.host,seq:t.seq,at:t.at});else{const E=JSON.stringify(t.blob||null);this.db.run(`INSERT OR REPLACE INTO library(id, kind, title, updated_at, deleted_at, host, seq, at, record, sealed, bytes, stamp)
9
+ VALUES(?, ?, '', ?, 0, ?, ?, ?, NULL, ?, ?, ?)`,[t.id,t.id.split(":")[0],e,String(t.host||""),s(t.seq),s(t.at),E,E.length,e]),r+=1}u.push(t.id)}return{written:u,sealed:r}}get(i){return L(this.db.get("SELECT * FROM library WHERE id = ?",[i]))}since({since:i=0,cursor:a="",limit:u=200,kind:r=null}={}){const t=Math.min(1e3,Math.max(1,s(u)||200));let e=s(i),n="";if(a){const T=String(a).indexOf(":");T>0&&(e=s(a.slice(0,T)),n=a.slice(T+1))}const l=[a?"(stamp > ? OR (stamp = ? AND id > ?))":"stamp > ?"],E=a?[e,e,n]:[e];r&&(l.push("kind = ?"),E.push(String(r)));const c=this.db.all(`SELECT * FROM library WHERE ${l.join(" AND ")} ORDER BY stamp ASC, id ASC LIMIT ?`,[...E,t+1]),o=c.length>t,h=o?c.slice(0,t):c,p=h.at(-1);return{records:h.map(L),next:o&&p?`${p.stamp}:${p.id}`:null}}stamps(){return this.db.all("SELECT id, updated_at, deleted_at FROM library").map(i=>({id:i.id,updatedAt:i.updated_at,deletedAt:i.deleted_at}))}clear(){const i=this.db.get("SELECT COUNT(*) c FROM library")?.c||0;return this.db.exec("DELETE FROM library"),i}}function L(d){if(!d)return null;if(d.deleted_at)return{id:d.id,kind:d.kind,updatedAt:d.updated_at,deletedAt:d.deleted_at,host:d.host,at:d.at};if(d.record)try{return{...JSON.parse(d.record),host:d.host,at:d.at}}catch{}let i=null;try{i=d.sealed?JSON.parse(d.sealed):null}catch{i=null}return{id:d.id,kind:d.kind,updatedAt:d.updated_at,deletedAt:0,sealed:i,host:d.host,at:d.at}}export{N as LosslessStore};
package/src/server.js CHANGED
@@ -1,19 +1,19 @@
1
- import{createServer as yt}from"node:http";import{loadConfig as Be}from"./config.js";import{startEntitlementRefresh as ht,maybeRevalidate as ft}from"./entitlement-refresh.js";import{redactSegments as fe,segment as Ce}from"./redact.js";import{pipeRestoredStream as gt,pipeRestoredOpenAIStream as bt,makeTokenRestorer as De,restoreDeep as wt}from"./stream.js";import{restoreText as kt,gatedDictionary as St,narrowSpecs as vt,makeToolHarness as Tt,placeholderToolNote as _t,placeholderNote as Ot,assertEndpointUrl as Et,capRunOptions as xt,isPaired as At}from"@chatpanel/pii";import{ensureGatewayToken as ge,currentGatewayToken as Pt,isAdminAuthorized as F,callerTrustOf as ce,setPinnedExtensionIds as $t,issuePairingCode as Nt,claimPairingCode as Bt}from"./gateway-token.js";import{installEgressLedger as Ct,egressAudit as Dt}from"./egress.js";import{initPolicy as It,activePolicy as jt,applyPolicyToConfig as Ie,managedSummary as ae,PolicyLoadError as Mt}from"./policy.js";import{routeAllowed as je,agentAllowed as Rt,egressAllowed as Lt}from"@chatpanel/events/policy.js";import{resolveBridgeUrl as de}from"./bridge.js";import{secureFetch as Me}from"./secure-fetch.js";import{streamBridgeChat as Re,readBridgeToken as ie,openBridgeChat as Gt}from"./bridge.js";import{createRelaySession as zt,getRelaySession as Le,endRelaySession as ue,pumpBridgeStream as Vt,deliverToolResult as Jt,toolsToSpecs as Ht,parseToolCallId as Ge,touchRelaySession as be}from"./toolrelay.js";import{shaperFor as we}from"./shape.js";import{startNer as Ut,ensureNer as ke}from"./ner.js";import{installTimestampedConsole as Ft}from"./log.js";import{saveBackupSecret as Wt,clearBackupSecret as Kt,loadBackupSecret as ze,hasBackupSecret as Ve}from"./history-store.js";import{createMemoryStore as Zt}from"./memory-store.js";import{createPrefsStore as Yt}from"./prefs-store.js";import{createTeamStore as Xt,loadOrCreateKey as Se}from"./team-store.js";import{createScorecardStore as Qt}from"./scorecard-store.js";import{createEngineLedgerStore as qt}from"./engine-ledger-store.js";import{createProjectStore as eo}from"./project-store.js";import{applicationsFor as to,recruitPass as oo}from"./recruiting.js";import{ensureBridge as ro}from"./bridge-supervisor.js";import{checkForUpdate as no,updateStatus as so,startUpdate as ao,updateJob as io}from"./update.js";import{createHistoryStore as lo}from"./sqlite-store.js";import{ingestBackups as ve}from"./backup-ingest.js";import*as B from"./ner-engine.js";import*as x from"./stt-engine.js";import*as $ from"./diarize-engine.js";import{MODEL_CATALOG as co,isKnownModel as uo,isValidCustomModelId as mo}from"./models.js";import{STT_MODEL_CATALOG as po,isKnownSttModel as yo,isValidCustomSttId as ho,DEFAULT_STT_MODEL as Te,STT_DTYPES as fo,isValidDtype as go}from"./stt-models.js";import*as k from"./tts-engine.js";import{TTS_MODEL_CATALOG as Je,TTS_VOICES as bo,isKnownTtsModel as wo,isValidCustomTtsId as ko,isKnownVoice as He,isValidVoiceId as Ue,DEFAULT_TTS_MODEL as Fe,DEFAULT_TTS_VOICE as Y,TTS_DTYPES as So,isValidTtsDtype as vo,MAX_TTS_CHARS as We,ttsModelHasCustomVoices as To,resolveDefaultModel as Ke,POCKET_VOICES as _o,DEFAULT_POCKET_VOICE as me,isPocketVoice as pe,ttsModelEngine as ye}from"./tts-models.js";import{ttsDestination as Oo,synthesizeRemote as Eo,isValidRemoteVoice as xo}from"./tts-remote.js";import{rawOrtAvailable as _e}from"./ort.js";import*as L from"./tts-voices.js";import{resolveTtsVoice as Ao}from"./tts-voice-resolve.js";import{resolvePro as q,checkQuota as Po,consume as $o,usage as No}from"./freegate.js";import{publicConfig as Ze,applyConfigPatch as Bo,applyNerModelSelection as Co,persistConfig as te,configPath as ee,bridgeAgentOptions as Ye}from"./configstore.js";import{resolveDestination as Xe,aggregateModelsAsync as Do,listDestinations as Io}from"./router.js";import{makeAccessEvent as Qe}from"./observability.js";import{createPersistentAccessLog as jo}from"./access-log-store.js";import{planQueries as Mo,multiSearch as Ro}from"./rrf.js";import*as Oe from"./openai.js";import*as qe from"./responses.js";import*as Ee from"./anthropic.js";const W="0.9.3",N=await lo(),H=await Zt(),K=Yt(),oe=Qt({key:Se()}),re=qt({key:Se()}),G=eo({key:Se()}),C=Xt({scorecards:oe,engines:re}),xe=new Set,et=(t,i)=>{for(const d of xe)try{d({applied:t,by:i,revision:K.revision})}catch{}},Ae=jo(),tt=new Set(["codex","claude","opencode","pi","kiro","antigravity","hermes"]),Lo=16,Go=/^mcp[_-]/i,ot=t=>t&&t.function&&t.function.name||t&&t.name||"",zo=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 Vo(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 Jo(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 Ho(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 Uo(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 Fo(t){const i=/^(model|harness):([^/]+)(?:\/(.+))?$/.exec(String(t||""));return i?{kind:i[1],id:i[2],...i[3]?{model:i[3]}:{}}:null}function Wo(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}`:""} · ${Uo(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",y=r.replace(/^\[\[|\]\]$/g,"");d.push(i==="values"?{token:y,type:c,value:o}:{token:y,type:c})}return d}function Ko(t,i,d){return Ee.matches(t)||"anthropic-version"in i?{kind:"anthropic",adapter:Ee,redactable:Ee.matches(t),base:d.upstreams?.anthropic?.baseUrl}:qe.matches(t)?{kind:"responses",adapter:qe,redactable:!0,base:d.upstreams?.openai?.baseUrl}:{kind:"openai",adapter:Oe,redactable:Oe.matches(t),base:d.upstreams?.openai?.baseUrl}}function Pe(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 Pe(t,i).agent}function Zo(t,i){if(i!=="openai"||!t)return!1;const d=Oe.extractLatestToolResult(t);if(!d)return!1;const r=Ge(d.tool_call_id);return!!(r&&Le(r.gwId))}function Yo(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 $e(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=B.health(),o=r.ok&&d==="full";return{source:"bundled",state:r.state,model:r.model||t?.ner?.model||null,installed:B.modelOnDisk(t?.ner?.model||void 0),error:r.error||null,ready:o,tier:d,coverage:o?"names":"patterns"}}async function dt(t){if(B.state()!=="off"){const d=B.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 Me(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 Xo(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=De(i.vault),u=r?r.clock():0;let c=u,y=!0;const g=()=>{r&&y&&(r.lap("upstream",u),c=r.clock(),y=!1)};await Vt(i,{onText:E=>{g(),be(i.id);const m=o.push(E);m&&t.write(d.sseDelta(m))},onToolRequest:({name:E,restoredArgs:m,toolId:M})=>{g(),be(i.id);const A=o.flush();A&&t.write(d.sseDelta(A)),t.write(d.sseToolCalls([{id:M,name:E,arguments:JSON.stringify(m)}])),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(),ue(i.id),r?.commit()},onError:E=>{t.write(`data: ${JSON.stringify({error:{message:E.message,type:"bridge_error"}})}
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"}})}
2
2
 
3
- `),t.end(),ue(i.id),r?.commit()}})}async function Qo(t,i,{kind:d,adapter:r,agent:o,run:u=null},c,y,g,E,m,M=null,A=null){const{messages:D,system:Z}=r.toTurn(c),{agentModel:R}=Pe(c?.model,g),j=Ye(g,{...R?{model:R}:{},...u||{}}),P=ie(g.bridge.token),O=we(d,c?.model||o),I={tier:g.redaction.tier==="full"?"full":"basic",dictionary:St(g.redaction,E),entities:[]},z=await de(g),T=zt({vault:y,redactOpts:I,bridgeUrl:z,token:P,harness:M});let U;try{U=await Gt({bridgeUrl:z,agent:o,token:P,messages:D,system:Z,specs:Ht(m),options:j,signal:void 0})}catch(X){return ue(T.id),A?.commit(),s(i,502,{error:{message:`bridge: ${X.message}`,type:"bridge_error"}})}return T.reader=U.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,A)}async function qo(t,i,d,r,o=null){be(i.id),i.rounds=(i.rounds||0)+1;try{const c=o?o.clock():0;await Jt(i,d),o&&o.lap("redact",c)}catch(c){return ue(i.id),o?.commit(),s(t,502,{error:{message:`tool-result: ${c.message}`,type:"bridge_error"}})}const u=we("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 er(t,i,{kind:d,adapter:r,redactable:o,pathname:u,agentOverride:c,harness:y,trace:g,run:E=null},m,M,A,D){if(!o)return g?.commit(),s(i,404,{error:`endpoint ${u} not supported by the bridge backend`});if(d==="openai"){const e=r.extractLatestToolResult(m);if(e){const a=Ge(e.tool_call_id),l=a&&Le(a.gwId);if(l)return qo(i,l,e.content,m?.model,g)}const n=r.extractTools(m);if(n.length&&m?.stream===!0)return Qo(t,i,{kind:d,adapter:r,agent:c||lt(m?.model,A),run:E},m,M,A,D,n,y,g)}const{messages:Z,system:R}=r.toTurn(m),j=c||lt(m?.model,A),P=m?.stream===!0,O=we(d,m?.model||j),I=ie(A.bridge.token),z=new AbortController;i.on("close",()=>{i.writableFinished||z.abort()});const{agentModel:T}=Pe(m?.model,A),U={bridgeUrl:await de(A),agent:j,token:I,messages:Z,system:R,signal:z.signal,options:Ye(A,{...T?{model:T}:{},...E||{}})};if(!P)try{let e="";const n=g?g.clock():0;await Re(U,p=>{e+=p}),g&&g.lap("upstream",n);const a=g?g.clock():0,l=O.full(kt(e,M));return g&&g.lap("restore",a),i.writeHead(200,{"content-type":O.contentType}),i.end(l),g?.commit()}catch(e){return g?.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=De(M),ne=g?g.clock():0;let se=ne;try{let e=!0;await Re(U,a=>{g&&e&&(g.lap("upstream",ne),se=g.clock(),e=!1);const l=X.push(a);l&&i.write(O.sseDelta(l))},O.sseActivity?a=>{try{i.write(O.sseActivity(wt(a,M)))}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"}})}
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
4
 
5
- `)}g&&g.lap("stream",se),i.end(),g?.commit()}function tr(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 or=9e4;function rr(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,y=Math.floor(c),g=Math.min(t.length-1,y+1),E=c-y;o[u]=t[y]*(1-E)+t[g]*E}return o}const nr=["/tts","/stt","/ner","/diarize","/skills","/redact","/config","/logs","/status","/admin"];async function sr(t,i,{adapter:d,kind:r,pathname:o,search:u,base:c,destKey:y,destProtocol:g,harness:E,trace:m},M,A){let D;const Z=m?m.clock():0;try{const O=Xo(t.headers,c);y&&(g==="anthropic"?(O["x-api-key"]=y,delete O.authorization):O.authorization=`Bearer ${y}`);const I=Et(tr(c,o,u)).toString();D=await fetch(I,{method:t.method,headers:O,body:["GET","HEAD"].includes(t.method)?void 0:M})}catch(O){return m?.commit(),s(i,502,{error:`upstream fetch failed: ${O.message}`})}const R=D.headers.get("content-type")||"",j={};if(D.headers.forEach((O,I)=>{nt.has(I.toLowerCase())||(j[I]=O)}),R.includes("text/event-stream")&&D.body){m&&m.lap("upstream",Z);const O=m?m.clock():0;i.writeHead(D.status,j);const I=r==="openai"?bt(D.body,i,A,E):gt(D.body,i,A);return Promise.resolve(I).finally(()=>{m&&m.lap("stream",O),m?.commit()})}const P=Buffer.from(await D.arrayBuffer());if(m&&m.lap("upstream",Z),A&&R.includes("application/json"))try{const O=m?m.clock():0,I=d.restoreResponse(JSON.parse(P.toString("utf8")),A,E);return m&&m.lap("restore",O),i.writeHead(D.status,{...j,"content-type":"application/json"}),i.end(Buffer.from(JSON.stringify(I),"utf8")),m?.commit()}catch{}i.writeHead(D.status,j),i.end(P),m?.commit()}function ar(t=Be()){$t(t.allowedExtensionIds||[]);const i=[],d=r=>{i.push(r),i.length>50&&i.shift()};return yt(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(!Jo(r.headers.origin,t))return s(o,403,{error:"origin not allowed"});if(r.headers.origin&&Ho(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:ge()}):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=Nt();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=Bt(e?.code);if(!n.ok)return console.log(`[gateway] pairing refused (${n.reason}) from ${ce(r)} caller`),s(o,403,{error:n.reason});console.log(`[gateway] paired a ${ce(r)} client${r.headers.origin?` (${r.headers.origin})`:""}`);const a=ie(t.bridge?.token);return s(o,200,{ok:!0,token:Pt()||ge(),...a?{bridgeToken:a}:{}})}if(c==="/whoami"&&r.method==="POST"){const e=ce(r);return s(o,200,{ok:!0,trust:e,paired:At(e),version:W})}if(c==="/audit"&&r.method==="GET")return F(r)?s(o,200,Dt(t,{version:W,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 no(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:io()})}if(c==="/update"&&r.method==="POST"){const e=ao(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/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=k.health();return s(o,200,{ok:!0,version:W,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)}:{},...he?{bridge:he.status()}:{},stt:{enabled:t.stt?.enabled!==!1,state:e.state,ready:e.ok,model:e.model||t.stt?.model||Te,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||Y,runtime:n.runtime,dtype:n.dtype}})}if(c==="/status"&&r.method==="GET"){ft(t);const e=await q(t.pro?.entitlementToken),n=await dt(t);return s(o,200,{ok:!0,version:W,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:$e(t),pro:{unlocked:e},usage:No(t),uptimeSeconds:Math.floor((Date.now()-at)/1e3),update:so(W)})}if(c==="/v1/history/ingest"&&r.method==="POST")try{const e=JSON.parse((await v(r,t.maxBodyBytes)).toString("utf8"))||{},n=N.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:K.revision,stamps:K.stamps()}):s(o,200,{ok:!0,revision:K.revision,sections:K.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=K.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?K.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)}
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
6
 
7
- `);e({type:"hello",revision:K.revision,stamps:K.stamps()});const n=l=>e({type:"changed",...l});xe.add(n);const a=setInterval(()=>{try{o.write(`: keep-alive
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
8
 
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:G.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:G.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:G.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]||"",p=e[4]||"",S=()=>s(o,404,{error:{message:`no project ${n}`,type:"not_found"}});if(p){const h=G.get(n);if(!h)return S();const w=h.jobs.find(f=>f.id===l);if(!w)return s(o,404,{error:{message:`no job ${l}`,type:"not_found"}});const b={cfg:t,prefsStore:K,scorecards:oe,engines:re};if(p==="/applications"&&r.method==="GET"){const f=await to(w,{...b,reach:u.searchParams.get("reach")||"any",chatModel:u.searchParams.get("chatModel")||null});return s(o,200,{ok:!0,job:w,...f})}if(p==="/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),V=await oo(w,{...b,record:h,reach:f.reach||"any",chatModel:f.chatModel||null,evaluation:f.evaluation||null,text:f.text??null,by:_});let J=null;for(const Q of V.events)Q.type==="job.updated"?J=G.updateJob(n,l,Q.job,{by:Q.by||_}):J=G.append(n,[Q]);return s(o,200,{ok:!0,project:J,decision:V.decision,applications:V.applications,evaluation:V.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=G.get(n,{events:u.searchParams.get("events")==="1"});return h?s(o,200,{ok:!0,project:h}):S()}if(!a&&r.method==="DELETE")return s(o,200,{ok:!0,removed:G.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),b=a==="/events"?G.append(n,h.events||[]):l?G.updateJob(n,l,h.patch||h,{by:w}):G.postJob(n,h.job||h,{by:w});return s(o,200,{ok:!0,project:b})}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(!G.get(n))return S();o.writeHead(200,{"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive"});const h=_=>o.write(`data: ${JSON.stringify(_)}
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
10
 
11
- `);let w=u.searchParams.has("after")?Number(u.searchParams.get("after")):-1;h({seq:-1,type:"hello",at:Date.now(),payload:{project:G.get(n),after:w}});const b=G.watch(n,_=>{_.seq>w&&(w=_.seq,h(_))});for(const _ of G.eventsSince(n,w))w=_.seq,h(_);const f=setInterval(()=>{try{o.write(`: keep
11
+ `);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
12
 
13
- `)}catch{}},25e3);r.on("close",()=>{clearInterval(f),b()});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||Fo(n);if(!l)return s(o,400,{error:{message:"model-ledger: engine required",type:"model_ledger_error"}});const p=await re.append({...a,engine:l,kind:a.kind||"call"});return p.key!==n?s(o,400,{error:{message:`model-ledger: entry is for ${p.key}, not ${n}`,type:"model_ledger_error"}}):s(o,200,{ok:!0,entry:p})}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:C.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:C.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=C.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 C.stop(n),s(o,200,{ok:!0,removed:C.remove(n)});if(a==="/stop"&&r.method==="POST"){const l=C.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:C.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"))||{},p=a==="/handoff"?C.handoff(n,{taskId:l.taskId,model:l.model,by:l.by,reason:l.reason}):C.claim(n,{client:l.client});return s(o,200,{ok:!0,run:p})}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:C.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"))||{},p=String(l.by||"person").slice(0,40),S=a==="/answer"?C.answer(n,{threadId:l.threadId,text:l.text,by:p}):a==="/decide"?C.decide(n,{postId:l.postId,status:l.status,by:p}):C.post(n,{threadId:l.threadId,text:l.text,by:p,kind:l.kind,replyTo:l.replyTo});return s(o,200,{ok:!0,run:S})}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:C.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(!C.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=b=>o.write(`data: ${JSON.stringify(b)}
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)}
14
14
 
15
- `),p=u.searchParams.has("after")?Number(u.searchParams.get("after")):NaN;let S=Number.isFinite(p)?p:-1;l({seq:-1,type:"hello",at:Date.now(),payload:{run:C.get(n),after:S}});const h=C.watch(n,b=>{b.seq==null?l(b):b.seq>S&&(S=b.seq,l(b))});for(const b of C.eventsSince(n,S))S=b.seq,l(b);const w=setInterval(()=>{try{o.write(`: keep-alive
15
+ `),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
16
 
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=N.clear();return s(o,200,{ok:!0,dropped:e,size:N.size})}if(c==="/v1/history/search"&&r.method==="POST")try{const e=JSON.parse((await v(r,t.maxBodyBytes)).toString("utf8"))||{},n=N.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:N.size,newest:N.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=Mo(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},p=Math.min(30,Math.max(5,Number(e.limit)||10)*2),S=await Ro(a,w=>N.search(w,{limit:p,...l}),{limit:Math.min(50,Math.max(1,Number(e.limit)||10))}),h=l.type?S:[...S.filter(w=>w.type==="brief"),...S.filter(w=>w.type!=="brief")];return s(o,200,{ok:!0,size:N.size,newest:N.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:N.related(e,{limit:n})})}if(c==="/v1/history/status"&&r.method==="GET")return s(o,200,{ok:!0,size:N.size,newest:N.newest,bytes:N.bytes});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:N.size,bytes:N.bytes,newest:N.newest}},access:Ae.snapshot(e)})}if(c==="/v1/observability/access"&&r.method==="POST")try{const e=JSON.parse((await v(r,t.maxBodyBytes)).toString("utf8"))||{},n=Ae.push(Qe({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/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,...N.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=N.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?Wt(String(e.passphrase)):Kt();const n=e.passphrase?await ve(N,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 ve(N,ze());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 ke(t),B.state()!=="off"){if(!B.isReady()){const n=B.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 B.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=B.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:B.state(),model:t.ner?.model||null})}try{const n=await v(r,t.maxBodyBytes),a=await Me(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:$e(t)});try{let n=e;const a=await q(t.pro?.entitlementToken);await ke(t);const l=await fe([Ce(()=>n,p=>{n=p})],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:$e(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=B.health().model||t.ner?.model||null,n=co.map(a=>({...a,installed:B.modelOnDisk(a.id)}));return e&&!n.some(a=>a.id===e)&&n.push({id:e,label:e,lang:"—",custom:!0,installed:B.modelOnDisk(e),note:"Custom model (from Hugging Face)."}),s(o,200,{active:e,state:B.state(),progress:B.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||!(uo(n)||mo(n)))return s(o,400,{error:{message:"unknown or invalid model id",type:"bad_model"}});Co(t,n);try{te(t,ee())}catch{}return B.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:B.state(),progress:B.progress()})}}if(c==="/stt/models"){if(r.method==="GET"){const e=x.health().model||t.stt?.model||Te,n=po.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:fo})}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||!(yo(n)||ho(n)))return s(o,400,{error:{message:"unknown or invalid model id",type:"bad_model"}});const a=typeof e.dtype=="string"&&go(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 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=$.health();return s(o,200,{active:$.DIARIZE_MODEL,state:e.state,progress:$.progress(),available:[{id:$.DIARIZE_MODEL,label:"Speaker embeddings (wavlm)",lang:"any",approxMB:100,note:"Tells voices apart for meeting transcription (who said what).",installed:$.modelOnDisk()}]})}if(r.method==="POST")return $.download({onLog:e=>console.log(e)}),s(o,202,{accepted:!0,active:$.DIARIZE_MODEL,state:$.state(),progress:$.progress()})}if(c==="/tts/models"){if(r.method==="GET"){const e=k.health().model||t.tts?.model||Ke(_e()),n=_e(),a=Je.find(p=>p.id===e)||null,l=Je.map(p=>({...p,installed:k.modelOnDisk(p.id),unavailable:p.requiresNative&&!n?"needs the npm gateway — the standalone binary cannot load this engine":void 0}));return e&&!l.some(p=>p.id===e)&&l.push({id:e,label:e,lang:"—",tier:"custom",custom:!0,installed:k.modelOnDisk(e),note:"Custom model (from Hugging Face)."}),s(o,200,{active:e,state:k.state(),progress:k.progress(),available:l,voice:t.tts?.voice||(ye(e)==="pocket-tts"?me:Y),arch:k.arch(),supportsVoices:k.arch()?k.supportsVoices():a?a.arch==="style-tts2"&&!!a.voices:!0,supportsCustomVoices:k.arch()?k.supportsCustomVoices():!!a?.customVoices,sampleRate:k.sampleRate(),voices:k.isPocket()||!k.arch()&&ye(e)==="pocket-tts"?(k.builtinVoices().length?k.builtinVoices():_o).map(p=>({id:p,label:p[0].toUpperCase()+p.slice(1),lang:"en",installed:k.builtinVoices().includes(p)})):k.arch()&&k.arch()!=="style-tts2"?[]:bo.map(p=>({...p,installed:k.voiceOnDisk(p.id,e)})),dtype:t.tts?.dtype||"auto",loadedDtype:k.health().dtype,runtime:k.health().runtime,dtypes:So})}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&&!(wo(n)||ko(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 p=L.parseCustomVoice(a);if(!(p?!!L.getVoice(p):pe(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"&&vo(e.dtype)?e.dtype:void 0;if(t.tts||(t.tts={enabled:!0,model:Fe,voice:Y,allowDownload:!0}),n&&(t.tts.model=n),a&&(t.tts.voice=a),n&&!a){const p=To(n),S=L.parseCustomVoice(t.tts.voice||""),h=!!(S&&L.getVoice(S));if(p&&!h)if(ye(n)==="pocket-tts")t.tts.voice=me;else{const b=L.listVoices();t.tts.voice=b.length?`custom:${b[0].id}`:""}else!p&&h&&(t.tts.voice=Y);const w=ye(n)==="pocket-tts";w&&!L.parseCustomVoice(t.tts.voice||"")&&!pe(t.tts.voice)&&(t.tts.voice=me),!w&&pe(t.tts.voice)&&(t.tts.voice=Y)}l&&(t.tts.dtype=l==="auto"?null:l);try{te(t,ee())}catch{}return n&&k.setModel(n,{onLog:p=>console.log(p),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:k.state(),progress:k.progress()})}}if(c==="/tts/voices"){if(r.method==="GET")return s(o,200,{voices:L.listVoices(),usable:k.supportsCustomVoices(),embedder:$.DIARIZE_MODEL,embedderReady:$.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(!L.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,{...L.renameVoice(l,n),usable:k.supportsCustomVoices()})}catch(p){return s(o,400,{error:{message:p.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(!$.isReady()){const f=$.download({onLog:J=>console.log(J)}),_=Symbol("timeout"),V=await Promise.race([f.then(()=>null).catch(J=>J),new Promise(J=>setTimeout(()=>J(_),or))]);if(V===_||!$.isReady())return s(o,503,{error:{message:V===_?"the speaker model is still downloading (~100 MB) — your recording was kept, press Save again shortly":`the speaker model failed to load: ${$.health().error||"unknown error"}`,type:"embedder_not_ready"},progress:$.progress()})}const p=Float32Array.from(a),S=await $.embed(p);let h=null;try{const f=await k.pocketForEncoding({allowDownload:t.tts?.allowDownload!==!1,log:_=>console.log(_)});f&&(h=await f.encodeVoice(rr(p,16e3,24e3)))}catch(f){console.log(`[tts] pocket conditioning unavailable for this voice (${f.message})`)}const w=l?L.replaceVoice(l,{vec:S,pocket:h}):L.saveVoice({name:n,vec:S,pocket:h}),b=l&&n&&n!==w.name?L.renameVoice(l,n):w;return console.log(`[tts] ${l?"re-recorded":"saved"} custom voice "${b.name}" (${(w.kinds||[]).join(" + ")}, sample discarded)`),s(o,l?200:201,{...w,...b,usable:k.supportsCustomVoices()})}catch(p){return s(o,400,{error:{message:p.message,type:"save_failed"}})}}if(r.method==="DELETE"){const e=u.searchParams.get("id")||"",n=L.deleteVoice(e);if(n&&t.tts?.voice===`custom:${e}`){const a=L.listVoices();t.tts.voice=a.length?`custom:${a[0].id}`:Y;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=Oo(t),p=e&&typeof e.voice=="string"&&e.voice.trim()?e.voice.trim():null,S=p||(l?l.voice:t.tts?.voice||Y);if(l&&!xo(S))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:le,contentType:mt,redacted:pt}=await Eo({dest:l,text:n,voice:S,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":mt,"Content-Length":String(le.length),"Cache-Control":"no-store","X-Tts-Provider":l.kind,"X-Tts-Redacted":String(pt)}),o.end(le)}if(!await k.ready({onLog:le=>console.log(le),allowDownload:t.tts?.allowDownload!==!1,model:t.tts?.model||Ke(_e()),dtype:t.tts?.dtype||"auto"}))return s(o,503,{error:{message:k.health().error||"tts model not ready",type:"tts_unavailable"}});const b=Ao({requested:p,configured:S,engine:k,voices:L,isPocketVoice:pe,isKnownVoice:He,isValidVoiceId:Ue,defaultVoice:Y,defaultPocketVoice:me});if(!b.ok)return s(o,b.status,{error:{message:b.message,type:b.type}});const{voice:f,customId:_,speakerEmbedding:V}=b,J=await k.synth(n,{voice:f,speed:a,speakerEmbedding:V}),Q=k.sampleRate(),Ne=h==="pcm"?Buffer.from(new Float32Array(J).buffer):k.toWav(J,Q);return o.writeHead(200,{"Content-Type":h==="pcm"?"application/octet-stream":"audio/wav","Content-Length":String(Ne.length),"Cache-Control":"no-store","X-Tts-Sample-Rate":String(Q),..._||k.isPocket()||k.supportsVoices()?{"X-Tts-Voice":f}:{}}),o.end(Ne)}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||Te,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&&!$.isReady()&&$.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)}
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)}
18
18
 
19
- `),p=a.redact?await q(t.pro?.entitlementToken):!0,S=async f=>{if(f.type!=="final"||!a.redact)return f;try{let _=f.text;return await fe([Ce(()=>_,V=>{_=V})],t.redaction,{isPro:p}),{...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 _=$.state();if(_==="downloading"||_==="loading"){l({type:"diarize-progress",state:_,...$.progress()||{}});return}}l({type:"state",state:f}),clearInterval(h)},500);h.unref?.();let w=Promise.resolve();const b=x.subscribe(n,f=>{w=w.then(async()=>{l(await S(f)),f.type==="end"&&(clearInterval(h),o.end())}).catch(()=>{})});r.on("close",()=>{clearInterval(h),b?.()});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,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"});Bo(t,e),Ie(t);try{te(t,ee())}catch(S){return s(o,500,{error:`could not persist config: ${S.message}`})}const n=t.redaction?.detection,a=!n||!n.backend||n.backend==="off",l=B.state();t.ner?.autostart&&a&&l!=="ready"&&l!=="loading"&&l!=="downloading"&&B.setModel(t.ner.model,{onLog:S=>console.log(S)}).then(S=>{S&&t.ner?.enableFullTier&&t.redaction.tier!=="full"&&(t.redaction.tier="full")});const p=await q(t.pro?.entitlementToken);return s(o,200,Ze(t,{proUnlocked:p}))}if(r.method==="GET"&&c==="/skills"){const e=await de(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`,{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 de(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)}`,{headers:{Accept:"application/json",...a?{Authorization:`Bearer ${a}`}:{}},signal:AbortSignal.timeout(8e3)}),p=await l.json().catch(()=>({}));return l.ok?s(o,200,{skill:p?.skill||null}):s(o,l.status,{error:{message:p?.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 Do(t));if(nr.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 y=Ko(c,r.headers,t);let g;try{g=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,m=null,M=g,A=0,D=0,Z=0,R=!1,j=!0;const P=t.logRequests&&y.redactable&&r.method==="POST"?Wo(d):null;if(y.redactable&&r.method==="POST"&&g.length){try{m=JSON.parse(g.toString("utf8"))}catch{m=null}if(m&&Zo(m,y.kind))M=g;else if(m){const e=t.tools||{};if(e.autoNarrow!==!1&&Array.isArray(m.tools)&&m.tools.length){const b=Number(e.maxPerTurn)>0?Number(e.maxPerTurn):Lo,f=e.narrowAll?null:V=>!Go.test(ot(V)),_=m.tools.length;m.tools=vt(m.tools,Vo(m,y.kind),{cap:b,keep:f,name:ot,description:zo}),Z=_-m.tools.length}j=await q(t.pro?.entitlementToken);const n=Po(t,j);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"}});R=String(r.headers["x-chatpanel-redaction"]||"").trim().toLowerCase()==="off"&&F(r),R||await ke(t);const a=R?[]:y.adapter.collectSegments(m,t.redaction),l=new AbortController;o.on("close",()=>{o.writableFinished||l.abort()});const p=P?P.clock():0,{vault:S,count:h,sanitized:w}=R?{vault:null,count:0,sanitized:0}:await fe(a,t.redaction,{signal:l.signal,isPro:j,onEgress:b=>Ae.push(Qe({ts:Date.now(),client:"redaction",tool:`detect:${b.backend}@${b.host||"local"}`,ok:b.ok,ms:b.ms,error:b.error}))});if(P&&P.lap("redact",p),E=S,A=h,D=w||0,!j&&h>0){$o(t,j);try{te(t,ee())}catch{}}if(!R&&Array.isArray(m.tools)&&m.tools.length&&typeof y.adapter.injectSystemNote=="function"){const b=Xe(m?.model,t,y.kind,{destination:String(r.headers["x-chatpanel-destination"]||m?.chatpanel?.destination||"").trim()}),f=!(b&&b.type==="api");y.adapter.injectSystemNote(m,_t({toolData:t.tools?.toolData,ownTools:f}))}else!R&&h>0&&typeof y.adapter.injectSystemNote=="function"&&y.adapter.injectSystemNote(m,Ot());M=Buffer.from(JSON.stringify(m),"utf8")}}const O=Tt({vault:E,toolData:t.tools?.toolData}),I=m&&typeof m.chatpanel=="object"&&m.chatpanel||null;I&&(delete m.chatpanel,M=Buffer.from(JSON.stringify(m),"utf8"));const z={destination:String(r.headers["x-chatpanel-destination"]||I?.destination||"").trim(),reach:String(r.headers["x-chatpanel-reach"]||I?.reach||"").trim(),run:ir(r.headers["x-chatpanel-run"],I?.run)},T=Xe(m?.model,t,y.kind,{destination:z.destination});if(z.destination&&(!T||T.id!==z.destination))return P?.commit(),s(o,404,{error:{message:`no destination "${z.destination}" is configured on this gateway`,type:"unknown_destination",known:Io(t).map(e=>e.id)}});P&&(P.meta={t:Date.now(),model:m?.model||null,dest:T?T.id:null,type:T?T.type:null,redacted:A,sanitized:D,narrowed:Z,detail:it(E,t.logDetail),redaction:R?"off":t.redaction.tier||"basic"});const U=jt();if(U&&T){const e=T.type==="api"?je(U,{model:m?.model||"",endpoint:T.baseUrl||""}):Rt(U,T.agent||T.id)?je(U,{model:m?.model||""}):{ok:!1,reason:`agent "${T.agent||T.id}" is not allowed by your organisation’s policy`};if(!e.ok)return P?.commit(),s(o,403,{error:{message:e.reason,type:"policy",code:"org_policy"}})}if(T&&T.type==="api")return T.baseUrl?Yo(T.baseUrl,t)?(P?.commit(),s(o,508,{error:{message:`destination "${T.id}" points back at the gateway (${T.baseUrl}) — refusing to forward (would loop).`,type:"loop_detected"}})):sr(r,o,{...y,pathname:c,search:u.search,base:T.baseUrl,destKey:T.apiKey,destProtocol:T.protocol,harness:O,trace:P},M,E):(P?.commit(),s(o,502,{error:`destination "${T.id}" has no baseUrl`}));const X=ce(r),ne=X==="local"&&t.bridge?.openAgentLane?"token":X;if(ne==="local")return P?.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=xt({...z.run||{},...z.reach?{reach:z.reach}:{}},ne);return er(r,o,{...y,pathname:c,agentOverride:T?.agent,harness:O,trace:P,run:Object.keys(se).length?se:null},m,E,t,j)})}function ir(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 he=null;async function Yr(t=Be()){Ft();let i=null;try{i=await It()}catch(y){throw y instanceof Mt&&(console.error(`[chatpanel-gateway] org policy: ${y.message}`),process.exit(78)),y}const d=i?.policy||null;d&&(Ie(t,d),console.log(`[chatpanel-gateway] ${i.label} — ${i.signed?"signed":"unsigned"} policy from ${i.source}`)),Ct(globalThis,{allow:d?.egress?(y,{local:g})=>Lt(d,y,{local:g}):null}),ge();const r=ar(t),o=Ut(t),u=ht(t);r.on("error",y=>{y&&y.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: ${y?.message||y}`),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"),ro(t).then(y=>{he=y}).catch(y=>console.log(` bridge : not supervised (${y?.message||y})`)),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()&&ve(N,ze()).then(y=>{y?.ok&&console.log(` warm : seeded ${y.ingested} records from ${y.file}`)}).catch(()=>{});const c=()=>{o?.stop(),u.stop(),he?.stop(),r.close(()=>process.exit(0))};return process.on("SIGINT",c),process.on("SIGTERM",c),r}export{W as VERSION,ar as createGateway,tr as joinUpstream,Pe as parseAgentModel,Yr as start};
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};
@@ -1,6 +1,6 @@
1
- import{join as E}from"node:path";import{mkdirSync as T,chmodSync as u,existsSync as p,statSync as b}from"node:fs";import m from"node:os";import{HistoryStore as R}from"./history-store.js";const h=E(m.homedir(),".chatpanel"),y=process.env.CHATPANEL_HISTORY_DB||E(h,"history.db");if(typeof Bun>"u"){const c=process.emitWarning.bind(process);process.emitWarning=(e,...s)=>typeof e=="string"&&e.includes("SQLite is an experimental")?void 0:c(e,...s)}async function S(c){if(typeof Bun<"u"){const{Database:r}=await import("bun:sqlite"),n=new r(c,{create:!0});return{exec:o=>n.run(o),run:(o,i=[])=>n.prepare(o).run(...i),all:(o,i=[])=>n.query(o).all(...i),get:(o,i=[])=>n.query(o).get(...i)}}const e="node:sqlite",{DatabaseSync:s}=await import(e),t=new s(c);return{exec:r=>t.exec(r),run:(r,n=[])=>t.prepare(r).run(...n),all:(r,n=[])=>t.prepare(r).all(...n),get:(r,n=[])=>t.prepare(r).get(...n)}}function f(c){const e=String(c||"").toLowerCase().match(/[a-z0-9][a-z0-9'_+-]*/g);return!e||!e.length?null:e.map(s=>`"${s.replace(/"/g,'""')}"`).join(" OR ")}class O{constructor({path:e=y}={}){this.path=e,this.db=null}async init(){if(this.path!==":memory:"){T(h,{recursive:!0,mode:448});try{u(h,448)}catch{}}if(this.db=await S(this.path),this.db.exec("PRAGMA journal_mode=WAL"),this.db.exec("CREATE TABLE IF NOT EXISTS records(id TEXT PRIMARY KEY, title TEXT, type TEXT, date INTEGER, chars INTEGER)"),this.db.exec("CREATE VIRTUAL TABLE IF NOT EXISTS fts USING fts5(id UNINDEXED, title, text, tokenize='unicode61')"),this.path!==":memory:")for(const e of[this.path,this.path+"-wal",this.path+"-shm"])try{p(e)&&u(e,384)}catch{}return this}load(){return this}get size(){return this.db.get("SELECT COUNT(*) c FROM records")?.c||0}get newest(){return this.db.get("SELECT MAX(date) m FROM records")?.m||0}get bytes(){if(this.path===":memory:")return 0;let e=0;for(const s of[this.path,`${this.path}-wal`,`${this.path}-shm`])try{p(s)&&(e+=b(s).size)}catch{}return e}bulk({upserts:e=[],removes:s=[]}={}){this.db.exec("BEGIN");try{for(const t of s)this.db.run("DELETE FROM records WHERE id = ?",[t]),this.db.run("DELETE FROM fts WHERE id = ?",[t]);for(const t of e){if(!t||!t.id)continue;const r=String(t.text||"");this.db.run("DELETE FROM fts WHERE id = ?",[t.id]),this.db.run("INSERT INTO fts(id, title, text) VALUES(?, ?, ?)",[t.id,t.title||"",r]),this.db.run("INSERT OR REPLACE INTO records(id, title, type, date, chars) VALUES(?, ?, ?, ?, ?)",[t.id,t.title||"",t.type||"",t.date||0,r.length])}this.db.exec("COMMIT")}catch(t){throw this.db.exec("ROLLBACK"),t}return this.size}search(e,{limit:s=10,offset:t=0,type:r=null,since:n=null,before:o=null}={}){const i=f(e);if(!i)return[];const a=["fts MATCH ?"],l=[i];return r&&(a.push("r.type = ?"),l.push(String(r))),n!=null&&(a.push("r.date >= ?"),l.push(Number(n))),o!=null&&(a.push("r.date <= ?"),l.push(Number(o))),l.push(s,t),this.db.all(`SELECT r.id id, r.title title, r.type type, r.date date, bm25(fts) b,
1
+ import{join as E}from"node:path";import{mkdirSync as m,chmodSync as u,existsSync as p,statSync as T}from"node:fs";import b from"node:os";import{HistoryStore as R}from"./history-store.js";import{LosslessStore as y}from"./lossless-store.js";const h=E(b.homedir(),".chatpanel"),S=process.env.CHATPANEL_HISTORY_DB||E(h,"history.db");if(typeof Bun>"u"){const c=process.emitWarning.bind(process);process.emitWarning=(e,...r)=>typeof e=="string"&&e.includes("SQLite is an experimental")?void 0:c(e,...r)}async function O(c){if(typeof Bun<"u"){const{Database:s}=await import("bun:sqlite"),n=new s(c,{create:!0});return{exec:o=>n.run(o),run:(o,i=[])=>n.prepare(o).run(...i),all:(o,i=[])=>n.query(o).all(...i),get:(o,i=[])=>n.query(o).get(...i)}}const e="node:sqlite",{DatabaseSync:r}=await import(e),t=new r(c);return{exec:s=>t.exec(s),run:(s,n=[])=>t.prepare(s).run(...n),all:(s,n=[])=>t.prepare(s).all(...n),get:(s,n=[])=>t.prepare(s).get(...n)}}function f(c){const e=String(c||"").toLowerCase().match(/[a-z0-9][a-z0-9'_+-]*/g);return!e||!e.length?null:e.map(r=>`"${r.replace(/"/g,'""')}"`).join(" OR ")}class g{constructor({path:e=S}={}){this.path=e,this.db=null}async init(){if(this.path!==":memory:"){m(h,{recursive:!0,mode:448});try{u(h,448)}catch{}}if(this.db=await O(this.path),this.db.exec("PRAGMA journal_mode=WAL"),this.db.exec("CREATE TABLE IF NOT EXISTS records(id TEXT PRIMARY KEY, title TEXT, type TEXT, date INTEGER, chars INTEGER)"),this.db.exec("CREATE VIRTUAL TABLE IF NOT EXISTS fts USING fts5(id UNINDEXED, title, text, tokenize='unicode61')"),this.lossless=new y(this.db).init(),this.path!==":memory:")for(const e of[this.path,this.path+"-wal",this.path+"-shm"])try{p(e)&&u(e,384)}catch{}return this}load(){return this}get size(){return this.db.get("SELECT COUNT(*) c FROM records")?.c||0}get newest(){return this.db.get("SELECT MAX(date) m FROM records")?.m||0}get bytes(){if(this.path===":memory:")return 0;let e=0;for(const r of[this.path,`${this.path}-wal`,`${this.path}-shm`])try{p(r)&&(e+=T(r).size)}catch{}return e}bulk({upserts:e=[],removes:r=[]}={}){this.db.exec("BEGIN");try{for(const t of r)this.db.run("DELETE FROM records WHERE id = ?",[t]),this.db.run("DELETE FROM fts WHERE id = ?",[t]);for(const t of e){if(!t||!t.id)continue;const s=String(t.text||"");this.db.run("DELETE FROM fts WHERE id = ?",[t.id]),this.db.run("INSERT INTO fts(id, title, text) VALUES(?, ?, ?)",[t.id,t.title||"",s]),this.db.run("INSERT OR REPLACE INTO records(id, title, type, date, chars) VALUES(?, ?, ?, ?, ?)",[t.id,t.title||"",t.type||"",t.date||0,s.length])}this.db.exec("COMMIT")}catch(t){throw this.db.exec("ROLLBACK"),t}return this.size}search(e,{limit:r=10,offset:t=0,type:s=null,since:n=null,before:o=null}={}){const i=f(e);if(!i)return[];const d=["fts MATCH ?"],l=[i];return s&&(d.push("r.type = ?"),l.push(String(s))),n!=null&&(d.push("r.date >= ?"),l.push(Number(n))),o!=null&&(d.push("r.date <= ?"),l.push(Number(o))),l.push(r,t),this.db.all(`SELECT r.id id, r.title title, r.type type, r.date date, bm25(fts) b,
2
2
  snippet(fts, 2, '«', '»', ' … ', 12) snip
3
3
  FROM fts JOIN records r ON r.id = fts.id
4
- WHERE ${a.join(" AND ")} ORDER BY b LIMIT ? OFFSET ?`,l).map(d=>({id:d.id,score:-d.b,title:d.title,type:d.type,date:d.date,snippet:d.snip||""}))}related(e,{limit:s=5}={}){const t=this.get(e);if(!t)return[];const r=f(`${t.title||""} ${String(t.text||"").slice(0,2e3)}`);if(!r)return[];const n=r.split(" OR ").slice(0,40).join(" OR ");return this.db.all(`SELECT r.id id, r.title title, r.type type, r.date date, bm25(fts) b
4
+ WHERE ${d.join(" AND ")} ORDER BY b LIMIT ? OFFSET ?`,l).map(a=>({id:a.id,score:-a.b,title:a.title,type:a.type,date:a.date,snippet:a.snip||""}))}related(e,{limit:r=5}={}){const t=this.get(e);if(!t)return[];const s=f(`${t.title||""} ${String(t.text||"").slice(0,2e3)}`);if(!s)return[];const n=s.split(" OR ").slice(0,40).join(" OR ");return this.db.all(`SELECT r.id id, r.title title, r.type type, r.date date, bm25(fts) b
5
5
  FROM fts JOIN records r ON r.id = fts.id
6
- WHERE fts MATCH ? AND r.id != ? ORDER BY b LIMIT ?`,[n,e,s]).map(i=>({id:i.id,score:-i.b,title:i.title,type:i.type,date:i.date}))}list({limit:e=50,offset:s=0,type:t=null}={}){const r=t?" WHERE type = ?":"",n=t?[String(t)]:[],o=this.db.get(`SELECT COUNT(*) c FROM records${r}`,n)?.c||0,i=this.db.all(`SELECT id, title, type, date, chars FROM records${r} ORDER BY date DESC LIMIT ? OFFSET ?`,[...n,e,s]);return{total:o,items:i}}get(e,{maxChars:s=null,offset:t=0}={}){const r=this.db.get("SELECT id, title, type, date FROM records WHERE id = ?",[e]);if(!r)return null;const o=this.db.get("SELECT text FROM fts WHERE id = ?",[e])?.text||"";let i=t?o.slice(t):o,a=!1;return s&&i.length>s&&(i=i.slice(0,s),a=!0),{...r,text:i,totalChars:o.length,offset:Number(t)||0,truncated:a}}clear(){const e=this.size;return this.db.exec("DELETE FROM records"),this.db.exec("DELETE FROM fts"),e}}async function x(c={}){try{return await new O(c).init()}catch(e){return console.log(`[warm] SQLite unavailable (${e.message}); using the encrypted file store`),new R(c).load()}}export{O as SqliteHistoryStore,x as createHistoryStore};
6
+ WHERE fts MATCH ? AND r.id != ? ORDER BY b LIMIT ?`,[n,e,r]).map(i=>({id:i.id,score:-i.b,title:i.title,type:i.type,date:i.date}))}list({limit:e=50,offset:r=0,type:t=null}={}){const s=t?" WHERE type = ?":"",n=t?[String(t)]:[],o=this.db.get(`SELECT COUNT(*) c FROM records${s}`,n)?.c||0,i=this.db.all(`SELECT id, title, type, date, chars FROM records${s} ORDER BY date DESC LIMIT ? OFFSET ?`,[...n,e,r]);return{total:o,items:i}}get(e,{maxChars:r=null,offset:t=0}={}){const s=this.db.get("SELECT id, title, type, date FROM records WHERE id = ?",[e]);if(!s)return null;const o=this.db.get("SELECT text FROM fts WHERE id = ?",[e])?.text||"";let i=t?o.slice(t):o,d=!1;return r&&i.length>r&&(i=i.slice(0,r),d=!0),{...s,text:i,totalChars:o.length,offset:Number(t)||0,truncated:d}}clear(){const e=this.size;return this.db.exec("DELETE FROM records"),this.db.exec("DELETE FROM fts"),e}}async function w(c={}){try{return await new g(c).init()}catch(e){console.log(`[warm] SQLite unavailable (${e.message}); using the encrypted file store`);const r=new R(c).load();return r.lossless=null,r}}export{g as SqliteHistoryStore,w as createHistoryStore};