@chatpanel/gateway 0.6.110 → 0.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (81) hide show
  1. package/README.md +24 -4
  2. package/bin/chatpanel-gateway-bin.mjs +1 -24
  3. package/bin/chatpanel-gateway.js +3 -97
  4. package/package.json +2 -7
  5. package/src/access-log-store.js +1 -45
  6. package/src/agent.js +2 -256
  7. package/src/anthropic.js +3 -83
  8. package/src/backup-decrypt.js +1 -45
  9. package/src/backup-ingest.js +6 -120
  10. package/src/bridge-supervisor.js +3 -212
  11. package/src/bridge.js +4 -252
  12. package/src/budget.js +1 -117
  13. package/src/config.js +1 -209
  14. package/src/configstore.js +1 -181
  15. package/src/connect-agents.js +22 -179
  16. package/src/diarize-engine.js +1 -188
  17. package/src/egress.js +2 -0
  18. package/src/engine-ledger-store.js +1 -150
  19. package/src/engine.js +1 -132
  20. package/src/entitlement-refresh.js +1 -84
  21. package/src/entitlement.js +1 -76
  22. package/src/extraction.js +4 -294
  23. package/src/freegate.js +1 -47
  24. package/src/gate.js +1 -75
  25. package/src/gateway-token.js +1 -60
  26. package/src/history-store.js +1 -251
  27. package/src/job.js +3 -148
  28. package/src/knowledge.js +3 -215
  29. package/src/local-status.js +6 -102
  30. package/src/log.js +1 -21
  31. package/src/mcp-cli.js +19 -113
  32. package/src/mcp.js +34 -546
  33. package/src/memory-store.js +1 -176
  34. package/src/memory.js +2 -642
  35. package/src/model-integrity.js +1 -82
  36. package/src/model-ledger.js +1 -229
  37. package/src/model-runtime.js +1 -37
  38. package/src/models.js +1 -92
  39. package/src/ner-engine.js +1 -318
  40. package/src/ner.js +1 -113
  41. package/src/observability.js +1 -123
  42. package/src/openai.js +2 -84
  43. package/src/ort.js +1 -52
  44. package/src/parakeet-engine.js +2 -228
  45. package/src/pocket-tts-engine.js +1 -520
  46. package/src/policy.js +2 -0
  47. package/src/prefs-store.js +1 -149
  48. package/src/project-store.js +1 -139
  49. package/src/project.js +1 -171
  50. package/src/recruit.js +3 -424
  51. package/src/recruiting.js +1 -93
  52. package/src/redact.js +2 -123
  53. package/src/responses.js +2 -80
  54. package/src/router.js +1 -292
  55. package/src/rrf.js +1 -93
  56. package/src/scorecard-store.js +1 -92
  57. package/src/scorecard.js +1 -336
  58. package/src/search-index.js +2 -134
  59. package/src/secure-fetch.js +1 -58
  60. package/src/sentencepiece.js +1 -184
  61. package/src/server.js +10 -2296
  62. package/src/service.js +11 -189
  63. package/src/shape.js +5 -121
  64. package/src/sqlite-store.js +3 -212
  65. package/src/stream.js +5 -182
  66. package/src/structured.js +4 -902
  67. package/src/stt-engine.js +1 -486
  68. package/src/stt-models.js +1 -144
  69. package/src/subject-kinds.js +1 -6
  70. package/src/subject-name.js +1 -97
  71. package/src/team-board.js +6 -338
  72. package/src/team-record.js +1 -226
  73. package/src/team-store.js +1 -261
  74. package/src/team.js +1 -303
  75. package/src/toolrelay.js +3 -122
  76. package/src/tts-engine.js +1 -453
  77. package/src/tts-models.js +1 -254
  78. package/src/tts-remote.js +1 -109
  79. package/src/tts-voice-resolve.js +1 -78
  80. package/src/tts-voices.js +1 -192
  81. package/src/update.js +1 -305
package/src/server.js CHANGED
@@ -1,2305 +1,19 @@
1
- // ChatPanel Privacy Gateway — a localhost server that redacts PII out of every
2
- // LLM request, then restores the placeholders in the reply. The model only ever
3
- // sees [[PERSON_1]] / [[EMAIL_2]] — the real values never leave the machine.
4
- //
5
- // Two backends (see config.js):
6
- // 'bridge' — drive the ChatPanel bridge's subscription-authed CLI agents
7
- // (codex/claude/opencode/pi). This is the privacy-bridge-between-
8
- // agents path: opencode → gateway (redact) → bridge → codex → restore.
9
- // 'api' — forward redacted traffic to a native provider API (local models,
10
- // BYO keys). The client's own auth header is passed through verbatim.
11
- //
12
- // GET /health → { ok, version, backend, tier }
13
- // GET /v1/models → list the agent(s) this gateway exposes
14
- // POST /v1/chat/completions → OpenAI protocol
15
- // POST /v1/responses → OpenAI Responses protocol (Codex)
16
- // POST /v1/messages → Anthropic protocol
17
- //
18
- // Binds 127.0.0.1 only and enforces a loopback Host (anti DNS-rebinding).
1
+ import{createServer as dt}from"node:http";import{loadConfig as xe}from"./config.js";import{startEntitlementRefresh as ut,maybeRevalidate as mt}from"./entitlement-refresh.js";import{redactSegments as me,segment as Ae}from"./redact.js";import{pipeRestoredStream as pt,pipeRestoredOpenAIStream as yt,makeTokenRestorer as Pe,restoreDeep as ht}from"./stream.js";import{restoreText as ft,gatedDictionary as gt,narrowSpecs as bt,makeToolHarness as wt,placeholderToolNote as kt,placeholderNote as St,assertEndpointUrl as vt}from"@chatpanel/pii";import{ensureGatewayToken as $e,isAdminAuthorized as K}from"./gateway-token.js";import{installEgressLedger as Tt,egressAudit as _t}from"./egress.js";import{initPolicy as Ot,activePolicy as Et,applyPolicyToConfig as Ne,managedSummary as re,PolicyLoadError as xt}from"./policy.js";import{routeAllowed as Be,agentAllowed as At,egressAllowed as Pt}from"@chatpanel/events/policy.js";import{resolveBridgeUrl as se}from"./bridge.js";import{secureFetch as Ce}from"./secure-fetch.js";import{streamBridgeChat as De,readBridgeToken as ae,openBridgeChat as $t}from"./bridge.js";import{createRelaySession as Nt,getRelaySession as je,endRelaySession as ie,pumpBridgeStream as Bt,deliverToolResult as Ct,toolsToSpecs as Dt,parseToolCallId as Ie,touchRelaySession as pe}from"./toolrelay.js";import{shaperFor as ye}from"./shape.js";import{startNer as jt,ensureNer as he}from"./ner.js";import{installTimestampedConsole as It}from"./log.js";import{saveBackupSecret as Mt,clearBackupSecret as Rt,loadBackupSecret as Me,hasBackupSecret as Re}from"./history-store.js";import{createMemoryStore as Lt}from"./memory-store.js";import{createPrefsStore as Gt}from"./prefs-store.js";import{createTeamStore as zt,loadOrCreateKey as fe}from"./team-store.js";import{createScorecardStore as Vt}from"./scorecard-store.js";import{createEngineLedgerStore as Jt}from"./engine-ledger-store.js";import{createProjectStore as Ht}from"./project-store.js";import{applicationsFor as Ut,recruitPass as Ft}from"./recruiting.js";import{ensureBridge as Wt}from"./bridge-supervisor.js";import{checkForUpdate as Kt,updateStatus as Zt,startUpdate as Yt,updateJob as Xt}from"./update.js";import{createHistoryStore as Qt}from"./sqlite-store.js";import{ingestBackups as ge}from"./backup-ingest.js";import*as B from"./ner-engine.js";import*as x from"./stt-engine.js";import*as P from"./diarize-engine.js";import{MODEL_CATALOG as qt,isKnownModel as eo,isValidCustomModelId as to}from"./models.js";import{STT_MODEL_CATALOG as oo,isKnownSttModel as ro,isValidCustomSttId as no,DEFAULT_STT_MODEL as be,STT_DTYPES as so,isValidDtype as ao}from"./stt-models.js";import*as S from"./tts-engine.js";import{TTS_MODEL_CATALOG as Le,TTS_VOICES as io,isKnownTtsModel as lo,isValidCustomTtsId as co,isKnownVoice as Ge,isValidVoiceId as ze,DEFAULT_TTS_MODEL as Ve,DEFAULT_TTS_VOICE as Y,TTS_DTYPES as uo,isValidTtsDtype as mo,MAX_TTS_CHARS as Je,ttsModelHasCustomVoices as po,resolveDefaultModel as He,POCKET_VOICES as yo,DEFAULT_POCKET_VOICE as le,isPocketVoice as ce,ttsModelEngine as de}from"./tts-models.js";import{ttsDestination as ho,synthesizeRemote as fo,isValidRemoteVoice as go}from"./tts-remote.js";import{rawOrtAvailable as we}from"./ort.js";import*as L from"./tts-voices.js";import{resolveTtsVoice as bo}from"./tts-voice-resolve.js";import{resolvePro as Q,checkQuota as wo,consume as ko,usage as So}from"./freegate.js";import{publicConfig as Ue,applyConfigPatch as vo,applyNerModelSelection as To,persistConfig as ee,configPath as q,bridgeAgentOptions as Fe}from"./configstore.js";import{resolveDestination as We,aggregateModelsAsync as _o,listDestinations as Oo}from"./router.js";import{makeAccessEvent as Ke}from"./observability.js";import{createPersistentAccessLog as Eo}from"./access-log-store.js";import{planQueries as xo,multiSearch as Ao}from"./rrf.js";import*as ke from"./openai.js";import*as Ze from"./responses.js";import*as Se from"./anthropic.js";const Z="0.8.0",$=await Qt(),J=await Lt(),F=Gt(),te=Vt({key:fe()}),oe=Jt({key:fe()}),G=Ht({key:fe()}),C=zt({scorecards:te,engines:oe}),ve=new Set,Ye=(t,l)=>{for(const d of ve)try{d({applied:t,by:l,revision:F.revision})}catch{}},Te=Eo(),Xe=new Set(["codex","claude","opencode","pi","kiro","antigravity","hermes"]),Po=16,$o=/^mcp[_-]/i,Qe=t=>t&&t.function&&t.function.name||t&&t.name||"",No=t=>t&&t.function&&t.function.description||t&&t.description||"";function qe(t){return typeof t=="string"?t:Array.isArray(t)?t.map(l=>typeof l=="string"?l:l&&(l.text||l.content)||"").join(" "):""}function Bo(t,l){if(!t)return"";if(l==="responses"){const r=t.input;return typeof r=="string"?r:Array.isArray(r)?r.map(o=>qe(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 qe(d[r].content);return""}const et=new Set(["host","connection","content-length","transfer-encoding","accept-encoding","content-encoding","keep-alive"]);function tt(t){if(!t)return!1;const l=t.replace(/:\d+$/,"").replace(/^\[|\]$/g,"");return l==="localhost"||l==="127.0.0.1"||l==="::1"}function Co(t,l){return!t||/^chrome-extension:\/\//.test(t)||/^moz-extension:\/\//.test(t)||/^http:\/\/(localhost|127\.0\.0\.1|\[::1\])(:\d+)?$/.test(t)?!0:Array.isArray(l.allowedOrigins)&&l.allowedOrigins.includes(t)}function Do(t,l){t.setHeader("Access-Control-Allow-Origin",l||"*"),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 ot=Date.now();function jo(t){if(!t)return"";const l={redact:"redact",upstream:"model",stream:"stream",restore:"restore",total:"total"};return Object.keys(t).map(d=>`${l[d]||d} ${t[d]}ms`).join(" · ")}function Io(t){const l=/^(model|harness):([^/]+)(?:\/(.+))?$/.exec(String(t||""));return l?{kind:l[1],id:l[2],...l[3]?{model:l[3]}:{}}:null}function Mo(t){const l=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()-l);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}`:""} · ${jo(d)}`)})}}}function rt(t,l){if(!t||!t.byToken||l!=="types"&&l!=="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",h=r.replace(/^\[\[|\]\]$/g,"");d.push(l==="values"?{token:h,type:c,value:o}:{token:h,type:c})}return d}function Ro(t,l,d){return Se.matches(t)||"anthropic-version"in l?{kind:"anthropic",adapter:Se,redactable:Se.matches(t),base:d.upstreams?.anthropic?.baseUrl}:Ze.matches(t)?{kind:"responses",adapter:Ze,redactable:!0,base:d.upstreams?.openai?.baseUrl}:{kind:"openai",adapter:ke,redactable:ke.matches(t),base:d.upstreams?.openai?.baseUrl}}function _e(t,l){const d=String(t||"");if(Xe.has(d))return{agent:d,agentModel:""};const r=d.indexOf("/");if(r>0){const o=d.slice(0,r);if(Xe.has(o))return{agent:o,agentModel:d.slice(r+1)}}return{agent:l.bridge.agent,agentModel:""}}function nt(t,l){return _e(t,l).agent}function Lo(t,l){if(l!=="openai"||!t)return!1;const d=ke.extractLatestToolResult(t);if(!d)return!1;const r=Ie(d.tool_call_id);return!!(r&&je(r.gwId))}function Go(t,l){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(l.port)}catch{return!1}}async function T(t,l){const d=[];let r=0;for await(const o of t){if(r+=o.length,l&&r>l){const u=new Error("payload too large");throw u.code=413,u}d.push(o)}return Buffer.concat(d)}function s(t,l,d){t.writeHead(l,{"content-type":"application/json"}),t.end(JSON.stringify(d))}function st(t){const l=t.redaction?.detection?.url;return!l||t.redaction?.detection?.backend==="off"?null:l}function Oe(t){const l=t?.redaction?.detection,d=t?.redaction?.tier==="full"?"full":"basic";if(l&&l.backend&&l.backend!=="off")return{source:"external",backend:l.backend,state:"external",model:l.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 at(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 l=st(t);if(!l)return{configured:!1,ok:!1,url:null,model:null};try{const d=await Ce(l.replace(/\/ner\/?$/,"")+"/health",{signal:AbortSignal.timeout(2e3)});if(!d.ok)return{configured:!0,ok:!1,url:l,model:null};const r=await d.json().catch(()=>({}));return{configured:!0,ok:!0,url:l,model:r.model||null}}catch{return{configured:!0,ok:!1,url:l,model:null}}}function zo(t,l){const d={};for(const[r,o]of Object.entries(t)){const u=r.toLowerCase();u.startsWith("x-chatpanel-")||et.has(u)||(d[r]=o)}d["accept-encoding"]="identity";try{d.host=new URL(l).host}catch{}return d}async function it(t,l,d,r){const o=Pe(l.vault),u=r?r.clock():0;let c=u,h=!0;const b=()=>{r&&h&&(r.lap("upstream",u),c=r.clock(),h=!1)};await Bt(l,{onText:E=>{b(),pe(l.id);const p=o.push(E);p&&t.write(d.sseDelta(p))},onToolRequest:({name:E,restoredArgs:p,toolId:M})=>{b(),pe(l.id);const A=o.flush();A&&t.write(d.sseDelta(A)),t.write(d.sseToolCalls([{id:M,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(),ie(l.id),r?.commit()},onError:E=>{t.write(`data: ${JSON.stringify({error:{message:E.message,type:"bridge_error"}})}
19
2
 
20
- import { createServer } from 'node:http';
21
- import { loadConfig } from './config.js';
22
- import { startEntitlementRefresh, maybeRevalidate } from './entitlement-refresh.js';
23
- import { redactSegments, segment } from './redact.js';
24
- import { pipeRestoredStream, pipeRestoredOpenAIStream, makeTokenRestorer, restoreDeep } from './stream.js';
25
- import { restoreText, gatedDictionary, narrowSpecs, makeToolHarness, placeholderToolNote, placeholderNote, assertEndpointUrl } from '@chatpanel/pii';
26
- import { ensureGatewayToken, isAdminAuthorized } from './gateway-token.js';
27
- import { resolveBridgeUrl } from './bridge.js';
28
- import { secureFetch } from './secure-fetch.js';
29
- import { streamBridgeChat, readBridgeToken, openBridgeChat } from './bridge.js';
30
- import { createRelaySession, getRelaySession, endRelaySession, pumpBridgeStream, deliverToolResult, toolsToSpecs, parseToolCallId, touchRelaySession } from './toolrelay.js';
31
- import { shaperFor } from './shape.js';
32
- import { startNer, ensureNer } from './ner.js';
33
- import { installTimestampedConsole } from './log.js';
34
- import { saveBackupSecret, clearBackupSecret, loadBackupSecret, hasBackupSecret } from './history-store.js';
35
- import { createMemoryStore } from './memory-store.js';
36
- import { createPrefsStore } from './prefs-store.js';
37
- import { createTeamStore, loadOrCreateKey as loadTeamKey } from './team-store.js';
38
- import { createScorecardStore } from './scorecard-store.js';
39
- import { createEngineLedgerStore } from './engine-ledger-store.js';
40
- import { createProjectStore } from './project-store.js';
41
- import { applicationsFor, recruitPass } from './recruiting.js';
42
- import { ensureBridge } from './bridge-supervisor.js';
43
- import { checkForUpdate, updateStatus, startUpdate, updateJob } from './update.js';
44
- import { createHistoryStore } from './sqlite-store.js';
45
- import { ingestBackups } from './backup-ingest.js';
46
- import * as nerEngine from './ner-engine.js';
47
- import * as sttEngine from './stt-engine.js';
48
- import * as diarizeEngine from './diarize-engine.js';
49
- import { MODEL_CATALOG, isKnownModel, isValidCustomModelId } from './models.js';
50
- import { STT_MODEL_CATALOG, isKnownSttModel, isValidCustomSttId, DEFAULT_STT_MODEL, STT_DTYPES, isValidDtype } from './stt-models.js';
51
- import * as ttsEngine from './tts-engine.js';
52
- import { TTS_MODEL_CATALOG, TTS_VOICES, isKnownTtsModel, isValidCustomTtsId, isKnownVoice, isValidVoiceId, DEFAULT_TTS_MODEL, DEFAULT_TTS_VOICE, TTS_DTYPES, isValidTtsDtype, MAX_TTS_CHARS, ttsModelHasCustomVoices, ttsModelRequiresNative, resolveDefaultModel, POCKET_VOICES, DEFAULT_POCKET_VOICE, isPocketVoice, ttsModelEngine as ttsModelEngineOf } from './tts-models.js';
53
- import { ttsDestination, synthesizeRemote, isValidRemoteVoice } from './tts-remote.js';
54
- import { rawOrtAvailable } from './ort.js';
55
- import * as ttsVoices from './tts-voices.js';
56
- import { resolveTtsVoice } from './tts-voice-resolve.js';
57
- import { resolvePro, checkQuota, consume, usage } from './freegate.js';
58
- import { publicConfig, applyConfigPatch, applyNerModelSelection, persistConfig, configPath, bridgeAgentOptions } from './configstore.js';
59
- import { resolveDestination, aggregateModelsAsync, listDestinations } from './router.js';
60
- import { makeAccessEvent } from './observability.js';
61
- import { createPersistentAccessLog } from './access-log-store.js';
62
- import { planQueries, multiSearch } from './rrf.js';
63
- import * as openai from './openai.js';
64
- import * as responses from './responses.js';
65
- import * as anthropic from './anthropic.js';
3
+ `),t.end(),ie(l.id),r?.commit()}})}async function Vo(t,l,{kind:d,adapter:r,agent:o,run:u=null},c,h,b,E,p,M=null,A=null){const{messages:D,system:W}=r.toTurn(c),{agentModel:R}=_e(c?.model,b),I=Fe(b,{...R?{model:R}:{},...u||{}}),N=ae(b.bridge.token),O=ye(d,c?.model||o),j={tier:b.redaction.tier==="full"?"full":"basic",dictionary:gt(b.redaction,E),entities:[]},H=await se(b),v=Nt({vault:h,redactOpts:j,bridgeUrl:H,token:N,harness:M});let U;try{U=await $t({bridgeUrl:H,agent:o,token:N,messages:D,system:W,specs:Dt(p),options:I,signal:void 0})}catch(e){return ie(v.id),A?.commit(),s(l,502,{error:{message:`bridge: ${e.message}`,type:"bridge_error"}})}return v.reader=U.body.getReader(),l.writeHead(200,{"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive"}),l.write(O.sseHead()),it(l,v,O,A)}async function Jo(t,l,d,r,o=null){pe(l.id),l.rounds=(l.rounds||0)+1;try{const c=o?o.clock():0;await Ct(l,d),o&&o.lap("redact",c)}catch(c){return ie(l.id),o?.commit(),s(t,502,{error:{message:`tool-result: ${c.message}`,type:"bridge_error"}})}const u=ye("openai",r||"codex");return t.writeHead(200,{"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive"}),t.write(u.sseHead()),it(t,l,u,o)}async function Ho(t,l,{kind:d,adapter:r,redactable:o,pathname:u,agentOverride:c,harness:h,trace:b,run:E=null},p,M,A,D){if(!o)return b?.commit(),s(l,404,{error:`endpoint ${u} not supported by the bridge backend`});if(d==="openai"){const i=r.extractLatestToolResult(p);if(i){const f=Ie(i.tool_call_id),y=f&&je(f.gwId);if(y)return Jo(l,y,i.content,p?.model,b)}const m=r.extractTools(p);if(m.length&&p?.stream===!0)return Vo(t,l,{kind:d,adapter:r,agent:c||nt(p?.model,A),run:E},p,M,A,D,m,h,b)}const{messages:W,system:R}=r.toTurn(p),I=c||nt(p?.model,A),N=p?.stream===!0,O=ye(d,p?.model||I),j=ae(A.bridge.token),H=new AbortController;l.on("close",()=>{l.writableFinished||H.abort()});const{agentModel:v}=_e(p?.model,A),U={bridgeUrl:await se(A),agent:I,token:j,messages:W,system:R,signal:H.signal,options:Fe(A,{...v?{model:v}:{},...E||{}})};if(!N)try{let i="";const m=b?b.clock():0;await De(U,k=>{i+=k}),b&&b.lap("upstream",m);const f=b?b.clock():0,y=O.full(ft(i,M));return b&&b.lap("restore",f),l.writeHead(200,{"content-type":O.contentType}),l.end(y),b?.commit()}catch(i){return b?.commit(),s(l,502,{error:{message:`bridge backend failed: ${i.message}`,type:"bridge_error"}})}l.writeHead(200,{"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive"}),l.write(O.sseHead());const e=Pe(M),n=b?b.clock():0;let a=n;try{let i=!0;await De(U,f=>{b&&i&&(b.lap("upstream",n),a=b.clock(),i=!1);const y=e.push(f);y&&l.write(O.sseDelta(y))},O.sseActivity?f=>{try{l.write(O.sseActivity(ht(f,M)))}catch{}}:null);const m=e.flush();m&&l.write(O.sseDelta(m)),l.write(O.sseTail())}catch(i){l.write(`data: ${JSON.stringify({error:{message:i.message,type:"bridge_error"}})}
66
4
 
67
- export const VERSION = '0.6.110';
5
+ `)}b&&b.lap("stream",a),l.end(),b?.commit()}function Uo(t,l,d=""){const r=String(t||"").replace(/\/+$/,""),o=String(l||"").split("/")[1];return o&&r.endsWith(`/${o}`)?r.slice(0,-(o.length+1))+l+d:r+l+d}const Fo=9e4;function Wo(t,l,d){if(l===d)return t;const r=l/d,o=new Float32Array(Math.floor(t.length/r));for(let u=0;u<o.length;u++){const c=u*r,h=Math.floor(c),b=Math.min(t.length-1,h+1),E=c-h;o[u]=t[h]*(1-E)+t[b]*E}return o}const Ko=["/tts","/stt","/ner","/diarize","/skills","/redact","/config","/logs","/status","/admin"];async function Zo(t,l,{adapter:d,kind:r,pathname:o,search:u,base:c,destKey:h,destProtocol:b,harness:E,trace:p},M,A){let D;const W=p?p.clock():0;try{const O=zo(t.headers,c);h&&(b==="anthropic"?(O["x-api-key"]=h,delete O.authorization):O.authorization=`Bearer ${h}`);const j=vt(Uo(c,o,u)).toString();D=await fetch(j,{method:t.method,headers:O,body:["GET","HEAD"].includes(t.method)?void 0:M})}catch(O){return p?.commit(),s(l,502,{error:`upstream fetch failed: ${O.message}`})}const R=D.headers.get("content-type")||"",I={};if(D.headers.forEach((O,j)=>{et.has(j.toLowerCase())||(I[j]=O)}),R.includes("text/event-stream")&&D.body){p&&p.lap("upstream",W);const O=p?p.clock():0;l.writeHead(D.status,I);const j=r==="openai"?yt(D.body,l,A,E):pt(D.body,l,A);return Promise.resolve(j).finally(()=>{p&&p.lap("stream",O),p?.commit()})}const N=Buffer.from(await D.arrayBuffer());if(p&&p.lap("upstream",W),A&&R.includes("application/json"))try{const O=p?p.clock():0,j=d.restoreResponse(JSON.parse(N.toString("utf8")),A,E);return p&&p.lap("restore",O),l.writeHead(D.status,{...I,"content-type":"application/json"}),l.end(Buffer.from(JSON.stringify(j),"utf8")),p?.commit()}catch{}l.writeHead(D.status,I),l.end(N),p?.commit()}function Yo(t=xe()){const l=[],d=r=>{l.push(r),l.length>50&&l.shift()};return dt(async(r,o)=>{const u=new URL(r.url,"http://127.0.0.1"),c=u.pathname;if(!tt(r.headers.host))return s(o,403,{error:"loopback only"});if(!Co(r.headers.origin,t))return s(o,403,{error:"origin not allowed"});if(r.headers.origin&&Do(o,r.headers.origin),r.method==="OPTIONS")return o.writeHead(204),o.end();if(c==="/admin/token"&&r.method==="POST")return K(r)?s(o,200,{token:$e()}):s(o,403,{error:"admin: extension origin or gateway token required"});if(c==="/audit"&&r.method==="GET")return K(r)?s(o,200,_t(t,{version:Z,startedAt:ot,managed:re()})):s(o,403,{error:"audit: extension origin or gateway token required"});if((c==="/config"||c==="/logs"||c==="/update")&&!K(r))return s(o,403,{error:"admin route: extension origin or gateway token required"});if(c==="/update"&&r.method==="GET"){const e=await Kt(Z,{force:u.searchParams.get("force")==="1"}).catch(n=>({current:Z,updateAvailable:!1,error:String(n?.message||n)}));return s(o,200,{ok:!0,update:e,job:Xt()})}if(c==="/update"&&r.method==="POST"){const e=Yt(Z);return s(o,e.already?409:202,{ok:!0,job:e})}if((c==="/v1/history/key"||c==="/v1/history/ingest-backup")&&r.method==="POST"&&!K(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"&&!K(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"&&!K(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"))&&!K(r))return s(o,403,{error:{message:"prefs: extension origin or gateway token required",type:"forbidden"}});if(c.startsWith("/v1/observability")&&!K(r))return s(o,403,{error:{message:"observability: extension origin or gateway token required",type:"forbidden"}});if(r.method==="GET"&&c==="/health"){const e=x.health(),n=S.health();return s(o,200,{ok:!0,version:Z,backend:t.backend,tier:t.redaction.tier,...re()?{managed:re()}:{},...process.env.CHATPANEL_MANAGED_BY?{managedBy:String(process.env.CHATPANEL_MANAGED_BY).slice(0,32)}:{},...ue?{bridge:ue.status()}:{},stt:{enabled:t.stt?.enabled!==!1,state:e.state,ready:e.ok,model:e.model||t.stt?.model||be,runtime:e.runtime,dtype:e.dtype},tts:{enabled:t.tts?.enabled!==!1,state:n.state,ready:n.ok,model:n.model||t.tts?.model||Ve,voice:t.tts?.voice||Y,runtime:n.runtime,dtype:n.dtype}})}if(c==="/status"&&r.method==="GET"){mt(t);const e=await Q(t.pro?.entitlementToken),n=await at(t);return s(o,200,{ok:!0,version:Z,backend:t.backend,tier:t.redaction.tier,...re()?{managed:re()}:{},...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:Oe(t),pro:{unlocked:e},usage:So(t),uptimeSeconds:Math.floor((Date.now()-ot)/1e3),update:Zt(Z)})}if(c==="/v1/history/ingest"&&r.method==="POST")try{const e=JSON.parse((await T(r,t.maxBodyBytes)).toString("utf8"))||{},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:F.revision,stamps:F.stamps()}):s(o,200,{ok:!0,revision:F.revision,sections:F.get(e)})}if(c==="/v1/prefs"&&(r.method==="POST"||r.method==="PUT"))try{const e=JSON.parse((await T(r,t.maxBodyBytes)).toString("utf8"))||{},n=F.put(e.sections||{},{by:e.by||""});return n.applied.length&&Ye(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?F.remove(e):!1;return n&&Ye([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=i=>o.write(`data: ${JSON.stringify(i)}
68
6
 
69
- // WARM search tier — SQLite + FTS5 record store (falls back to an encrypted-JSON
70
- // store if SQLite can't load), fed by the extension's ingest sync + backup-ingest.
71
- // Persistent + memory-mapped, so a restart needs no re-ingest (no cold start).
72
- // See docs/architecture-data-tiers.
73
- const historyStore = await createHistoryStore();
74
- const memoryStore = await createMemoryStore();
75
- const prefsStore = createPrefsStore();
76
- const scorecards = createScorecardStore({ key: loadTeamKey() });
77
- const engines = createEngineLedgerStore({ key: loadTeamKey() });
78
- const projectStore = createProjectStore({ key: loadTeamKey() });
79
- const teamStore = createTeamStore({ scorecards, engines });
80
- // Who is watching prefs change — a client with a live subscription is told the moment a
81
- // section is written by the other client, instead of waiting for its next focus.
82
- const prefsWatchers = new Set();
83
- const notifyPrefs = (applied, by) => { for (const fn of prefsWatchers) { try { fn({ applied, by, revision: prefsStore.revision }); } catch { /* gone */ } } };
7
+ `);e({type:"hello",revision:F.revision,stamps:F.stamps()});const n=i=>e({type:"changed",...i});ve.add(n);const a=setInterval(()=>{try{o.write(`: keep-alive
84
8
 
85
- // OBSERVABILITY — a ring of "which agent read what, when", persisted across restarts (the
86
- // gateway updates often; an empty panel after each restart reads as "nothing is set up").
87
- // Populated by the MCP process (chatpanel-gateway mcp) reporting each tool call, so a person
88
- // can SEE cross-agent access in ChatPanel's dashboard. Safe to persist: every event is
89
- // metadata only — client/tool/ms + a REDACTED note (a search query's text is never in it).
90
- const accessLog = createPersistentAccessLog();
9
+ `)}catch{}},25e3);o.on("close",()=>{ve.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 T(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]||"",i=e[3]||"",m=e[4]||"",f=()=>s(o,404,{error:{message:`no project ${n}`,type:"not_found"}});if(m){const y=G.get(n);if(!y)return f();const k=y.jobs.find(g=>g.id===i);if(!k)return s(o,404,{error:{message:`no job ${i}`,type:"not_found"}});const w={cfg:t,prefsStore:F,scorecards:te,engines:oe};if(m==="/applications"&&r.method==="GET"){const g=await Ut(k,{...w,reach:u.searchParams.get("reach")||"any",chatModel:u.searchParams.get("chatModel")||null});return s(o,200,{ok:!0,job:k,...g})}if(m==="/recruit"&&r.method==="POST"){if(!["open","evaluating"].includes(k.status))return s(o,400,{error:{message:`job ${i} is ${k.status}; only an open job is recruited`,type:"project_error"}});try{const g=JSON.parse((await T(r,t.maxBodyBytes)).toString("utf8"))||{},_=String(g.by||"evaluator").slice(0,80),z=await Ft(k,{...w,record:y,reach:g.reach||"any",chatModel:g.chatModel||null,evaluation:g.evaluation||null,text:g.text??null,by:_});let V=null;for(const X of z.events)X.type==="job.updated"?V=G.updateJob(n,i,X.job,{by:X.by||_}):V=G.append(n,[X]);return s(o,200,{ok:!0,project:V,decision:z.decision,applications:z.applications,evaluation:z.evaluation})}catch(g){return s(o,400,{error:{message:`recruit: ${g.message}`,type:"project_error"}})}}return s(o,405,{error:{message:"method not allowed",type:"project_error"}})}if(!a&&r.method==="GET"){const y=G.get(n,{events:u.searchParams.get("events")==="1"});return y?s(o,200,{ok:!0,project:y}):f()}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 y=JSON.parse((await T(r,t.maxBodyBytes)).toString("utf8"))||{},k=String(y.by||"person").slice(0,80),w=a==="/events"?G.append(n,y.events||[]):i?G.updateJob(n,i,y.patch||y,{by:k}):G.postJob(n,y.job||y,{by:k});return s(o,200,{ok:!0,project:w})}catch(y){return s(o,y.message.startsWith("no ")?404:400,{error:{message:`project: ${y.message}`,type:"project_error"}})}if(a==="/events"&&r.method==="GET"){if(!G.get(n))return f();o.writeHead(200,{"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive"});const y=_=>o.write(`data: ${JSON.stringify(_)}
91
10
 
92
- const KNOWN_AGENTS = new Set(['codex', 'claude', 'opencode', 'pi', 'kiro', 'antigravity', 'hermes']);
11
+ `);let k=u.searchParams.has("after")?Number(u.searchParams.get("after")):-1;y({seq:-1,type:"hello",at:Date.now(),payload:{project:G.get(n),after:k}});const w=G.watch(n,_=>{_.seq>k&&(k=_.seq,y(_))});for(const _ of G.eventsSince(n,k))k=_.seq,y(_);const g=setInterval(()=>{try{o.write(`: keep
93
12
 
94
- // Auto-narrow: arm only the top-K most-relevant MCP tools per turn (speed). Mirrors
95
- // the extension's AUTO mode via the SAME shared ranker. We narrow only tools whose
96
- // name looks like an MCP tool (server-prefixed) so a client's CORE tools (bash,
97
- // read, edit…) are never dropped — that would break agent clients like OpenCode.
98
- const DEFAULT_GATEWAY_TOOL_CAP = 16;
99
- const MCP_NAME_RE = /^mcp[_-]/i;
100
- const toolName = (t) => (t && t.function && t.function.name) || (t && t.name) || '';
101
- const toolDesc = (t) => (t && t.function && t.function.description) || (t && t.description) || '';
13
+ `)}catch{}},25e3);r.on("close",()=>{clearInterval(g),w()});return}}}if(c==="/v1/agents/scorecards"&&r.method==="GET")return s(o,200,{ok:!0,agents:te.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 te.get(n)});if(r.method==="POST")try{const a=JSON.parse((await T(r,t.maxBodyBytes)).toString("utf8"))||{},i=await te.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 oe.fromRating(te.chains.get(n)||[],{...i,jobKind:a.jobKind?String(a.jobKind).slice(0,60):void 0}),s(o,200,{ok:!0,entry:i})}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:oe.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 oe.get(n,{entries:u.searchParams.get("entries")==="1",minCalls:a})})}if(e[2]==="entries"&&r.method==="POST")try{const a=JSON.parse((await T(r,t.maxBodyBytes)).toString("utf8"))||{},i=a.engine||Io(n);if(!i)return s(o,400,{error:{message:"model-ledger: engine required",type:"model_ledger_error"}});const m=await oe.append({...a,engine:i,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: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 T(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 i=C.get(n,{events:u.searchParams.get("events")==="1"});return i?s(o,200,{ok:!0,run:i}):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 i=C.stop(n);return i?s(o,200,{ok:!0,run:i}):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(i){return s(o,404,{error:{message:`team run: ${i.message}`,type:"team_error"}})}if((a==="/handoff"||a==="/claim")&&r.method==="POST")try{const i=JSON.parse((await T(r,t.maxBodyBytes)).toString("utf8"))||{},m=a==="/handoff"?C.handoff(n,{taskId:i.taskId,model:i.model,by:i.by,reason:i.reason}):C.claim(n,{client:i.client});return s(o,200,{ok:!0,run:m})}catch(i){return s(o,i.message.startsWith("no ")?404:400,{error:{message:`team run: ${i.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(i){return s(o,i.message.startsWith("no ")?404:400,{error:{message:`team run: ${i.message}`,type:"team_error"}})}if((a==="/answer"||a==="/decide"||a==="/post")&&r.method==="POST")try{const i=JSON.parse((await T(r,t.maxBodyBytes)).toString("utf8"))||{},m=String(i.by||"person").slice(0,40),f=a==="/answer"?C.answer(n,{threadId:i.threadId,text:i.text,by:m}):a==="/decide"?C.decide(n,{postId:i.postId,status:i.status,by:m}):C.post(n,{threadId:i.threadId,text:i.text,by:m,kind:i.kind,replyTo:i.replyTo});return s(o,200,{ok:!0,run:f})}catch(i){return s(o,i.message.startsWith("no ")?404:400,{error:{message:`team run: ${i.message}`,type:"team_error"}})}if(a==="/events"&&r.method==="POST")try{const i=JSON.parse((await T(r,t.maxBodyBytes)).toString("utf8"))||{};return s(o,200,{ok:!0,run:C.append(n,i.events||[])})}catch(i){return s(o,i.message.startsWith("no run")?404:400,{error:{message:`team run: ${i.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 i=w=>o.write(`data: ${JSON.stringify(w)}
102
14
 
103
- // Flatten message/content shapes to the latest user text — the query we rank tools against.
104
- function textFromContent(content) {
105
- if (typeof content === 'string') return content;
106
- if (Array.isArray(content)) return content.map((p) => (typeof p === 'string' ? p : (p && (p.text || p.content)) || '')).join(' ');
107
- return '';
108
- }
109
- function latestUserText(body, kind) {
110
- if (!body) return '';
111
- if (kind === 'responses') {
112
- const inp = body.input;
113
- if (typeof inp === 'string') return inp;
114
- if (Array.isArray(inp)) return inp.map((x) => textFromContent(x && (x.content ?? x))).join(' ');
115
- return '';
116
- }
117
- const msgs = Array.isArray(body.messages) ? body.messages : [];
118
- for (let i = msgs.length - 1; i >= 0; i--) {
119
- if (msgs[i] && msgs[i].role === 'user') return textFromContent(msgs[i].content);
120
- }
121
- return '';
122
- }
15
+ `),m=u.searchParams.has("after")?Number(u.searchParams.get("after")):NaN;let f=Number.isFinite(m)?m:-1;i({seq:-1,type:"hello",at:Date.now(),payload:{run:C.get(n),after:f}});const y=C.watch(n,w=>{w.seq==null?i(w):w.seq>f&&(f=w.seq,i(w))});for(const w of C.eventsSince(n,f))f=w.seq,i(w);const k=setInterval(()=>{try{o.write(`: keep-alive
123
16
 
124
- const HOP_BY_HOP = new Set([
125
- 'host', 'connection', 'content-length', 'transfer-encoding',
126
- 'accept-encoding', 'content-encoding', 'keep-alive',
127
- ]);
17
+ `)}catch{}},25e3);o.on("close",()=>{y(),clearInterval(k)});return}}}if(c==="/v1/memory/list"&&r.method==="GET")return s(o,200,{ok:!0,size:J.size,memories:J.list()});if(c==="/v1/memory/recall"&&r.method==="POST")try{const e=JSON.parse((await T(r,t.maxBodyBytes)).toString("utf8"))||{},n=J.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:J.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 T(r,t.maxBodyBytes)).toString("utf8"))||{},n=J.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:J.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 T(r,t.maxBodyBytes)).toString("utf8"))||{},{removed:n}=J.forget(String(e.query||""));return s(o,200,{ok:!0,removed:n,size:J.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 T(r,t.maxBodyBytes)).toString("utf8"))||{},n=J.bulk({upserts:Array.isArray(e.upserts)?e.upserts:[],removes:Array.isArray(e.removes)?e.removes:[]});return s(o,200,{ok:!0,...n,memories:J.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:J.clear(),size:J.size});if(c==="/v1/history/clear"&&r.method==="POST"){const e=$.clear();return s(o,200,{ok:!0,dropped:e,size:$.size})}if(c==="/v1/history/search"&&r.method==="POST")try{const e=JSON.parse((await T(r,t.maxBodyBytes)).toString("utf8"))||{},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:$.size,newest:$.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 T(r,t.maxBodyBytes)).toString("utf8"))||{},n=String(e.question||e.query||""),a=xo(n,{extra:Array.isArray(e.queries)?e.queries.map(String):[],max:Math.min(6,Math.max(1,Number(e.maxQueries)||4))}),i={type:e.type?String(e.type):null,since:e.since!=null?Number(e.since):null,before:e.before!=null?Number(e.before):null},m=Math.min(30,Math.max(5,Number(e.limit)||10)*2),f=await Ao(a,k=>$.search(k,{limit:m,...i}),{limit:Math.min(50,Math.max(1,Number(e.limit)||10))}),y=i.type?f:[...f.filter(k=>k.type==="brief"),...f.filter(k=>k.type!=="brief")];return s(o,200,{ok:!0,size:$.size,newest:$.newest,queries:a,results:y})}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:$.related(e,{limit:n})})}if(c==="/v1/history/status"&&r.method==="GET")return s(o,200,{ok:!0,size:$.size,newest:$.newest,bytes:$.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:$.size,bytes:$.bytes,newest:$.newest}},access:Te.snapshot(e)})}if(c==="/v1/observability/access"&&r.method==="POST")try{const e=JSON.parse((await T(r,t.maxBodyBytes)).toString("utf8"))||{},n=Te.push(Ke({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,...$.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=$.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:Re()});if(c==="/v1/history/key"&&r.method==="POST")try{const e=JSON.parse((await T(r,t.maxBodyBytes)).toString("utf8"))||{};e.passphrase?Mt(String(e.passphrase)):Rt();const n=e.passphrase?await ge($,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 ge($,Me());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 at(t);return s(o,e.ok?200:503,e)}if(r.method==="POST"){if(await he(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 T(r,t.maxBodyBytes);let a="";try{a=JSON.parse(n.toString("utf8"))?.text||""}catch{}const i=await B.detect(a);return s(o,200,{entities:i})}catch(n){return s(o,500,{error:{message:`NER error: ${n.message}`,type:"ner_error"}})}}const e=st(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 T(r,t.maxBodyBytes),a=await Ce(e,{method:"POST",headers:{"content-type":"application/json"},body:n,signal:AbortSignal.timeout(8e3)}),i=await a.text();return o.writeHead(a.status,{"content-type":"application/json"}),o.end(i)}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 T(r,t.maxBodyBytes)).toString("utf8"))?.text||"")}catch{e=""}if(!e)return s(o,200,{text:"",count:0,sanitized:0,entities:[],detector:Oe(t)});try{let n=e;const a=await Q(t.pro?.entitlementToken);await he(t);const i=await me([Ae(()=>n,m=>{n=m})],t.redaction,{isPro:a});return s(o,200,{text:n,count:i.count||0,sanitized:i.sanitized||0,tier:t.redaction?.tier==="full"?"full":"basic",entities:rt(i.vault,"types")||[],detector:Oe(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=qt.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 T(r,t.maxBodyBytes)).toString("utf8"))}catch{e=null}const n=e&&typeof e.id=="string"?e.id.trim():null;if(!n||!(eo(n)||to(n)))return s(o,400,{error:{message:"unknown or invalid model id",type:"bad_model"}});To(t,n);try{ee(t,q())}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||be,n=oo.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:so})}if(r.method==="POST"){let e=null;try{e=JSON.parse((await T(r,t.maxBodyBytes)).toString("utf8"))}catch{e=null}const n=e&&typeof e.id=="string"?e.id.trim():null;if(!n||!(ro(n)||no(n)))return s(o,400,{error:{message:"unknown or invalid model id",type:"bad_model"}});const a=typeof e.dtype=="string"&&ao(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{ee(t,q())}catch{}return x.setModel(n,{onLog:i=>console.log(i),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=P.health();return s(o,200,{active:P.DIARIZE_MODEL,state:e.state,progress:P.progress(),available:[{id:P.DIARIZE_MODEL,label:"Speaker embeddings (wavlm)",lang:"any",approxMB:100,note:"Tells voices apart for meeting transcription (who said what).",installed:P.modelOnDisk()}]})}if(r.method==="POST")return P.download({onLog:e=>console.log(e)}),s(o,202,{accepted:!0,active:P.DIARIZE_MODEL,state:P.state(),progress:P.progress()})}if(c==="/tts/models"){if(r.method==="GET"){const e=S.health().model||t.tts?.model||He(we()),n=we(),a=Le.find(m=>m.id===e)||null,i=Le.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&&!i.some(m=>m.id===e)&&i.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:i,voice:t.tts?.voice||(de(e)==="pocket-tts"?le:Y),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()&&de(e)==="pocket-tts"?(S.builtinVoices().length?S.builtinVoices():yo).map(m=>({id:m,label:m[0].toUpperCase()+m.slice(1),lang:"en",installed:S.builtinVoices().includes(m)})):S.arch()&&S.arch()!=="style-tts2"?[]:io.map(m=>({...m,installed:S.voiceOnDisk(m.id,e)})),dtype:t.tts?.dtype||"auto",loadedDtype:S.health().dtype,runtime:S.health().runtime,dtypes:uo})}if(r.method==="POST"){let e=null;try{e=JSON.parse((await T(r,t.maxBodyBytes)).toString("utf8"))}catch{e=null}const n=e&&typeof e.id=="string"?e.id.trim():null;if(n&&!(lo(n)||co(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=L.parseCustomVoice(a);if(!(m?!!L.getVoice(m):ce(a)||Ge(a)&&ze(a)))return s(o,400,{error:{message:"unknown or invalid voice",type:"bad_voice"}})}const i=e&&typeof e.dtype=="string"&&mo(e.dtype)?e.dtype:void 0;if(t.tts||(t.tts={enabled:!0,model:Ve,voice:Y,allowDownload:!0}),n&&(t.tts.model=n),a&&(t.tts.voice=a),n&&!a){const m=po(n),f=L.parseCustomVoice(t.tts.voice||""),y=!!(f&&L.getVoice(f));if(m&&!y)if(de(n)==="pocket-tts")t.tts.voice=le;else{const w=L.listVoices();t.tts.voice=w.length?`custom:${w[0].id}`:""}else!m&&y&&(t.tts.voice=Y);const k=de(n)==="pocket-tts";k&&!L.parseCustomVoice(t.tts.voice||"")&&!ce(t.tts.voice)&&(t.tts.voice=le),!k&&ce(t.tts.voice)&&(t.tts.voice=Y)}i&&(t.tts.dtype=i==="auto"?null:i);try{ee(t,q())}catch{}return n&&S.setModel(n,{onLog:m=>console.log(m),dtype:i||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:L.listVoices(),usable:S.supportsCustomVoices(),embedder:P.DIARIZE_MODEL,embedderReady:P.isReady()});if(r.method==="POST"){let e=null;try{e=JSON.parse((await T(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,i=e&&typeof e.id=="string"?e.id.trim():"";if(i){if(!L.getVoice(i))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(i,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(!P.isReady()){const g=P.download({onLog:V=>console.log(V)}),_=Symbol("timeout"),z=await Promise.race([g.then(()=>null).catch(V=>V),new Promise(V=>setTimeout(()=>V(_),Fo))]);if(z===_||!P.isReady())return s(o,503,{error:{message:z===_?"the speaker model is still downloading (~100 MB) — your recording was kept, press Save again shortly":`the speaker model failed to load: ${P.health().error||"unknown error"}`,type:"embedder_not_ready"},progress:P.progress()})}const m=Float32Array.from(a),f=await P.embed(m);let y=null;try{const g=await S.pocketForEncoding({allowDownload:t.tts?.allowDownload!==!1,log:_=>console.log(_)});g&&(y=await g.encodeVoice(Wo(m,16e3,24e3)))}catch(g){console.log(`[tts] pocket conditioning unavailable for this voice (${g.message})`)}const k=i?L.replaceVoice(i,{vec:f,pocket:y}):L.saveVoice({name:n,vec:f,pocket:y}),w=i&&n&&n!==k.name?L.renameVoice(i,n):k;return console.log(`[tts] ${i?"re-recorded":"saved"} custom voice "${w.name}" (${(k.kinds||[]).join(" + ")}, sample discarded)`),s(o,i?200:201,{...k,...w,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=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{ee(t,q())}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 T(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>Je)return s(o,413,{error:{message:`text too long (max ${Je} chars)`,type:"too_long"}});const a=Number.isFinite(e.speed)?Math.min(2,Math.max(.5,e.speed)):1,i=ho(t),m=e&&typeof e.voice=="string"&&e.voice.trim()?e.voice.trim():null,f=m||(i?i.voice:t.tts?.voice||Y);if(i&&!go(f))return s(o,400,{error:{message:"unknown or invalid voice",type:"bad_voice"}});const y=e&&typeof e.response_format=="string"?e.response_format.toLowerCase():"wav";if(y!=="wav"&&y!=="pcm")return s(o,400,{error:{message:`unsupported response_format "${y}" — this gateway synthesizes wav`,type:"bad_format"}});try{if(i){const{audio:ne,contentType:lt,redacted:ct}=await fo({dest:i,text:n,voice:f,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":lt,"Content-Length":String(ne.length),"Cache-Control":"no-store","X-Tts-Provider":i.kind,"X-Tts-Redacted":String(ct)}),o.end(ne)}if(!await S.ready({onLog:ne=>console.log(ne),allowDownload:t.tts?.allowDownload!==!1,model:t.tts?.model||He(we()),dtype:t.tts?.dtype||"auto"}))return s(o,503,{error:{message:S.health().error||"tts model not ready",type:"tts_unavailable"}});const w=bo({requested:m,configured:f,engine:S,voices:L,isPocketVoice:ce,isKnownVoice:Ge,isValidVoiceId:ze,defaultVoice:Y,defaultPocketVoice:le});if(!w.ok)return s(o,w.status,{error:{message:w.message,type:w.type}});const{voice:g,customId:_,speakerEmbedding:z}=w,V=await S.synth(n,{voice:g,speed:a,speakerEmbedding:z}),X=S.sampleRate(),Ee=y==="pcm"?Buffer.from(new Float32Array(V).buffer):S.toWav(V,X);return o.writeHead(200,{"Content-Type":y==="pcm"?"application/octet-stream":"audio/wav","Content-Length":String(Ee.length),"Cache-Control":"no-store","X-Tts-Sample-Rate":String(X),..._||S.isPocket()||S.supportsVoices()?{"X-Tts-Voice":g}:{}}),o.end(Ee)}catch(k){return s(o,500,{error:{message:k.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 T(r,t.maxBodyBytes)).toString("utf8")||"{}")}catch{e=null}x.isReady()||x.init({model:t.stt?.model||be,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&&!P.isReady()&&P.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 T(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 i=g=>o.write(`data: ${JSON.stringify(g)}
128
18
 
129
- function isLoopbackHost(host) {
130
- if (!host) return false;
131
- const name = host.replace(/:\d+$/, '').replace(/^\[|\]$/g, '');
132
- return name === 'localhost' || name === '127.0.0.1' || name === '::1';
133
- }
134
-
135
- // Local CLI clients send no Origin; browsers always do. We allow the trusted
136
- // local UIs (the ChatPanel extension + localhost) and anything the operator
137
- // allowlists — and reject every other web origin, so a malicious page can't drive
138
- // the gateway (and thus codex). Mirrors the bridge's origin model.
139
- function originAllowed(origin, cfg) {
140
- if (!origin) return true; // no Origin → a local process (opencode/codex/SDK)
141
- if (/^chrome-extension:\/\//.test(origin) || /^moz-extension:\/\//.test(origin)) return true;
142
- if (/^http:\/\/(localhost|127\.0\.0\.1|\[::1\])(:\d+)?$/.test(origin)) return true;
143
- return Array.isArray(cfg.allowedOrigins) && cfg.allowedOrigins.includes(origin);
144
- }
145
-
146
- function setCors(res, origin) {
147
- res.setHeader('Access-Control-Allow-Origin', origin || '*');
148
- res.setHeader('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS');
149
- res.setHeader('Access-Control-Allow-Headers', 'Content-Type, Authorization, X-ChatPanel-Token');
150
- res.setHeader('Vary', 'Origin');
151
- }
152
-
153
- const STARTED_AT = Date.now();
154
-
155
- // Render a timings map as a compact one-liner for the console log.
156
- function fmtTimings(t) {
157
- if (!t) return '';
158
- const label = { redact: 'redact', upstream: 'model', stream: 'stream', restore: 'restore', total: 'total' };
159
- return Object.keys(t).map((k) => `${label[k] || k} ${t[k]}ms`).join(' · ');
160
- }
161
-
162
- // Per-request timing + summary. Created ONLY when logging is on — when it's off
163
- // the handler passes a null trace and every `trace?.…` call short-circuits, so we
164
- // don't even read the clock: logging then adds zero latency. The committed entry
165
- // is flushed to the in-memory ring via setImmediate, i.e. AFTER the response has
166
- // been handed back, so recording (and the console line) never sits on the request
167
- // path. `timings` are wall-clock ms per stage of the flow:
168
- // redact prompt → harness[redact] → model input
169
- // upstream model input → model output. Non-stream: full call. Stream: time to
170
- // first token (model/connection latency). Shown as "model".
171
- // stream first token → last token (generation), streaming responses only
172
- // restore model output → harness[restore] → user response (non-stream; for
173
- // streams restore is inline per chunk, so it's folded into stream)
174
- // total end-to-end through the gateway
175
- /** `model:<id>[/<model>]` / `harness:<id>[/<model>]` → the record's engine, or null. */
176
- function engineFromKey(key) {
177
- const m = /^(model|harness):([^/]+)(?:\/(.+))?$/.exec(String(key || ''));
178
- return m ? { kind: m[1], id: m[2], ...(m[3] ? { model: m[3] } : {}) } : null;
179
- }
180
-
181
- function mkTrace(sink) {
182
- const start = performance.now();
183
- const timings = {};
184
- let done = false;
185
- const mark = (name, ms) => { timings[name] = Math.round(ms * 10) / 10; };
186
- return {
187
- meta: {}, timings, mark,
188
- // Stamp the duration of an already-completed stage (`t0` from clock()).
189
- lap(name, t0) { mark(name, performance.now() - t0); },
190
- clock() { return performance.now(); },
191
- commit() {
192
- if (done) return; done = true;
193
- mark('total', performance.now() - start);
194
- const entry = /** @type {any} */ ({ ...this.meta, timings });
195
- setImmediate(() => {
196
- sink(entry);
197
- console.log(`[gateway] model=${entry.model || '-'} → ${entry.dest ? `${entry.dest}(${entry.type})` : 'none'} · ${entry.redaction === 'off' ? 'redaction OFF (client request)' : `redacted ${entry.redacted || 0}`}${entry.sanitized ? ` · scrubbed ${entry.sanitized} hidden` : ''}${entry.narrowed ? ` · narrowed -${entry.narrowed}` : ''} · ${fmtTimings(timings)}`);
198
- });
199
- },
200
- };
201
- }
202
-
203
- // Build the optional per-request redaction breakdown from the request's vault.
204
- // 'types' → [{ token:'PERSON_1', type:'PERSON' }] (no real values)
205
- // 'values' → [{ token:'PERSON_1', type:'PERSON', value:'…' }] (the real PII; opt-in)
206
- // Lives only in the in-memory ring — never written to disk by persistConfig.
207
- function redactionDetail(vault, mode) {
208
- if (!vault || !vault.byToken || (mode !== 'types' && mode !== 'values')) return undefined;
209
- const out = [];
210
- for (const [token, value] of vault.byToken) {
211
- const m = /^\[\[([A-Z][A-Z0-9]*)_\d+\]\]$/.exec(token);
212
- const t = m ? m[1] : 'PII';
213
- const bare = token.replace(/^\[\[|\]\]$/g, '');
214
- out.push(mode === 'values' ? { token: bare, type: t, value } : { token: bare, type: t });
215
- }
216
- return out;
217
- }
218
-
219
- // Classify a request: which protocol kind + adapter, whether it's a redactable
220
- // chat endpoint, and (api backend) which upstream base URL.
221
- function route(pathname, headers, cfg) {
222
- if (anthropic.matches(pathname) || 'anthropic-version' in headers) {
223
- return { kind: 'anthropic', adapter: anthropic, redactable: anthropic.matches(pathname), base: cfg.upstreams?.anthropic?.baseUrl };
224
- }
225
- if (responses.matches(pathname)) {
226
- return { kind: 'responses', adapter: responses, redactable: true, base: cfg.upstreams?.openai?.baseUrl };
227
- }
228
- return { kind: 'openai', adapter: openai, redactable: openai.matches(pathname), base: cfg.upstreams?.openai?.baseUrl };
229
- }
230
-
231
- /**
232
- * An agent id, and the model to run it with.
233
- *
234
- * A CLI agent is not one model. Claude Code takes `opus`, `sonnet` or `haiku`; the others
235
- * have their own lists. Picking `claude` alone leaves the CLI on whatever default it has,
236
- * which is how a user gets "this version does not support that model" from a tool they never
237
- * chose a model for. So `claude/opus` names both, and the slash is the only new syntax.
238
- *
239
- * A bare agent id still works and still means "the agent's own default" — every client that
240
- * predates this keeps working, which is the whole reason the model is a SUFFIX rather than a
241
- * change to the id.
242
- */
243
- export function parseAgentModel(model, cfg) {
244
- const raw = String(model || '');
245
- if (KNOWN_AGENTS.has(raw)) return { agent: raw, agentModel: '' };
246
- const slash = raw.indexOf('/');
247
- if (slash > 0) {
248
- const head = raw.slice(0, slash);
249
- if (KNOWN_AGENTS.has(head)) return { agent: head, agentModel: raw.slice(slash + 1) };
250
- }
251
- return { agent: cfg.bridge.agent, agentModel: '' };
252
- }
253
-
254
- function pickAgent(model, cfg) {
255
- return parseAgentModel(model, cfg).agent;
256
- }
257
-
258
- // A follow-up request carrying a tool result for a PARKED relay session. Such a
259
- // request must NOT be redacted here: the relay owns redaction/restore through its
260
- // OWN (round-1) vault, so re-redacting with a fresh vault would put the tool
261
- // result's new tokens in the wrong vault and leave them unrestored in the reply.
262
- function isRelayResume(body, kind) {
263
- if (kind !== 'openai' || !body) return false;
264
- const tr = openai.extractLatestToolResult(body);
265
- if (!tr) return false;
266
- const parsed = parseToolCallId(tr.tool_call_id);
267
- return !!(parsed && getRelaySession(parsed.gwId));
268
- }
269
-
270
- // Guard against an api destination pointing back at THIS gateway (loopback host +
271
- // our own port) — forwarding there would loop forever.
272
- function isSelfUrl(baseUrl, cfg) {
273
- try {
274
- const u = new URL(baseUrl);
275
- const host = u.hostname.replace(/^\[|\]$/g, '');
276
- const loop = host === '127.0.0.1' || host === 'localhost' || host === '::1';
277
- const port = u.port || (u.protocol === 'https:' ? '443' : '80');
278
- return loop && String(port) === String(cfg.port);
279
- } catch { return false; }
280
- }
281
-
282
- async function readBody(req, maxBytes) {
283
- const chunks = [];
284
- let size = 0;
285
- for await (const c of req) {
286
- size += c.length;
287
- if (maxBytes && size > maxBytes) { const e = new Error('payload too large'); e.code = 413; throw e; }
288
- chunks.push(c);
289
- }
290
- return Buffer.concat(chunks);
291
- }
292
-
293
- function sendJson(res, status, obj) {
294
- res.writeHead(status, { 'content-type': 'application/json' });
295
- res.end(JSON.stringify(obj));
296
- }
297
-
298
- // A USER-configured external detector's URL and its sibling /health. Returns null
299
- // when no external detector is wired (the bundled in-process engine is handled
300
- // separately in probeNerHealth / the /ner route).
301
- function nerBaseUrl(cfg) {
302
- const url = cfg.redaction?.detection?.url;
303
- if (!url || cfg.redaction?.detection?.backend === 'off') return null;
304
- return url;
305
- }
306
-
307
- /**
308
- * CAN THIS GATEWAY REDACT NAMES RIGHT NOW — the question every privacy UI has to answer
309
- * before it draws a shield.
310
- *
311
- * Deterministic patterns (emails, phones, cards, keys) always run, so a redaction with no
312
- * detector behind it produces text that LOOKS redacted. `coverage` names the difference:
313
- * 'names' means people, organisations and places are covered too; 'patterns' means they are
314
- * not, and the client is expected to say so rather than let the shield imply it.
315
- *
316
- * Synchronous on purpose — it reports the engine's own state and never probes the network,
317
- * so it can sit on a per-keystroke route.
318
- */
319
- function detectorStatus(cfg) {
320
- const det = cfg?.redaction?.detection;
321
- const tier = cfg?.redaction?.tier === 'full' ? 'full' : 'basic';
322
- if (det && det.backend && det.backend !== 'off') {
323
- // A user's own detector: we cannot know it is up without sending it text, and a probe
324
- // per keystroke is not a trade worth making. Report it as configured and let the turn
325
- // itself be the test.
326
- return { source: 'external', backend: det.backend, state: 'external', model: det.model || null, ready: true, tier, coverage: tier === 'full' ? 'names' : 'patterns' };
327
- }
328
- const h = nerEngine.health();
329
- const ready = h.ok && tier === 'full';
330
- return {
331
- source: 'bundled',
332
- state: h.state, // 'off' | 'loading' | 'downloading' | 'ready' | 'error'
333
- model: h.model || cfg?.ner?.model || null,
334
- // Weights on disk with the engine off is the recoverable case (it starts on the next
335
- // request); no weights is the case that needs the user to install a model.
336
- installed: nerEngine.modelOnDisk(cfg?.ner?.model || undefined),
337
- error: h.error || null,
338
- ready,
339
- tier,
340
- coverage: ready ? 'names' : 'patterns',
341
- };
342
- }
343
-
344
- // Health of the detector for /status. The bundled IN-PROCESS engine takes
345
- // precedence; its public contract URL is the gateway's own /ner (no second port).
346
- // A user-configured external detector is probed over HTTP as before.
347
- async function probeNerHealth(cfg) {
348
- if (nerEngine.state() !== 'off') {
349
- const h = nerEngine.health();
350
- return {
351
- configured: h.configured,
352
- ok: h.ok,
353
- state: h.state,
354
- model: h.model,
355
- error: h.error || null,
356
- url: h.configured ? `http://${cfg.host}:${cfg.port}/ner` : null,
357
- };
358
- }
359
- const url = nerBaseUrl(cfg);
360
- if (!url) return { configured: false, ok: false, url: null, model: null };
361
- try {
362
- // secureFetch: scheme + host policy AND resolved-IP validation (DNS-rebinding).
363
- const r = await secureFetch(url.replace(/\/ner\/?$/, '') + '/health', { signal: AbortSignal.timeout(2000) });
364
- if (!r.ok) return { configured: true, ok: false, url, model: null };
365
- const j = await r.json().catch(() => ({}));
366
- return { configured: true, ok: true, url, model: j.model || null };
367
- } catch {
368
- return { configured: true, ok: false, url, model: null };
369
- }
370
- }
371
-
372
- function forwardHeaders(headers, base) {
373
- const out = {};
374
- for (const [k, v] of Object.entries(headers)) {
375
- const lower = k.toLowerCase();
376
- // ChatPanel's own routing metadata is for THIS hop and is not the provider's business.
377
- if (lower.startsWith('x-chatpanel-')) continue;
378
- if (!HOP_BY_HOP.has(lower)) out[k] = v;
379
- }
380
- out['accept-encoding'] = 'identity'; // must read plain text to restore tokens
381
- try { out.host = new URL(base).host; } catch { /* leave unset */ }
382
- return out;
383
- }
384
-
385
- // ---- backend: bridge -------------------------------------------------------
386
-
387
- // Stream the bridge SSE through the OpenAI shaper, parking on a tool call.
388
- // `trace` (when present) times the agent turn: 'upstream' = time to first token,
389
- // 'stream' = first token → park/done. The turn ends at a tool-call (parked, the
390
- // client runs the tool and POSTs back, resuming a fresh trace) or at onDone.
391
- async function pumpRelay(res, s, shaper, trace) {
392
- const restorer = makeTokenRestorer(s.vault);
393
- const t0 = trace ? trace.clock() : 0;
394
- let sStart = t0;
395
- let first = true;
396
- const tick = () => { if (trace && first) { trace.lap('upstream', t0); sStart = trace.clock(); first = false; } };
397
- await pumpBridgeStream(s, {
398
- onText: (text) => { tick(); touchRelaySession(s.id); const r = restorer.push(text); if (r) res.write(shaper.sseDelta(r)); },
399
- onToolRequest: ({ name, restoredArgs, toolId }) => {
400
- tick(); touchRelaySession(s.id);
401
- const tail = restorer.flush(); if (tail) res.write(shaper.sseDelta(tail));
402
- res.write(shaper.sseToolCalls([{ id: toolId, name, arguments: JSON.stringify(restoredArgs) }]));
403
- res.write(shaper.sseToolFinish());
404
- if (trace) trace.lap('stream', sStart);
405
- res.end(); trace?.commit(); // park: turn ends with tool_calls; the session stays alive for the follow-up
406
- },
407
- onDone: () => { const tail = restorer.flush(); if (tail) res.write(shaper.sseDelta(tail)); res.write(shaper.sseTail()); if (trace) trace.lap('stream', sStart); res.end(); endRelaySession(s.id); trace?.commit(); },
408
- onError: (e) => { res.write(`data: ${JSON.stringify({ error: { message: e.message, type: 'bridge_error' } })}\n\n`); res.end(); endRelaySession(s.id); trace?.commit(); },
409
- });
410
- }
411
-
412
- // New tool-enabled turn: open the bridge with the client's tools as MCP specs.
413
- async function startRelay(req, res, { kind, adapter, agent, run = null }, body, vault, cfg, isPro, tools, harness = null, trace = null) {
414
- const { messages, system } = adapter.toTurn(body);
415
- // The model half of `claude/opus` and the team role's run options travel with a
416
- // tool-using turn the same as with a plain one (handleBridge below).
417
- const { agentModel } = parseAgentModel(body?.model, cfg);
418
- const options = bridgeAgentOptions(cfg, { ...(agentModel ? { model: agentModel } : {}), ...(run || {}) });
419
- const token = readBridgeToken(cfg.bridge.token);
420
- const shaper = shaperFor(kind, body?.model || agent);
421
- // Full tier for everyone here (the free allowance is enforced in the main
422
- // handler), but the custom dictionary stays capped for free.
423
- const redactOpts = { tier: cfg.redaction.tier === 'full' ? 'full' : 'basic', dictionary: gatedDictionary(cfg.redaction, isPro), entities: [] };
424
- const bridgeUrl = await resolveBridgeUrl(cfg);
425
- // The session's life is idle time, re-armed on every round (toolrelay.js) — not a flat
426
- // clock from here, which ended every long tool-using turn at 135 s.
427
- const s = createRelaySession({ vault, redactOpts, bridgeUrl, token, harness });
428
- // The placeholder note is already in `system` (injected into the body after
429
- // redaction in the main handler), so toTurn() carried it here — nothing to add.
430
- let resp;
431
- try {
432
- resp = await openBridgeChat({ bridgeUrl, agent, token, messages, system, specs: toolsToSpecs(tools), options, signal: undefined });
433
- } catch (e) { endRelaySession(s.id); trace?.commit(); return sendJson(res, 502, { error: { message: `bridge: ${e.message}`, type: 'bridge_error' } }); }
434
- s.reader = resp.body.getReader();
435
- res.writeHead(200, { 'content-type': 'text/event-stream', 'cache-control': 'no-cache', connection: 'keep-alive' });
436
- res.write(shaper.sseHead());
437
- return pumpRelay(res, s, shaper, trace);
438
- }
439
-
440
- // Follow-up turn carrying a tool result: feed it to the parked agent + resume.
441
- // The relay redacts the tool result with ITS vault (the main handler skips
442
- // redaction for a relay-resume), so time that here as the 'redact' leg.
443
- async function resumeRelay(res, s, toolContent, model, trace = null) {
444
- touchRelaySession(s.id); s.rounds = (s.rounds || 0) + 1;
445
- try {
446
- const rd0 = trace ? trace.clock() : 0;
447
- await deliverToolResult(s, toolContent);
448
- if (trace) trace.lap('redact', rd0);
449
- } catch (e) { endRelaySession(s.id); trace?.commit(); return sendJson(res, 502, { error: { message: `tool-result: ${e.message}`, type: 'bridge_error' } }); }
450
- const shaper = shaperFor('openai', model || 'codex');
451
- res.writeHead(200, { 'content-type': 'text/event-stream', 'cache-control': 'no-cache', connection: 'keep-alive' });
452
- res.write(shaper.sseHead());
453
- return pumpRelay(res, s, shaper, trace);
454
- }
455
-
456
- async function handleBridge(req, res, { kind, adapter, redactable, pathname, agentOverride, harness, trace, run = null }, body, vault, cfg, isPro) {
457
- if (!redactable) {
458
- trace?.commit();
459
- return sendJson(res, 404, { error: `endpoint ${pathname} not supported by the bridge backend` });
460
- }
461
-
462
- // Tool relay (OpenAI protocol + agent destinations). A follow-up request carries
463
- // a tool result for a parked session; a new request with `tools` starts one.
464
- // The relay streams its own multi-turn flow and commits the trace when its turn
465
- // ends (parked on a tool call, or done).
466
- if (kind === 'openai') {
467
- const toolResult = adapter.extractLatestToolResult(body);
468
- if (toolResult) {
469
- const parsed = parseToolCallId(toolResult.tool_call_id);
470
- const s = parsed && getRelaySession(parsed.gwId);
471
- if (s) return resumeRelay(res, s, toolResult.content, body?.model, trace);
472
- }
473
- const tools = adapter.extractTools(body);
474
- if (tools.length && body?.stream === true) {
475
- return startRelay(req, res, { kind, adapter, agent: agentOverride || pickAgent(body?.model, cfg), run }, body, vault, cfg, isPro, tools, harness, trace);
476
- }
477
- }
478
-
479
- const { messages, system } = adapter.toTurn(body);
480
- const agent = agentOverride || pickAgent(body?.model, cfg);
481
- const wantStream = body?.stream === true;
482
- const shaper = shaperFor(kind, body?.model || agent);
483
- const token = readBridgeToken(cfg.bridge.token);
484
- const ac = new AbortController();
485
- // STOP MUST REACH THE AGENT. The client pressing Stop aborts ITS request; the bridge only
486
- // kills the CLI when the gateway's request to it goes away, and that happened only if the
487
- // gateway noticed. It listened on `req 'close'`, which on this Node fires when the REQUEST
488
- // is complete — the body was read long ago — not when the socket is cut mid-response. So
489
- // Stop in the desktop stopped nothing: Codex wrote its whole essay to nobody (measured:
490
- // the process outlived the abort by the length of the answer). The RESPONSE closing is
491
- // the signal for a severed connection; a response that finished normally is not a stop.
492
- res.on('close', () => { if (!res.writableFinished) ac.abort(); });
493
-
494
- // The model half of `claude/opus`, handed to the CLI as its `--model`. Absent for a bare
495
- // agent id, which leaves the agent on its own default exactly as before.
496
- const { agentModel } = parseAgentModel(body?.model, cfg);
497
- const turn = {
498
- bridgeUrl: await resolveBridgeUrl(cfg), agent, token, messages, system, signal: ac.signal,
499
- // Permissions and working directory from the gateway's config (the desktop's Settings →
500
- // Engine → Agents), plus the model half of `claude/opus` when the caller named one.
501
- options: bridgeAgentOptions(cfg, { ...(agentModel ? { model: agentModel } : {}), ...(run || {}) }),
502
- };
503
-
504
- if (!wantStream) {
505
- try {
506
- let full = '';
507
- const up0 = trace ? trace.clock() : 0;
508
- await streamBridgeChat(turn, (t) => { full += t; });
509
- if (trace) trace.lap('upstream', up0);
510
- const rs0 = trace ? trace.clock() : 0;
511
- const out = shaper.full(restoreText(full, vault));
512
- if (trace) trace.lap('restore', rs0);
513
- res.writeHead(200, { 'content-type': shaper.contentType });
514
- res.end(out);
515
- return trace?.commit();
516
- } catch (e) {
517
- trace?.commit();
518
- return sendJson(res, 502, { error: { message: `bridge backend failed: ${e.message}`, type: 'bridge_error' } });
519
- }
520
- }
521
-
522
- res.writeHead(200, { 'content-type': 'text/event-stream', 'cache-control': 'no-cache', connection: 'keep-alive' });
523
- res.write(shaper.sseHead());
524
- const restorer = makeTokenRestorer(vault);
525
- const up0 = trace ? trace.clock() : 0;
526
- let sStart = up0;
527
- try {
528
- let first = true;
529
- await streamBridgeChat(turn, (chunk) => {
530
- if (trace && first) { trace.lap('upstream', up0); sStart = trace.clock(); first = false; } // time-to-first-token
531
- const restored = restorer.push(chunk);
532
- if (restored) res.write(shaper.sseDelta(restored));
533
- }, shaper.sseActivity ? (evt) => {
534
- // Activity is the agent describing its own work, so it can name a file it read — and
535
- // it was handed PLACEHOLDERS, so what it echoes contains them. It is restored like any
536
- // other text on the way back: a status line is not a side channel that skips the
537
- // round trip and shows the user "[[PERSON_1]].md".
538
- //
539
- // restoreDeep, NOT the streaming restorer above: that one holds a partial token across
540
- // chunks, and pushing an unrelated object through it would splice activity text into
541
- // the middle of the assistant's message.
542
- try {
543
- res.write(shaper.sseActivity(restoreDeep(evt, vault)));
544
- } catch { /* a client that hung up mid-turn is not a reason to fail the turn */ }
545
- } : null);
546
- const tail = restorer.flush();
547
- if (tail) res.write(shaper.sseDelta(tail));
548
- res.write(shaper.sseTail());
549
- } catch (e) {
550
- res.write(`data: ${JSON.stringify({ error: { message: e.message, type: 'bridge_error' } })}\n\n`);
551
- }
552
- if (trace) trace.lap('stream', sStart);
553
- res.end();
554
- trace?.commit();
555
- }
556
-
557
- // ---- backend: api ----------------------------------------------------------
558
-
559
- // Join a destination's base URL to the incoming path WITHOUT doubling the API version.
560
- //
561
- // Every OpenAI-compatible provider tells you to paste a base that already ends at the version
562
- // — https://integrate.api.nvidia.com/v1, https://openrouter.ai/api/v1, https://router.hugging
563
- // face.co/v1 — and the request arriving here carries the version too (/v1/chat/completions).
564
- // Concatenating them produced /v1/v1/chat/completions, and what came back was the provider's
565
- // own "404 page not found". That reads like a broken gateway, or a wrong model, or a dead
566
- // channel — anything except the mis-joined URL it actually was.
567
- //
568
- // Matching on the leading segment rather than hardcoding "v1" so a provider on /v2 or a beta
569
- // path is joined correctly too.
570
- export function joinUpstream(base, pathname, search = '') {
571
- const b = String(base || '').replace(/\/+$/, '');
572
- const seg = String(pathname || '').split('/')[1];
573
- if (seg && b.endsWith(`/${seg}`)) return b.slice(0, -(seg.length + 1)) + pathname + search;
574
- return b + pathname + search;
575
- }
576
-
577
- // Paths this gateway serves ITSELF. Used only to tell "you asked for a local
578
- // feature I do not have" apart from "you asked me to proxy something upstream" —
579
- // without it, calling a route added in a newer version reports a provider failure.
580
- // How long to wait for the speaker model before telling the caller to retry. Long
581
- // enough to cover loading one already on disk (seconds) plus a slow first fetch,
582
- // short enough that a stuck download does not hold a request open forever.
583
- const EMBEDDER_WAIT_MS = 90_000;
584
-
585
- // Linear resample. Good enough for a voice-print sample — the encoder cares about
586
- // timbre, not the last decibel of fidelity — and it avoids a dependency for one
587
- // rate conversion.
588
- function resample(input, from, to) {
589
- if (from === to) return input;
590
- const ratio = from / to;
591
- const out = new Float32Array(Math.floor(input.length / ratio));
592
- for (let i = 0; i < out.length; i++) {
593
- const pos = i * ratio;
594
- const a = Math.floor(pos);
595
- const b = Math.min(input.length - 1, a + 1);
596
- const f = pos - a;
597
- out[i] = input[a] * (1 - f) + input[b] * f;
598
- }
599
- return out;
600
- }
601
-
602
- const LOCAL_NAMESPACES = ['/tts', '/stt', '/ner', '/diarize', '/skills', '/redact', '/config', '/logs', '/status', '/admin'];
603
-
604
- async function handleApi(req, res, { adapter, kind, pathname, search, base, destKey, destProtocol, harness, trace }, outBody, vault) {
605
- let upstream;
606
- const up0 = trace ? trace.clock() : 0;
607
- try {
608
- const headers = forwardHeaders(req.headers, base);
609
- // If the destination carries its own key (imported from a configured API),
610
- // forward WITH it instead of relying on the client's auth header.
611
- if (destKey) {
612
- if (destProtocol === 'anthropic') { headers['x-api-key'] = destKey; delete headers.authorization; }
613
- else { headers.authorization = `Bearer ${destKey}`; }
614
- }
615
- // SSRF guard on the config-supplied upstream: block cloud-metadata + non-http(s)
616
- // BEFORE the fetch. Loopback/LAN stay allowed (Ollama/LM Studio/homelab are the
617
- // point of a BYO gateway); only the credential-theft pivot is refused.
618
- const upstreamUrl = assertEndpointUrl(joinUpstream(base, pathname, search)).toString();
619
- upstream = await fetch(upstreamUrl, {
620
- method: req.method,
621
- headers,
622
- body: ['GET', 'HEAD'].includes(req.method) ? undefined : outBody,
623
- });
624
- } catch (e) {
625
- trace?.commit();
626
- return sendJson(res, 502, { error: `upstream fetch failed: ${e.message}` });
627
- }
628
-
629
- const ct = upstream.headers.get('content-type') || '';
630
- const resHeaders = {};
631
- upstream.headers.forEach((v, k) => { if (!HOP_BY_HOP.has(k.toLowerCase())) resHeaders[k] = v; });
632
-
633
- if (ct.includes('text/event-stream') && upstream.body) {
634
- if (trace) trace.lap('upstream', up0); // model latency to response headers
635
- const sStart = trace ? trace.clock() : 0;
636
- res.writeHead(upstream.status, resHeaders);
637
- // OpenAI streaming: restore tool-call args via the harness (real, or kept
638
- // redacted for remote MCP under redactRemote) while keeping visible text
639
- // pseudonymized. Other protocols: generic restore. The 'stream' leg spans
640
- // the body; commit once it finishes (total then covers the whole response).
641
- const piped = kind === 'openai'
642
- ? pipeRestoredOpenAIStream(upstream.body, res, vault, harness)
643
- : pipeRestoredStream(upstream.body, res, vault);
644
- return Promise.resolve(piped).finally(() => { if (trace) trace.lap('stream', sStart); trace?.commit(); });
645
- }
646
-
647
- const buf = Buffer.from(await upstream.arrayBuffer());
648
- if (trace) trace.lap('upstream', up0);
649
- if (vault && ct.includes('application/json')) {
650
- try {
651
- const rs0 = trace ? trace.clock() : 0;
652
- const json = adapter.restoreResponse(JSON.parse(buf.toString('utf8')), vault, harness);
653
- if (trace) trace.lap('restore', rs0);
654
- res.writeHead(upstream.status, { ...resHeaders, 'content-type': 'application/json' });
655
- res.end(Buffer.from(JSON.stringify(json), 'utf8'));
656
- return trace?.commit();
657
- } catch { /* fall through */ }
658
- }
659
- res.writeHead(upstream.status, resHeaders);
660
- res.end(buf);
661
- trace?.commit();
662
- }
663
-
664
- // ---- server ----------------------------------------------------------------
665
-
666
- export function createGateway(cfg = loadConfig()) {
667
- // Per-gateway ring of recent request summaries for the extension's monitoring
668
- // view (newest last). Counts + optional redaction detail + per-stage timings —
669
- // see mkTrace. Lives only here, never persisted to disk.
670
- const recentRequests = [];
671
- const recordRequest = (entry) => {
672
- recentRequests.push(entry);
673
- if (recentRequests.length > 50) recentRequests.shift();
674
- };
675
- return createServer(async (req, res) => {
676
- const url = new URL(req.url, 'http://127.0.0.1');
677
- const pathname = url.pathname;
678
-
679
- if (!isLoopbackHost(req.headers.host)) return sendJson(res, 403, { error: 'loopback only' });
680
- if (!originAllowed(req.headers.origin, cfg)) return sendJson(res, 403, { error: 'origin not allowed' });
681
-
682
- // CORS for the trusted local UIs (extension/localhost). Preflight ends here.
683
- if (req.headers.origin) setCors(res, req.headers.origin);
684
- if (req.method === 'OPTIONS') { res.writeHead(204); return res.end(); }
685
-
686
- // Admin-token handshake. The extension authenticates admin routes by its
687
- // chrome-extension:// Origin, but Chrome OMITS Origin on GET requests to a host the
688
- // extension has permission for — so config READS (GET /config) would fail. A POST
689
- // still carries the Origin, so the extension POSTs here (authorized by Origin) to get
690
- // the token, then sends it as `Authorization: Bearer` on the GET admin routes. A
691
- // drive-by web page can't reach this: its Origin isn't chrome-extension:// (Origin
692
- // check) and it has no token. Additive route — old extensions ignore it.
693
- if (pathname === '/admin/token' && req.method === 'POST') {
694
- if (!isAdminAuthorized(req)) return sendJson(res, 403, { error: 'admin: extension origin or gateway token required' });
695
- return sendJson(res, 200, { token: ensureGatewayToken() });
696
- }
697
-
698
- // M2: ADMIN routes reconfigure the gateway (POST /config) or expose its in-memory
699
- // logs (GET /logs). Unlike the /v1 data plane (open to any local client — the
700
- // product), these must not be reachable by a no-Origin local process or a drive-by
701
- // localhost web page. Require the extension Origin or the gateway token.
702
- if ((pathname === '/config' || pathname === '/logs' || pathname === '/update') && !isAdminAuthorized(req)) {
703
- return sendJson(res, 403, { error: 'admin route: extension origin or gateway token required' });
704
- }
705
- // SELF-UPDATE (0.6.107) — src/update.js. Admin-gated: it installs software. Nothing in the
706
- // request chooses WHAT is installed (the package and the release host are pinned), so the
707
- // most a caller can do is move this gateway to its channel's latest.
708
- // GET /update[?force=1] → { ok, update: { current, latest, updateAvailable, mode, canSelfUpdate, npmCommand, stale, error }, job }
709
- // POST /update → 202 { ok, job } starts it; watch GET /update, then /status until `version` moves
710
- if (pathname === '/update' && req.method === 'GET') {
711
- const update = await checkForUpdate(VERSION, { force: url.searchParams.get('force') === '1' }).catch((e) => ({ current: VERSION, updateAvailable: false, error: String(e?.message || e) }));
712
- return sendJson(res, 200, { ok: true, update, job: updateJob() });
713
- }
714
- if (pathname === '/update' && req.method === 'POST') {
715
- const job = startUpdate(VERSION);
716
- return sendJson(res, job.already ? 409 : 202, { ok: true, job });
717
- }
718
- if ((pathname === '/v1/history/key' || pathname === '/v1/history/ingest-backup')
719
- && req.method === 'POST' && !isAdminAuthorized(req)) {
720
- return sendJson(res, 403, { error: { message: 'history key route: extension origin or gateway token required', type: 'forbidden' } });
721
- }
722
- // Reads of the warm index are open (that's the product — Codex/OpenCode query it).
723
- // WRITES are not: a drive-by localhost page or a random local process must not be
724
- // able to inject records the model then trusts as the user's real history. Ingest
725
- // requires the extension Origin (which its POST always carries) or the gateway token.
726
- if ((pathname === '/v1/history/ingest' || pathname === '/v1/history/clear') && req.method === 'POST' && !isAdminAuthorized(req)) {
727
- return sendJson(res, 403, { error: { message: 'history write — extension origin or gateway token required', type: 'forbidden' } });
728
- }
729
- // Memory WRITES follow the same rule as history ingest, for a stronger reason: a memory is
730
- // carried into every future turn on every model, so a drive-by localhost page that could
731
- // POST one would be installing a standing instruction, not injecting a single record.
732
- // Reads stay open — that IS the product (Codex and Claude Code recall through it).
733
- if ((pathname === '/v1/memory/remember' || pathname === '/v1/memory/forget'
734
- || pathname === '/v1/memory/sync' || pathname === '/v1/memory/clear')
735
- && req.method === 'POST' && !isAdminAuthorized(req)) {
736
- return sendJson(res, 403, { error: { message: 'memory write — extension origin or gateway token required', type: 'forbidden' } });
737
- }
738
- // Client preferences travel between the extension and the desktop through here, and an
739
- // MCP server entry can carry an Authorization header — so READS are gated too, unlike
740
- // history and memory. A drive-by page must not learn what tools the user connected.
741
- if ((pathname === '/v1/prefs' || pathname.startsWith('/v1/prefs/') || pathname.startsWith('/v1/teams') || pathname.startsWith('/v1/agents') || pathname.startsWith('/v1/projects')) && !isAdminAuthorized(req)) {
742
- return sendJson(res, 403, { error: { message: 'prefs: extension origin or gateway token required', type: 'forbidden' } });
743
- }
744
- // The access log is who-read-what — sensitive, and writable only by the local MCP
745
- // process (which sends the gateway token). Extension Origin or token for both the
746
- // read (dashboard) and the report (MCP child); a drive-by page has neither.
747
- if (pathname.startsWith('/v1/observability') && !isAdminAuthorized(req)) {
748
- return sendJson(res, 403, { error: { message: 'observability: extension origin or gateway token required', type: 'forbidden' } });
749
- }
750
-
751
- if (req.method === 'GET' && pathname === '/health') {
752
- // `stt` is ADDITIVE (Tesla rule): old clients ignore it, new clients use it
753
- // to auto-detect local dictation. `enabled` reflects config; the model only
754
- // downloads on first use, so state may be 'off' while still available.
755
- const stt = sttEngine.health();
756
- const tts = ttsEngine.health();
757
- return sendJson(res, 200, {
758
- ok: true, version: VERSION, backend: cfg.backend, tier: cfg.redaction.tier,
759
- // WHO STARTED THIS PROCESS — additive. ChatPanel Desktop sets CHATPANEL_MANAGED_BY=desktop
760
- // on the login service it registers, so a client can say "provided by the desktop app"
761
- // and stop offering install.sh for a gateway that is already installed. Absent otherwise.
762
- ...(process.env.CHATPANEL_MANAGED_BY ? { managedBy: String(process.env.CHATPANEL_MANAGED_BY).slice(0, 32) } : {}),
763
- // THE BRIDGE THIS GATEWAY RUNS OR ADOPTED — additive. `mode` is adopted | embedded |
764
- // standalone | off; a client can say "bridge: provided by the gateway" and stop
765
- // offering a second installer.
766
- ...(bridgeSupervisor ? { bridge: bridgeSupervisor.status() } : {}),
767
- // `runtime` = 'native' (npm, fast quantized) | 'wasm' (binary, slow fp32) —
768
- // the extension uses it to advise the far-faster native gateway.
769
- stt: { enabled: cfg.stt?.enabled !== false, state: stt.state, ready: stt.ok, model: stt.model || cfg.stt?.model || DEFAULT_STT_MODEL, runtime: stt.runtime, dtype: stt.dtype },
770
- // `tts` is ADDITIVE the same way: an older extension ignores it, a newer
771
- // one uses it to offer local read-aloud instead of browser speech.
772
- tts: { enabled: cfg.tts?.enabled !== false, state: tts.state, ready: tts.ok, model: tts.model || cfg.tts?.model || DEFAULT_TTS_MODEL, voice: cfg.tts?.voice || DEFAULT_TTS_VOICE, runtime: tts.runtime, dtype: tts.dtype },
773
- });
774
- }
775
-
776
- // --- Config API (the extension's "Gateway" tab is a client of these) ---
777
- if (pathname === '/status' && req.method === 'GET') {
778
- maybeRevalidate(cfg); // throttled, fire-and-forget: reflect a refund/revoke quickly
779
- const proUnlocked = await resolvePro(cfg.pro?.entitlementToken);
780
- const health = await probeNerHealth(cfg); // live GET /health on the detector
781
- return sendJson(res, 200, {
782
- ok: true, version: VERSION, backend: cfg.backend, tier: cfg.redaction.tier,
783
- ...(process.env.CHATPANEL_MANAGED_BY ? { managedBy: String(process.env.CHATPANEL_MANAGED_BY).slice(0, 32) } : {}), // see /health
784
- ner: {
785
- autostart: !!cfg.ner?.autostart,
786
- configured: health.configured,
787
- ready: health.ok, // the detector actually answered /health
788
- model: health.model, // e.g. "en_core_web_sm"
789
- url: health.url,
790
- },
791
- // Additive: one block that answers "are names covered right now", for clients that
792
- // draw a privacy indicator and must not overstate it. See detectorStatus.
793
- detector: detectorStatus(cfg),
794
- pro: { unlocked: proUnlocked }, usage: usage(cfg),
795
- uptimeSeconds: Math.floor((Date.now() - STARTED_AT) / 1000),
796
- // ADDITIVE (0.6.107): is there a newer gateway on this install's channel, and can this
797
- // process apply it itself (POST /update)? Answered from the last check, refreshed in
798
- // the background (0.6.108) — /status never waits on the network; an older extension
799
- // ignores the key.
800
- update: updateStatus(VERSION),
801
- });
802
- }
803
- // --- WARM search tier. The extension pushes its DECRYPTED records to this LOCAL
804
- // process (on-device, loopback- + origin-gated above) which holds a BM25 index off
805
- // the browser thread and answers full-corpus search — for the panel AND other local
806
- // tools. Ranks identically to the browser hot tier (shared tokenizer/BM25).
807
- // POST /v1/history/ingest { upserts:[{id,text,title,type,date}], removes:[id] } → { size }
808
- // POST /v1/history/search { query, limit } → { results }
809
- // GET /v1/history/status → { size }
810
- // GET /v1/history/list?limit&offset → { total, items:[{id,title,type,date,chars}] }
811
- // GET /v1/history/get?id=… → { record:{id,title,type,date,text} } (for external UIs)
812
- if (pathname === '/v1/history/ingest' && req.method === 'POST') {
813
- try {
814
- const body = JSON.parse((await readBody(req, cfg.maxBodyBytes)).toString('utf8')) || {};
815
- const size = historyStore.bulk({
816
- upserts: Array.isArray(body.upserts) ? body.upserts : [],
817
- removes: Array.isArray(body.removes) ? body.removes : [],
818
- });
819
- return sendJson(res, 200, { ok: true, size });
820
- } catch (e) {
821
- return sendJson(res, 400, { error: { message: `ingest failed: ${e.message}`, type: 'ingest_error' } });
822
- }
823
- }
824
- // --- CLIENT PREFERENCES — the settings every client shares (prefs-store.js).
825
- // GET /v1/prefs[?section=id][&stamps=1] → { ok, revision, sections: { id: { value, updatedAt, by } } }
826
- // POST /v1/prefs { sections: { id: { value, updatedAt } }, by } → { ok, revision, applied, kept, sections }
827
- // DELETE /v1/prefs?section=id → { ok, removed }
828
- if (pathname === '/v1/prefs' && req.method === 'GET') {
829
- const section = String(url.searchParams.get('section') || '');
830
- if (url.searchParams.get('stamps')) return sendJson(res, 200, { ok: true, revision: prefsStore.revision, stamps: prefsStore.stamps() });
831
- return sendJson(res, 200, { ok: true, revision: prefsStore.revision, sections: prefsStore.get(section) });
832
- }
833
- if (pathname === '/v1/prefs' && (req.method === 'POST' || req.method === 'PUT')) {
834
- try {
835
- const body = JSON.parse((await readBody(req, cfg.maxBodyBytes)).toString('utf8')) || {};
836
- const out = prefsStore.put(body.sections || {}, { by: body.by || '' });
837
- if (out.applied.length) notifyPrefs(out.applied, body.by || '');
838
- return sendJson(res, 200, { ok: true, ...out });
839
- } catch (e) {
840
- return sendJson(res, 400, { error: { message: `prefs write failed: ${e.message}`, type: 'prefs_error' } });
841
- }
842
- }
843
- if (pathname === '/v1/prefs' && req.method === 'DELETE') {
844
- const section = String(url.searchParams.get('section') || '');
845
- const removed = section ? prefsStore.remove(section) : false;
846
- if (removed) notifyPrefs([section], '');
847
- return sendJson(res, 200, { ok: true, removed });
848
- }
849
- // Live prefs: one SSE stream a client keeps open, told which sections the OTHER client
850
- // wrote. Without it a team defined on the desktop reached the extension at its next
851
- // focus; with it, at once. `{ type: 'hello', revision }` first, so a reader knows where
852
- // it stands; a heartbeat keeps proxies from closing an idle stream.
853
- if (pathname === '/v1/prefs/events' && req.method === 'GET') {
854
- res.writeHead(200, { 'content-type': 'text/event-stream', 'cache-control': 'no-cache', connection: 'keep-alive' });
855
- const sendEv = (ev) => res.write(`data: ${JSON.stringify(ev)}\n\n`);
856
- sendEv({ type: 'hello', revision: prefsStore.revision, stamps: prefsStore.stamps() });
857
- const fn = (ev) => sendEv({ type: 'changed', ...ev });
858
- prefsWatchers.add(fn);
859
- const beat = setInterval(() => { try { res.write(': keep-alive\n\n'); } catch { /* closed */ } }, 25_000);
860
- res.on('close', () => { prefsWatchers.delete(fn); clearInterval(beat); });
861
- return undefined;
862
- }
863
-
864
- // --- PROJECTS. The page a goal starts on and everything done for it (project-store.js):
865
- // GET /v1/projects[?limit&status] → { ok, projects } newest activity first, jobs counted
866
- // POST /v1/projects { id, project, by } → { ok, project } open a record (idempotent) / update the page
867
- // GET /v1/projects/jobs → { ok, jobs } the job board: every open posting across projects
868
- // GET /v1/projects/:id[?events=1] → { ok, project } the record: jobs, runs, spend, decisions, report
869
- // POST /v1/projects/:id/events { events } → { ok, project } the executive loop appends (status, run.linked, run.spent, decision, report)
870
- // POST /v1/projects/:id/jobs { job, by } → { ok, project } post a job
871
- // POST /v1/projects/:id/jobs/:jobId { patch, by } → { ok, project } move it along its machine / applications / recruited / result
872
- // GET /v1/projects/:id/jobs/:jobId/applications[?reach&chatModel] → { ok, job, applications, prompt, rows }
873
- // the pool applies at once (recruiting.js); `prompt` is the evaluator's, for the client's structured call
874
- // POST /v1/projects/:id/jobs/:jobId/recruit { by, reach, chatModel, evaluation? | text? } → { ok, project, decision, applications }
875
- // one pass: fit recomputed here, the client's evaluation read through the schema, the pick (or the
876
- // proposal) landed as events — with no evaluation the fit decides
877
- // GET /v1/projects/:id/events[?after] (SSE) hello, replay, then live
878
- // DELETE /v1/projects/:id
879
- if (pathname === '/v1/projects' && req.method === 'GET') return sendJson(res, 200, { ok: true, projects: projectStore.list({ limit: url.searchParams.get('limit') || 50, status: url.searchParams.get('status') || '' }) });
880
- if (pathname === '/v1/projects/jobs' && req.method === 'GET') return sendJson(res, 200, { ok: true, jobs: projectStore.openJobs() });
881
- if (pathname === '/v1/projects' && req.method === 'POST') {
882
- try {
883
- const body = JSON.parse((await readBody(req, cfg.maxBodyBytes)).toString('utf8')) || {};
884
- return sendJson(res, 200, { ok: true, project: projectStore.create({ id: body.id || body.project?.id, project: body.project || null, by: body.by }) });
885
- } catch (e) { return sendJson(res, 400, { error: { message: `project: ${e.message}`, type: 'project_error' } }); }
886
- }
887
- {
888
- const m = /^\/v1\/projects\/([a-zA-Z0-9_-]{1,64})(\/events|\/jobs(?:\/([a-zA-Z0-9_-]{1,64})(\/applications|\/recruit)?)?)?$/.exec(pathname);
889
- if (m) {
890
- const id = m[1]; const sub = m[2] || ''; const jobId = m[3] || ''; const act = m[4] || '';
891
- const notFound = () => sendJson(res, 404, { error: { message: `no project ${id}`, type: 'not_found' } });
892
- if (act) {
893
- const rec = projectStore.get(id);
894
- if (!rec) return notFound();
895
- const job = rec.jobs.find((j) => j.id === jobId);
896
- if (!job) return sendJson(res, 404, { error: { message: `no job ${jobId}`, type: 'not_found' } });
897
- const stores = { cfg, prefsStore, scorecards, engines };
898
- if (act === '/applications' && req.method === 'GET') {
899
- const out = await applicationsFor(job, { ...stores, reach: url.searchParams.get('reach') || 'any', chatModel: url.searchParams.get('chatModel') || null });
900
- return sendJson(res, 200, { ok: true, job, ...out });
901
- }
902
- if (act === '/recruit' && req.method === 'POST') {
903
- if (!['open', 'evaluating'].includes(job.status)) return sendJson(res, 400, { error: { message: `job ${jobId} is ${job.status}; only an open job is recruited`, type: 'project_error' } });
904
- try {
905
- const body = JSON.parse((await readBody(req, cfg.maxBodyBytes)).toString('utf8')) || {};
906
- const by = String(body.by || 'evaluator').slice(0, 80);
907
- const pass = await recruitPass(job, { ...stores, record: rec, reach: body.reach || 'any', chatModel: body.chatModel || null, evaluation: body.evaluation || null, text: body.text ?? null, by });
908
- // Through the store's own moves, so the job's machine is checked on every step.
909
- let project = null;
910
- for (const e of pass.events) {
911
- if (e.type === 'job.updated') project = projectStore.updateJob(id, jobId, e.job, { by: e.by || by });
912
- else project = projectStore.append(id, [e]);
913
- }
914
- return sendJson(res, 200, { ok: true, project, decision: pass.decision, applications: pass.applications, evaluation: pass.evaluation });
915
- } catch (e) { return sendJson(res, 400, { error: { message: `recruit: ${e.message}`, type: 'project_error' } }); }
916
- }
917
- return sendJson(res, 405, { error: { message: 'method not allowed', type: 'project_error' } });
918
- }
919
- if (!sub && req.method === 'GET') { const p = projectStore.get(id, { events: url.searchParams.get('events') === '1' }); return p ? sendJson(res, 200, { ok: true, project: p }) : notFound(); }
920
- if (!sub && req.method === 'DELETE') return sendJson(res, 200, { ok: true, removed: projectStore.remove(id) });
921
- if (req.method === 'POST' && (sub === '/events' || sub.startsWith('/jobs'))) {
922
- try {
923
- const body = JSON.parse((await readBody(req, cfg.maxBodyBytes)).toString('utf8')) || {};
924
- const by = String(body.by || 'person').slice(0, 80);
925
- const project = sub === '/events' ? projectStore.append(id, body.events || [])
926
- : jobId ? projectStore.updateJob(id, jobId, body.patch || body, { by })
927
- : projectStore.postJob(id, body.job || body, { by });
928
- return sendJson(res, 200, { ok: true, project });
929
- } catch (e) { return sendJson(res, e.message.startsWith('no ') ? 404 : 400, { error: { message: `project: ${e.message}`, type: 'project_error' } }); }
930
- }
931
- if (sub === '/events' && req.method === 'GET') {
932
- if (!projectStore.get(id)) return notFound();
933
- res.writeHead(200, { 'content-type': 'text/event-stream', 'cache-control': 'no-cache', connection: 'keep-alive' });
934
- const sendEv = (ev) => res.write(`data: ${JSON.stringify(ev)}\n\n`);
935
- let last = url.searchParams.has('after') ? Number(url.searchParams.get('after')) : -1;
936
- sendEv({ seq: -1, type: 'hello', at: Date.now(), payload: { project: projectStore.get(id), after: last } });
937
- const off = projectStore.watch(id, (ev) => { if (ev.seq > last) { last = ev.seq; sendEv(ev); } });
938
- for (const ev of projectStore.eventsSince(id, last)) { last = ev.seq; sendEv(ev); }
939
- const beat = setInterval(() => { try { res.write(': keep\n\n'); } catch { /* closed */ } }, 25_000);
940
- req.on('close', () => { clearInterval(beat); off(); });
941
- return undefined;
942
- }
943
- }
944
- }
945
- // --- SCORECARDS. Every agent's attested record (scorecard-store.js): the chain, its card,
946
- // whether it verifies; a person's rating appended from either client.
947
- if (pathname === '/v1/agents/scorecards' && req.method === 'GET') return sendJson(res, 200, { ok: true, agents: scorecards.list() });
948
- {
949
- const m = /^\/v1\/agents\/([a-zA-Z0-9_.:@+-]{1,120})\/scorecard$/.exec(pathname);
950
- if (m) {
951
- const agentId = decodeURIComponent(m[1]);
952
- if (req.method === 'GET') return sendJson(res, 200, { ok: true, ...(await scorecards.get(agentId)) });
953
- if (req.method === 'POST') {
954
- try {
955
- const body = JSON.parse((await readBody(req, cfg.maxBodyBytes)).toString('utf8')) || {};
956
- const entry = await scorecards.append({ agentId, kind: 'rating', runId: body.runId, taskId: body.taskId, jobId: body.jobId, rating: { by: String(body.by || 'person').slice(0, 40), score: body.score, note: body.note, about: body.about }, refs: body.refs });
957
- // The verdict is the engine's too: it lands on the ledger of what served the task.
958
- engines.fromRating(scorecards.chains.get(agentId) || [], { ...entry, jobKind: body.jobKind ? String(body.jobKind).slice(0, 60) : undefined });
959
- return sendJson(res, 200, { ok: true, entry });
960
- } catch (e) { return sendJson(res, 400, { error: { message: `scorecard: ${e.message}`, type: 'scorecard_error' } }); }
961
- }
962
- }
963
- }
964
- // --- ENGINES. Every model's / harness's attested ledger (engine-ledger-store.js): the
965
- // card a client feeds applyCard, the chain on request; a host's observed call, a
966
- // person's price or capability proof appended from either client.
967
- // GET /v1/engines[?minCalls] → { ok, engines: [card] }
968
- // GET /v1/engines/:key/card[?entries=1] → { ok, key, card, entries?, verified?, attested? }
969
- // POST /v1/engines/:key/entries { kind, engine, call|rating|price|capability|declined, … }
970
- if (pathname === '/v1/engines' && req.method === 'GET') {
971
- const minCalls = Number(url.searchParams.get('minCalls')) || undefined;
972
- return sendJson(res, 200, { ok: true, engines: engines.list({ minCalls }) });
973
- }
974
- {
975
- const m = /^\/v1\/engines\/(.+)\/(card|entries)$/.exec(pathname);
976
- if (m) {
977
- const key = decodeURIComponent(m[1]).slice(0, 300);
978
- if (m[2] === 'card' && req.method === 'GET') {
979
- const minCalls = Number(url.searchParams.get('minCalls')) || undefined;
980
- return sendJson(res, 200, { ok: true, ...(await engines.get(key, { entries: url.searchParams.get('entries') === '1', minCalls })) });
981
- }
982
- if (m[2] === 'entries' && req.method === 'POST') {
983
- try {
984
- const body = JSON.parse((await readBody(req, cfg.maxBodyBytes)).toString('utf8')) || {};
985
- const engine = body.engine || engineFromKey(key);
986
- if (!engine) return sendJson(res, 400, { error: { message: 'model-ledger: engine required', type: 'model_ledger_error' } });
987
- const entry = await engines.append({ ...body, engine, kind: body.kind || 'call' });
988
- if (entry.key !== key) return sendJson(res, 400, { error: { message: `model-ledger: entry is for ${entry.key}, not ${key}`, type: 'model_ledger_error' } });
989
- return sendJson(res, 200, { ok: true, entry });
990
- } catch (e) { return sendJson(res, 400, { error: { message: `model-ledger: ${e.message}`, type: 'model_ledger_error' } }); }
991
- }
992
- }
993
- }
994
- // --- TEAM RUNS. The board every client can read (team-store.js).
995
- // GET /v1/teams/runs[?limit&team] → { ok, runs } newest first, no boards
996
- // POST /v1/teams/runs { id, team, request, client } → { ok, run }
997
- // GET /v1/teams/runs/:id[?events=1] → { ok, run } the board, the tasks, the proposal
998
- // POST /v1/teams/runs/:id/events { events: [...] } → { ok, run } the running client appends
999
- // GET /v1/teams/runs/:id/events[?after=seq] (SSE) replay from `after`, then live
1000
- // POST /v1/teams/runs/:id/answer { threadId, text, by } → { ok, run } a person answers an ask (0.6.81)
1001
- // POST /v1/teams/runs/:id/decide { postId, status, by } → { ok, run } approve / reject a post
1002
- // POST /v1/teams/runs/:id/post { threadId, text, kind?, replyTo?, by } → { ok, run }
1003
- // DELETE /v1/teams/runs/:id/threads/:threadId → { ok, run } a person removes a thread from the board (0.6.106)
1004
- // POST /v1/teams/runs/:id/handoff { taskId, model, by, reason } → { ok, run } continue a task on another model (0.6.85)
1005
- // GET /v1/teams/runs/:id/checkpoint → { ok, checkpoint } what resumeTeam needs, from the record
1006
- // POST /v1/teams/runs/:id/claim { client } → { ok, run } a client takes a stopped/stale run over
1007
- // POST /v1/teams/runs/:id/stop → { ok, run } a stop request any client may make
1008
- // DELETE /v1/teams/runs/:id → { ok, removed } a live run is stopped first (0.6.110)
1009
- if (pathname === '/v1/teams/runs' && req.method === 'GET') {
1010
- return sendJson(res, 200, { ok: true, runs: teamStore.list({ limit: url.searchParams.get('limit') || 50, team: url.searchParams.get('team') || '' }) });
1011
- }
1012
- if (pathname === '/v1/teams/runs' && req.method === 'POST') {
1013
- try {
1014
- const body = JSON.parse((await readBody(req, cfg.maxBodyBytes)).toString('utf8')) || {};
1015
- return sendJson(res, 200, { ok: true, run: teamStore.create({ id: body.id, client: body.client, team: body.team, request: body.request }) });
1016
- } catch (e) {
1017
- return sendJson(res, 400, { error: { message: `team run: ${e.message}`, type: 'team_error' } });
1018
- }
1019
- }
1020
- {
1021
- const m = /^\/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(pathname);
1022
- if (m) {
1023
- const id = m[1];
1024
- const sub = m[2] || '';
1025
- if (!sub && req.method === 'GET') {
1026
- const run = teamStore.get(id, { events: url.searchParams.get('events') === '1' });
1027
- return run ? sendJson(res, 200, { ok: true, run }) : sendJson(res, 404, { error: { message: `no run ${id}`, type: 'not_found' } });
1028
- }
1029
- if (!sub && req.method === 'DELETE') {
1030
- // A live run is stopped BEFORE its record goes (0.6.110), so the client running it
1031
- // hears `run.stop-requested` on its tail. Removing the record alone left the member
1032
- // working on for a run nobody could see, its appends failing until it gave up.
1033
- teamStore.stop(id);
1034
- return sendJson(res, 200, { ok: true, removed: teamStore.remove(id) });
1035
- }
1036
- if (sub === '/stop' && req.method === 'POST') {
1037
- const run = teamStore.stop(id);
1038
- return run ? sendJson(res, 200, { ok: true, run }) : sendJson(res, 404, { error: { message: `no run ${id}`, type: 'not_found' } });
1039
- }
1040
- // The board, from a person on ANY client (0.6.81): answer an ask, decide on a post,
1041
- // post a note. Each is appended as events, so the running client's tail sees it.
1042
- // A task's continuation from another client (0.6.85): hand a task to another model; read
1043
- // the checkpoint to resume a run whose client went away; claim it when resuming.
1044
- if (sub === '/checkpoint' && req.method === 'GET') {
1045
- try { return sendJson(res, 200, { ok: true, checkpoint: teamStore.checkpoint(id) }); } catch (e) { return sendJson(res, 404, { error: { message: `team run: ${e.message}`, type: 'team_error' } }); }
1046
- }
1047
- if ((sub === '/handoff' || sub === '/claim') && req.method === 'POST') {
1048
- try {
1049
- const body = JSON.parse((await readBody(req, cfg.maxBodyBytes)).toString('utf8')) || {};
1050
- const run = sub === '/handoff' ? teamStore.handoff(id, { taskId: body.taskId, model: body.model, by: body.by, reason: body.reason }) : teamStore.claim(id, { client: body.client });
1051
- return sendJson(res, 200, { ok: true, run });
1052
- } catch (e) {
1053
- return sendJson(res, e.message.startsWith('no ') ? 404 : 400, { error: { message: `team run: ${e.message}`, type: 'team_error' } });
1054
- }
1055
- }
1056
- if (sub.startsWith('/threads/') && req.method === 'DELETE') {
1057
- try { return sendJson(res, 200, { ok: true, run: teamStore.removeThread(id, { threadId: sub.slice('/threads/'.length), by: 'person' }) }); } catch (e) { return sendJson(res, e.message.startsWith('no ') ? 404 : 400, { error: { message: `team run: ${e.message}`, type: 'team_error' } }); }
1058
- }
1059
- if ((sub === '/answer' || sub === '/decide' || sub === '/post') && req.method === 'POST') {
1060
- try {
1061
- const body = JSON.parse((await readBody(req, cfg.maxBodyBytes)).toString('utf8')) || {};
1062
- const by = String(body.by || 'person').slice(0, 40);
1063
- const run = sub === '/answer' ? teamStore.answer(id, { threadId: body.threadId, text: body.text, by })
1064
- : sub === '/decide' ? teamStore.decide(id, { postId: body.postId, status: body.status, by })
1065
- : teamStore.post(id, { threadId: body.threadId, text: body.text, by, kind: body.kind, replyTo: body.replyTo });
1066
- return sendJson(res, 200, { ok: true, run });
1067
- } catch (e) {
1068
- return sendJson(res, e.message.startsWith('no ') ? 404 : 400, { error: { message: `team run: ${e.message}`, type: 'team_error' } });
1069
- }
1070
- }
1071
- if (sub === '/events' && req.method === 'POST') {
1072
- try {
1073
- const body = JSON.parse((await readBody(req, cfg.maxBodyBytes)).toString('utf8')) || {};
1074
- return sendJson(res, 200, { ok: true, run: teamStore.append(id, body.events || []) });
1075
- } catch (e) {
1076
- return sendJson(res, e.message.startsWith('no run') ? 404 : 400, { error: { message: `team run: ${e.message}`, type: 'team_error' } });
1077
- }
1078
- }
1079
- if (sub === '/events' && req.method === 'GET') {
1080
- if (!teamStore.get(id)) return sendJson(res, 404, { error: { message: `no run ${id}`, type: 'not_found' } });
1081
- res.writeHead(200, { 'content-type': 'text/event-stream', 'cache-control': 'no-cache', connection: 'keep-alive' });
1082
- const sendEv = (ev) => res.write(`data: ${JSON.stringify(ev)}\n\n`);
1083
- // `Number(null)` is 0, not NaN: an absent `after` must mean "from the start" (-1),
1084
- // or the first event of every run is skipped.
1085
- const after = url.searchParams.has('after') ? Number(url.searchParams.get('after')) : NaN;
1086
- // The record as it stands, FIRST — it flushes the headers (writeHead alone sends
1087
- // nothing, and a reader whose fetch has not resolved can miss the opening events),
1088
- // and a late reader gets the board without a second request. Then replay from
1089
- // `after`, then tail; the watcher is registered before the replay is read and
1090
- // duplicates are dropped by seq, so nothing lands in the gap.
1091
- let last = Number.isFinite(after) ? after : -1;
1092
- sendEv({ seq: -1, type: 'hello', at: Date.now(), payload: { run: teamStore.get(id), after: last } });
1093
- // A stream event (a task's text delta) has no seq: it is never stored, so it is passed live and never replayed.
1094
- const off = teamStore.watch(id, (ev) => { if (ev.seq == null) sendEv(ev); else if (ev.seq > last) { last = ev.seq; sendEv(ev); } });
1095
- for (const ev of teamStore.eventsSince(id, last)) { last = ev.seq; sendEv(ev); }
1096
- const beat = setInterval(() => { try { res.write(': keep-alive\n\n'); } catch { /* closed */ } }, 25_000);
1097
- res.on('close', () => { off(); clearInterval(beat); });
1098
- return undefined;
1099
- }
1100
- }
1101
- }
1102
-
1103
- // --- MEMORY. Small, durable facts about the user, reachable by every local agent.
1104
- // GET /v1/memory/list → { memories }
1105
- // POST /v1/memory/recall { text, scopes } → { memories, block }
1106
- // POST /v1/memory/remember { text, kind, … }→ { action, record }
1107
- // POST /v1/memory/forget { query } → { removed }
1108
- // POST /v1/memory/sync { upserts, removes } → { size, merged, memories }
1109
- if (pathname === '/v1/memory/list' && req.method === 'GET') {
1110
- return sendJson(res, 200, { ok: true, size: memoryStore.size, memories: memoryStore.list() });
1111
- }
1112
- if (pathname === '/v1/memory/recall' && req.method === 'POST') {
1113
- try {
1114
- const body = JSON.parse((await readBody(req, cfg.maxBodyBytes)).toString('utf8')) || {};
1115
- const got = memoryStore.recall({
1116
- text: String(body.text || ''),
1117
- scopes: Array.isArray(body.scopes) && body.scopes.length ? body.scopes.map(String) : ['global'],
1118
- limit: Number(body.limit) || 0,
1119
- maxChars: Number(body.maxChars) || 0,
1120
- });
1121
- return sendJson(res, 200, { ok: true, size: memoryStore.size, ...got });
1122
- } catch (e) {
1123
- return sendJson(res, 400, { error: { message: `recall failed: ${e.message}`, type: 'memory_error' } });
1124
- }
1125
- }
1126
- if (pathname === '/v1/memory/remember' && req.method === 'POST') {
1127
- try {
1128
- const body = JSON.parse((await readBody(req, cfg.maxBodyBytes)).toString('utf8')) || {};
1129
- const out = memoryStore.remember({
1130
- text: String(body.text || ''),
1131
- kind: body.kind ? String(body.kind) : 'fact',
1132
- scope: body.scope ? String(body.scope) : 'global',
1133
- tags: Array.isArray(body.tags) ? body.tags.map(String) : [],
1134
- // WHO PROPOSED IT, always recorded. There is no confirm dialog on a CLI, so
1135
- // attribution plus an inspectable list in the extension IS the accountability —
1136
- // see the MCP server's note on why writes are allowed but never anonymous.
1137
- source: {
1138
- via: String(body.source?.via || 'mcp'),
1139
- surface: String(body.source?.surface || 'mcp'),
1140
- agent: String(body.source?.agent || ''),
1141
- ref: String(body.source?.ref || ''),
1142
- },
1143
- });
1144
- return sendJson(res, 200, { ok: true, action: out.action, record: out.record, replaced: out.replaces || null, size: memoryStore.size });
1145
- } catch (e) {
1146
- return sendJson(res, 400, { error: { message: e.message, type: 'memory_error' } });
1147
- }
1148
- }
1149
- if (pathname === '/v1/memory/forget' && req.method === 'POST') {
1150
- try {
1151
- const body = JSON.parse((await readBody(req, cfg.maxBodyBytes)).toString('utf8')) || {};
1152
- const { removed } = memoryStore.forget(String(body.query || ''));
1153
- return sendJson(res, 200, { ok: true, removed, size: memoryStore.size });
1154
- } catch (e) {
1155
- return sendJson(res, 400, { error: { message: e.message, type: 'memory_error' } });
1156
- }
1157
- }
1158
- if (pathname === '/v1/memory/sync' && req.method === 'POST') {
1159
- try {
1160
- const body = JSON.parse((await readBody(req, cfg.maxBodyBytes)).toString('utf8')) || {};
1161
- const out = memoryStore.bulk({
1162
- upserts: Array.isArray(body.upserts) ? body.upserts : [],
1163
- removes: Array.isArray(body.removes) ? body.removes : [],
1164
- });
1165
- // The full set comes BACK, so one round trip is the whole two-way merge: the client
1166
- // pushes what it has and receives what the agents wrote. Convergent because both
1167
- // sides reconcile with the same function.
1168
- return sendJson(res, 200, { ok: true, ...out, memories: memoryStore.list() });
1169
- } catch (e) {
1170
- return sendJson(res, 400, { error: { message: `memory sync failed: ${e.message}`, type: 'memory_error' } });
1171
- }
1172
- }
1173
- if (pathname === '/v1/memory/clear' && req.method === 'POST') {
1174
- return sendJson(res, 200, { ok: true, dropped: memoryStore.clear(), size: memoryStore.size });
1175
- }
1176
-
1177
- if (pathname === '/v1/history/clear' && req.method === 'POST') {
1178
- const dropped = historyStore.clear();
1179
- return sendJson(res, 200, { ok: true, dropped, size: historyStore.size });
1180
- }
1181
- if (pathname === '/v1/history/search' && req.method === 'POST') {
1182
- try {
1183
- const body = JSON.parse((await readBody(req, cfg.maxBodyBytes)).toString('utf8')) || {};
1184
- const results = historyStore.search(String(body.query || ''), {
1185
- limit: Number(body.limit) || 10,
1186
- offset: Math.max(0, Number(body.offset) || 0),
1187
- type: body.type ? String(body.type) : null,
1188
- since: body.since != null ? Number(body.since) : null,
1189
- before: body.before != null ? Number(body.before) : null,
1190
- });
1191
- return sendJson(res, 200, { ok: true, size: historyStore.size, newest: historyStore.newest, results });
1192
- } catch (e) {
1193
- return sendJson(res, 400, { error: { message: `search failed: ${e.message}`, type: 'search_error' } });
1194
- }
1195
- }
1196
- // SMART SEARCH — one round trip that expands the question into several complementary
1197
- // queries, runs them all, and RRF-fuses the results. A natural-language question is a
1198
- // poor BM25 query; asking three ways and fusing beats asking once, and doing it here
1199
- // means the agent pays one call instead of probing repeatedly.
1200
- if (pathname === '/v1/history/smart-search' && req.method === 'POST') {
1201
- try {
1202
- const body = JSON.parse((await readBody(req, cfg.maxBodyBytes)).toString('utf8')) || {};
1203
- const question = String(body.question || body.query || '');
1204
- // The agent's own formulations lead (it understands the domain); planQueries adds
1205
- // deterministic variants and dedupes.
1206
- const queries = planQueries(question, {
1207
- extra: Array.isArray(body.queries) ? body.queries.map(String) : [],
1208
- max: Math.min(6, Math.max(1, Number(body.maxQueries) || 4)),
1209
- });
1210
- const filters = {
1211
- type: body.type ? String(body.type) : null,
1212
- since: body.since != null ? Number(body.since) : null,
1213
- before: body.before != null ? Number(body.before) : null,
1214
- };
1215
- const perQuery = Math.min(30, Math.max(5, Number(body.limit) || 10) * 2);
1216
- const fused = await multiSearch(
1217
- queries,
1218
- (q) => historyStore.search(q, { limit: perQuery, ...filters }),
1219
- { limit: Math.min(50, Math.max(1, Number(body.limit) || 10)) },
1220
- );
1221
- // BRIEFS LEAD. A brief is the compaction: when one matches, it answers with what a
1222
- // dozen records say, with a citation to each, and reading it saves an agent opening
1223
- // the dozen. Stable-partitioned to the front rather than re-scored, so rank among
1224
- // briefs and rank among records are both untouched — and only when the caller has
1225
- // not asked for one type, which is a question about records, not about briefs.
1226
- const results = filters.type
1227
- ? fused
1228
- : [...fused.filter((r) => r.type === 'brief'), ...fused.filter((r) => r.type !== 'brief')];
1229
- return sendJson(res, 200, {
1230
- ok: true, size: historyStore.size, newest: historyStore.newest, queries, results,
1231
- });
1232
- } catch (e) {
1233
- return sendJson(res, 400, { error: { message: `smart search failed: ${e.message}`, type: 'search_error' } });
1234
- }
1235
- }
1236
- // Graph navigation — records most connected to a given one.
1237
- if (pathname === '/v1/history/related' && req.method === 'GET') {
1238
- const id = String(url.searchParams.get('id') || '');
1239
- const limit = Math.min(30, Math.max(1, Number(url.searchParams.get('limit')) || 5));
1240
- return sendJson(res, 200, { ok: true, results: historyStore.related(id, { limit }) });
1241
- }
1242
- if (pathname === '/v1/history/status' && req.method === 'GET') {
1243
- return sendJson(res, 200, { ok: true, size: historyStore.size, newest: historyStore.newest, bytes: historyStore.bytes });
1244
- }
1245
-
1246
- // OBSERVABILITY (admin-gated above).
1247
- // GET /v1/observability → { storage:{warm:{records,bytes,newest}}, access:[…] }
1248
- // POST /v1/observability/access ← the MCP process reports one tool call
1249
- if (pathname === '/v1/observability' && req.method === 'GET') {
1250
- const limit = Math.min(500, Math.max(1, Number(url.searchParams.get('limit')) || 200));
1251
- return sendJson(res, 200, {
1252
- ok: true,
1253
- storage: { warm: { records: historyStore.size, bytes: historyStore.bytes, newest: historyStore.newest } },
1254
- access: accessLog.snapshot(limit),
1255
- });
1256
- }
1257
- if (pathname === '/v1/observability/access' && req.method === 'POST') {
1258
- try {
1259
- const body = JSON.parse((await readBody(req, cfg.maxBodyBytes)).toString('utf8')) || {};
1260
- const evt = accessLog.push(makeAccessEvent({ ts: Date.now(), ...body }));
1261
- return sendJson(res, 200, { ok: true, event: evt });
1262
- } catch (e) {
1263
- return sendJson(res, 400, { error: { message: `access log failed: ${e.message}`, type: 'observability_error' } });
1264
- }
1265
- }
1266
- if (pathname === '/v1/history/list' && req.method === 'GET') {
1267
- const limit = Math.min(500, Math.max(1, Number(url.searchParams.get('limit')) || 50));
1268
- const offset = Math.max(0, Number(url.searchParams.get('offset')) || 0);
1269
- const type = url.searchParams.get('type') || null;
1270
- return sendJson(res, 200, { ok: true, ...historyStore.list({ limit, offset, type }) });
1271
- }
1272
- if (pathname === '/v1/history/get' && req.method === 'GET') {
1273
- const maxChars = url.searchParams.get('maxChars') != null ? Math.max(1, Number(url.searchParams.get('maxChars')) || 0) : null;
1274
- const offset = Math.max(0, Number(url.searchParams.get('offset')) || 0);
1275
- const record = historyStore.get(String(url.searchParams.get('id') || ''), { maxChars, offset });
1276
- if (!record) return sendJson(res, 404, { error: { message: 'no such record', type: 'not_found' } });
1277
- return sendJson(res, 200, { ok: true, record });
1278
- }
1279
- // Key-handoff (loopback only): store the user's backup passphrase so the gateway
1280
- // can decrypt their daily backups unattended. Encrypted at rest with the local
1281
- // key. { passphrase } → stores it and does one immediate ingest. { passphrase:'' }
1282
- // forgets it. GET → whether a key is held (never returns the key itself).
1283
- if (pathname === '/v1/history/key' && req.method === 'GET') {
1284
- return sendJson(res, 200, { ok: true, hasKey: hasBackupSecret() });
1285
- }
1286
- if (pathname === '/v1/history/key' && req.method === 'POST') {
1287
- try {
1288
- const body = JSON.parse((await readBody(req, cfg.maxBodyBytes)).toString('utf8')) || {};
1289
- if (body.passphrase) saveBackupSecret(String(body.passphrase)); else clearBackupSecret();
1290
- const result = body.passphrase ? await ingestBackups(historyStore, String(body.passphrase)) : { ok: true, ingested: 0 };
1291
- return sendJson(res, 200, { ok: true, hasKey: !!body.passphrase, ...result });
1292
- } catch (e) {
1293
- return sendJson(res, 400, { error: { message: `key handoff failed: ${e.message}`, type: 'key_error' } });
1294
- }
1295
- }
1296
- // Trigger an encrypted archive refresh now using the stored key. Every rotating
1297
- // weekday snapshot that matches the key contributes records; newest values win.
1298
- if (pathname === '/v1/history/ingest-backup' && req.method === 'POST') {
1299
- try {
1300
- const result = await ingestBackups(historyStore, loadBackupSecret());
1301
- return sendJson(res, result.ok ? 200 : 409, result);
1302
- } catch (e) {
1303
- return sendJson(res, 400, { error: { message: `backup ingest failed: ${e.message}`, type: 'ingest_error' } });
1304
- }
1305
- }
1306
-
1307
- // The detector, on the gateway's own port (no second port). GET → health;
1308
- // POST {text} → {entities}. The bundled engine runs IN-PROCESS; a user's own
1309
- // external detector (if configured) is proxied for back-compat.
1310
- if (pathname === '/ner') {
1311
- if (req.method === 'GET') {
1312
- const health = await probeNerHealth(cfg);
1313
- return sendJson(res, health.ok ? 200 : 503, health);
1314
- }
1315
- if (req.method === 'POST') {
1316
- // A POST here IS the request to detect, so start the bundled engine if it is not
1317
- // running and its weights are already on disk (see ensureNer — it never downloads).
1318
- // Without this a config with `ner.autostart:false` answered 503 until a restart,
1319
- // and the client read that as "redaction is broken" while the model sat unused.
1320
- await ensureNer(cfg);
1321
- // In-process engine path.
1322
- if (nerEngine.state() !== 'off') {
1323
- // NOT READY IS NOT AN ANSWER. `detect()` returns [] when the pipeline is still
1324
- // loading or failed to load, and 200 {entities:[]} is indistinguishable from
1325
- // "this text contains no names" — the one lie a privacy layer must never tell.
1326
- // Say which state it is in instead, and let the caller show "starting…".
1327
- if (!nerEngine.isReady()) {
1328
- const h = nerEngine.health();
1329
- return sendJson(res, 503, {
1330
- error: {
1331
- message: h.state === 'error'
1332
- ? `NER model failed to load: ${h.error || 'unknown error'}`
1333
- : `NER model is ${h.state} — not ready yet`,
1334
- type: h.state === 'error' ? 'ner_error' : 'ner_loading',
1335
- },
1336
- state: h.state,
1337
- model: h.model,
1338
- });
1339
- }
1340
- try {
1341
- const body = await readBody(req, cfg.maxBodyBytes);
1342
- let text = '';
1343
- try { text = JSON.parse(body.toString('utf8'))?.text || ''; } catch { /* empty */ }
1344
- const entities = await nerEngine.detect(text);
1345
- return sendJson(res, 200, { entities });
1346
- } catch (e) {
1347
- return sendJson(res, 500, { error: { message: `NER error: ${e.message}`, type: 'ner_error' } });
1348
- }
1349
- }
1350
- // External detector proxy (user-configured endpoint).
1351
- const url = nerBaseUrl(cfg);
1352
- if (!url) {
1353
- // The bundled engine is the intended detector here and it is not running. Say
1354
- // WHY — "not configured" sent a user hunting through settings that were already
1355
- // correct, when the real answer was that the model was never downloaded.
1356
- const onDisk = nerEngine.modelOnDisk(cfg.ner?.model || undefined);
1357
- return sendJson(res, 503, {
1358
- error: {
1359
- message: onDisk
1360
- ? 'the bundled detector could not start — deterministic-only redaction'
1361
- : 'no entity detector is installed — deterministic-only redaction (install one from Gateway settings)',
1362
- type: onDisk ? 'ner_error' : 'ner_not_installed',
1363
- },
1364
- state: nerEngine.state(),
1365
- model: cfg.ner?.model || null,
1366
- });
1367
- }
1368
- try {
1369
- const body = await readBody(req, cfg.maxBodyBytes);
1370
- // secureFetch: scheme/host policy + resolved-IP check before POSTing raw text to the detector.
1371
- const r = await secureFetch(url, { method: 'POST', headers: { 'content-type': 'application/json' }, body, signal: AbortSignal.timeout(8000) });
1372
- const text = await r.text();
1373
- res.writeHead(r.status, { 'content-type': 'application/json' });
1374
- return res.end(text);
1375
- } catch (e) {
1376
- return sendJson(res, 502, { error: { message: `NER unreachable: ${e.message}`, type: 'ner_unreachable' } });
1377
- }
1378
- }
1379
- }
1380
- // WHAT THE MODEL WOULD RECEIVE. A client asks "if I sent this, what leaves the
1381
- // machine?" and gets back the redacted text plus the token→type map.
1382
- //
1383
- // WHY THIS IS A GATEWAY ROUTE AND NOT A CLIENT FUNCTION. A preview computed in the
1384
- // client is a SECOND redactor, and the day the two disagree the client is confidently
1385
- // showing the user something other than what was sent — which is worse than showing
1386
- // nothing, because it is believed. This runs the SAME redactSegments over the SAME
1387
- // config, tier, dictionary and detector as a real request, so it cannot drift: if the
1388
- // preview is wrong, the redaction is wrong too, and that is one bug rather than two.
1389
- //
1390
- // Real values NEVER appear in the response. The mapping is token→type only ('types'),
1391
- // never the 'values' detail an operator can opt into for their own logs: this answer
1392
- // crosses a process boundary to a UI, and the client already has the original text.
1393
- // The vault is discarded when this returns, so these tokens are not reusable.
1394
- if (pathname === '/redact' && req.method === 'POST') {
1395
- let text = '';
1396
- try { text = String(JSON.parse((await readBody(req, cfg.maxBodyBytes)).toString('utf8'))?.text || ''); }
1397
- catch { text = ''; }
1398
- if (!text) return sendJson(res, 200, { text: '', count: 0, sanitized: 0, entities: [], detector: detectorStatus(cfg) });
1399
- try {
1400
- let out = text;
1401
- const isPro = await resolvePro(cfg.pro?.entitlementToken);
1402
- // Same start-on-demand as a real turn, for the same reason — and so the preview
1403
- // keeps describing the request rather than a weaker version of it.
1404
- await ensureNer(cfg);
1405
- const r = await redactSegments(
1406
- [segment(() => out, (v) => { out = v; })],
1407
- cfg.redaction,
1408
- { isPro },
1409
- );
1410
- return sendJson(res, 200, {
1411
- text: out,
1412
- count: r.count || 0,
1413
- sanitized: r.sanitized || 0,
1414
- tier: cfg.redaction?.tier === 'full' ? 'full' : 'basic',
1415
- entities: redactionDetail(r.vault, 'types') || [],
1416
- // WHAT THIS PREVIEW COULD NOT SEE — additive, and the whole reason a client can be
1417
- // honest. Patterns catch emails, phones and card numbers with no detector at all,
1418
- // so a preview with the detector down looks identical to a clean one: same text,
1419
- // same shield, names intact. `coverage` is the difference, said out loud.
1420
- detector: detectorStatus(cfg),
1421
- });
1422
- } catch (e) {
1423
- // Fail LOUD. A preview that silently returns the original text would tell the user
1424
- // "nothing here is sensitive" at the exact moment redaction is broken.
1425
- return sendJson(res, 500, { error: { message: `redaction preview failed: ${e.message}`, type: 'redact_error' } });
1426
- }
1427
- }
1428
-
1429
- // Model manager (the extension's Gateway settings drive these). GET lists the
1430
- // catalog with install state + live download progress; POST switches the active
1431
- // model (downloading it first if needed) and persists the choice.
1432
- if (pathname === '/ner/models') {
1433
- if (req.method === 'GET') {
1434
- const active = nerEngine.health().model || cfg.ner?.model || null;
1435
- const available = /** @type {any[]} */ (MODEL_CATALOG.map((m) => ({ ...m, installed: nerEngine.modelOnDisk(m.id) })));
1436
- // Surface an active BYO (non-catalog) model so the UI shows it too.
1437
- if (active && !available.some((m) => m.id === active)) {
1438
- available.push({ id: active, label: active, lang: '—', custom: true, installed: nerEngine.modelOnDisk(active), note: 'Custom model (from Hugging Face).' });
1439
- }
1440
- return sendJson(res, 200, {
1441
- active,
1442
- state: nerEngine.state(),
1443
- progress: nerEngine.progress(),
1444
- available,
1445
- });
1446
- }
1447
- if (req.method === 'POST') {
1448
- let body = null;
1449
- try { body = JSON.parse((await readBody(req, cfg.maxBodyBytes)).toString('utf8')); } catch { body = null; }
1450
- const id = body && typeof body.id === 'string' ? body.id.trim() : null;
1451
- // Curated catalog OR a strictly-validated BYO id (org/name, from HF).
1452
- if (!id || !(isKnownModel(id) || isValidCustomModelId(id))) return sendJson(res, 400, { error: { message: 'unknown or invalid model id', type: 'bad_model' } });
1453
- // Persist first so a restart keeps the choice, then (re)load. Don't block the
1454
- // response on a possibly-long download — the client polls GET for progress.
1455
- applyNerModelSelection(cfg, id);
1456
- try { persistConfig(cfg, configPath()); } catch { /* best effort */ }
1457
- nerEngine.setModel(id, { onLog: (m) => console.log(m) }).then((ok) => {
1458
- if (ok && cfg.ner?.enableFullTier && cfg.redaction.tier !== 'full') cfg.redaction.tier = 'full';
1459
- });
1460
- return sendJson(res, 202, { accepted: true, active: id, state: nerEngine.state(), progress: nerEngine.progress() });
1461
- }
1462
- }
1463
- // --- Local speech-to-text (dictation). Whisper runs IN-PROCESS (stt-engine.js,
1464
- // same ONNX engine + model dir as NER); audio arrives as 16 kHz mono Float32 PCM
1465
- // chunks over loopback and ONLY TEXT ever leaves this process. Wire contract
1466
- // (additive; see docs in the hub repo):
1467
- // POST /stt/sessions {lang?} → 201 { id } (ensures the model)
1468
- // POST /stt/sessions/:id/audio binary Float32 PCM chunk → { ok }
1469
- // GET /stt/sessions/:id/events SSE: progress | interim | final | error | end
1470
- // DELETE /stt/sessions/:id flush tail → { ok }
1471
- // GET/POST /stt/models catalog + progress / switch (mirrors /ner/models)
1472
- if (pathname === '/stt/models') {
1473
- if (req.method === 'GET') {
1474
- const active = sttEngine.health().model || cfg.stt?.model || DEFAULT_STT_MODEL;
1475
- const available = /** @type {any[]} */ (STT_MODEL_CATALOG.map((m) => ({ ...m, installed: sttEngine.modelOnDisk(m.id) })));
1476
- // Surface an active CUSTOM (non-catalog) model so the UI can show it too.
1477
- if (active && !available.some((m) => m.id === active)) {
1478
- available.push({ id: active, label: active, lang: '—', tier: 'custom', custom: true, installed: sttEngine.modelOnDisk(active), note: 'Custom model (from Hugging Face).' });
1479
- }
1480
- return sendJson(res, 200, {
1481
- active,
1482
- state: sttEngine.state(),
1483
- progress: sttEngine.progress(),
1484
- available,
1485
- // Precision (quantization) picker: current choice + selectable options +
1486
- // the dtype actually loaded. On WASM only fp32 loads (see runtimeDtype).
1487
- dtype: cfg.stt?.dtype || 'auto',
1488
- loadedDtype: sttEngine.health().dtype,
1489
- runtime: sttEngine.health().runtime,
1490
- dtypes: STT_DTYPES,
1491
- });
1492
- }
1493
- if (req.method === 'POST') {
1494
- let body = null;
1495
- try { body = JSON.parse((await readBody(req, cfg.maxBodyBytes)).toString('utf8')); } catch { body = null; }
1496
- const id = body && typeof body.id === 'string' ? body.id.trim() : null;
1497
- // Curated catalog OR a strictly-validated custom whisper id (Advanced).
1498
- if (!id || !(isKnownSttModel(id) || isValidCustomSttId(id))) return sendJson(res, 400, { error: { message: 'unknown or invalid model id', type: 'bad_model' } });
1499
- // Optional precision override (q8/q4/fp16/…); 'auto' clears it.
1500
- const dtype = typeof body.dtype === 'string' && isValidDtype(body.dtype) ? body.dtype : undefined;
1501
- if (cfg.stt) cfg.stt.model = id; else cfg.stt = { enabled: true, model: id, allowDownload: true };
1502
- if (dtype) cfg.stt.dtype = dtype === 'auto' ? null : dtype;
1503
- try { persistConfig(cfg, configPath()); } catch { /* best effort */ }
1504
- sttEngine.setModel(id, { onLog: (m) => console.log(m), dtype: dtype || cfg.stt.dtype || 'auto' });
1505
- return sendJson(res, 202, { accepted: true, active: id, dtype: cfg.stt.dtype || 'auto', state: sttEngine.state(), progress: sttEngine.progress() });
1506
- }
1507
- }
1508
- // Speaker (diarization) model manager — the "who said what" x-vector model.
1509
- // GET → status + install state; POST → force-download it (ignores the
1510
- // allowDownload config flag; explicit user action from the Gateway tab).
1511
- if (pathname === '/diarize/model') {
1512
- if (req.method === 'GET') {
1513
- const h = diarizeEngine.health();
1514
- return sendJson(res, 200, {
1515
- active: diarizeEngine.DIARIZE_MODEL,
1516
- state: h.state,
1517
- progress: diarizeEngine.progress(),
1518
- available: [{ id: diarizeEngine.DIARIZE_MODEL, label: 'Speaker embeddings (wavlm)', lang: 'any', approxMB: 100, note: 'Tells voices apart for meeting transcription (who said what).', installed: diarizeEngine.modelOnDisk() }],
1519
- });
1520
- }
1521
- if (req.method === 'POST') {
1522
- diarizeEngine.download({ onLog: (m) => console.log(m) });
1523
- return sendJson(res, 202, { accepted: true, active: diarizeEngine.DIARIZE_MODEL, state: diarizeEngine.state(), progress: diarizeEngine.progress() });
1524
- }
1525
- }
1526
- // --- Local text-to-speech (voice out). Kokoro runs IN-PROCESS (tts-engine.js),
1527
- // so audio is synthesized on this machine and never leaves it. Phase 4 of
1528
- // docs/voice-pipeline.md. Model manager first, then synthesis.
1529
- if (pathname === '/tts/models') {
1530
- if (req.method === 'GET') {
1531
- const active = ttsEngine.health().model || cfg.tts?.model || resolveDefaultModel(rawOrtAvailable());
1532
- // A model needing the native runtime is still LISTED on the binary, with the
1533
- // reason — hiding it makes "why can't I clone my voice?" unanswerable.
1534
- const nativeOk = rawOrtAvailable();
1535
- const activeEntry = TTS_MODEL_CATALOG.find((m) => m.id === active) || null;
1536
- const available = /** @type {any[]} */ (TTS_MODEL_CATALOG.map((m) => ({
1537
- ...m,
1538
- installed: ttsEngine.modelOnDisk(m.id),
1539
- unavailable: m.requiresNative && !nativeOk
1540
- ? 'needs the npm gateway — the standalone binary cannot load this engine'
1541
- : undefined,
1542
- })));
1543
- if (active && !available.some((m) => m.id === active)) {
1544
- available.push({ id: active, label: active, lang: '—', tier: 'custom', custom: true, installed: ttsEngine.modelOnDisk(active), note: 'Custom model (from Hugging Face).' });
1545
- }
1546
- return sendJson(res, 200, {
1547
- active,
1548
- state: ttsEngine.state(),
1549
- progress: ttsEngine.progress(),
1550
- available,
1551
- // The default voice belongs to the model's own namespace: Kokoro's
1552
- // af_heart means nothing to Pocket, and vice versa.
1553
- voice: cfg.tts?.voice || (ttsModelEngineOf(active) === 'pocket-tts' ? DEFAULT_POCKET_VOICE : DEFAULT_TTS_VOICE),
1554
- // Architecture decides whether voices mean anything: Kokoro picks one from
1555
- // a style bank, VITS/MMS is single-speaker. An empty list tells the UI to
1556
- // hide the picker rather than offer choices that cannot take effect.
1557
- arch: ttsEngine.arch(),
1558
- // Until a model is LOADED the engine knows nothing, and answering "no voices"
1559
- // for a model that has eight made the client hide its picker on every fresh
1560
- // install (state 'off' → supportsVoices false → the single-speaker branch). Before
1561
- // the first load, the catalog answers for the active model.
1562
- supportsVoices: ttsEngine.arch() ? ttsEngine.supportsVoices() : (activeEntry ? activeEntry.arch === 'style-tts2' && !!activeEntry.voices : true),
1563
- supportsCustomVoices: ttsEngine.arch() ? ttsEngine.supportsCustomVoices() : !!activeEntry?.customVoices,
1564
- sampleRate: ttsEngine.sampleRate(),
1565
- // Built-in voices belong to Kokoro alone. VITS is single-speaker and
1566
- // SpeechT5 speaks only in a RECORDED voice, so offering Kokoro's list
1567
- // for either would be offering choices that cannot take effect.
1568
- voices: (ttsEngine.isPocket() || (!ttsEngine.arch() && ttsModelEngineOf(active) === 'pocket-tts'))
1569
- // Pocket ships eight speakers in an optional 52 MB file; report what is
1570
- // actually loaded rather than the catalog's aspiration.
1571
- ? (ttsEngine.builtinVoices().length ? ttsEngine.builtinVoices() : POCKET_VOICES)
1572
- .map((n) => ({ id: n, label: n[0].toUpperCase() + n.slice(1), lang: 'en', installed: ttsEngine.builtinVoices().includes(n) }))
1573
- : ttsEngine.arch() && ttsEngine.arch() !== 'style-tts2'
1574
- ? []
1575
- : TTS_VOICES.map((v) => ({ ...v, installed: ttsEngine.voiceOnDisk(v.id, active) })),
1576
- dtype: cfg.tts?.dtype || 'auto',
1577
- loadedDtype: ttsEngine.health().dtype,
1578
- runtime: ttsEngine.health().runtime,
1579
- dtypes: TTS_DTYPES,
1580
- });
1581
- }
1582
- if (req.method === 'POST') {
1583
- let body = null;
1584
- try { body = JSON.parse((await readBody(req, cfg.maxBodyBytes)).toString('utf8')); } catch { body = null; }
1585
- const id = body && typeof body.id === 'string' ? body.id.trim() : null;
1586
- if (id && !(isKnownTtsModel(id) || isValidCustomTtsId(id))) return sendJson(res, 400, { error: { message: 'unknown or invalid model id', type: 'bad_model' } });
1587
- // A voice id becomes a filename, so it is checked against the catalog AND
1588
- // its shape before it is ever persisted.
1589
- // A default voice may be a built-in Kokoro one OR a saved custom one; both
1590
- // live in the same field, so both shapes are accepted and both validated.
1591
- const voice = body && typeof body.voice === 'string' ? body.voice.trim() : null;
1592
- if (voice) {
1593
- const cid = ttsVoices.parseCustomVoice(voice);
1594
- const okVoice = cid ? !!ttsVoices.getVoice(cid) : (isPocketVoice(voice) || (isKnownVoice(voice) && isValidVoiceId(voice)));
1595
- if (!okVoice) return sendJson(res, 400, { error: { message: 'unknown or invalid voice', type: 'bad_voice' } });
1596
- }
1597
- const dtype = body && typeof body.dtype === 'string' && isValidTtsDtype(body.dtype) ? body.dtype : undefined;
1598
- if (!cfg.tts) cfg.tts = { enabled: true, model: DEFAULT_TTS_MODEL, voice: DEFAULT_TTS_VOICE, allowDownload: true };
1599
- if (id) cfg.tts.model = id;
1600
- if (voice) cfg.tts.voice = voice;
1601
- // Switching model must revalidate the voice, or the config ends up naming a
1602
- // Kokoro voice for SpeechT5 (which then has nothing to speak in) or a
1603
- // recorded voice for Kokoro (which cannot use one). Both states look like
1604
- // "text-to-speech is broken" from the outside, and both are reachable with
1605
- // two clicks. Only rewrite when the CURRENT voice cannot work for the new
1606
- // model — never override a voice the caller just set.
1607
- if (id && !voice) {
1608
- const wantsCustom = ttsModelHasCustomVoices(id);
1609
- // "Is it a custom voice" is not enough — it must be one that still
1610
- // EXISTS. A config naming a deleted voice is exactly the state that made
1611
- // every later request fail with "no such saved voice".
1612
- const curId = ttsVoices.parseCustomVoice(cfg.tts.voice || '');
1613
- const isCustom = !!(curId && ttsVoices.getVoice(curId));
1614
- if (wantsCustom && !isCustom) {
1615
- // Switching to a cloning model does not mean "start speaking as the user".
1616
- // A model with built-in speakers gets its default speaker; only SpeechT5,
1617
- // which has no built-ins, falls back to a saved voice.
1618
- if (ttsModelEngineOf(id) === 'pocket-tts') {
1619
- cfg.tts.voice = DEFAULT_POCKET_VOICE;
1620
- } else {
1621
- const saved = ttsVoices.listVoices();
1622
- cfg.tts.voice = saved.length ? `custom:${saved[0].id}` : '';
1623
- }
1624
- } else if (!wantsCustom && isCustom) {
1625
- cfg.tts.voice = DEFAULT_TTS_VOICE;
1626
- }
1627
- // Kokoro and Pocket name their speakers differently; carrying one over
1628
- // leaves a voice the new model has never heard of.
1629
- const toPocket = ttsModelEngineOf(id) === 'pocket-tts';
1630
- if (toPocket && !ttsVoices.parseCustomVoice(cfg.tts.voice || '') && !isPocketVoice(cfg.tts.voice)) cfg.tts.voice = DEFAULT_POCKET_VOICE;
1631
- if (!toPocket && isPocketVoice(cfg.tts.voice)) cfg.tts.voice = DEFAULT_TTS_VOICE;
1632
- }
1633
- if (dtype) cfg.tts.dtype = dtype === 'auto' ? null : dtype;
1634
- try { persistConfig(cfg, configPath()); } catch { /* best effort */ }
1635
- if (id) ttsEngine.setModel(id, { onLog: (m) => console.log(m), dtype: dtype || cfg.tts.dtype || 'auto' });
1636
- return sendJson(res, 202, { accepted: true, active: cfg.tts.model, voice: cfg.tts.voice, dtype: cfg.tts.dtype || 'auto', state: ttsEngine.state(), progress: ttsEngine.progress() });
1637
- }
1638
- }
1639
-
1640
- // --- Custom voices: a speaker embedding derived from a sample the user
1641
- // recorded. The AUDIO is embedded in-process and then discarded; only the 512
1642
- // floats are stored, under ~/.chatpanel, and they never leave this machine.
1643
- // See src/tts-voices.js for why the rules here are tighter than elsewhere.
1644
- if (pathname === '/tts/voices') {
1645
- if (req.method === 'GET') {
1646
- return sendJson(res, 200, {
1647
- voices: ttsVoices.listVoices(),
1648
- // Whether a saved voice can actually be USED right now depends on the
1649
- // active model — only SpeechT5 takes an embedding. Saying so here stops
1650
- // the UI offering voices that would be silently ignored.
1651
- usable: ttsEngine.supportsCustomVoices(),
1652
- embedder: diarizeEngine.DIARIZE_MODEL,
1653
- embedderReady: diarizeEngine.isReady(),
1654
- });
1655
- }
1656
- if (req.method === 'POST') {
1657
- let body = null;
1658
- try { body = JSON.parse((await readBody(req, cfg.maxBodyBytes)).toString('utf8')); } catch { body = null; }
1659
- const name = body && typeof body.name === 'string' ? body.name.trim() : '';
1660
- const pcm = body && Array.isArray(body.pcm) ? body.pcm : null;
1661
- // An `id` means UPDATE an existing voice rather than create one. The id is
1662
- // preserved either way, because `custom:<id>` is what the config and every
1663
- // client hold — a rename or a re-record must not orphan those.
1664
- const editId = body && typeof body.id === 'string' ? body.id.trim() : '';
1665
- if (editId) {
1666
- if (!ttsVoices.getVoice(editId)) return sendJson(res, 404, { error: { message: 'no such saved voice', type: 'bad_voice' } });
1667
- // Rename only — no new audio, so the prints are left exactly as they are.
1668
- if (!pcm) {
1669
- if (!name) return sendJson(res, 400, { error: { message: 'a name is required', type: 'bad_request' } });
1670
- try {
1671
- return sendJson(res, 200, { ...ttsVoices.renameVoice(editId, name), usable: ttsEngine.supportsCustomVoices() });
1672
- } catch (e) { return sendJson(res, 400, { error: { message: e.message, type: 'rename_failed' } }); }
1673
- }
1674
- // Re-record: same rules as a fresh take, then swap the prints in place.
1675
- if (pcm.length < 16000) {
1676
- return sendJson(res, 400, { error: { message: 'need at least 1 second of 16 kHz mono audio', type: 'sample_too_short' } });
1677
- }
1678
- } else if (!name) {
1679
- return sendJson(res, 400, { error: { message: 'a name is required', type: 'bad_request' } });
1680
- }
1681
- if (!pcm || pcm.length < 16000) {
1682
- // Under a second of audio produces an embedding dominated by whatever
1683
- // noise happened to be in it, and the resulting voice is arbitrary.
1684
- return sendJson(res, 400, { error: { message: 'need at least 1 second of 16 kHz mono audio', type: 'sample_too_short' } });
1685
- }
1686
- try {
1687
- // The embedder is the speaker model diarization already uses. WAIT for it
1688
- // rather than bailing: it is usually already on disk, where loading takes
1689
- // a couple of seconds — and the caller is holding a recording someone
1690
- // just made, so returning early means they lose it and record again.
1691
- // Only a genuine first-time download can outlast the ceiling, and that is
1692
- // the one case worth reporting as "come back in a moment".
1693
- if (!diarizeEngine.isReady()) {
1694
- const load = diarizeEngine.download({ onLog: (m) => console.log(m) });
1695
- const timedOut = Symbol('timeout');
1696
- const raced = await Promise.race([
1697
- load.then(() => null).catch((e) => e),
1698
- new Promise((r) => setTimeout(() => r(timedOut), EMBEDDER_WAIT_MS)),
1699
- ]);
1700
- if (raced === timedOut || !diarizeEngine.isReady()) {
1701
- return sendJson(res, 503, {
1702
- error: {
1703
- message: raced === timedOut
1704
- ? 'the speaker model is still downloading (~100 MB) — your recording was kept, press Save again shortly'
1705
- : `the speaker model failed to load: ${diarizeEngine.health().error || 'unknown error'}`,
1706
- type: 'embedder_not_ready',
1707
- },
1708
- progress: diarizeEngine.progress(),
1709
- });
1710
- }
1711
- }
1712
- const audio = Float32Array.from(pcm);
1713
- const vec = await diarizeEngine.embed(audio);
1714
-
1715
- // A voice print is engine-specific and the SAMPLE is about to be thrown
1716
- // away, so anything this voice might later need must be derived now.
1717
- // Pocket TTS is the engine that actually reproduces a speaker, so its
1718
- // conditioning is computed whenever its bundle is present — failing that
1719
- // is not fatal, it just means this voice works only with SpeechT5.
1720
- let pocket = null;
1721
- try {
1722
- const pt = await ttsEngine.pocketForEncoding({ allowDownload: cfg.tts?.allowDownload !== false, log: (m) => console.log(m) });
1723
- // The recorder sends 16 kHz; Mimi wants 24 kHz.
1724
- if (pt) pocket = await pt.encodeVoice(resample(audio, 16000, 24000));
1725
- } catch (e) {
1726
- console.log(`[tts] pocket conditioning unavailable for this voice (${e.message})`);
1727
- }
1728
-
1729
- const saved = editId
1730
- ? ttsVoices.replaceVoice(editId, { vec, pocket })
1731
- : ttsVoices.saveVoice({ name, vec, pocket });
1732
- // A rename may ride along with a re-record, so apply it after the swap.
1733
- const final = editId && name && name !== saved.name ? ttsVoices.renameVoice(editId, name) : saved;
1734
- console.log(`[tts] ${editId ? 're-recorded' : 'saved'} custom voice "${final.name}" (${(saved.kinds || []).join(' + ')}, sample discarded)`);
1735
- return sendJson(res, editId ? 200 : 201, { ...saved, ...final, usable: ttsEngine.supportsCustomVoices() });
1736
- } catch (e) {
1737
- return sendJson(res, 400, { error: { message: e.message, type: 'save_failed' } });
1738
- }
1739
- }
1740
- if (req.method === 'DELETE') {
1741
- const id = url.searchParams.get('id') || '';
1742
- // Deleting someone's voice print is not a soft delete — the file is gone.
1743
- const deleted = ttsVoices.deleteVoice(id);
1744
- // …and the config must not keep NAMING it. A stored voice that no longer
1745
- // exists makes every later request fail with "no such saved voice", which
1746
- // is a confusing way to be told "you deleted that one".
1747
- if (deleted && cfg.tts?.voice === `custom:${id}`) {
1748
- const left = ttsVoices.listVoices();
1749
- cfg.tts.voice = left.length ? `custom:${left[0].id}` : DEFAULT_TTS_VOICE;
1750
- try { persistConfig(cfg, configPath()); } catch { /* best effort */ }
1751
- }
1752
- return sendJson(res, 200, { deleted, voice: cfg.tts?.voice });
1753
- }
1754
- }
1755
-
1756
- // POST /tts — { text, voice?, speed? } → audio/wav — and its OpenAI-compatible
1757
- // twin POST /v1/audio/speech ({ input, voice, speed, response_format }), so any
1758
- // OpenAI client or tunnel can drive local speech with no ChatPanel-specific code.
1759
- // Both go through ONE handler: two routes must never drift into two behaviours.
1760
- //
1761
- // Deliberately NOT redacted. Every other stage in the voice pipeline redacts at
1762
- // the model-send chokepoint because the text is about to leave the machine;
1763
- // synthesis is local, so there is nothing to protect it from — and reading
1764
- // "[[PERSON_1]]" aloud to the person who wrote it is a bug, not privacy.
1765
- if ((pathname === '/tts' || pathname === '/v1/audio/speech') && req.method === 'POST') {
1766
- if (cfg.tts?.enabled === false) return sendJson(res, 503, { error: { message: 'tts is disabled in gateway config', type: 'tts_disabled' } });
1767
- let body = null;
1768
- try { body = JSON.parse((await readBody(req, cfg.maxBodyBytes)).toString('utf8')); } catch { body = null; }
1769
- // `input` is OpenAI's field name, `text` is ours — accept either on both routes.
1770
- const text = body && typeof (body.input ?? body.text) === 'string' ? String(body.input ?? body.text).trim() : '';
1771
- if (!text) return sendJson(res, 400, { error: { message: 'text is required', type: 'bad_request' } });
1772
- if (text.length > MAX_TTS_CHARS) return sendJson(res, 413, { error: { message: `text too long (max ${MAX_TTS_CHARS} chars)`, type: 'too_long' } });
1773
- const speed = Number.isFinite(body.speed) ? Math.min(2, Math.max(0.5, body.speed)) : 1;
1774
- const dest = ttsDestination(cfg);
1775
- // A remote destination has its own voice namespace (an ElevenLabs voice id is
1776
- // not a Kokoro one), so the local catalog check would reject every valid id.
1777
- const rawVoice = body && typeof body.voice === 'string' && body.voice.trim() ? body.voice.trim() : null;
1778
- const voice = rawVoice || (dest ? dest.voice : (cfg.tts?.voice || DEFAULT_TTS_VOICE));
1779
- // A REMOTE destination has its own voice namespace, so it is validated here;
1780
- // local voices cannot be resolved until the model is loaded, because which
1781
- // KIND of voice is valid depends on the architecture. See below.
1782
- if (dest && !isValidRemoteVoice(voice)) {
1783
- return sendJson(res, 400, { error: { message: 'unknown or invalid voice', type: 'bad_voice' } });
1784
- }
1785
- // We synthesize WAV only. Say so rather than returning WAV bytes under an mp3
1786
- // content-type — a client that trusts the header would play noise.
1787
- const fmt = body && typeof body.response_format === 'string' ? body.response_format.toLowerCase() : 'wav';
1788
- if (fmt !== 'wav' && fmt !== 'pcm') return sendJson(res, 400, { error: { message: `unsupported response_format "${fmt}" — this gateway synthesizes wav`, type: 'bad_format' } });
1789
- try {
1790
- // Remote destination: the caller's own auth goes upstream, the text is
1791
- // redacted first unless this destination explicitly opted out, and the
1792
- // vendor's own audio format is passed straight through rather than
1793
- // re-wrapped — we did not synthesize it and must not claim its container.
1794
- if (dest) {
1795
- const { audio, contentType, redacted } = await synthesizeRemote({
1796
- dest, text, voice, speed,
1797
- auth: req.headers.authorization || req.headers['xi-api-key'] || '',
1798
- redaction: cfg.redaction,
1799
- isPro: await resolvePro(cfg.pro?.entitlementToken),
1800
- });
1801
- res.writeHead(200, {
1802
- 'Content-Type': contentType,
1803
- 'Content-Length': String(audio.length),
1804
- 'Cache-Control': 'no-store',
1805
- // Say what actually left. A caller that asked for privacy can verify it,
1806
- // and one that turned it off can see that it is off.
1807
- 'X-Tts-Provider': dest.kind,
1808
- 'X-Tts-Redacted': String(redacted),
1809
- });
1810
- return res.end(audio);
1811
- }
1812
- const ok = await ttsEngine.ready({
1813
- onLog: (m) => console.log(m),
1814
- allowDownload: cfg.tts?.allowDownload !== false,
1815
- model: cfg.tts?.model || resolveDefaultModel(rawOrtAvailable()),
1816
- dtype: cfg.tts?.dtype || 'auto',
1817
- });
1818
- if (!ok) return sendJson(res, 503, { error: { message: ttsEngine.health().error || 'tts model not ready', type: 'tts_unavailable' } });
1819
- // Voices are resolved AFTER the model is up, because what counts as a valid
1820
- // voice is a property of the architecture: Kokoro takes a style-bank name,
1821
- // SpeechT5 takes a recorded embedding, VITS takes neither. Resolving first
1822
- // meant a `custom:` voice could reach a freshly-loaded Kokoro and fail deep
1823
- // in the engine with "invalid voice id".
1824
- const picked = resolveTtsVoice({
1825
- requested: rawVoice, configured: voice, engine: ttsEngine, voices: ttsVoices,
1826
- isPocketVoice, isKnownVoice, isValidVoiceId,
1827
- defaultVoice: DEFAULT_TTS_VOICE, defaultPocketVoice: DEFAULT_POCKET_VOICE,
1828
- });
1829
- if (!picked.ok) return sendJson(res, picked.status, { error: { message: picked.message, type: picked.type } });
1830
- const { voice: useVoice, customId, speakerEmbedding } = picked;
1831
-
1832
- const pcm = await ttsEngine.synth(text, { voice: useVoice, speed, speakerEmbedding });
1833
- // The ACTIVE model's rate, not the constant: a VITS/MMS model emits 16 kHz
1834
- // and writing it into a 24 kHz header plays it fast and chipmunked.
1835
- const rate = ttsEngine.sampleRate();
1836
- const out = fmt === 'pcm' ? Buffer.from(new Float32Array(pcm).buffer) : ttsEngine.toWav(pcm, rate);
1837
- res.writeHead(200, {
1838
- 'Content-Type': fmt === 'pcm' ? 'application/octet-stream' : 'audio/wav',
1839
- 'Content-Length': String(out.length),
1840
- 'Cache-Control': 'no-store',
1841
- 'X-Tts-Sample-Rate': String(rate),
1842
- // Say which voice actually spoke, so a caller (or a person debugging one)
1843
- // can check the setting took. Single-speaker models have nothing to say.
1844
- ...(customId || ttsEngine.isPocket() || ttsEngine.supportsVoices() ? { 'X-Tts-Voice': useVoice } : {}),
1845
- });
1846
- return res.end(out);
1847
- } catch (e) {
1848
- return sendJson(res, 500, { error: { message: e.message, type: 'tts_failed' } });
1849
- }
1850
- }
1851
-
1852
- if (pathname === '/stt/sessions' && req.method === 'POST') {
1853
- if (cfg.stt?.enabled === false) return sendJson(res, 403, { error: { message: 'STT disabled in gateway config', type: 'stt_disabled' } });
1854
- let body = null;
1855
- try { body = JSON.parse((await readBody(req, cfg.maxBodyBytes)).toString('utf8') || '{}'); } catch { body = null; }
1856
- // Kick the model load on first use (single-flight; downloads once). The
1857
- // client follows progress on the session's SSE stream.
1858
- if (!sttEngine.isReady()) {
1859
- sttEngine.init({ model: cfg.stt?.model || DEFAULT_STT_MODEL, allowDownload: cfg.stt?.allowDownload !== false, dtype: cfg.stt?.dtype || undefined, onLog: (m) => console.log(m) });
1860
- }
1861
- // Diarization is another OPTIONAL stage: load its model only when a session
1862
- // asks for it (never on the dictation path).
1863
- const wantDiarize = body?.diarize === true && cfg.stt?.diarize !== false;
1864
- if (wantDiarize && !diarizeEngine.isReady()) {
1865
- diarizeEngine.init({ allowDownload: cfg.stt?.allowDownload !== false, onLog: (m) => console.log(m) });
1866
- }
1867
- try {
1868
- // `redact: true` chains the OPTIONAL redaction hop onto finals (STT → NER,
1869
- // same composable model as everything else: any stage, with or without).
1870
- // `diarize: true` (+ optional `speakerLabel` to pin the mic channel to a
1871
- // name) attaches a speaker to each final.
1872
- // `endSilenceMs` (additive) lets a voice conversation wait longer for a
1873
- // sentence to finish than dictation into a text box needs to.
1874
- const { id } = sttEngine.createSession({ lang: body?.lang, redact: body?.redact === true, diarize: wantDiarize, speakerLabel: body?.speakerLabel, endSilenceMs: body?.endSilenceMs });
1875
- return sendJson(res, 201, { id, state: sttEngine.state() });
1876
- } catch (e) {
1877
- return sendJson(res, e.code === 'too_many_sessions' ? 429 : 500, { error: { message: e.message, type: e.code || 'stt_error' } });
1878
- }
1879
- }
1880
- {
1881
- const m = pathname.match(/^\/stt\/sessions\/([0-9a-f-]{36})(\/audio|\/events)?$/);
1882
- if (m) {
1883
- const sid = m[1];
1884
- if (m[2] === '/audio' && req.method === 'POST') {
1885
- try {
1886
- const raw = await readBody(req, cfg.maxBodyBytes);
1887
- sttEngine.pushAudio(sid, sttEngine.toFloat32(raw));
1888
- return sendJson(res, 200, { ok: true, state: sttEngine.state() });
1889
- } catch (e) {
1890
- return sendJson(res, e.code === 'no_session' ? 404 : 400, { error: { message: e.message, type: e.code || 'stt_error' } });
1891
- }
1892
- }
1893
- if (m[2] === '/events' && req.method === 'GET') {
1894
- const sess = sttEngine.getSession(sid);
1895
- if (!sess) return sendJson(res, 404, { error: { message: 'no such session', type: 'no_session' } });
1896
- res.writeHead(200, { 'content-type': 'text/event-stream', 'cache-control': 'no-cache', connection: 'keep-alive' });
1897
- const send = (ev) => res.write(`data: ${JSON.stringify(ev)}\n\n`);
1898
- // Optional STT → NER hop: redact FINALS through the same shared guard as
1899
- // chat traffic (one implementation, composed — never a second redactor).
1900
- // Interims stay raw (transient, loopback-only). NOTE: the vault is
1901
- // discarded, so these placeholders are permanent — that's the point.
1902
- const sttIsPro = sess.redact ? await resolvePro(cfg.pro?.entitlementToken) : true;
1903
- const maybeRedact = async (ev) => {
1904
- if (ev.type !== 'final' || !sess.redact) return ev;
1905
- try {
1906
- let t = ev.text;
1907
- await redactSegments([segment(() => t, (v) => { t = v; })], cfg.redaction, { isPro: sttIsPro });
1908
- return { ...ev, text: t };
1909
- } catch { return ev; } // fail-open: raw text is still local-only
1910
- };
1911
- // While the model is loading/downloading, stream progress so the UI can
1912
- // show "downloading 43%" instead of dead air on first-ever dictation.
1913
- send({ type: 'state', state: sttEngine.state() });
1914
- const progressTimer = setInterval(() => {
1915
- const st = sttEngine.state();
1916
- if (st === 'downloading' || st === 'loading') { send({ type: 'progress', state: st, ...(sttEngine.progress() || {}) }); return; }
1917
- if (st === 'error') { send({ type: 'error', code: 'model_failed', message: sttEngine.health().error || 'model failed to load', fatal: true }); clearInterval(progressTimer); return; }
1918
- // STT ready — if diarization is on, surface ITS one-time download too, so
1919
- // "who said what" doesn't silently lag while the speaker model fetches.
1920
- if (sess.diarize) {
1921
- const ds = diarizeEngine.state();
1922
- if (ds === 'downloading' || ds === 'loading') { send({ type: 'diarize-progress', state: ds, ...(diarizeEngine.progress() || {}) }); return; }
1923
- }
1924
- send({ type: 'state', state: st }); clearInterval(progressTimer);
1925
- }, 500);
1926
- progressTimer.unref?.();
1927
- // Redaction is async — chain events so finals can't overtake interims.
1928
- let evChain = Promise.resolve();
1929
- const unsub = sttEngine.subscribe(sid, (ev) => {
1930
- evChain = evChain.then(async () => {
1931
- send(await maybeRedact(ev));
1932
- if (ev.type === 'end') { clearInterval(progressTimer); res.end(); }
1933
- }).catch(() => {});
1934
- });
1935
- req.on('close', () => { clearInterval(progressTimer); unsub?.(); });
1936
- return;
1937
- }
1938
- if (!m[2] && req.method === 'DELETE') {
1939
- await sttEngine.endSession(sid);
1940
- return sendJson(res, 200, { ok: true });
1941
- }
1942
- }
1943
- }
1944
- if (pathname === '/logs' && req.method === 'GET') {
1945
- return sendJson(res, 200, { entries: [...recentRequests].reverse() }); // newest first; counts only, unless logDetail enriches each entry
1946
- }
1947
- if (pathname === '/config' && req.method === 'GET') {
1948
- const proUnlocked = await resolvePro(cfg.pro?.entitlementToken);
1949
- return sendJson(res, 200, publicConfig(cfg, { proUnlocked }));
1950
- }
1951
- if (pathname === '/config' && req.method === 'POST') {
1952
- let patch = null;
1953
- try { patch = JSON.parse((await readBody(req, cfg.maxBodyBytes)).toString('utf8')); } catch { patch = null; }
1954
- if (!patch || typeof patch !== 'object') return sendJson(res, 400, { error: 'invalid config patch' });
1955
- applyConfigPatch(cfg, patch);
1956
- try { persistConfig(cfg, configPath()); } catch (e) { return sendJson(res, 500, { error: `could not persist config: ${e.message}` }); }
1957
- // The bundled NER engine only auto-loads at startup. If the user just switched
1958
- // detection BACK to the bundled engine (or it never loaded because an external
1959
- // detector was configured at boot), load it now so it doesn't stay "not running"
1960
- // until a restart. (An external detector needs no engine.) Fire-and-forget.
1961
- const det = cfg.redaction?.detection;
1962
- const usingBundled = !det || !det.backend || det.backend === 'off';
1963
- const st = nerEngine.state();
1964
- if (cfg.ner?.autostart && usingBundled && st !== 'ready' && st !== 'loading' && st !== 'downloading') {
1965
- nerEngine.setModel(cfg.ner.model, { onLog: (m) => console.log(m) }).then((ok) => {
1966
- if (ok && cfg.ner?.enableFullTier && cfg.redaction.tier !== 'full') cfg.redaction.tier = 'full';
1967
- });
1968
- }
1969
- const proUnlocked = await resolvePro(cfg.pro?.entitlementToken);
1970
- return sendJson(res, 200, publicConfig(cfg, { proUnlocked }));
1971
- }
1972
-
1973
- // THE SKILLS ON THIS MACHINE, asked of the gateway rather than the bridge.
1974
- //
1975
- // The bridge is what reads the user's disk, so this proxies it — but a client should
1976
- // have ONE address for everything. A client that talks to the gateway for models and the
1977
- // bridge for skills has to know both are up, hold both tokens, and handle two failure
1978
- // modes for one screen; and the direct-to-bridge path is the one with no policy in front
1979
- // of it, so making it necessary for a feature is how it becomes the habit.
1980
- if (req.method === 'GET' && pathname === '/skills') {
1981
- const base = await resolveBridgeUrl(cfg);
1982
- if (!base) return sendJson(res, 503, { error: { message: 'no bridge is configured', type: 'no_bridge' } });
1983
- const token = readBridgeToken(cfg.bridge?.token);
1984
- try {
1985
- const r = await fetch(`${base}/skills`, {
1986
- headers: { Accept: 'application/json', ...(token ? { Authorization: `Bearer ${token}` } : {}) },
1987
- signal: AbortSignal.timeout(8000),
1988
- });
1989
- const data = await r.json().catch(() => ({}));
1990
- if (!r.ok) return sendJson(res, r.status, { error: { message: data?.error || `bridge ${r.status}`, type: 'bridge_error' } });
1991
- return sendJson(res, 200, { skills: Array.isArray(data?.skills) ? data.skills : [] });
1992
- } catch (e) {
1993
- return sendJson(res, 502, { error: { message: `bridge unreachable: ${e.message}`, type: 'bridge_unreachable' } });
1994
- }
1995
- }
1996
-
1997
- // ONE skill, with the prompt the list deliberately leaves out.
1998
- //
1999
- // /skills answers `promptChars` — a COUNT — because a list of ninety-five skills carrying
2000
- // ninety-five prompt bodies is a megabyte nobody asked for. A client that wants to scope a
2001
- // task to a skill needs the body itself, and the only other way to get it was to go
2002
- // straight at the bridge, which is the habit the /skills comment above exists to prevent.
2003
- //
2004
- // The id is passed through as ONE path segment, encoded. A skill id is a file name on the
2005
- // user's disk, so letting a slash or a `..` reach the bridge's reader would be asking it
2006
- // to open something else; the bridge validates too, and this is the half we own.
2007
- if (req.method === 'GET' && /^\/skills\/[^/]+$/.test(pathname)) {
2008
- const id = decodeURIComponent(pathname.slice('/skills/'.length));
2009
- if (!id || id === '.' || id === '..' || id.includes('/') || id.includes('\\')) {
2010
- return sendJson(res, 400, { error: { message: 'not a skill id', type: 'invalid_request' } });
2011
- }
2012
- const base = await resolveBridgeUrl(cfg);
2013
- if (!base) return sendJson(res, 503, { error: { message: 'no bridge is configured', type: 'no_bridge' } });
2014
- const token = readBridgeToken(cfg.bridge?.token);
2015
- try {
2016
- const r = await fetch(`${base}/skills/${encodeURIComponent(id)}`, {
2017
- headers: { Accept: 'application/json', ...(token ? { Authorization: `Bearer ${token}` } : {}) },
2018
- signal: AbortSignal.timeout(8000),
2019
- });
2020
- const data = await r.json().catch(() => ({}));
2021
- if (!r.ok) return sendJson(res, r.status, { error: { message: data?.error || `bridge ${r.status}`, type: 'bridge_error' } });
2022
- return sendJson(res, 200, { skill: data?.skill || null });
2023
- } catch (e) {
2024
- return sendJson(res, 502, { error: { message: `bridge unreachable: ${e.message}`, type: 'bridge_unreachable' } });
2025
- }
2026
- }
2027
-
2028
- // Model discovery — aggregate every destination's models.
2029
- if (req.method === 'GET' && /\/models$/.test(pathname)) {
2030
- return sendJson(res, 200, await aggregateModelsAsync(cfg));
2031
- }
2032
-
2033
- // Anything under a LOCAL namespace that reached here matched no route, which
2034
- // almost always means the caller is newer than this gateway. Falling through to
2035
- // the model proxy makes that arrive as "upstream fetch failed", pointing the
2036
- // user at their model provider for a feature their gateway simply does not
2037
- // have yet — so these 404 with the actual reason instead.
2038
- if (LOCAL_NAMESPACES.some((ns) => pathname === ns || pathname.startsWith(`${ns}/`))) {
2039
- return sendJson(res, 404, {
2040
- error: {
2041
- message: `this gateway (${VERSION}) has no ${pathname} — update it to use this feature`,
2042
- type: 'unknown_endpoint',
2043
- },
2044
- });
2045
- }
2046
-
2047
- const r = route(pathname, req.headers, cfg);
2048
- let raw;
2049
- try {
2050
- raw = await readBody(req, cfg.maxBodyBytes);
2051
- } catch (e) {
2052
- sendJson(res, e.code === 413 ? 413 : 400, { error: e.code === 413 ? 'payload too large' : 'bad request' });
2053
- req.destroy(); // stop reading an oversized/aborted upload; don't leave the socket half-open
2054
- return;
2055
- }
2056
-
2057
- // Redact the request body for the known chat endpoints.
2058
- let vault = null;
2059
- let body = null;
2060
- let outBody = raw;
2061
- let redactedCount = 0;
2062
- let sanitizedCount = 0;
2063
- let narrowedTools = 0;
2064
- let redactionOff = false;
2065
- let isPro = true;
2066
- // Off the hot path: only build a trace when logging is on, so it adds nothing
2067
- // when off (no clock reads, no record, no console line).
2068
- const trace = (cfg.logRequests && r.redactable && req.method === 'POST') ? mkTrace(recordRequest) : null;
2069
- if (r.redactable && req.method === 'POST' && raw.length) {
2070
- try { body = JSON.parse(raw.toString('utf8')); } catch { body = null; }
2071
- if (body && isRelayResume(body, r.kind)) {
2072
- // Relay tool-result follow-up: do NOT redact here — the parked session
2073
- // redacts the tool result + restores the reply with ITS vault. Pass raw.
2074
- outBody = raw;
2075
- } else if (body) {
2076
- // Auto-narrow tools to the top-K most relevant for this turn (speed) —
2077
- // same shared ranker as the extension's AUTO mode. Only MCP-named tools
2078
- // are narrowed; the client's core tools (bash/read/edit…) are always kept,
2079
- // unless tools.narrowAll is set. Mutates body.tools BEFORE redaction so
2080
- // both the API forward and the bridge relay see the trimmed set.
2081
- const tcfg = cfg.tools || {};
2082
- if (tcfg.autoNarrow !== false && Array.isArray(body.tools) && body.tools.length) {
2083
- const cap = Number(tcfg.maxPerTurn) > 0 ? Number(tcfg.maxPerTurn) : DEFAULT_GATEWAY_TOOL_CAP;
2084
- const keep = tcfg.narrowAll ? null : (t) => !MCP_NAME_RE.test(toolName(t));
2085
- const before = body.tools.length;
2086
- body.tools = narrowSpecs(body.tools, latestUserText(body, r.kind), { cap, keep, name: toolName, description: toolDesc });
2087
- narrowedTools = before - body.tools.length;
2088
- }
2089
- // Free users get full-tier redaction within a fixed lifetime allowance —
2090
- // checked here, consumed below once a redaction actually happens. Over the
2091
- // cap returns 402.
2092
- isPro = await resolvePro(cfg.pro?.entitlementToken);
2093
- const allow = checkQuota(cfg, isPro);
2094
- if (!allow.allowed) {
2095
- return sendJson(res, 402, { error: {
2096
- message: `ChatPanel Gateway free trial used up (${allow.cap} redactions). Add a ChatPanel Pro entitlement token to unlock unlimited full-tier redaction (names/orgs).`,
2097
- type: 'free_limit_reached',
2098
- } });
2099
- }
2100
- // REDACTION OFF, FOR THIS REQUEST, BECAUSE THE USER SAID SO. A note task that reads
2101
- // "write about NVIDIA GPUs" had NVIDIA replaced with an organisation placeholder, and
2102
- // the model — seeing only [[ORG_1]] — guessed a different company and wrote about
2103
- // that. The policy is right for the corpus and wrong for the user's own instruction,
2104
- // and only the user can tell which a given turn is. So an AUTHENTICATED local client
2105
- // (the desktop, the extension — both hold the gateway token) may send
2106
- // `X-ChatPanel-Redaction: off`; the trace records it so the ledger says "redaction
2107
- // was off for this turn" rather than "0 redactions", which would read as "nothing to
2108
- // redact". Anonymous callers cannot switch it off: that is what the token is for.
2109
- redactionOff = String(req.headers['x-chatpanel-redaction'] || '').trim().toLowerCase() === 'off' && isAdminAuthorized(req);
2110
- // The detector must be up BEFORE the text is redacted, not after someone notices it
2111
- // wasn't. redactSegments consults the engine and falls open when it is not ready, so
2112
- // a gateway whose engine never autostarted sent names through at full tier without a
2113
- // word. Cheap after the first call: ready → a state check, absent weights → nothing.
2114
- if (!redactionOff) await ensureNer(cfg);
2115
- const segs = redactionOff ? [] : r.adapter.collectSegments(body, cfg.redaction);
2116
- const ac = new AbortController();
2117
- res.on('close', () => { if (!res.writableFinished) ac.abort(); });
2118
- const rd0 = trace ? trace.clock() : 0;
2119
- // Redact at the configured tier for everyone (free users get name/org
2120
- // redaction within their allowance); the custom dictionary stays capped for
2121
- // free (isPro decides that inside).
2122
- const { vault: v, count, sanitized } = redactionOff ? { vault: null, count: 0, sanitized: 0 } : await redactSegments(segs, cfg.redaction, {
2123
- signal: ac.signal,
2124
- isPro,
2125
- // A detector is the only hop that sees the request BEFORE redaction. It is guarded
2126
- // (SSRF) but was not visible: /v1/observability/access is where a user answers
2127
- // "what left my machine", and this was the one thing missing from it.
2128
- onEgress: (e) => accessLog.push(makeAccessEvent({
2129
- ts: Date.now(),
2130
- client: 'redaction',
2131
- tool: `detect:${e.backend}@${e.host || 'local'}`,
2132
- ok: e.ok,
2133
- ms: e.ms,
2134
- error: e.error,
2135
- })),
2136
- });
2137
- if (trace) trace.lap('redact', rd0);
2138
- vault = v;
2139
- redactedCount = count;
2140
- sanitizedCount = sanitized || 0;
2141
- // Consume one lifetime free credit only when we actually redacted
2142
- // something, then persist. (No-op / no write for Pro.)
2143
- if (!isPro && count > 0) {
2144
- consume(cfg, isPro);
2145
- try { persistConfig(cfg, configPath()); } catch { /* best effort — usage is advisory */ }
2146
- }
2147
- // When tools are armed, tell the model placeholders are auto-restored for
2148
- // tools (so privacy-aware models USE them instead of refusing). Injected
2149
- // AFTER redaction so the note isn't itself redacted. Covers BOTH the API
2150
- // forward and the relay (which reads system from this same body).
2151
- if (!redactionOff && Array.isArray(body.tools) && body.tools.length && typeof r.adapter.injectSystemNote === 'function') {
2152
- // A relayed CLI agent brings tools of its own that run PAST this proxy and get the
2153
- // placeholder literally; an API model has only the tools in this request. The note
2154
- // has to say which is which, so the destination is looked up here — the same
2155
- // resolution as below, on the same hint, just earlier. No destination means the
2156
- // legacy bridge path, which is an agent.
2157
- const early = resolveDestination(body?.model, cfg, r.kind, {
2158
- destination: String(req.headers['x-chatpanel-destination'] || body?.chatpanel?.destination || '').trim(),
2159
- });
2160
- const ownTools = !(early && early.type === 'api');
2161
- r.adapter.injectSystemNote(body, placeholderToolNote({ toolData: cfg.tools?.toolData, ownTools }));
2162
- } else if (!redactionOff && count > 0 && typeof r.adapter.injectSystemNote === 'function') {
2163
- // No tools, but something WAS replaced: the model still meets [[LOCATION_1]] and, told
2164
- // nothing, a coding agent stops to ask what the "unresolved placeholder" means.
2165
- r.adapter.injectSystemNote(body, placeholderNote());
2166
- }
2167
- outBody = Buffer.from(JSON.stringify(body), 'utf8');
2168
- }
2169
- }
2170
-
2171
- // THE shared tool harness — same one the extension uses. The gateway only needs
2172
- // ② (tool args): restore to real for the client to run, or keep the redacted
2173
- // token for remote MCP tools when tools.toolData is "redactRemote". Results are
2174
- // re-redacted by the NEXT request's normal redaction, so ③ isn't needed here.
2175
- const harness = makeToolHarness({ vault, toolData: cfg.tools?.toolData });
2176
-
2177
- // Route by the requested model → a destination (agent via the bridge, or an
2178
- // API we forward to). Falls back to the legacy backend when none configured.
2179
- // ChatPanel's own routing envelope, never the provider's business. A caller that knows
2180
- // WHICH destination it means says so here instead of hoping a model id is unique — 39 ids
2181
- // on a three-provider machine already collide once you ignore case, and two providers
2182
- // offering the same id exactly is ordinary. Without this, `dests.find(...)` picks whichever
2183
- // destination happens to come first and the call goes out on the wrong provider's key.
2184
- // ChatPanel's routing metadata travels in HEADERS, not in the request body.
2185
- //
2186
- // It started as a `chatpanel` field on the JSON body, and NVIDIA answered "unsupported
2187
- // parameters" — OpenAI-compatible providers validate the body strictly and reject fields
2188
- // they do not know, while ignoring headers they do not know. A body field also breaks
2189
- // against any gateway older than the one that strips it, which is every gateway already
2190
- // installed. The body belongs to the provider; this hop gets its own channel.
2191
- //
2192
- // The legacy body field is still honoured (and removed) so a client that has not updated
2193
- // yet keeps working instead of 400ing at the provider.
2194
- const legacy = (body && typeof body.chatpanel === 'object' && body.chatpanel) || null;
2195
- if (legacy) {
2196
- delete body.chatpanel;
2197
- outBody = Buffer.from(JSON.stringify(body), 'utf8');
2198
- }
2199
- const hint = {
2200
- destination: String(req.headers['x-chatpanel-destination'] || legacy?.destination || '').trim(),
2201
- reach: String(req.headers['x-chatpanel-reach'] || legacy?.reach || '').trim(),
2202
- // A TEAM ROLE'S RUN, for the bridge (pillars §14.2): `{ grants, workspace, connectionId }`
2203
- // — URI-encoded JSON in a header (the body belongs to the provider), the legacy body
2204
- // field also honoured. Only the bridge path reads it; an API destination never sees it.
2205
- run: readRunHint(req.headers['x-chatpanel-run'], legacy?.run),
2206
- };
2207
- const dest = resolveDestination(body?.model, cfg, r.kind, { destination: hint.destination });
2208
- // An EXPLICIT destination that does not resolve is an error, not an invitation to fall
2209
- // back. Falling back would send a credential-bearing call to a provider the user did not
2210
- // choose — the silent-misroute version of the bug this field exists to prevent.
2211
- if (hint.destination && (!dest || dest.id !== hint.destination)) {
2212
- trace?.commit();
2213
- return sendJson(res, 404, {
2214
- error: {
2215
- message: `no destination "${hint.destination}" is configured on this gateway`,
2216
- type: 'unknown_destination',
2217
- known: listDestinations(cfg).map((d) => d.id),
2218
- },
2219
- });
2220
- }
2221
- if (trace) {
2222
- trace.meta = { t: Date.now(), model: body?.model || null, dest: dest ? dest.id : null, type: dest ? dest.type : null, redacted: redactedCount, sanitized: sanitizedCount, narrowed: narrowedTools, detail: redactionDetail(vault, cfg.logDetail), redaction: redactionOff ? 'off' : (cfg.redaction.tier || 'basic') };
2223
- }
2224
- if (dest && dest.type === 'api') {
2225
- if (!dest.baseUrl) { trace?.commit(); return sendJson(res, 502, { error: `destination "${dest.id}" has no baseUrl` }); }
2226
- if (isSelfUrl(dest.baseUrl, cfg)) {
2227
- trace?.commit();
2228
- return sendJson(res, 508, { error: { message: `destination "${dest.id}" points back at the gateway (${dest.baseUrl}) — refusing to forward (would loop).`, type: 'loop_detected' } });
2229
- }
2230
- return handleApi(req, res, { ...r, pathname, search: url.search, base: dest.baseUrl, destKey: dest.apiKey, destProtocol: dest.protocol, harness, trace }, outBody, vault);
2231
- }
2232
- return handleBridge(req, res, { ...r, pathname, agentOverride: dest?.agent, harness, trace, run: hint.run }, body, vault, cfg, isPro);
2233
- });
2234
- }
2235
-
2236
- /** `{ grants[], workspace{ repo, projectId, jobId, base? }, connectionId }` from the header or the legacy field — shaped, never a token. */
2237
- function readRunHint(header, legacy) {
2238
- let raw = legacy && typeof legacy === 'object' ? legacy : null;
2239
- if (!raw && header) { try { raw = JSON.parse(decodeURIComponent(String(header))); } catch { raw = null; } }
2240
- if (!raw || typeof raw !== 'object') return null;
2241
- const out = {};
2242
- if (Array.isArray(raw.grants)) out.grants = raw.grants.map((g) => String(g).slice(0, 80)).slice(0, 32);
2243
- if (raw.workspace && typeof raw.workspace === 'object' && raw.workspace.repo) {
2244
- const w = raw.workspace;
2245
- out.workspace = { repo: String(w.repo).slice(0, 400), projectId: String(w.projectId || '').slice(0, 120), jobId: String(w.jobId || '').slice(0, 120), ...(w.base ? { base: String(w.base).slice(0, 120) } : {}) };
2246
- }
2247
- if (raw.connectionId) out.connectionId = String(raw.connectionId).slice(0, 64);
2248
- return Object.keys(out).length ? out : null;
2249
- }
2250
-
2251
- let bridgeSupervisor = null; // the running gateway's bridge controller (bridge-supervisor.js), for /health and shutdown
2252
-
2253
- export function start(cfg = loadConfig()) {
2254
- installTimestampedConsole(); // every gateway log line gets a clock — before anything logs
2255
- ensureGatewayToken(); // M2: load/create the admin-route token (best-effort)
2256
- const server = createGateway(cfg);
2257
- const ner = startNer(cfg); // may mutate cfg.redaction when it comes up
2258
- // Re-validate the stored entitlement online on an interval; clears it and drops
2259
- // the gateway to Free when the worker reports it invalid (see
2260
- // entitlement-refresh.js).
2261
- const entitlement = startEntitlementRefresh(cfg);
2262
- // Fail LOUD on a port clash instead of crashing with a raw stack trace. We bind a
2263
- // FIXED port (4320) so the extension / install.sh / OpenCode can always find us; if
2264
- // something else already holds it, tell the user exactly how to recover (pick a new
2265
- // port, restart, and point the extension's Gateway tab at it) rather than silently
2266
- // dying or drifting to a random port.
2267
- server.on('error', (e) => {
2268
- if (e && e.code === 'EADDRINUSE') {
2269
- console.error(`Port ${cfg.port} is already in use — another app (or a second gateway) has it.`);
2270
- console.error(`Fix: free the port, or set a different one — edit "port" in ${configPath()} (or the extension's Gateway tab) and restart. The extension must point at the same port.`);
2271
- process.exit(1);
2272
- }
2273
- console.error(`Gateway server error: ${e?.message || e}`);
2274
- process.exit(1);
2275
- });
2276
- server.listen(cfg.port, cfg.host, () => {
2277
- console.log(`ChatPanel Privacy Gateway v${VERSION} on http://${cfg.host}:${cfg.port}`);
2278
- console.log(` backend : ${cfg.backend}` + (cfg.backend === 'bridge' ? ` (agent: ${cfg.bridge.agent}, via ${cfg.bridge.url})` : ''));
2279
- // THE GATEWAY CARRIES THE BRIDGE (bridge-supervisor.js): adopt one that already answers
2280
- // (the desktop's, a standalone, launchd's), else start the embedded copy as a child and
2281
- // keep it up. One install for the user; two processes on purpose. Best-effort and
2282
- // non-fatal: the gateway runs without a bridge, it just has no local agents.
2283
- ensureBridge(cfg).then((c) => { bridgeSupervisor = c; }).catch((e) => console.log(` bridge : not supervised (${e?.message || e})`));
2284
- console.log(` redaction: ${cfg.redaction.tier}` + (cfg.redaction.detection?.backend && cfg.redaction.detection.backend !== 'off'
2285
- ? ` + ${cfg.redaction.detection.backend} detector` : (cfg.ner?.autostart ? ' (+ NER starting…)' : '')));
2286
- // M7: a non-loopback bind exposes the gateway on the LAN, where the per-request
2287
- // loopback Host check is trivially satisfied by a spoofed `Host: 127.0.0.1`. The
2288
- // /v1 data plane forwards with the client's own key, but make the exposure LOUD.
2289
- if (!isLoopbackHost(cfg.host)) {
2290
- console.error(`⚠ SECURITY: gateway bound to NON-LOOPBACK host ${cfg.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.`);
2291
- }
2292
- });
2293
- // If the user handed off a backup key, refresh the warm store from the encrypted
2294
- // rotating archive in the background — so the gateway stays current even when the
2295
- // extension never runs. Best-effort; never blocks startup or crashes it.
2296
- if (hasBackupSecret()) {
2297
- ingestBackups(historyStore, loadBackupSecret())
2298
- .then((r) => { if (r?.ok) console.log(` warm : seeded ${r.ingested} records from ${r.file}`); })
2299
- .catch(() => {});
2300
- }
2301
- const shutdown = () => { ner?.stop(); entitlement.stop(); bridgeSupervisor?.stop(); server.close(() => process.exit(0)); };
2302
- process.on('SIGINT', shutdown);
2303
- process.on('SIGTERM', shutdown);
2304
- return server;
2305
- }
19
+ `),m=a.redact?await Q(t.pro?.entitlementToken):!0,f=async g=>{if(g.type!=="final"||!a.redact)return g;try{let _=g.text;return await me([Ae(()=>_,z=>{_=z})],t.redaction,{isPro:m}),{...g,text:_}}catch{return g}};i({type:"state",state:x.state()});const y=setInterval(()=>{const g=x.state();if(g==="downloading"||g==="loading"){i({type:"progress",state:g,...x.progress()||{}});return}if(g==="error"){i({type:"error",code:"model_failed",message:x.health().error||"model failed to load",fatal:!0}),clearInterval(y);return}if(a.diarize){const _=P.state();if(_==="downloading"||_==="loading"){i({type:"diarize-progress",state:_,...P.progress()||{}});return}}i({type:"state",state:g}),clearInterval(y)},500);y.unref?.();let k=Promise.resolve();const w=x.subscribe(n,g=>{k=k.then(async()=>{i(await f(g)),g.type==="end"&&(clearInterval(y),o.end())}).catch(()=>{})});r.on("close",()=>{clearInterval(y),w?.()});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:[...l].reverse()});if(c==="/config"&&r.method==="GET"){const e=await Q(t.pro?.entitlementToken);return s(o,200,Ue(t,{proUnlocked:e}))}if(c==="/config"&&r.method==="POST"){let e=null;try{e=JSON.parse((await T(r,t.maxBodyBytes)).toString("utf8"))}catch{e=null}if(!e||typeof e!="object")return s(o,400,{error:"invalid config patch"});vo(t,e),Ne(t);try{ee(t,q())}catch(f){return s(o,500,{error:`could not persist config: ${f.message}`})}const n=t.redaction?.detection,a=!n||!n.backend||n.backend==="off",i=B.state();t.ner?.autostart&&a&&i!=="ready"&&i!=="loading"&&i!=="downloading"&&B.setModel(t.ner.model,{onLog:f=>console.log(f)}).then(f=>{f&&t.ner?.enableFullTier&&t.redaction.tier!=="full"&&(t.redaction.tier="full")});const m=await Q(t.pro?.entitlementToken);return s(o,200,Ue(t,{proUnlocked:m}))}if(r.method==="GET"&&c==="/skills"){const e=await se(t);if(!e)return s(o,503,{error:{message:"no bridge is configured",type:"no_bridge"}});const n=ae(t.bridge?.token);try{const a=await fetch(`${e}/skills`,{headers:{Accept:"application/json",...n?{Authorization:`Bearer ${n}`}:{}},signal:AbortSignal.timeout(8e3)}),i=await a.json().catch(()=>({}));return a.ok?s(o,200,{skills:Array.isArray(i?.skills)?i.skills:[]}):s(o,a.status,{error:{message:i?.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 se(t);if(!n)return s(o,503,{error:{message:"no bridge is configured",type:"no_bridge"}});const a=ae(t.bridge?.token);try{const i=await fetch(`${n}/skills/${encodeURIComponent(e)}`,{headers:{Accept:"application/json",...a?{Authorization:`Bearer ${a}`}:{}},signal:AbortSignal.timeout(8e3)}),m=await i.json().catch(()=>({}));return i.ok?s(o,200,{skill:m?.skill||null}):s(o,i.status,{error:{message:m?.error||`bridge ${i.status}`,type:"bridge_error"}})}catch(i){return s(o,502,{error:{message:`bridge unreachable: ${i.message}`,type:"bridge_unreachable"}})}}if(r.method==="GET"&&/\/models$/.test(c))return s(o,200,await _o(t));if(Ko.some(e=>c===e||c.startsWith(`${e}/`)))return s(o,404,{error:{message:`this gateway (${Z}) has no ${c} — update it to use this feature`,type:"unknown_endpoint"}});const h=Ro(c,r.headers,t);let b;try{b=await T(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,M=b,A=0,D=0,W=0,R=!1,I=!0;const N=t.logRequests&&h.redactable&&r.method==="POST"?Mo(d):null;if(h.redactable&&r.method==="POST"&&b.length){try{p=JSON.parse(b.toString("utf8"))}catch{p=null}if(p&&Lo(p,h.kind))M=b;else if(p){const e=t.tools||{};if(e.autoNarrow!==!1&&Array.isArray(p.tools)&&p.tools.length){const w=Number(e.maxPerTurn)>0?Number(e.maxPerTurn):Po,g=e.narrowAll?null:z=>!$o.test(Qe(z)),_=p.tools.length;p.tools=bt(p.tools,Bo(p,h.kind),{cap:w,keep:g,name:Qe,description:No}),W=_-p.tools.length}I=await Q(t.pro?.entitlementToken);const n=wo(t,I);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"&&K(r),R||await he(t);const a=R?[]:h.adapter.collectSegments(p,t.redaction),i=new AbortController;o.on("close",()=>{o.writableFinished||i.abort()});const m=N?N.clock():0,{vault:f,count:y,sanitized:k}=R?{vault:null,count:0,sanitized:0}:await me(a,t.redaction,{signal:i.signal,isPro:I,onEgress:w=>Te.push(Ke({ts:Date.now(),client:"redaction",tool:`detect:${w.backend}@${w.host||"local"}`,ok:w.ok,ms:w.ms,error:w.error}))});if(N&&N.lap("redact",m),E=f,A=y,D=k||0,!I&&y>0){ko(t,I);try{ee(t,q())}catch{}}if(!R&&Array.isArray(p.tools)&&p.tools.length&&typeof h.adapter.injectSystemNote=="function"){const w=We(p?.model,t,h.kind,{destination:String(r.headers["x-chatpanel-destination"]||p?.chatpanel?.destination||"").trim()}),g=!(w&&w.type==="api");h.adapter.injectSystemNote(p,kt({toolData:t.tools?.toolData,ownTools:g}))}else!R&&y>0&&typeof h.adapter.injectSystemNote=="function"&&h.adapter.injectSystemNote(p,St());M=Buffer.from(JSON.stringify(p),"utf8")}}const O=wt({vault:E,toolData:t.tools?.toolData}),j=p&&typeof p.chatpanel=="object"&&p.chatpanel||null;j&&(delete p.chatpanel,M=Buffer.from(JSON.stringify(p),"utf8"));const H={destination:String(r.headers["x-chatpanel-destination"]||j?.destination||"").trim(),reach:String(r.headers["x-chatpanel-reach"]||j?.reach||"").trim(),run:Xo(r.headers["x-chatpanel-run"],j?.run)},v=We(p?.model,t,h.kind,{destination:H.destination});if(H.destination&&(!v||v.id!==H.destination))return N?.commit(),s(o,404,{error:{message:`no destination "${H.destination}" is configured on this gateway`,type:"unknown_destination",known:Oo(t).map(e=>e.id)}});N&&(N.meta={t:Date.now(),model:p?.model||null,dest:v?v.id:null,type:v?v.type:null,redacted:A,sanitized:D,narrowed:W,detail:rt(E,t.logDetail),redaction:R?"off":t.redaction.tier||"basic"});const U=Et();if(U&&v){const e=v.type==="api"?Be(U,{model:p?.model||"",endpoint:v.baseUrl||""}):At(U,v.agent||v.id)?Be(U,{model:p?.model||""}):{ok:!1,reason:`agent "${v.agent||v.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"}})}return v&&v.type==="api"?v.baseUrl?Go(v.baseUrl,t)?(N?.commit(),s(o,508,{error:{message:`destination "${v.id}" points back at the gateway (${v.baseUrl}) — refusing to forward (would loop).`,type:"loop_detected"}})):Zo(r,o,{...h,pathname:c,search:u.search,base:v.baseUrl,destKey:v.apiKey,destProtocol:v.protocol,harness:O,trace:N},M,E):(N?.commit(),s(o,502,{error:`destination "${v.id}" has no baseUrl`})):Ho(r,o,{...h,pathname:c,agentOverride:v?.agent,harness:O,trace:N,run:H.run},p,E,t,I)})}function Xo(t,l){let d=l&&typeof l=="object"?l: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 ue=null;async function Gr(t=xe()){It();let l=null;try{l=await Ot()}catch(h){throw h instanceof xt&&(console.error(`[chatpanel-gateway] org policy: ${h.message}`),process.exit(78)),h}const d=l?.policy||null;d&&(Ne(t,d),console.log(`[chatpanel-gateway] ${l.label} — ${l.signed?"signed":"unsigned"} policy from ${l.source}`)),Tt(globalThis,{allow:d?.egress?(h,{local:b})=>Pt(d,h,{local:b}):null}),$e();const r=Yo(t),o=jt(t),u=ut(t);r.on("error",h=>{h&&h.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 ${q()} (or the extension's Gateway tab) and restart. The extension must point at the same port.`),process.exit(1)),console.error(`Gateway server error: ${h?.message||h}`),process.exit(1)}),r.listen(t.port,t.host,()=>{console.log(`ChatPanel Privacy Gateway v${Z} on http://${t.host}:${t.port}`),console.log(` backend : ${t.backend}`+(t.backend==="bridge"?` (agent: ${t.bridge.agent}, via ${t.bridge.url})`:"")),Wt(t).then(h=>{ue=h}).catch(h=>console.log(` bridge : not supervised (${h?.message||h})`)),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…)":"")),tt(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.`)}),Re()&&ge($,Me()).then(h=>{h?.ok&&console.log(` warm : seeded ${h.ingested} records from ${h.file}`)}).catch(()=>{});const c=()=>{o?.stop(),u.stop(),ue?.stop(),r.close(()=>process.exit(0))};return process.on("SIGINT",c),process.on("SIGTERM",c),r}export{Z as VERSION,Yo as createGateway,Uo as joinUpstream,_e as parseAgentModel,Gr as start};