@chatpanel/gateway 0.6.109 → 0.7.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +24 -4
- package/bin/chatpanel-gateway-bin.mjs +1 -24
- package/bin/chatpanel-gateway.js +3 -97
- package/package.json +1 -7
- package/src/access-log-store.js +1 -45
- package/src/agent.js +2 -256
- package/src/anthropic.js +3 -83
- package/src/backup-decrypt.js +1 -45
- package/src/backup-ingest.js +6 -120
- package/src/bridge-supervisor.js +3 -212
- package/src/bridge.js +4 -252
- package/src/budget.js +1 -117
- package/src/config.js +1 -209
- package/src/configstore.js +1 -181
- package/src/connect-agents.js +22 -179
- package/src/diarize-engine.js +1 -188
- package/src/egress.js +2 -0
- package/src/engine-ledger-store.js +1 -150
- package/src/engine.js +1 -132
- package/src/entitlement-refresh.js +1 -84
- package/src/entitlement.js +1 -76
- package/src/extraction.js +4 -294
- package/src/freegate.js +1 -47
- package/src/gate.js +1 -75
- package/src/gateway-token.js +1 -60
- package/src/history-store.js +1 -251
- package/src/job.js +3 -148
- package/src/knowledge.js +3 -215
- package/src/local-status.js +6 -102
- package/src/log.js +1 -21
- package/src/mcp-cli.js +19 -113
- package/src/mcp.js +34 -546
- package/src/memory-store.js +1 -176
- package/src/memory.js +2 -642
- package/src/model-integrity.js +1 -82
- package/src/model-ledger.js +1 -229
- package/src/model-runtime.js +1 -37
- package/src/models.js +1 -92
- package/src/ner-engine.js +1 -318
- package/src/ner.js +1 -113
- package/src/observability.js +1 -123
- package/src/openai.js +2 -84
- package/src/ort.js +1 -52
- package/src/parakeet-engine.js +2 -228
- package/src/pocket-tts-engine.js +1 -520
- package/src/prefs-store.js +1 -149
- package/src/project-store.js +1 -139
- package/src/project.js +1 -171
- package/src/recruit.js +3 -424
- package/src/recruiting.js +1 -93
- package/src/redact.js +2 -123
- package/src/responses.js +2 -80
- package/src/router.js +1 -292
- package/src/rrf.js +1 -93
- package/src/scorecard-store.js +1 -92
- package/src/scorecard.js +1 -336
- package/src/search-index.js +2 -134
- package/src/secure-fetch.js +1 -58
- package/src/sentencepiece.js +1 -184
- package/src/server.js +10 -2290
- package/src/service.js +11 -189
- package/src/shape.js +5 -121
- package/src/sqlite-store.js +3 -212
- package/src/stream.js +5 -182
- package/src/structured.js +4 -902
- package/src/stt-engine.js +1 -486
- package/src/stt-models.js +1 -144
- package/src/subject-kinds.js +1 -6
- package/src/subject-name.js +1 -97
- package/src/team-board.js +6 -338
- package/src/team-record.js +1 -226
- package/src/team-store.js +1 -261
- package/src/team.js +1 -303
- package/src/toolrelay.js +3 -122
- package/src/tts-engine.js +1 -453
- package/src/tts-models.js +1 -254
- package/src/tts-remote.js +1 -109
- package/src/tts-voice-resolve.js +1 -78
- package/src/tts-voices.js +1 -192
- package/src/update.js +1 -305
package/src/server.js
CHANGED
|
@@ -1,2299 +1,19 @@
|
|
|
1
|
-
|
|
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 at}from"node:http";import{loadConfig as Oe}from"./config.js";import{startEntitlementRefresh as it,maybeRevalidate as lt}from"./entitlement-refresh.js";import{redactSegments as de,segment as Ee}from"./redact.js";import{pipeRestoredStream as ct,pipeRestoredOpenAIStream as dt,makeTokenRestorer as xe,restoreDeep as ut}from"./stream.js";import{restoreText as mt,gatedDictionary as pt,narrowSpecs as yt,makeToolHarness as ht,placeholderToolNote as ft,placeholderNote as gt,assertEndpointUrl as bt}from"@chatpanel/pii";import{ensureGatewayToken as Ae,isAdminAuthorized as W}from"./gateway-token.js";import{installEgressLedger as wt,egressAudit as kt}from"./egress.js";import{resolveBridgeUrl as re}from"./bridge.js";import{secureFetch as Pe}from"./secure-fetch.js";import{streamBridgeChat as $e,readBridgeToken as ne,openBridgeChat as St}from"./bridge.js";import{createRelaySession as vt,getRelaySession as Ne,endRelaySession as se,pumpBridgeStream as Tt,deliverToolResult as _t,toolsToSpecs as Ot,parseToolCallId as Be,touchRelaySession as ue}from"./toolrelay.js";import{shaperFor as me}from"./shape.js";import{startNer as Et,ensureNer as pe}from"./ner.js";import{installTimestampedConsole as xt}from"./log.js";import{saveBackupSecret as At,clearBackupSecret as Pt,loadBackupSecret as Ce,hasBackupSecret as De}from"./history-store.js";import{createMemoryStore as $t}from"./memory-store.js";import{createPrefsStore as Nt}from"./prefs-store.js";import{createTeamStore as Bt,loadOrCreateKey as ye}from"./team-store.js";import{createScorecardStore as Ct}from"./scorecard-store.js";import{createEngineLedgerStore as Dt}from"./engine-ledger-store.js";import{createProjectStore as jt}from"./project-store.js";import{applicationsFor as It,recruitPass as Mt}from"./recruiting.js";import{ensureBridge as Rt}from"./bridge-supervisor.js";import{checkForUpdate as Lt,updateStatus as Gt,startUpdate as zt,updateJob as Vt}from"./update.js";import{createHistoryStore as Jt}from"./sqlite-store.js";import{ingestBackups as he}from"./backup-ingest.js";import*as N from"./ner-engine.js";import*as E from"./stt-engine.js";import*as P from"./diarize-engine.js";import{MODEL_CATALOG as Ht,isKnownModel as Ut,isValidCustomModelId as Ft}from"./models.js";import{STT_MODEL_CATALOG as Wt,isKnownSttModel as Kt,isValidCustomSttId as Zt,DEFAULT_STT_MODEL as fe,STT_DTYPES as Yt,isValidDtype as Xt}from"./stt-models.js";import*as k from"./tts-engine.js";import{TTS_MODEL_CATALOG as je,TTS_VOICES as Qt,isKnownTtsModel as qt,isValidCustomTtsId as eo,isKnownVoice as Ie,isValidVoiceId as Me,DEFAULT_TTS_MODEL as Re,DEFAULT_TTS_VOICE as Z,TTS_DTYPES as to,isValidTtsDtype as oo,MAX_TTS_CHARS as Le,ttsModelHasCustomVoices as ro,resolveDefaultModel as Ge,POCKET_VOICES as no,DEFAULT_POCKET_VOICE as ae,isPocketVoice as ie,ttsModelEngine as le}from"./tts-models.js";import{ttsDestination as so,synthesizeRemote as ao,isValidRemoteVoice as io}from"./tts-remote.js";import{rawOrtAvailable as ge}from"./ort.js";import*as L from"./tts-voices.js";import{resolveTtsVoice as lo}from"./tts-voice-resolve.js";import{resolvePro as X,checkQuota as co,consume as uo,usage as mo}from"./freegate.js";import{publicConfig as ze,applyConfigPatch as po,applyNerModelSelection as yo,persistConfig as q,configPath as Q,bridgeAgentOptions as Ve}from"./configstore.js";import{resolveDestination as Je,aggregateModelsAsync as ho,listDestinations as fo}from"./router.js";import{makeAccessEvent as He}from"./observability.js";import{createPersistentAccessLog as go}from"./access-log-store.js";import{planQueries as bo,multiSearch as wo}from"./rrf.js";import*as be from"./openai.js";import*as Ue from"./responses.js";import*as we from"./anthropic.js";const K="0.7.0",$=await Jt(),J=await $t(),U=Nt(),ee=Ct({key:ye()}),te=Dt({key:ye()}),G=jt({key:ye()}),C=Bt({scorecards:ee,engines:te}),ke=new Set,Fe=(t,i)=>{for(const d of ke)try{d({applied:t,by:i,revision:U.revision})}catch{}},Se=go(),We=new Set(["codex","claude","opencode","pi","kiro","antigravity","hermes"]),ko=16,So=/^mcp[_-]/i,Ke=t=>t&&t.function&&t.function.name||t&&t.name||"",vo=t=>t&&t.function&&t.function.description||t&&t.description||"";function Ze(t){return typeof t=="string"?t:Array.isArray(t)?t.map(i=>typeof i=="string"?i:i&&(i.text||i.content)||"").join(" "):""}function To(t,i){if(!t)return"";if(i==="responses"){const r=t.input;return typeof r=="string"?r:Array.isArray(r)?r.map(o=>Ze(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 Ze(d[r].content);return""}const Ye=new Set(["host","connection","content-length","transfer-encoding","accept-encoding","content-encoding","keep-alive"]);function Xe(t){if(!t)return!1;const i=t.replace(/:\d+$/,"").replace(/^\[|\]$/g,"");return i==="localhost"||i==="127.0.0.1"||i==="::1"}function _o(t,i){return!t||/^chrome-extension:\/\//.test(t)||/^moz-extension:\/\//.test(t)||/^http:\/\/(localhost|127\.0\.0\.1|\[::1\])(:\d+)?$/.test(t)?!0:Array.isArray(i.allowedOrigins)&&i.allowedOrigins.includes(t)}function Oo(t,i){t.setHeader("Access-Control-Allow-Origin",i||"*"),t.setHeader("Access-Control-Allow-Methods","GET, POST, PUT, DELETE, OPTIONS"),t.setHeader("Access-Control-Allow-Headers","Content-Type, Authorization, X-ChatPanel-Token"),t.setHeader("Vary","Origin")}const Qe=Date.now();function Eo(t){if(!t)return"";const i={redact:"redact",upstream:"model",stream:"stream",restore:"restore",total:"total"};return Object.keys(t).map(d=>`${i[d]||d} ${t[d]}ms`).join(" · ")}function xo(t){const i=/^(model|harness):([^/]+)(?:\/(.+))?$/.exec(String(t||""));return i?{kind:i[1],id:i[2],...i[3]?{model:i[3]}:{}}:null}function Ao(t){const i=performance.now(),d={};let r=!1;const o=(u,c)=>{d[u]=Math.round(c*10)/10};return{meta:{},timings:d,mark:o,lap(u,c){o(u,performance.now()-c)},clock(){return performance.now()},commit(){if(r)return;r=!0,o("total",performance.now()-i);const u={...this.meta,timings:d};setImmediate(()=>{t(u),console.log(`[gateway] model=${u.model||"-"} → ${u.dest?`${u.dest}(${u.type})`:"none"} · ${u.redaction==="off"?"redaction OFF (client request)":`redacted ${u.redacted||0}`}${u.sanitized?` · scrubbed ${u.sanitized} hidden`:""}${u.narrowed?` · narrowed -${u.narrowed}`:""} · ${Eo(d)}`)})}}}function qe(t,i){if(!t||!t.byToken||i!=="types"&&i!=="values")return;const d=[];for(const[r,o]of t.byToken){const u=/^\[\[([A-Z][A-Z0-9]*)_\d+\]\]$/.exec(r),c=u?u[1]:"PII",S=r.replace(/^\[\[|\]\]$/g,"");d.push(i==="values"?{token:S,type:c,value:o}:{token:S,type:c})}return d}function Po(t,i,d){return we.matches(t)||"anthropic-version"in i?{kind:"anthropic",adapter:we,redactable:we.matches(t),base:d.upstreams?.anthropic?.baseUrl}:Ue.matches(t)?{kind:"responses",adapter:Ue,redactable:!0,base:d.upstreams?.openai?.baseUrl}:{kind:"openai",adapter:be,redactable:be.matches(t),base:d.upstreams?.openai?.baseUrl}}function ve(t,i){const d=String(t||"");if(We.has(d))return{agent:d,agentModel:""};const r=d.indexOf("/");if(r>0){const o=d.slice(0,r);if(We.has(o))return{agent:o,agentModel:d.slice(r+1)}}return{agent:i.bridge.agent,agentModel:""}}function et(t,i){return ve(t,i).agent}function $o(t,i){if(i!=="openai"||!t)return!1;const d=be.extractLatestToolResult(t);if(!d)return!1;const r=Be(d.tool_call_id);return!!(r&&Ne(r.gwId))}function No(t,i){try{const d=new URL(t),r=d.hostname.replace(/^\[|\]$/g,""),o=r==="127.0.0.1"||r==="localhost"||r==="::1",u=d.port||(d.protocol==="https:"?"443":"80");return o&&String(u)===String(i.port)}catch{return!1}}async function v(t,i){const d=[];let r=0;for await(const o of t){if(r+=o.length,i&&r>i){const u=new Error("payload too large");throw u.code=413,u}d.push(o)}return Buffer.concat(d)}function s(t,i,d){t.writeHead(i,{"content-type":"application/json"}),t.end(JSON.stringify(d))}function tt(t){const i=t.redaction?.detection?.url;return!i||t.redaction?.detection?.backend==="off"?null:i}function Te(t){const i=t?.redaction?.detection,d=t?.redaction?.tier==="full"?"full":"basic";if(i&&i.backend&&i.backend!=="off")return{source:"external",backend:i.backend,state:"external",model:i.model||null,ready:!0,tier:d,coverage:d==="full"?"names":"patterns"};const r=N.health(),o=r.ok&&d==="full";return{source:"bundled",state:r.state,model:r.model||t?.ner?.model||null,installed:N.modelOnDisk(t?.ner?.model||void 0),error:r.error||null,ready:o,tier:d,coverage:o?"names":"patterns"}}async function ot(t){if(N.state()!=="off"){const d=N.health();return{configured:d.configured,ok:d.ok,state:d.state,model:d.model,error:d.error||null,url:d.configured?`http://${t.host}:${t.port}/ner`:null}}const i=tt(t);if(!i)return{configured:!1,ok:!1,url:null,model:null};try{const d=await Pe(i.replace(/\/ner\/?$/,"")+"/health",{signal:AbortSignal.timeout(2e3)});if(!d.ok)return{configured:!0,ok:!1,url:i,model:null};const r=await d.json().catch(()=>({}));return{configured:!0,ok:!0,url:i,model:r.model||null}}catch{return{configured:!0,ok:!1,url:i,model:null}}}function Bo(t,i){const d={};for(const[r,o]of Object.entries(t)){const u=r.toLowerCase();u.startsWith("x-chatpanel-")||Ye.has(u)||(d[r]=o)}d["accept-encoding"]="identity";try{d.host=new URL(i).host}catch{}return d}async function rt(t,i,d,r){const o=xe(i.vault),u=r?r.clock():0;let c=u,S=!0;const w=()=>{r&&S&&(r.lap("upstream",u),c=r.clock(),S=!1)};await Tt(i,{onText:O=>{w(),ue(i.id);const p=o.push(O);p&&t.write(d.sseDelta(p))},onToolRequest:({name:O,restoredArgs:p,toolId:M})=>{w(),ue(i.id);const A=o.flush();A&&t.write(d.sseDelta(A)),t.write(d.sseToolCalls([{id:M,name:O,arguments:JSON.stringify(p)}])),t.write(d.sseToolFinish()),r&&r.lap("stream",c),t.end(),r?.commit()},onDone:()=>{const O=o.flush();O&&t.write(d.sseDelta(O)),t.write(d.sseTail()),r&&r.lap("stream",c),t.end(),se(i.id),r?.commit()},onError:O=>{t.write(`data: ${JSON.stringify({error:{message:O.message,type:"bridge_error"}})}
|
|
19
2
|
|
|
20
|
-
|
|
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(),se(i.id),r?.commit()}})}async function Co(t,i,{kind:d,adapter:r,agent:o,run:u=null},c,S,w,O,p,M=null,A=null){const{messages:D,system:F}=r.toTurn(c),{agentModel:R}=ve(c?.model,w),I=Ve(w,{...R?{model:R}:{},...u||{}}),B=ne(w.bridge.token),_=me(d,c?.model||o),j={tier:w.redaction.tier==="full"?"full":"basic",dictionary:pt(w.redaction,O),entities:[]},H=await re(w),x=vt({vault:S,redactOpts:j,bridgeUrl:H,token:B,harness:M});let e;try{e=await St({bridgeUrl:H,agent:o,token:B,messages:D,system:F,specs:Ot(p),options:I,signal:void 0})}catch(n){return se(x.id),A?.commit(),s(i,502,{error:{message:`bridge: ${n.message}`,type:"bridge_error"}})}return x.reader=e.body.getReader(),i.writeHead(200,{"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive"}),i.write(_.sseHead()),rt(i,x,_,A)}async function Do(t,i,d,r,o=null){ue(i.id),i.rounds=(i.rounds||0)+1;try{const c=o?o.clock():0;await _t(i,d),o&&o.lap("redact",c)}catch(c){return se(i.id),o?.commit(),s(t,502,{error:{message:`tool-result: ${c.message}`,type:"bridge_error"}})}const u=me("openai",r||"codex");return t.writeHead(200,{"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive"}),t.write(u.sseHead()),rt(t,i,u,o)}async function jo(t,i,{kind:d,adapter:r,redactable:o,pathname:u,agentOverride:c,harness:S,trace:w,run:O=null},p,M,A,D){if(!o)return w?.commit(),s(i,404,{error:`endpoint ${u} not supported by the bridge backend`});if(d==="openai"){const m=r.extractLatestToolResult(p);if(m){const y=Be(m.tool_call_id),h=y&&Ne(y.gwId);if(h)return Do(i,h,m.content,p?.model,w)}const f=r.extractTools(p);if(f.length&&p?.stream===!0)return Co(t,i,{kind:d,adapter:r,agent:c||et(p?.model,A),run:O},p,M,A,D,f,S,w)}const{messages:F,system:R}=r.toTurn(p),I=c||et(p?.model,A),B=p?.stream===!0,_=me(d,p?.model||I),j=ne(A.bridge.token),H=new AbortController;i.on("close",()=>{i.writableFinished||H.abort()});const{agentModel:x}=ve(p?.model,A),e={bridgeUrl:await re(A),agent:I,token:j,messages:F,system:R,signal:H.signal,options:Ve(A,{...x?{model:x}:{},...O||{}})};if(!B)try{let m="";const f=w?w.clock():0;await $e(e,g=>{m+=g}),w&&w.lap("upstream",f);const y=w?w.clock():0,h=_.full(mt(m,M));return w&&w.lap("restore",y),i.writeHead(200,{"content-type":_.contentType}),i.end(h),w?.commit()}catch(m){return w?.commit(),s(i,502,{error:{message:`bridge backend failed: ${m.message}`,type:"bridge_error"}})}i.writeHead(200,{"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive"}),i.write(_.sseHead());const n=xe(M),a=w?w.clock():0;let l=a;try{let m=!0;await $e(e,y=>{w&&m&&(w.lap("upstream",a),l=w.clock(),m=!1);const h=n.push(y);h&&i.write(_.sseDelta(h))},_.sseActivity?y=>{try{i.write(_.sseActivity(ut(y,M)))}catch{}}:null);const f=n.flush();f&&i.write(_.sseDelta(f)),i.write(_.sseTail())}catch(m){i.write(`data: ${JSON.stringify({error:{message:m.message,type:"bridge_error"}})}
|
|
66
4
|
|
|
67
|
-
|
|
5
|
+
`)}w&&w.lap("stream",l),i.end(),w?.commit()}function Io(t,i,d=""){const r=String(t||"").replace(/\/+$/,""),o=String(i||"").split("/")[1];return o&&r.endsWith(`/${o}`)?r.slice(0,-(o.length+1))+i+d:r+i+d}const Mo=9e4;function Ro(t,i,d){if(i===d)return t;const r=i/d,o=new Float32Array(Math.floor(t.length/r));for(let u=0;u<o.length;u++){const c=u*r,S=Math.floor(c),w=Math.min(t.length-1,S+1),O=c-S;o[u]=t[S]*(1-O)+t[w]*O}return o}const Lo=["/tts","/stt","/ner","/diarize","/skills","/redact","/config","/logs","/status","/admin"];async function Go(t,i,{adapter:d,kind:r,pathname:o,search:u,base:c,destKey:S,destProtocol:w,harness:O,trace:p},M,A){let D;const F=p?p.clock():0;try{const _=Bo(t.headers,c);S&&(w==="anthropic"?(_["x-api-key"]=S,delete _.authorization):_.authorization=`Bearer ${S}`);const j=bt(Io(c,o,u)).toString();D=await fetch(j,{method:t.method,headers:_,body:["GET","HEAD"].includes(t.method)?void 0:M})}catch(_){return p?.commit(),s(i,502,{error:`upstream fetch failed: ${_.message}`})}const R=D.headers.get("content-type")||"",I={};if(D.headers.forEach((_,j)=>{Ye.has(j.toLowerCase())||(I[j]=_)}),R.includes("text/event-stream")&&D.body){p&&p.lap("upstream",F);const _=p?p.clock():0;i.writeHead(D.status,I);const j=r==="openai"?dt(D.body,i,A,O):ct(D.body,i,A);return Promise.resolve(j).finally(()=>{p&&p.lap("stream",_),p?.commit()})}const B=Buffer.from(await D.arrayBuffer());if(p&&p.lap("upstream",F),A&&R.includes("application/json"))try{const _=p?p.clock():0,j=d.restoreResponse(JSON.parse(B.toString("utf8")),A,O);return p&&p.lap("restore",_),i.writeHead(D.status,{...I,"content-type":"application/json"}),i.end(Buffer.from(JSON.stringify(j),"utf8")),p?.commit()}catch{}i.writeHead(D.status,I),i.end(B),p?.commit()}function zo(t=Oe()){const i=[],d=r=>{i.push(r),i.length>50&&i.shift()};return at(async(r,o)=>{const u=new URL(r.url,"http://127.0.0.1"),c=u.pathname;if(!Xe(r.headers.host))return s(o,403,{error:"loopback only"});if(!_o(r.headers.origin,t))return s(o,403,{error:"origin not allowed"});if(r.headers.origin&&Oo(o,r.headers.origin),r.method==="OPTIONS")return o.writeHead(204),o.end();if(c==="/admin/token"&&r.method==="POST")return W(r)?s(o,200,{token:Ae()}):s(o,403,{error:"admin: extension origin or gateway token required"});if(c==="/audit"&&r.method==="GET")return W(r)?s(o,200,kt(t,{version:K,startedAt:Qe})):s(o,403,{error:"audit: extension origin or gateway token required"});if((c==="/config"||c==="/logs"||c==="/update")&&!W(r))return s(o,403,{error:"admin route: extension origin or gateway token required"});if(c==="/update"&&r.method==="GET"){const e=await Lt(K,{force:u.searchParams.get("force")==="1"}).catch(n=>({current:K,updateAvailable:!1,error:String(n?.message||n)}));return s(o,200,{ok:!0,update:e,job:Vt()})}if(c==="/update"&&r.method==="POST"){const e=zt(K);return s(o,e.already?409:202,{ok:!0,job:e})}if((c==="/v1/history/key"||c==="/v1/history/ingest-backup")&&r.method==="POST"&&!W(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"&&!W(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"&&!W(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"))&&!W(r))return s(o,403,{error:{message:"prefs: extension origin or gateway token required",type:"forbidden"}});if(c.startsWith("/v1/observability")&&!W(r))return s(o,403,{error:{message:"observability: extension origin or gateway token required",type:"forbidden"}});if(r.method==="GET"&&c==="/health"){const e=E.health(),n=k.health();return s(o,200,{ok:!0,version:K,backend:t.backend,tier:t.redaction.tier,...process.env.CHATPANEL_MANAGED_BY?{managedBy:String(process.env.CHATPANEL_MANAGED_BY).slice(0,32)}:{},...ce?{bridge:ce.status()}:{},stt:{enabled:t.stt?.enabled!==!1,state:e.state,ready:e.ok,model:e.model||t.stt?.model||fe,runtime:e.runtime,dtype:e.dtype},tts:{enabled:t.tts?.enabled!==!1,state:n.state,ready:n.ok,model:n.model||t.tts?.model||Re,voice:t.tts?.voice||Z,runtime:n.runtime,dtype:n.dtype}})}if(c==="/status"&&r.method==="GET"){lt(t);const e=await X(t.pro?.entitlementToken),n=await ot(t);return s(o,200,{ok:!0,version:K,backend:t.backend,tier:t.redaction.tier,...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:Te(t),pro:{unlocked:e},usage:mo(t),uptimeSeconds:Math.floor((Date.now()-Qe)/1e3),update:Gt(K)})}if(c==="/v1/history/ingest"&&r.method==="POST")try{const e=JSON.parse((await v(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:U.revision,stamps:U.stamps()}):s(o,200,{ok:!0,revision:U.revision,sections:U.get(e)})}if(c==="/v1/prefs"&&(r.method==="POST"||r.method==="PUT"))try{const e=JSON.parse((await v(r,t.maxBodyBytes)).toString("utf8"))||{},n=U.put(e.sections||{},{by:e.by||""});return n.applied.length&&Fe(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?U.remove(e):!1;return n&&Fe([e],""),s(o,200,{ok:!0,removed:n})}if(c==="/v1/prefs/events"&&r.method==="GET"){o.writeHead(200,{"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive"});const e=l=>o.write(`data: ${JSON.stringify(l)}
|
|
68
6
|
|
|
69
|
-
|
|
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:U.revision,stamps:U.stamps()});const n=l=>e({type:"changed",...l});ke.add(n);const a=setInterval(()=>{try{o.write(`: keep-alive
|
|
84
8
|
|
|
85
|
-
|
|
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",()=>{ke.delete(n),clearInterval(a)});return}if(c==="/v1/projects"&&r.method==="GET")return s(o,200,{ok:!0,projects:G.list({limit:u.searchParams.get("limit")||50,status:u.searchParams.get("status")||""})});if(c==="/v1/projects/jobs"&&r.method==="GET")return s(o,200,{ok:!0,jobs:G.openJobs()});if(c==="/v1/projects"&&r.method==="POST")try{const e=JSON.parse((await v(r,t.maxBodyBytes)).toString("utf8"))||{};return s(o,200,{ok:!0,project:G.create({id:e.id||e.project?.id,project:e.project||null,by:e.by})})}catch(e){return s(o,400,{error:{message:`project: ${e.message}`,type:"project_error"}})}{const e=/^\/v1\/projects\/([a-zA-Z0-9_-]{1,64})(\/events|\/jobs(?:\/([a-zA-Z0-9_-]{1,64})(\/applications|\/recruit)?)?)?$/.exec(c);if(e){const n=e[1],a=e[2]||"",l=e[3]||"",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 h=y.jobs.find(b=>b.id===l);if(!h)return s(o,404,{error:{message:`no job ${l}`,type:"not_found"}});const g={cfg:t,prefsStore:U,scorecards:ee,engines:te};if(m==="/applications"&&r.method==="GET"){const b=await It(h,{...g,reach:u.searchParams.get("reach")||"any",chatModel:u.searchParams.get("chatModel")||null});return s(o,200,{ok:!0,job:h,...b})}if(m==="/recruit"&&r.method==="POST"){if(!["open","evaluating"].includes(h.status))return s(o,400,{error:{message:`job ${l} is ${h.status}; only an open job is recruited`,type:"project_error"}});try{const b=JSON.parse((await v(r,t.maxBodyBytes)).toString("utf8"))||{},T=String(b.by||"evaluator").slice(0,80),z=await Mt(h,{...g,record:y,reach:b.reach||"any",chatModel:b.chatModel||null,evaluation:b.evaluation||null,text:b.text??null,by:T});let V=null;for(const Y of z.events)Y.type==="job.updated"?V=G.updateJob(n,l,Y.job,{by:Y.by||T}):V=G.append(n,[Y]);return s(o,200,{ok:!0,project:V,decision:z.decision,applications:z.applications,evaluation:z.evaluation})}catch(b){return s(o,400,{error:{message:`recruit: ${b.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 v(r,t.maxBodyBytes)).toString("utf8"))||{},h=String(y.by||"person").slice(0,80),g=a==="/events"?G.append(n,y.events||[]):l?G.updateJob(n,l,y.patch||y,{by:h}):G.postJob(n,y.job||y,{by:h});return s(o,200,{ok:!0,project:g})}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=T=>o.write(`data: ${JSON.stringify(T)}
|
|
91
10
|
|
|
92
|
-
|
|
11
|
+
`);let h=u.searchParams.has("after")?Number(u.searchParams.get("after")):-1;y({seq:-1,type:"hello",at:Date.now(),payload:{project:G.get(n),after:h}});const g=G.watch(n,T=>{T.seq>h&&(h=T.seq,y(T))});for(const T of G.eventsSince(n,h))h=T.seq,y(T);const b=setInterval(()=>{try{o.write(`: keep
|
|
93
12
|
|
|
94
|
-
|
|
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(b),g()});return}}}if(c==="/v1/agents/scorecards"&&r.method==="GET")return s(o,200,{ok:!0,agents:ee.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 ee.get(n)});if(r.method==="POST")try{const a=JSON.parse((await v(r,t.maxBodyBytes)).toString("utf8"))||{},l=await ee.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 te.fromRating(ee.chains.get(n)||[],{...l,jobKind:a.jobKind?String(a.jobKind).slice(0,60):void 0}),s(o,200,{ok:!0,entry:l})}catch(a){return s(o,400,{error:{message:`scorecard: ${a.message}`,type:"scorecard_error"}})}}}if(c==="/v1/engines"&&r.method==="GET"){const e=Number(u.searchParams.get("minCalls"))||void 0;return s(o,200,{ok:!0,engines:te.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 te.get(n,{entries:u.searchParams.get("entries")==="1",minCalls:a})})}if(e[2]==="entries"&&r.method==="POST")try{const a=JSON.parse((await v(r,t.maxBodyBytes)).toString("utf8"))||{},l=a.engine||xo(n);if(!l)return s(o,400,{error:{message:"model-ledger: engine required",type:"model_ledger_error"}});const m=await te.append({...a,engine:l,kind:a.kind||"call"});return m.key!==n?s(o,400,{error:{message:`model-ledger: entry is for ${m.key}, not ${n}`,type:"model_ledger_error"}}):s(o,200,{ok:!0,entry:m})}catch(a){return s(o,400,{error:{message:`model-ledger: ${a.message}`,type:"model_ledger_error"}})}}}if(c==="/v1/teams/runs"&&r.method==="GET")return s(o,200,{ok:!0,runs:C.list({limit:u.searchParams.get("limit")||50,team:u.searchParams.get("team")||""})});if(c==="/v1/teams/runs"&&r.method==="POST")try{const e=JSON.parse((await v(r,t.maxBodyBytes)).toString("utf8"))||{};return s(o,200,{ok:!0,run:C.create({id:e.id,client:e.client,team:e.team,request:e.request})})}catch(e){return s(o,400,{error:{message:`team run: ${e.message}`,type:"team_error"}})}{const e=/^\/v1\/teams\/runs\/([a-zA-Z0-9_-]{4,64})(\/events|\/stop|\/answer|\/decide|\/post|\/handoff|\/checkpoint|\/claim|\/threads\/[a-zA-Z0-9_:-]{1,80})?$/.exec(c);if(e){const n=e[1],a=e[2]||"";if(!a&&r.method==="GET"){const l=C.get(n,{events:u.searchParams.get("events")==="1"});return l?s(o,200,{ok:!0,run:l}):s(o,404,{error:{message:`no run ${n}`,type:"not_found"}})}if(!a&&r.method==="DELETE")return C.stop(n),s(o,200,{ok:!0,removed:C.remove(n)});if(a==="/stop"&&r.method==="POST"){const l=C.stop(n);return l?s(o,200,{ok:!0,run:l}):s(o,404,{error:{message:`no run ${n}`,type:"not_found"}})}if(a==="/checkpoint"&&r.method==="GET")try{return s(o,200,{ok:!0,checkpoint:C.checkpoint(n)})}catch(l){return s(o,404,{error:{message:`team run: ${l.message}`,type:"team_error"}})}if((a==="/handoff"||a==="/claim")&&r.method==="POST")try{const l=JSON.parse((await v(r,t.maxBodyBytes)).toString("utf8"))||{},m=a==="/handoff"?C.handoff(n,{taskId:l.taskId,model:l.model,by:l.by,reason:l.reason}):C.claim(n,{client:l.client});return s(o,200,{ok:!0,run:m})}catch(l){return s(o,l.message.startsWith("no ")?404:400,{error:{message:`team run: ${l.message}`,type:"team_error"}})}if(a.startsWith("/threads/")&&r.method==="DELETE")try{return s(o,200,{ok:!0,run:C.removeThread(n,{threadId:a.slice(9),by:"person"})})}catch(l){return s(o,l.message.startsWith("no ")?404:400,{error:{message:`team run: ${l.message}`,type:"team_error"}})}if((a==="/answer"||a==="/decide"||a==="/post")&&r.method==="POST")try{const l=JSON.parse((await v(r,t.maxBodyBytes)).toString("utf8"))||{},m=String(l.by||"person").slice(0,40),f=a==="/answer"?C.answer(n,{threadId:l.threadId,text:l.text,by:m}):a==="/decide"?C.decide(n,{postId:l.postId,status:l.status,by:m}):C.post(n,{threadId:l.threadId,text:l.text,by:m,kind:l.kind,replyTo:l.replyTo});return s(o,200,{ok:!0,run:f})}catch(l){return s(o,l.message.startsWith("no ")?404:400,{error:{message:`team run: ${l.message}`,type:"team_error"}})}if(a==="/events"&&r.method==="POST")try{const l=JSON.parse((await v(r,t.maxBodyBytes)).toString("utf8"))||{};return s(o,200,{ok:!0,run:C.append(n,l.events||[])})}catch(l){return s(o,l.message.startsWith("no run")?404:400,{error:{message:`team run: ${l.message}`,type:"team_error"}})}if(a==="/events"&&r.method==="GET"){if(!C.get(n))return s(o,404,{error:{message:`no run ${n}`,type:"not_found"}});o.writeHead(200,{"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive"});const l=g=>o.write(`data: ${JSON.stringify(g)}
|
|
102
14
|
|
|
103
|
-
|
|
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;l({seq:-1,type:"hello",at:Date.now(),payload:{run:C.get(n),after:f}});const y=C.watch(n,g=>{g.seq==null?l(g):g.seq>f&&(f=g.seq,l(g))});for(const g of C.eventsSince(n,f))f=g.seq,l(g);const h=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(h)});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 v(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 v(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 v(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 v(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 v(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 v(r,t.maxBodyBytes)).toString("utf8"))||{},n=String(e.question||e.query||""),a=bo(n,{extra:Array.isArray(e.queries)?e.queries.map(String):[],max:Math.min(6,Math.max(1,Number(e.maxQueries)||4))}),l={type:e.type?String(e.type):null,since:e.since!=null?Number(e.since):null,before:e.before!=null?Number(e.before):null},m=Math.min(30,Math.max(5,Number(e.limit)||10)*2),f=await wo(a,h=>$.search(h,{limit:m,...l}),{limit:Math.min(50,Math.max(1,Number(e.limit)||10))}),y=l.type?f:[...f.filter(h=>h.type==="brief"),...f.filter(h=>h.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:Se.snapshot(e)})}if(c==="/v1/observability/access"&&r.method==="POST")try{const e=JSON.parse((await v(r,t.maxBodyBytes)).toString("utf8"))||{},n=Se.push(He({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:De()});if(c==="/v1/history/key"&&r.method==="POST")try{const e=JSON.parse((await v(r,t.maxBodyBytes)).toString("utf8"))||{};e.passphrase?At(String(e.passphrase)):Pt();const n=e.passphrase?await he($,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 he($,Ce());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 ot(t);return s(o,e.ok?200:503,e)}if(r.method==="POST"){if(await pe(t),N.state()!=="off"){if(!N.isReady()){const n=N.health();return s(o,503,{error:{message:n.state==="error"?`NER model failed to load: ${n.error||"unknown error"}`:`NER model is ${n.state} — not ready yet`,type:n.state==="error"?"ner_error":"ner_loading"},state:n.state,model:n.model})}try{const n=await v(r,t.maxBodyBytes);let a="";try{a=JSON.parse(n.toString("utf8"))?.text||""}catch{}const l=await N.detect(a);return s(o,200,{entities:l})}catch(n){return s(o,500,{error:{message:`NER error: ${n.message}`,type:"ner_error"}})}}const e=tt(t);if(!e){const n=N.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:N.state(),model:t.ner?.model||null})}try{const n=await v(r,t.maxBodyBytes),a=await Pe(e,{method:"POST",headers:{"content-type":"application/json"},body:n,signal:AbortSignal.timeout(8e3)}),l=await a.text();return o.writeHead(a.status,{"content-type":"application/json"}),o.end(l)}catch(n){return s(o,502,{error:{message:`NER unreachable: ${n.message}`,type:"ner_unreachable"}})}}}if(c==="/redact"&&r.method==="POST"){let e="";try{e=String(JSON.parse((await v(r,t.maxBodyBytes)).toString("utf8"))?.text||"")}catch{e=""}if(!e)return s(o,200,{text:"",count:0,sanitized:0,entities:[],detector:Te(t)});try{let n=e;const a=await X(t.pro?.entitlementToken);await pe(t);const l=await de([Ee(()=>n,m=>{n=m})],t.redaction,{isPro:a});return s(o,200,{text:n,count:l.count||0,sanitized:l.sanitized||0,tier:t.redaction?.tier==="full"?"full":"basic",entities:qe(l.vault,"types")||[],detector:Te(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=N.health().model||t.ner?.model||null,n=Ht.map(a=>({...a,installed:N.modelOnDisk(a.id)}));return e&&!n.some(a=>a.id===e)&&n.push({id:e,label:e,lang:"—",custom:!0,installed:N.modelOnDisk(e),note:"Custom model (from Hugging Face)."}),s(o,200,{active:e,state:N.state(),progress:N.progress(),available:n})}if(r.method==="POST"){let e=null;try{e=JSON.parse((await v(r,t.maxBodyBytes)).toString("utf8"))}catch{e=null}const n=e&&typeof e.id=="string"?e.id.trim():null;if(!n||!(Ut(n)||Ft(n)))return s(o,400,{error:{message:"unknown or invalid model id",type:"bad_model"}});yo(t,n);try{q(t,Q())}catch{}return N.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:N.state(),progress:N.progress()})}}if(c==="/stt/models"){if(r.method==="GET"){const e=E.health().model||t.stt?.model||fe,n=Wt.map(a=>({...a,installed:E.modelOnDisk(a.id)}));return e&&!n.some(a=>a.id===e)&&n.push({id:e,label:e,lang:"—",tier:"custom",custom:!0,installed:E.modelOnDisk(e),note:"Custom model (from Hugging Face)."}),s(o,200,{active:e,state:E.state(),progress:E.progress(),available:n,dtype:t.stt?.dtype||"auto",loadedDtype:E.health().dtype,runtime:E.health().runtime,dtypes:Yt})}if(r.method==="POST"){let e=null;try{e=JSON.parse((await v(r,t.maxBodyBytes)).toString("utf8"))}catch{e=null}const n=e&&typeof e.id=="string"?e.id.trim():null;if(!n||!(Kt(n)||Zt(n)))return s(o,400,{error:{message:"unknown or invalid model id",type:"bad_model"}});const a=typeof e.dtype=="string"&&Xt(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{q(t,Q())}catch{}return E.setModel(n,{onLog:l=>console.log(l),dtype:a||t.stt.dtype||"auto"}),s(o,202,{accepted:!0,active:n,dtype:t.stt.dtype||"auto",state:E.state(),progress:E.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=k.health().model||t.tts?.model||Ge(ge()),n=ge(),a=je.find(m=>m.id===e)||null,l=je.map(m=>({...m,installed:k.modelOnDisk(m.id),unavailable:m.requiresNative&&!n?"needs the npm gateway — the standalone binary cannot load this engine":void 0}));return e&&!l.some(m=>m.id===e)&&l.push({id:e,label:e,lang:"—",tier:"custom",custom:!0,installed:k.modelOnDisk(e),note:"Custom model (from Hugging Face)."}),s(o,200,{active:e,state:k.state(),progress:k.progress(),available:l,voice:t.tts?.voice||(le(e)==="pocket-tts"?ae:Z),arch:k.arch(),supportsVoices:k.arch()?k.supportsVoices():a?a.arch==="style-tts2"&&!!a.voices:!0,supportsCustomVoices:k.arch()?k.supportsCustomVoices():!!a?.customVoices,sampleRate:k.sampleRate(),voices:k.isPocket()||!k.arch()&&le(e)==="pocket-tts"?(k.builtinVoices().length?k.builtinVoices():no).map(m=>({id:m,label:m[0].toUpperCase()+m.slice(1),lang:"en",installed:k.builtinVoices().includes(m)})):k.arch()&&k.arch()!=="style-tts2"?[]:Qt.map(m=>({...m,installed:k.voiceOnDisk(m.id,e)})),dtype:t.tts?.dtype||"auto",loadedDtype:k.health().dtype,runtime:k.health().runtime,dtypes:to})}if(r.method==="POST"){let e=null;try{e=JSON.parse((await v(r,t.maxBodyBytes)).toString("utf8"))}catch{e=null}const n=e&&typeof e.id=="string"?e.id.trim():null;if(n&&!(qt(n)||eo(n)))return s(o,400,{error:{message:"unknown or invalid model id",type:"bad_model"}});const a=e&&typeof e.voice=="string"?e.voice.trim():null;if(a){const m=L.parseCustomVoice(a);if(!(m?!!L.getVoice(m):ie(a)||Ie(a)&&Me(a)))return s(o,400,{error:{message:"unknown or invalid voice",type:"bad_voice"}})}const l=e&&typeof e.dtype=="string"&&oo(e.dtype)?e.dtype:void 0;if(t.tts||(t.tts={enabled:!0,model:Re,voice:Z,allowDownload:!0}),n&&(t.tts.model=n),a&&(t.tts.voice=a),n&&!a){const m=ro(n),f=L.parseCustomVoice(t.tts.voice||""),y=!!(f&&L.getVoice(f));if(m&&!y)if(le(n)==="pocket-tts")t.tts.voice=ae;else{const g=L.listVoices();t.tts.voice=g.length?`custom:${g[0].id}`:""}else!m&&y&&(t.tts.voice=Z);const h=le(n)==="pocket-tts";h&&!L.parseCustomVoice(t.tts.voice||"")&&!ie(t.tts.voice)&&(t.tts.voice=ae),!h&&ie(t.tts.voice)&&(t.tts.voice=Z)}l&&(t.tts.dtype=l==="auto"?null:l);try{q(t,Q())}catch{}return n&&k.setModel(n,{onLog:m=>console.log(m),dtype:l||t.tts.dtype||"auto"}),s(o,202,{accepted:!0,active:t.tts.model,voice:t.tts.voice,dtype:t.tts.dtype||"auto",state:k.state(),progress:k.progress()})}}if(c==="/tts/voices"){if(r.method==="GET")return s(o,200,{voices:L.listVoices(),usable:k.supportsCustomVoices(),embedder:P.DIARIZE_MODEL,embedderReady:P.isReady()});if(r.method==="POST"){let e=null;try{e=JSON.parse((await v(r,t.maxBodyBytes)).toString("utf8"))}catch{e=null}const n=e&&typeof e.name=="string"?e.name.trim():"",a=e&&Array.isArray(e.pcm)?e.pcm:null,l=e&&typeof e.id=="string"?e.id.trim():"";if(l){if(!L.getVoice(l))return s(o,404,{error:{message:"no such saved voice",type:"bad_voice"}});if(!a){if(!n)return s(o,400,{error:{message:"a name is required",type:"bad_request"}});try{return s(o,200,{...L.renameVoice(l,n),usable:k.supportsCustomVoices()})}catch(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 b=P.download({onLog:V=>console.log(V)}),T=Symbol("timeout"),z=await Promise.race([b.then(()=>null).catch(V=>V),new Promise(V=>setTimeout(()=>V(T),Mo))]);if(z===T||!P.isReady())return s(o,503,{error:{message:z===T?"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 b=await k.pocketForEncoding({allowDownload:t.tts?.allowDownload!==!1,log:T=>console.log(T)});b&&(y=await b.encodeVoice(Ro(m,16e3,24e3)))}catch(b){console.log(`[tts] pocket conditioning unavailable for this voice (${b.message})`)}const h=l?L.replaceVoice(l,{vec:f,pocket:y}):L.saveVoice({name:n,vec:f,pocket:y}),g=l&&n&&n!==h.name?L.renameVoice(l,n):h;return console.log(`[tts] ${l?"re-recorded":"saved"} custom voice "${g.name}" (${(h.kinds||[]).join(" + ")}, sample discarded)`),s(o,l?200:201,{...h,...g,usable:k.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}`:Z;try{q(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 v(r,t.maxBodyBytes)).toString("utf8"))}catch{e=null}const n=e&&typeof(e.input??e.text)=="string"?String(e.input??e.text).trim():"";if(!n)return s(o,400,{error:{message:"text is required",type:"bad_request"}});if(n.length>Le)return s(o,413,{error:{message:`text too long (max ${Le} chars)`,type:"too_long"}});const a=Number.isFinite(e.speed)?Math.min(2,Math.max(.5,e.speed)):1,l=so(t),m=e&&typeof e.voice=="string"&&e.voice.trim()?e.voice.trim():null,f=m||(l?l.voice:t.tts?.voice||Z);if(l&&!io(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(l){const{audio:oe,contentType:nt,redacted:st}=await ao({dest:l,text:n,voice:f,speed:a,auth:r.headers.authorization||r.headers["xi-api-key"]||"",redaction:t.redaction,isPro:await X(t.pro?.entitlementToken)});return o.writeHead(200,{"Content-Type":nt,"Content-Length":String(oe.length),"Cache-Control":"no-store","X-Tts-Provider":l.kind,"X-Tts-Redacted":String(st)}),o.end(oe)}if(!await k.ready({onLog:oe=>console.log(oe),allowDownload:t.tts?.allowDownload!==!1,model:t.tts?.model||Ge(ge()),dtype:t.tts?.dtype||"auto"}))return s(o,503,{error:{message:k.health().error||"tts model not ready",type:"tts_unavailable"}});const g=lo({requested:m,configured:f,engine:k,voices:L,isPocketVoice:ie,isKnownVoice:Ie,isValidVoiceId:Me,defaultVoice:Z,defaultPocketVoice:ae});if(!g.ok)return s(o,g.status,{error:{message:g.message,type:g.type}});const{voice:b,customId:T,speakerEmbedding:z}=g,V=await k.synth(n,{voice:b,speed:a,speakerEmbedding:z}),Y=k.sampleRate(),_e=y==="pcm"?Buffer.from(new Float32Array(V).buffer):k.toWav(V,Y);return o.writeHead(200,{"Content-Type":y==="pcm"?"application/octet-stream":"audio/wav","Content-Length":String(_e.length),"Cache-Control":"no-store","X-Tts-Sample-Rate":String(Y),...T||k.isPocket()||k.supportsVoices()?{"X-Tts-Voice":b}:{}}),o.end(_e)}catch(h){return s(o,500,{error:{message:h.message,type:"tts_failed"}})}}if(c==="/stt/sessions"&&r.method==="POST"){if(t.stt?.enabled===!1)return s(o,403,{error:{message:"STT disabled in gateway config",type:"stt_disabled"}});let e=null;try{e=JSON.parse((await v(r,t.maxBodyBytes)).toString("utf8")||"{}")}catch{e=null}E.isReady()||E.init({model:t.stt?.model||fe,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}=E.createSession({lang:e?.lang,redact:e?.redact===!0,diarize:n,speakerLabel:e?.speakerLabel,endSilenceMs:e?.endSilenceMs});return s(o,201,{id:a,state:E.state()})}catch(a){return s(o,a.code==="too_many_sessions"?429:500,{error:{message:a.message,type:a.code||"stt_error"}})}}{const e=c.match(/^\/stt\/sessions\/([0-9a-f-]{36})(\/audio|\/events)?$/);if(e){const n=e[1];if(e[2]==="/audio"&&r.method==="POST")try{const a=await v(r,t.maxBodyBytes);return E.pushAudio(n,E.toFloat32(a)),s(o,200,{ok:!0,state:E.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=E.getSession(n);if(!a)return s(o,404,{error:{message:"no such session",type:"no_session"}});o.writeHead(200,{"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive"});const l=b=>o.write(`data: ${JSON.stringify(b)}
|
|
128
18
|
|
|
129
|
-
function
|
|
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 }
|
|
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') return sendJson(res, 200, { ok: true, removed: teamStore.remove(id) });
|
|
1030
|
-
if (sub === '/stop' && req.method === 'POST') {
|
|
1031
|
-
const run = teamStore.stop(id);
|
|
1032
|
-
return run ? sendJson(res, 200, { ok: true, run }) : sendJson(res, 404, { error: { message: `no run ${id}`, type: 'not_found' } });
|
|
1033
|
-
}
|
|
1034
|
-
// The board, from a person on ANY client (0.6.81): answer an ask, decide on a post,
|
|
1035
|
-
// post a note. Each is appended as events, so the running client's tail sees it.
|
|
1036
|
-
// A task's continuation from another client (0.6.85): hand a task to another model; read
|
|
1037
|
-
// the checkpoint to resume a run whose client went away; claim it when resuming.
|
|
1038
|
-
if (sub === '/checkpoint' && req.method === 'GET') {
|
|
1039
|
-
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' } }); }
|
|
1040
|
-
}
|
|
1041
|
-
if ((sub === '/handoff' || sub === '/claim') && req.method === 'POST') {
|
|
1042
|
-
try {
|
|
1043
|
-
const body = JSON.parse((await readBody(req, cfg.maxBodyBytes)).toString('utf8')) || {};
|
|
1044
|
-
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 });
|
|
1045
|
-
return sendJson(res, 200, { ok: true, run });
|
|
1046
|
-
} catch (e) {
|
|
1047
|
-
return sendJson(res, e.message.startsWith('no ') ? 404 : 400, { error: { message: `team run: ${e.message}`, type: 'team_error' } });
|
|
1048
|
-
}
|
|
1049
|
-
}
|
|
1050
|
-
if (sub.startsWith('/threads/') && req.method === 'DELETE') {
|
|
1051
|
-
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' } }); }
|
|
1052
|
-
}
|
|
1053
|
-
if ((sub === '/answer' || sub === '/decide' || sub === '/post') && req.method === 'POST') {
|
|
1054
|
-
try {
|
|
1055
|
-
const body = JSON.parse((await readBody(req, cfg.maxBodyBytes)).toString('utf8')) || {};
|
|
1056
|
-
const by = String(body.by || 'person').slice(0, 40);
|
|
1057
|
-
const run = sub === '/answer' ? teamStore.answer(id, { threadId: body.threadId, text: body.text, by })
|
|
1058
|
-
: sub === '/decide' ? teamStore.decide(id, { postId: body.postId, status: body.status, by })
|
|
1059
|
-
: teamStore.post(id, { threadId: body.threadId, text: body.text, by, kind: body.kind, replyTo: body.replyTo });
|
|
1060
|
-
return sendJson(res, 200, { ok: true, run });
|
|
1061
|
-
} catch (e) {
|
|
1062
|
-
return sendJson(res, e.message.startsWith('no ') ? 404 : 400, { error: { message: `team run: ${e.message}`, type: 'team_error' } });
|
|
1063
|
-
}
|
|
1064
|
-
}
|
|
1065
|
-
if (sub === '/events' && req.method === 'POST') {
|
|
1066
|
-
try {
|
|
1067
|
-
const body = JSON.parse((await readBody(req, cfg.maxBodyBytes)).toString('utf8')) || {};
|
|
1068
|
-
return sendJson(res, 200, { ok: true, run: teamStore.append(id, body.events || []) });
|
|
1069
|
-
} catch (e) {
|
|
1070
|
-
return sendJson(res, e.message.startsWith('no run') ? 404 : 400, { error: { message: `team run: ${e.message}`, type: 'team_error' } });
|
|
1071
|
-
}
|
|
1072
|
-
}
|
|
1073
|
-
if (sub === '/events' && req.method === 'GET') {
|
|
1074
|
-
if (!teamStore.get(id)) return sendJson(res, 404, { error: { message: `no run ${id}`, type: 'not_found' } });
|
|
1075
|
-
res.writeHead(200, { 'content-type': 'text/event-stream', 'cache-control': 'no-cache', connection: 'keep-alive' });
|
|
1076
|
-
const sendEv = (ev) => res.write(`data: ${JSON.stringify(ev)}\n\n`);
|
|
1077
|
-
// `Number(null)` is 0, not NaN: an absent `after` must mean "from the start" (-1),
|
|
1078
|
-
// or the first event of every run is skipped.
|
|
1079
|
-
const after = url.searchParams.has('after') ? Number(url.searchParams.get('after')) : NaN;
|
|
1080
|
-
// The record as it stands, FIRST — it flushes the headers (writeHead alone sends
|
|
1081
|
-
// nothing, and a reader whose fetch has not resolved can miss the opening events),
|
|
1082
|
-
// and a late reader gets the board without a second request. Then replay from
|
|
1083
|
-
// `after`, then tail; the watcher is registered before the replay is read and
|
|
1084
|
-
// duplicates are dropped by seq, so nothing lands in the gap.
|
|
1085
|
-
let last = Number.isFinite(after) ? after : -1;
|
|
1086
|
-
sendEv({ seq: -1, type: 'hello', at: Date.now(), payload: { run: teamStore.get(id), after: last } });
|
|
1087
|
-
// A stream event (a task's text delta) has no seq: it is never stored, so it is passed live and never replayed.
|
|
1088
|
-
const off = teamStore.watch(id, (ev) => { if (ev.seq == null) sendEv(ev); else if (ev.seq > last) { last = ev.seq; sendEv(ev); } });
|
|
1089
|
-
for (const ev of teamStore.eventsSince(id, last)) { last = ev.seq; sendEv(ev); }
|
|
1090
|
-
const beat = setInterval(() => { try { res.write(': keep-alive\n\n'); } catch { /* closed */ } }, 25_000);
|
|
1091
|
-
res.on('close', () => { off(); clearInterval(beat); });
|
|
1092
|
-
return undefined;
|
|
1093
|
-
}
|
|
1094
|
-
}
|
|
1095
|
-
}
|
|
1096
|
-
|
|
1097
|
-
// --- MEMORY. Small, durable facts about the user, reachable by every local agent.
|
|
1098
|
-
// GET /v1/memory/list → { memories }
|
|
1099
|
-
// POST /v1/memory/recall { text, scopes } → { memories, block }
|
|
1100
|
-
// POST /v1/memory/remember { text, kind, … }→ { action, record }
|
|
1101
|
-
// POST /v1/memory/forget { query } → { removed }
|
|
1102
|
-
// POST /v1/memory/sync { upserts, removes } → { size, merged, memories }
|
|
1103
|
-
if (pathname === '/v1/memory/list' && req.method === 'GET') {
|
|
1104
|
-
return sendJson(res, 200, { ok: true, size: memoryStore.size, memories: memoryStore.list() });
|
|
1105
|
-
}
|
|
1106
|
-
if (pathname === '/v1/memory/recall' && req.method === 'POST') {
|
|
1107
|
-
try {
|
|
1108
|
-
const body = JSON.parse((await readBody(req, cfg.maxBodyBytes)).toString('utf8')) || {};
|
|
1109
|
-
const got = memoryStore.recall({
|
|
1110
|
-
text: String(body.text || ''),
|
|
1111
|
-
scopes: Array.isArray(body.scopes) && body.scopes.length ? body.scopes.map(String) : ['global'],
|
|
1112
|
-
limit: Number(body.limit) || 0,
|
|
1113
|
-
maxChars: Number(body.maxChars) || 0,
|
|
1114
|
-
});
|
|
1115
|
-
return sendJson(res, 200, { ok: true, size: memoryStore.size, ...got });
|
|
1116
|
-
} catch (e) {
|
|
1117
|
-
return sendJson(res, 400, { error: { message: `recall failed: ${e.message}`, type: 'memory_error' } });
|
|
1118
|
-
}
|
|
1119
|
-
}
|
|
1120
|
-
if (pathname === '/v1/memory/remember' && req.method === 'POST') {
|
|
1121
|
-
try {
|
|
1122
|
-
const body = JSON.parse((await readBody(req, cfg.maxBodyBytes)).toString('utf8')) || {};
|
|
1123
|
-
const out = memoryStore.remember({
|
|
1124
|
-
text: String(body.text || ''),
|
|
1125
|
-
kind: body.kind ? String(body.kind) : 'fact',
|
|
1126
|
-
scope: body.scope ? String(body.scope) : 'global',
|
|
1127
|
-
tags: Array.isArray(body.tags) ? body.tags.map(String) : [],
|
|
1128
|
-
// WHO PROPOSED IT, always recorded. There is no confirm dialog on a CLI, so
|
|
1129
|
-
// attribution plus an inspectable list in the extension IS the accountability —
|
|
1130
|
-
// see the MCP server's note on why writes are allowed but never anonymous.
|
|
1131
|
-
source: {
|
|
1132
|
-
via: String(body.source?.via || 'mcp'),
|
|
1133
|
-
surface: String(body.source?.surface || 'mcp'),
|
|
1134
|
-
agent: String(body.source?.agent || ''),
|
|
1135
|
-
ref: String(body.source?.ref || ''),
|
|
1136
|
-
},
|
|
1137
|
-
});
|
|
1138
|
-
return sendJson(res, 200, { ok: true, action: out.action, record: out.record, replaced: out.replaces || null, size: memoryStore.size });
|
|
1139
|
-
} catch (e) {
|
|
1140
|
-
return sendJson(res, 400, { error: { message: e.message, type: 'memory_error' } });
|
|
1141
|
-
}
|
|
1142
|
-
}
|
|
1143
|
-
if (pathname === '/v1/memory/forget' && req.method === 'POST') {
|
|
1144
|
-
try {
|
|
1145
|
-
const body = JSON.parse((await readBody(req, cfg.maxBodyBytes)).toString('utf8')) || {};
|
|
1146
|
-
const { removed } = memoryStore.forget(String(body.query || ''));
|
|
1147
|
-
return sendJson(res, 200, { ok: true, removed, size: memoryStore.size });
|
|
1148
|
-
} catch (e) {
|
|
1149
|
-
return sendJson(res, 400, { error: { message: e.message, type: 'memory_error' } });
|
|
1150
|
-
}
|
|
1151
|
-
}
|
|
1152
|
-
if (pathname === '/v1/memory/sync' && req.method === 'POST') {
|
|
1153
|
-
try {
|
|
1154
|
-
const body = JSON.parse((await readBody(req, cfg.maxBodyBytes)).toString('utf8')) || {};
|
|
1155
|
-
const out = memoryStore.bulk({
|
|
1156
|
-
upserts: Array.isArray(body.upserts) ? body.upserts : [],
|
|
1157
|
-
removes: Array.isArray(body.removes) ? body.removes : [],
|
|
1158
|
-
});
|
|
1159
|
-
// The full set comes BACK, so one round trip is the whole two-way merge: the client
|
|
1160
|
-
// pushes what it has and receives what the agents wrote. Convergent because both
|
|
1161
|
-
// sides reconcile with the same function.
|
|
1162
|
-
return sendJson(res, 200, { ok: true, ...out, memories: memoryStore.list() });
|
|
1163
|
-
} catch (e) {
|
|
1164
|
-
return sendJson(res, 400, { error: { message: `memory sync failed: ${e.message}`, type: 'memory_error' } });
|
|
1165
|
-
}
|
|
1166
|
-
}
|
|
1167
|
-
if (pathname === '/v1/memory/clear' && req.method === 'POST') {
|
|
1168
|
-
return sendJson(res, 200, { ok: true, dropped: memoryStore.clear(), size: memoryStore.size });
|
|
1169
|
-
}
|
|
1170
|
-
|
|
1171
|
-
if (pathname === '/v1/history/clear' && req.method === 'POST') {
|
|
1172
|
-
const dropped = historyStore.clear();
|
|
1173
|
-
return sendJson(res, 200, { ok: true, dropped, size: historyStore.size });
|
|
1174
|
-
}
|
|
1175
|
-
if (pathname === '/v1/history/search' && req.method === 'POST') {
|
|
1176
|
-
try {
|
|
1177
|
-
const body = JSON.parse((await readBody(req, cfg.maxBodyBytes)).toString('utf8')) || {};
|
|
1178
|
-
const results = historyStore.search(String(body.query || ''), {
|
|
1179
|
-
limit: Number(body.limit) || 10,
|
|
1180
|
-
offset: Math.max(0, Number(body.offset) || 0),
|
|
1181
|
-
type: body.type ? String(body.type) : null,
|
|
1182
|
-
since: body.since != null ? Number(body.since) : null,
|
|
1183
|
-
before: body.before != null ? Number(body.before) : null,
|
|
1184
|
-
});
|
|
1185
|
-
return sendJson(res, 200, { ok: true, size: historyStore.size, newest: historyStore.newest, results });
|
|
1186
|
-
} catch (e) {
|
|
1187
|
-
return sendJson(res, 400, { error: { message: `search failed: ${e.message}`, type: 'search_error' } });
|
|
1188
|
-
}
|
|
1189
|
-
}
|
|
1190
|
-
// SMART SEARCH — one round trip that expands the question into several complementary
|
|
1191
|
-
// queries, runs them all, and RRF-fuses the results. A natural-language question is a
|
|
1192
|
-
// poor BM25 query; asking three ways and fusing beats asking once, and doing it here
|
|
1193
|
-
// means the agent pays one call instead of probing repeatedly.
|
|
1194
|
-
if (pathname === '/v1/history/smart-search' && req.method === 'POST') {
|
|
1195
|
-
try {
|
|
1196
|
-
const body = JSON.parse((await readBody(req, cfg.maxBodyBytes)).toString('utf8')) || {};
|
|
1197
|
-
const question = String(body.question || body.query || '');
|
|
1198
|
-
// The agent's own formulations lead (it understands the domain); planQueries adds
|
|
1199
|
-
// deterministic variants and dedupes.
|
|
1200
|
-
const queries = planQueries(question, {
|
|
1201
|
-
extra: Array.isArray(body.queries) ? body.queries.map(String) : [],
|
|
1202
|
-
max: Math.min(6, Math.max(1, Number(body.maxQueries) || 4)),
|
|
1203
|
-
});
|
|
1204
|
-
const filters = {
|
|
1205
|
-
type: body.type ? String(body.type) : null,
|
|
1206
|
-
since: body.since != null ? Number(body.since) : null,
|
|
1207
|
-
before: body.before != null ? Number(body.before) : null,
|
|
1208
|
-
};
|
|
1209
|
-
const perQuery = Math.min(30, Math.max(5, Number(body.limit) || 10) * 2);
|
|
1210
|
-
const fused = await multiSearch(
|
|
1211
|
-
queries,
|
|
1212
|
-
(q) => historyStore.search(q, { limit: perQuery, ...filters }),
|
|
1213
|
-
{ limit: Math.min(50, Math.max(1, Number(body.limit) || 10)) },
|
|
1214
|
-
);
|
|
1215
|
-
// BRIEFS LEAD. A brief is the compaction: when one matches, it answers with what a
|
|
1216
|
-
// dozen records say, with a citation to each, and reading it saves an agent opening
|
|
1217
|
-
// the dozen. Stable-partitioned to the front rather than re-scored, so rank among
|
|
1218
|
-
// briefs and rank among records are both untouched — and only when the caller has
|
|
1219
|
-
// not asked for one type, which is a question about records, not about briefs.
|
|
1220
|
-
const results = filters.type
|
|
1221
|
-
? fused
|
|
1222
|
-
: [...fused.filter((r) => r.type === 'brief'), ...fused.filter((r) => r.type !== 'brief')];
|
|
1223
|
-
return sendJson(res, 200, {
|
|
1224
|
-
ok: true, size: historyStore.size, newest: historyStore.newest, queries, results,
|
|
1225
|
-
});
|
|
1226
|
-
} catch (e) {
|
|
1227
|
-
return sendJson(res, 400, { error: { message: `smart search failed: ${e.message}`, type: 'search_error' } });
|
|
1228
|
-
}
|
|
1229
|
-
}
|
|
1230
|
-
// Graph navigation — records most connected to a given one.
|
|
1231
|
-
if (pathname === '/v1/history/related' && req.method === 'GET') {
|
|
1232
|
-
const id = String(url.searchParams.get('id') || '');
|
|
1233
|
-
const limit = Math.min(30, Math.max(1, Number(url.searchParams.get('limit')) || 5));
|
|
1234
|
-
return sendJson(res, 200, { ok: true, results: historyStore.related(id, { limit }) });
|
|
1235
|
-
}
|
|
1236
|
-
if (pathname === '/v1/history/status' && req.method === 'GET') {
|
|
1237
|
-
return sendJson(res, 200, { ok: true, size: historyStore.size, newest: historyStore.newest, bytes: historyStore.bytes });
|
|
1238
|
-
}
|
|
1239
|
-
|
|
1240
|
-
// OBSERVABILITY (admin-gated above).
|
|
1241
|
-
// GET /v1/observability → { storage:{warm:{records,bytes,newest}}, access:[…] }
|
|
1242
|
-
// POST /v1/observability/access ← the MCP process reports one tool call
|
|
1243
|
-
if (pathname === '/v1/observability' && req.method === 'GET') {
|
|
1244
|
-
const limit = Math.min(500, Math.max(1, Number(url.searchParams.get('limit')) || 200));
|
|
1245
|
-
return sendJson(res, 200, {
|
|
1246
|
-
ok: true,
|
|
1247
|
-
storage: { warm: { records: historyStore.size, bytes: historyStore.bytes, newest: historyStore.newest } },
|
|
1248
|
-
access: accessLog.snapshot(limit),
|
|
1249
|
-
});
|
|
1250
|
-
}
|
|
1251
|
-
if (pathname === '/v1/observability/access' && req.method === 'POST') {
|
|
1252
|
-
try {
|
|
1253
|
-
const body = JSON.parse((await readBody(req, cfg.maxBodyBytes)).toString('utf8')) || {};
|
|
1254
|
-
const evt = accessLog.push(makeAccessEvent({ ts: Date.now(), ...body }));
|
|
1255
|
-
return sendJson(res, 200, { ok: true, event: evt });
|
|
1256
|
-
} catch (e) {
|
|
1257
|
-
return sendJson(res, 400, { error: { message: `access log failed: ${e.message}`, type: 'observability_error' } });
|
|
1258
|
-
}
|
|
1259
|
-
}
|
|
1260
|
-
if (pathname === '/v1/history/list' && req.method === 'GET') {
|
|
1261
|
-
const limit = Math.min(500, Math.max(1, Number(url.searchParams.get('limit')) || 50));
|
|
1262
|
-
const offset = Math.max(0, Number(url.searchParams.get('offset')) || 0);
|
|
1263
|
-
const type = url.searchParams.get('type') || null;
|
|
1264
|
-
return sendJson(res, 200, { ok: true, ...historyStore.list({ limit, offset, type }) });
|
|
1265
|
-
}
|
|
1266
|
-
if (pathname === '/v1/history/get' && req.method === 'GET') {
|
|
1267
|
-
const maxChars = url.searchParams.get('maxChars') != null ? Math.max(1, Number(url.searchParams.get('maxChars')) || 0) : null;
|
|
1268
|
-
const offset = Math.max(0, Number(url.searchParams.get('offset')) || 0);
|
|
1269
|
-
const record = historyStore.get(String(url.searchParams.get('id') || ''), { maxChars, offset });
|
|
1270
|
-
if (!record) return sendJson(res, 404, { error: { message: 'no such record', type: 'not_found' } });
|
|
1271
|
-
return sendJson(res, 200, { ok: true, record });
|
|
1272
|
-
}
|
|
1273
|
-
// Key-handoff (loopback only): store the user's backup passphrase so the gateway
|
|
1274
|
-
// can decrypt their daily backups unattended. Encrypted at rest with the local
|
|
1275
|
-
// key. { passphrase } → stores it and does one immediate ingest. { passphrase:'' }
|
|
1276
|
-
// forgets it. GET → whether a key is held (never returns the key itself).
|
|
1277
|
-
if (pathname === '/v1/history/key' && req.method === 'GET') {
|
|
1278
|
-
return sendJson(res, 200, { ok: true, hasKey: hasBackupSecret() });
|
|
1279
|
-
}
|
|
1280
|
-
if (pathname === '/v1/history/key' && req.method === 'POST') {
|
|
1281
|
-
try {
|
|
1282
|
-
const body = JSON.parse((await readBody(req, cfg.maxBodyBytes)).toString('utf8')) || {};
|
|
1283
|
-
if (body.passphrase) saveBackupSecret(String(body.passphrase)); else clearBackupSecret();
|
|
1284
|
-
const result = body.passphrase ? await ingestBackups(historyStore, String(body.passphrase)) : { ok: true, ingested: 0 };
|
|
1285
|
-
return sendJson(res, 200, { ok: true, hasKey: !!body.passphrase, ...result });
|
|
1286
|
-
} catch (e) {
|
|
1287
|
-
return sendJson(res, 400, { error: { message: `key handoff failed: ${e.message}`, type: 'key_error' } });
|
|
1288
|
-
}
|
|
1289
|
-
}
|
|
1290
|
-
// Trigger an encrypted archive refresh now using the stored key. Every rotating
|
|
1291
|
-
// weekday snapshot that matches the key contributes records; newest values win.
|
|
1292
|
-
if (pathname === '/v1/history/ingest-backup' && req.method === 'POST') {
|
|
1293
|
-
try {
|
|
1294
|
-
const result = await ingestBackups(historyStore, loadBackupSecret());
|
|
1295
|
-
return sendJson(res, result.ok ? 200 : 409, result);
|
|
1296
|
-
} catch (e) {
|
|
1297
|
-
return sendJson(res, 400, { error: { message: `backup ingest failed: ${e.message}`, type: 'ingest_error' } });
|
|
1298
|
-
}
|
|
1299
|
-
}
|
|
1300
|
-
|
|
1301
|
-
// The detector, on the gateway's own port (no second port). GET → health;
|
|
1302
|
-
// POST {text} → {entities}. The bundled engine runs IN-PROCESS; a user's own
|
|
1303
|
-
// external detector (if configured) is proxied for back-compat.
|
|
1304
|
-
if (pathname === '/ner') {
|
|
1305
|
-
if (req.method === 'GET') {
|
|
1306
|
-
const health = await probeNerHealth(cfg);
|
|
1307
|
-
return sendJson(res, health.ok ? 200 : 503, health);
|
|
1308
|
-
}
|
|
1309
|
-
if (req.method === 'POST') {
|
|
1310
|
-
// A POST here IS the request to detect, so start the bundled engine if it is not
|
|
1311
|
-
// running and its weights are already on disk (see ensureNer — it never downloads).
|
|
1312
|
-
// Without this a config with `ner.autostart:false` answered 503 until a restart,
|
|
1313
|
-
// and the client read that as "redaction is broken" while the model sat unused.
|
|
1314
|
-
await ensureNer(cfg);
|
|
1315
|
-
// In-process engine path.
|
|
1316
|
-
if (nerEngine.state() !== 'off') {
|
|
1317
|
-
// NOT READY IS NOT AN ANSWER. `detect()` returns [] when the pipeline is still
|
|
1318
|
-
// loading or failed to load, and 200 {entities:[]} is indistinguishable from
|
|
1319
|
-
// "this text contains no names" — the one lie a privacy layer must never tell.
|
|
1320
|
-
// Say which state it is in instead, and let the caller show "starting…".
|
|
1321
|
-
if (!nerEngine.isReady()) {
|
|
1322
|
-
const h = nerEngine.health();
|
|
1323
|
-
return sendJson(res, 503, {
|
|
1324
|
-
error: {
|
|
1325
|
-
message: h.state === 'error'
|
|
1326
|
-
? `NER model failed to load: ${h.error || 'unknown error'}`
|
|
1327
|
-
: `NER model is ${h.state} — not ready yet`,
|
|
1328
|
-
type: h.state === 'error' ? 'ner_error' : 'ner_loading',
|
|
1329
|
-
},
|
|
1330
|
-
state: h.state,
|
|
1331
|
-
model: h.model,
|
|
1332
|
-
});
|
|
1333
|
-
}
|
|
1334
|
-
try {
|
|
1335
|
-
const body = await readBody(req, cfg.maxBodyBytes);
|
|
1336
|
-
let text = '';
|
|
1337
|
-
try { text = JSON.parse(body.toString('utf8'))?.text || ''; } catch { /* empty */ }
|
|
1338
|
-
const entities = await nerEngine.detect(text);
|
|
1339
|
-
return sendJson(res, 200, { entities });
|
|
1340
|
-
} catch (e) {
|
|
1341
|
-
return sendJson(res, 500, { error: { message: `NER error: ${e.message}`, type: 'ner_error' } });
|
|
1342
|
-
}
|
|
1343
|
-
}
|
|
1344
|
-
// External detector proxy (user-configured endpoint).
|
|
1345
|
-
const url = nerBaseUrl(cfg);
|
|
1346
|
-
if (!url) {
|
|
1347
|
-
// The bundled engine is the intended detector here and it is not running. Say
|
|
1348
|
-
// WHY — "not configured" sent a user hunting through settings that were already
|
|
1349
|
-
// correct, when the real answer was that the model was never downloaded.
|
|
1350
|
-
const onDisk = nerEngine.modelOnDisk(cfg.ner?.model || undefined);
|
|
1351
|
-
return sendJson(res, 503, {
|
|
1352
|
-
error: {
|
|
1353
|
-
message: onDisk
|
|
1354
|
-
? 'the bundled detector could not start — deterministic-only redaction'
|
|
1355
|
-
: 'no entity detector is installed — deterministic-only redaction (install one from Gateway settings)',
|
|
1356
|
-
type: onDisk ? 'ner_error' : 'ner_not_installed',
|
|
1357
|
-
},
|
|
1358
|
-
state: nerEngine.state(),
|
|
1359
|
-
model: cfg.ner?.model || null,
|
|
1360
|
-
});
|
|
1361
|
-
}
|
|
1362
|
-
try {
|
|
1363
|
-
const body = await readBody(req, cfg.maxBodyBytes);
|
|
1364
|
-
// secureFetch: scheme/host policy + resolved-IP check before POSTing raw text to the detector.
|
|
1365
|
-
const r = await secureFetch(url, { method: 'POST', headers: { 'content-type': 'application/json' }, body, signal: AbortSignal.timeout(8000) });
|
|
1366
|
-
const text = await r.text();
|
|
1367
|
-
res.writeHead(r.status, { 'content-type': 'application/json' });
|
|
1368
|
-
return res.end(text);
|
|
1369
|
-
} catch (e) {
|
|
1370
|
-
return sendJson(res, 502, { error: { message: `NER unreachable: ${e.message}`, type: 'ner_unreachable' } });
|
|
1371
|
-
}
|
|
1372
|
-
}
|
|
1373
|
-
}
|
|
1374
|
-
// WHAT THE MODEL WOULD RECEIVE. A client asks "if I sent this, what leaves the
|
|
1375
|
-
// machine?" and gets back the redacted text plus the token→type map.
|
|
1376
|
-
//
|
|
1377
|
-
// WHY THIS IS A GATEWAY ROUTE AND NOT A CLIENT FUNCTION. A preview computed in the
|
|
1378
|
-
// client is a SECOND redactor, and the day the two disagree the client is confidently
|
|
1379
|
-
// showing the user something other than what was sent — which is worse than showing
|
|
1380
|
-
// nothing, because it is believed. This runs the SAME redactSegments over the SAME
|
|
1381
|
-
// config, tier, dictionary and detector as a real request, so it cannot drift: if the
|
|
1382
|
-
// preview is wrong, the redaction is wrong too, and that is one bug rather than two.
|
|
1383
|
-
//
|
|
1384
|
-
// Real values NEVER appear in the response. The mapping is token→type only ('types'),
|
|
1385
|
-
// never the 'values' detail an operator can opt into for their own logs: this answer
|
|
1386
|
-
// crosses a process boundary to a UI, and the client already has the original text.
|
|
1387
|
-
// The vault is discarded when this returns, so these tokens are not reusable.
|
|
1388
|
-
if (pathname === '/redact' && req.method === 'POST') {
|
|
1389
|
-
let text = '';
|
|
1390
|
-
try { text = String(JSON.parse((await readBody(req, cfg.maxBodyBytes)).toString('utf8'))?.text || ''); }
|
|
1391
|
-
catch { text = ''; }
|
|
1392
|
-
if (!text) return sendJson(res, 200, { text: '', count: 0, sanitized: 0, entities: [], detector: detectorStatus(cfg) });
|
|
1393
|
-
try {
|
|
1394
|
-
let out = text;
|
|
1395
|
-
const isPro = await resolvePro(cfg.pro?.entitlementToken);
|
|
1396
|
-
// Same start-on-demand as a real turn, for the same reason — and so the preview
|
|
1397
|
-
// keeps describing the request rather than a weaker version of it.
|
|
1398
|
-
await ensureNer(cfg);
|
|
1399
|
-
const r = await redactSegments(
|
|
1400
|
-
[segment(() => out, (v) => { out = v; })],
|
|
1401
|
-
cfg.redaction,
|
|
1402
|
-
{ isPro },
|
|
1403
|
-
);
|
|
1404
|
-
return sendJson(res, 200, {
|
|
1405
|
-
text: out,
|
|
1406
|
-
count: r.count || 0,
|
|
1407
|
-
sanitized: r.sanitized || 0,
|
|
1408
|
-
tier: cfg.redaction?.tier === 'full' ? 'full' : 'basic',
|
|
1409
|
-
entities: redactionDetail(r.vault, 'types') || [],
|
|
1410
|
-
// WHAT THIS PREVIEW COULD NOT SEE — additive, and the whole reason a client can be
|
|
1411
|
-
// honest. Patterns catch emails, phones and card numbers with no detector at all,
|
|
1412
|
-
// so a preview with the detector down looks identical to a clean one: same text,
|
|
1413
|
-
// same shield, names intact. `coverage` is the difference, said out loud.
|
|
1414
|
-
detector: detectorStatus(cfg),
|
|
1415
|
-
});
|
|
1416
|
-
} catch (e) {
|
|
1417
|
-
// Fail LOUD. A preview that silently returns the original text would tell the user
|
|
1418
|
-
// "nothing here is sensitive" at the exact moment redaction is broken.
|
|
1419
|
-
return sendJson(res, 500, { error: { message: `redaction preview failed: ${e.message}`, type: 'redact_error' } });
|
|
1420
|
-
}
|
|
1421
|
-
}
|
|
1422
|
-
|
|
1423
|
-
// Model manager (the extension's Gateway settings drive these). GET lists the
|
|
1424
|
-
// catalog with install state + live download progress; POST switches the active
|
|
1425
|
-
// model (downloading it first if needed) and persists the choice.
|
|
1426
|
-
if (pathname === '/ner/models') {
|
|
1427
|
-
if (req.method === 'GET') {
|
|
1428
|
-
const active = nerEngine.health().model || cfg.ner?.model || null;
|
|
1429
|
-
const available = /** @type {any[]} */ (MODEL_CATALOG.map((m) => ({ ...m, installed: nerEngine.modelOnDisk(m.id) })));
|
|
1430
|
-
// Surface an active BYO (non-catalog) model so the UI shows it too.
|
|
1431
|
-
if (active && !available.some((m) => m.id === active)) {
|
|
1432
|
-
available.push({ id: active, label: active, lang: '—', custom: true, installed: nerEngine.modelOnDisk(active), note: 'Custom model (from Hugging Face).' });
|
|
1433
|
-
}
|
|
1434
|
-
return sendJson(res, 200, {
|
|
1435
|
-
active,
|
|
1436
|
-
state: nerEngine.state(),
|
|
1437
|
-
progress: nerEngine.progress(),
|
|
1438
|
-
available,
|
|
1439
|
-
});
|
|
1440
|
-
}
|
|
1441
|
-
if (req.method === 'POST') {
|
|
1442
|
-
let body = null;
|
|
1443
|
-
try { body = JSON.parse((await readBody(req, cfg.maxBodyBytes)).toString('utf8')); } catch { body = null; }
|
|
1444
|
-
const id = body && typeof body.id === 'string' ? body.id.trim() : null;
|
|
1445
|
-
// Curated catalog OR a strictly-validated BYO id (org/name, from HF).
|
|
1446
|
-
if (!id || !(isKnownModel(id) || isValidCustomModelId(id))) return sendJson(res, 400, { error: { message: 'unknown or invalid model id', type: 'bad_model' } });
|
|
1447
|
-
// Persist first so a restart keeps the choice, then (re)load. Don't block the
|
|
1448
|
-
// response on a possibly-long download — the client polls GET for progress.
|
|
1449
|
-
applyNerModelSelection(cfg, id);
|
|
1450
|
-
try { persistConfig(cfg, configPath()); } catch { /* best effort */ }
|
|
1451
|
-
nerEngine.setModel(id, { onLog: (m) => console.log(m) }).then((ok) => {
|
|
1452
|
-
if (ok && cfg.ner?.enableFullTier && cfg.redaction.tier !== 'full') cfg.redaction.tier = 'full';
|
|
1453
|
-
});
|
|
1454
|
-
return sendJson(res, 202, { accepted: true, active: id, state: nerEngine.state(), progress: nerEngine.progress() });
|
|
1455
|
-
}
|
|
1456
|
-
}
|
|
1457
|
-
// --- Local speech-to-text (dictation). Whisper runs IN-PROCESS (stt-engine.js,
|
|
1458
|
-
// same ONNX engine + model dir as NER); audio arrives as 16 kHz mono Float32 PCM
|
|
1459
|
-
// chunks over loopback and ONLY TEXT ever leaves this process. Wire contract
|
|
1460
|
-
// (additive; see docs in the hub repo):
|
|
1461
|
-
// POST /stt/sessions {lang?} → 201 { id } (ensures the model)
|
|
1462
|
-
// POST /stt/sessions/:id/audio binary Float32 PCM chunk → { ok }
|
|
1463
|
-
// GET /stt/sessions/:id/events SSE: progress | interim | final | error | end
|
|
1464
|
-
// DELETE /stt/sessions/:id flush tail → { ok }
|
|
1465
|
-
// GET/POST /stt/models catalog + progress / switch (mirrors /ner/models)
|
|
1466
|
-
if (pathname === '/stt/models') {
|
|
1467
|
-
if (req.method === 'GET') {
|
|
1468
|
-
const active = sttEngine.health().model || cfg.stt?.model || DEFAULT_STT_MODEL;
|
|
1469
|
-
const available = /** @type {any[]} */ (STT_MODEL_CATALOG.map((m) => ({ ...m, installed: sttEngine.modelOnDisk(m.id) })));
|
|
1470
|
-
// Surface an active CUSTOM (non-catalog) model so the UI can show it too.
|
|
1471
|
-
if (active && !available.some((m) => m.id === active)) {
|
|
1472
|
-
available.push({ id: active, label: active, lang: '—', tier: 'custom', custom: true, installed: sttEngine.modelOnDisk(active), note: 'Custom model (from Hugging Face).' });
|
|
1473
|
-
}
|
|
1474
|
-
return sendJson(res, 200, {
|
|
1475
|
-
active,
|
|
1476
|
-
state: sttEngine.state(),
|
|
1477
|
-
progress: sttEngine.progress(),
|
|
1478
|
-
available,
|
|
1479
|
-
// Precision (quantization) picker: current choice + selectable options +
|
|
1480
|
-
// the dtype actually loaded. On WASM only fp32 loads (see runtimeDtype).
|
|
1481
|
-
dtype: cfg.stt?.dtype || 'auto',
|
|
1482
|
-
loadedDtype: sttEngine.health().dtype,
|
|
1483
|
-
runtime: sttEngine.health().runtime,
|
|
1484
|
-
dtypes: STT_DTYPES,
|
|
1485
|
-
});
|
|
1486
|
-
}
|
|
1487
|
-
if (req.method === 'POST') {
|
|
1488
|
-
let body = null;
|
|
1489
|
-
try { body = JSON.parse((await readBody(req, cfg.maxBodyBytes)).toString('utf8')); } catch { body = null; }
|
|
1490
|
-
const id = body && typeof body.id === 'string' ? body.id.trim() : null;
|
|
1491
|
-
// Curated catalog OR a strictly-validated custom whisper id (Advanced).
|
|
1492
|
-
if (!id || !(isKnownSttModel(id) || isValidCustomSttId(id))) return sendJson(res, 400, { error: { message: 'unknown or invalid model id', type: 'bad_model' } });
|
|
1493
|
-
// Optional precision override (q8/q4/fp16/…); 'auto' clears it.
|
|
1494
|
-
const dtype = typeof body.dtype === 'string' && isValidDtype(body.dtype) ? body.dtype : undefined;
|
|
1495
|
-
if (cfg.stt) cfg.stt.model = id; else cfg.stt = { enabled: true, model: id, allowDownload: true };
|
|
1496
|
-
if (dtype) cfg.stt.dtype = dtype === 'auto' ? null : dtype;
|
|
1497
|
-
try { persistConfig(cfg, configPath()); } catch { /* best effort */ }
|
|
1498
|
-
sttEngine.setModel(id, { onLog: (m) => console.log(m), dtype: dtype || cfg.stt.dtype || 'auto' });
|
|
1499
|
-
return sendJson(res, 202, { accepted: true, active: id, dtype: cfg.stt.dtype || 'auto', state: sttEngine.state(), progress: sttEngine.progress() });
|
|
1500
|
-
}
|
|
1501
|
-
}
|
|
1502
|
-
// Speaker (diarization) model manager — the "who said what" x-vector model.
|
|
1503
|
-
// GET → status + install state; POST → force-download it (ignores the
|
|
1504
|
-
// allowDownload config flag; explicit user action from the Gateway tab).
|
|
1505
|
-
if (pathname === '/diarize/model') {
|
|
1506
|
-
if (req.method === 'GET') {
|
|
1507
|
-
const h = diarizeEngine.health();
|
|
1508
|
-
return sendJson(res, 200, {
|
|
1509
|
-
active: diarizeEngine.DIARIZE_MODEL,
|
|
1510
|
-
state: h.state,
|
|
1511
|
-
progress: diarizeEngine.progress(),
|
|
1512
|
-
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() }],
|
|
1513
|
-
});
|
|
1514
|
-
}
|
|
1515
|
-
if (req.method === 'POST') {
|
|
1516
|
-
diarizeEngine.download({ onLog: (m) => console.log(m) });
|
|
1517
|
-
return sendJson(res, 202, { accepted: true, active: diarizeEngine.DIARIZE_MODEL, state: diarizeEngine.state(), progress: diarizeEngine.progress() });
|
|
1518
|
-
}
|
|
1519
|
-
}
|
|
1520
|
-
// --- Local text-to-speech (voice out). Kokoro runs IN-PROCESS (tts-engine.js),
|
|
1521
|
-
// so audio is synthesized on this machine and never leaves it. Phase 4 of
|
|
1522
|
-
// docs/voice-pipeline.md. Model manager first, then synthesis.
|
|
1523
|
-
if (pathname === '/tts/models') {
|
|
1524
|
-
if (req.method === 'GET') {
|
|
1525
|
-
const active = ttsEngine.health().model || cfg.tts?.model || resolveDefaultModel(rawOrtAvailable());
|
|
1526
|
-
// A model needing the native runtime is still LISTED on the binary, with the
|
|
1527
|
-
// reason — hiding it makes "why can't I clone my voice?" unanswerable.
|
|
1528
|
-
const nativeOk = rawOrtAvailable();
|
|
1529
|
-
const activeEntry = TTS_MODEL_CATALOG.find((m) => m.id === active) || null;
|
|
1530
|
-
const available = /** @type {any[]} */ (TTS_MODEL_CATALOG.map((m) => ({
|
|
1531
|
-
...m,
|
|
1532
|
-
installed: ttsEngine.modelOnDisk(m.id),
|
|
1533
|
-
unavailable: m.requiresNative && !nativeOk
|
|
1534
|
-
? 'needs the npm gateway — the standalone binary cannot load this engine'
|
|
1535
|
-
: undefined,
|
|
1536
|
-
})));
|
|
1537
|
-
if (active && !available.some((m) => m.id === active)) {
|
|
1538
|
-
available.push({ id: active, label: active, lang: '—', tier: 'custom', custom: true, installed: ttsEngine.modelOnDisk(active), note: 'Custom model (from Hugging Face).' });
|
|
1539
|
-
}
|
|
1540
|
-
return sendJson(res, 200, {
|
|
1541
|
-
active,
|
|
1542
|
-
state: ttsEngine.state(),
|
|
1543
|
-
progress: ttsEngine.progress(),
|
|
1544
|
-
available,
|
|
1545
|
-
// The default voice belongs to the model's own namespace: Kokoro's
|
|
1546
|
-
// af_heart means nothing to Pocket, and vice versa.
|
|
1547
|
-
voice: cfg.tts?.voice || (ttsModelEngineOf(active) === 'pocket-tts' ? DEFAULT_POCKET_VOICE : DEFAULT_TTS_VOICE),
|
|
1548
|
-
// Architecture decides whether voices mean anything: Kokoro picks one from
|
|
1549
|
-
// a style bank, VITS/MMS is single-speaker. An empty list tells the UI to
|
|
1550
|
-
// hide the picker rather than offer choices that cannot take effect.
|
|
1551
|
-
arch: ttsEngine.arch(),
|
|
1552
|
-
// Until a model is LOADED the engine knows nothing, and answering "no voices"
|
|
1553
|
-
// for a model that has eight made the client hide its picker on every fresh
|
|
1554
|
-
// install (state 'off' → supportsVoices false → the single-speaker branch). Before
|
|
1555
|
-
// the first load, the catalog answers for the active model.
|
|
1556
|
-
supportsVoices: ttsEngine.arch() ? ttsEngine.supportsVoices() : (activeEntry ? activeEntry.arch === 'style-tts2' && !!activeEntry.voices : true),
|
|
1557
|
-
supportsCustomVoices: ttsEngine.arch() ? ttsEngine.supportsCustomVoices() : !!activeEntry?.customVoices,
|
|
1558
|
-
sampleRate: ttsEngine.sampleRate(),
|
|
1559
|
-
// Built-in voices belong to Kokoro alone. VITS is single-speaker and
|
|
1560
|
-
// SpeechT5 speaks only in a RECORDED voice, so offering Kokoro's list
|
|
1561
|
-
// for either would be offering choices that cannot take effect.
|
|
1562
|
-
voices: (ttsEngine.isPocket() || (!ttsEngine.arch() && ttsModelEngineOf(active) === 'pocket-tts'))
|
|
1563
|
-
// Pocket ships eight speakers in an optional 52 MB file; report what is
|
|
1564
|
-
// actually loaded rather than the catalog's aspiration.
|
|
1565
|
-
? (ttsEngine.builtinVoices().length ? ttsEngine.builtinVoices() : POCKET_VOICES)
|
|
1566
|
-
.map((n) => ({ id: n, label: n[0].toUpperCase() + n.slice(1), lang: 'en', installed: ttsEngine.builtinVoices().includes(n) }))
|
|
1567
|
-
: ttsEngine.arch() && ttsEngine.arch() !== 'style-tts2'
|
|
1568
|
-
? []
|
|
1569
|
-
: TTS_VOICES.map((v) => ({ ...v, installed: ttsEngine.voiceOnDisk(v.id, active) })),
|
|
1570
|
-
dtype: cfg.tts?.dtype || 'auto',
|
|
1571
|
-
loadedDtype: ttsEngine.health().dtype,
|
|
1572
|
-
runtime: ttsEngine.health().runtime,
|
|
1573
|
-
dtypes: TTS_DTYPES,
|
|
1574
|
-
});
|
|
1575
|
-
}
|
|
1576
|
-
if (req.method === 'POST') {
|
|
1577
|
-
let body = null;
|
|
1578
|
-
try { body = JSON.parse((await readBody(req, cfg.maxBodyBytes)).toString('utf8')); } catch { body = null; }
|
|
1579
|
-
const id = body && typeof body.id === 'string' ? body.id.trim() : null;
|
|
1580
|
-
if (id && !(isKnownTtsModel(id) || isValidCustomTtsId(id))) return sendJson(res, 400, { error: { message: 'unknown or invalid model id', type: 'bad_model' } });
|
|
1581
|
-
// A voice id becomes a filename, so it is checked against the catalog AND
|
|
1582
|
-
// its shape before it is ever persisted.
|
|
1583
|
-
// A default voice may be a built-in Kokoro one OR a saved custom one; both
|
|
1584
|
-
// live in the same field, so both shapes are accepted and both validated.
|
|
1585
|
-
const voice = body && typeof body.voice === 'string' ? body.voice.trim() : null;
|
|
1586
|
-
if (voice) {
|
|
1587
|
-
const cid = ttsVoices.parseCustomVoice(voice);
|
|
1588
|
-
const okVoice = cid ? !!ttsVoices.getVoice(cid) : (isPocketVoice(voice) || (isKnownVoice(voice) && isValidVoiceId(voice)));
|
|
1589
|
-
if (!okVoice) return sendJson(res, 400, { error: { message: 'unknown or invalid voice', type: 'bad_voice' } });
|
|
1590
|
-
}
|
|
1591
|
-
const dtype = body && typeof body.dtype === 'string' && isValidTtsDtype(body.dtype) ? body.dtype : undefined;
|
|
1592
|
-
if (!cfg.tts) cfg.tts = { enabled: true, model: DEFAULT_TTS_MODEL, voice: DEFAULT_TTS_VOICE, allowDownload: true };
|
|
1593
|
-
if (id) cfg.tts.model = id;
|
|
1594
|
-
if (voice) cfg.tts.voice = voice;
|
|
1595
|
-
// Switching model must revalidate the voice, or the config ends up naming a
|
|
1596
|
-
// Kokoro voice for SpeechT5 (which then has nothing to speak in) or a
|
|
1597
|
-
// recorded voice for Kokoro (which cannot use one). Both states look like
|
|
1598
|
-
// "text-to-speech is broken" from the outside, and both are reachable with
|
|
1599
|
-
// two clicks. Only rewrite when the CURRENT voice cannot work for the new
|
|
1600
|
-
// model — never override a voice the caller just set.
|
|
1601
|
-
if (id && !voice) {
|
|
1602
|
-
const wantsCustom = ttsModelHasCustomVoices(id);
|
|
1603
|
-
// "Is it a custom voice" is not enough — it must be one that still
|
|
1604
|
-
// EXISTS. A config naming a deleted voice is exactly the state that made
|
|
1605
|
-
// every later request fail with "no such saved voice".
|
|
1606
|
-
const curId = ttsVoices.parseCustomVoice(cfg.tts.voice || '');
|
|
1607
|
-
const isCustom = !!(curId && ttsVoices.getVoice(curId));
|
|
1608
|
-
if (wantsCustom && !isCustom) {
|
|
1609
|
-
// Switching to a cloning model does not mean "start speaking as the user".
|
|
1610
|
-
// A model with built-in speakers gets its default speaker; only SpeechT5,
|
|
1611
|
-
// which has no built-ins, falls back to a saved voice.
|
|
1612
|
-
if (ttsModelEngineOf(id) === 'pocket-tts') {
|
|
1613
|
-
cfg.tts.voice = DEFAULT_POCKET_VOICE;
|
|
1614
|
-
} else {
|
|
1615
|
-
const saved = ttsVoices.listVoices();
|
|
1616
|
-
cfg.tts.voice = saved.length ? `custom:${saved[0].id}` : '';
|
|
1617
|
-
}
|
|
1618
|
-
} else if (!wantsCustom && isCustom) {
|
|
1619
|
-
cfg.tts.voice = DEFAULT_TTS_VOICE;
|
|
1620
|
-
}
|
|
1621
|
-
// Kokoro and Pocket name their speakers differently; carrying one over
|
|
1622
|
-
// leaves a voice the new model has never heard of.
|
|
1623
|
-
const toPocket = ttsModelEngineOf(id) === 'pocket-tts';
|
|
1624
|
-
if (toPocket && !ttsVoices.parseCustomVoice(cfg.tts.voice || '') && !isPocketVoice(cfg.tts.voice)) cfg.tts.voice = DEFAULT_POCKET_VOICE;
|
|
1625
|
-
if (!toPocket && isPocketVoice(cfg.tts.voice)) cfg.tts.voice = DEFAULT_TTS_VOICE;
|
|
1626
|
-
}
|
|
1627
|
-
if (dtype) cfg.tts.dtype = dtype === 'auto' ? null : dtype;
|
|
1628
|
-
try { persistConfig(cfg, configPath()); } catch { /* best effort */ }
|
|
1629
|
-
if (id) ttsEngine.setModel(id, { onLog: (m) => console.log(m), dtype: dtype || cfg.tts.dtype || 'auto' });
|
|
1630
|
-
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() });
|
|
1631
|
-
}
|
|
1632
|
-
}
|
|
1633
|
-
|
|
1634
|
-
// --- Custom voices: a speaker embedding derived from a sample the user
|
|
1635
|
-
// recorded. The AUDIO is embedded in-process and then discarded; only the 512
|
|
1636
|
-
// floats are stored, under ~/.chatpanel, and they never leave this machine.
|
|
1637
|
-
// See src/tts-voices.js for why the rules here are tighter than elsewhere.
|
|
1638
|
-
if (pathname === '/tts/voices') {
|
|
1639
|
-
if (req.method === 'GET') {
|
|
1640
|
-
return sendJson(res, 200, {
|
|
1641
|
-
voices: ttsVoices.listVoices(),
|
|
1642
|
-
// Whether a saved voice can actually be USED right now depends on the
|
|
1643
|
-
// active model — only SpeechT5 takes an embedding. Saying so here stops
|
|
1644
|
-
// the UI offering voices that would be silently ignored.
|
|
1645
|
-
usable: ttsEngine.supportsCustomVoices(),
|
|
1646
|
-
embedder: diarizeEngine.DIARIZE_MODEL,
|
|
1647
|
-
embedderReady: diarizeEngine.isReady(),
|
|
1648
|
-
});
|
|
1649
|
-
}
|
|
1650
|
-
if (req.method === 'POST') {
|
|
1651
|
-
let body = null;
|
|
1652
|
-
try { body = JSON.parse((await readBody(req, cfg.maxBodyBytes)).toString('utf8')); } catch { body = null; }
|
|
1653
|
-
const name = body && typeof body.name === 'string' ? body.name.trim() : '';
|
|
1654
|
-
const pcm = body && Array.isArray(body.pcm) ? body.pcm : null;
|
|
1655
|
-
// An `id` means UPDATE an existing voice rather than create one. The id is
|
|
1656
|
-
// preserved either way, because `custom:<id>` is what the config and every
|
|
1657
|
-
// client hold — a rename or a re-record must not orphan those.
|
|
1658
|
-
const editId = body && typeof body.id === 'string' ? body.id.trim() : '';
|
|
1659
|
-
if (editId) {
|
|
1660
|
-
if (!ttsVoices.getVoice(editId)) return sendJson(res, 404, { error: { message: 'no such saved voice', type: 'bad_voice' } });
|
|
1661
|
-
// Rename only — no new audio, so the prints are left exactly as they are.
|
|
1662
|
-
if (!pcm) {
|
|
1663
|
-
if (!name) return sendJson(res, 400, { error: { message: 'a name is required', type: 'bad_request' } });
|
|
1664
|
-
try {
|
|
1665
|
-
return sendJson(res, 200, { ...ttsVoices.renameVoice(editId, name), usable: ttsEngine.supportsCustomVoices() });
|
|
1666
|
-
} catch (e) { return sendJson(res, 400, { error: { message: e.message, type: 'rename_failed' } }); }
|
|
1667
|
-
}
|
|
1668
|
-
// Re-record: same rules as a fresh take, then swap the prints in place.
|
|
1669
|
-
if (pcm.length < 16000) {
|
|
1670
|
-
return sendJson(res, 400, { error: { message: 'need at least 1 second of 16 kHz mono audio', type: 'sample_too_short' } });
|
|
1671
|
-
}
|
|
1672
|
-
} else if (!name) {
|
|
1673
|
-
return sendJson(res, 400, { error: { message: 'a name is required', type: 'bad_request' } });
|
|
1674
|
-
}
|
|
1675
|
-
if (!pcm || pcm.length < 16000) {
|
|
1676
|
-
// Under a second of audio produces an embedding dominated by whatever
|
|
1677
|
-
// noise happened to be in it, and the resulting voice is arbitrary.
|
|
1678
|
-
return sendJson(res, 400, { error: { message: 'need at least 1 second of 16 kHz mono audio', type: 'sample_too_short' } });
|
|
1679
|
-
}
|
|
1680
|
-
try {
|
|
1681
|
-
// The embedder is the speaker model diarization already uses. WAIT for it
|
|
1682
|
-
// rather than bailing: it is usually already on disk, where loading takes
|
|
1683
|
-
// a couple of seconds — and the caller is holding a recording someone
|
|
1684
|
-
// just made, so returning early means they lose it and record again.
|
|
1685
|
-
// Only a genuine first-time download can outlast the ceiling, and that is
|
|
1686
|
-
// the one case worth reporting as "come back in a moment".
|
|
1687
|
-
if (!diarizeEngine.isReady()) {
|
|
1688
|
-
const load = diarizeEngine.download({ onLog: (m) => console.log(m) });
|
|
1689
|
-
const timedOut = Symbol('timeout');
|
|
1690
|
-
const raced = await Promise.race([
|
|
1691
|
-
load.then(() => null).catch((e) => e),
|
|
1692
|
-
new Promise((r) => setTimeout(() => r(timedOut), EMBEDDER_WAIT_MS)),
|
|
1693
|
-
]);
|
|
1694
|
-
if (raced === timedOut || !diarizeEngine.isReady()) {
|
|
1695
|
-
return sendJson(res, 503, {
|
|
1696
|
-
error: {
|
|
1697
|
-
message: raced === timedOut
|
|
1698
|
-
? 'the speaker model is still downloading (~100 MB) — your recording was kept, press Save again shortly'
|
|
1699
|
-
: `the speaker model failed to load: ${diarizeEngine.health().error || 'unknown error'}`,
|
|
1700
|
-
type: 'embedder_not_ready',
|
|
1701
|
-
},
|
|
1702
|
-
progress: diarizeEngine.progress(),
|
|
1703
|
-
});
|
|
1704
|
-
}
|
|
1705
|
-
}
|
|
1706
|
-
const audio = Float32Array.from(pcm);
|
|
1707
|
-
const vec = await diarizeEngine.embed(audio);
|
|
1708
|
-
|
|
1709
|
-
// A voice print is engine-specific and the SAMPLE is about to be thrown
|
|
1710
|
-
// away, so anything this voice might later need must be derived now.
|
|
1711
|
-
// Pocket TTS is the engine that actually reproduces a speaker, so its
|
|
1712
|
-
// conditioning is computed whenever its bundle is present — failing that
|
|
1713
|
-
// is not fatal, it just means this voice works only with SpeechT5.
|
|
1714
|
-
let pocket = null;
|
|
1715
|
-
try {
|
|
1716
|
-
const pt = await ttsEngine.pocketForEncoding({ allowDownload: cfg.tts?.allowDownload !== false, log: (m) => console.log(m) });
|
|
1717
|
-
// The recorder sends 16 kHz; Mimi wants 24 kHz.
|
|
1718
|
-
if (pt) pocket = await pt.encodeVoice(resample(audio, 16000, 24000));
|
|
1719
|
-
} catch (e) {
|
|
1720
|
-
console.log(`[tts] pocket conditioning unavailable for this voice (${e.message})`);
|
|
1721
|
-
}
|
|
1722
|
-
|
|
1723
|
-
const saved = editId
|
|
1724
|
-
? ttsVoices.replaceVoice(editId, { vec, pocket })
|
|
1725
|
-
: ttsVoices.saveVoice({ name, vec, pocket });
|
|
1726
|
-
// A rename may ride along with a re-record, so apply it after the swap.
|
|
1727
|
-
const final = editId && name && name !== saved.name ? ttsVoices.renameVoice(editId, name) : saved;
|
|
1728
|
-
console.log(`[tts] ${editId ? 're-recorded' : 'saved'} custom voice "${final.name}" (${(saved.kinds || []).join(' + ')}, sample discarded)`);
|
|
1729
|
-
return sendJson(res, editId ? 200 : 201, { ...saved, ...final, usable: ttsEngine.supportsCustomVoices() });
|
|
1730
|
-
} catch (e) {
|
|
1731
|
-
return sendJson(res, 400, { error: { message: e.message, type: 'save_failed' } });
|
|
1732
|
-
}
|
|
1733
|
-
}
|
|
1734
|
-
if (req.method === 'DELETE') {
|
|
1735
|
-
const id = url.searchParams.get('id') || '';
|
|
1736
|
-
// Deleting someone's voice print is not a soft delete — the file is gone.
|
|
1737
|
-
const deleted = ttsVoices.deleteVoice(id);
|
|
1738
|
-
// …and the config must not keep NAMING it. A stored voice that no longer
|
|
1739
|
-
// exists makes every later request fail with "no such saved voice", which
|
|
1740
|
-
// is a confusing way to be told "you deleted that one".
|
|
1741
|
-
if (deleted && cfg.tts?.voice === `custom:${id}`) {
|
|
1742
|
-
const left = ttsVoices.listVoices();
|
|
1743
|
-
cfg.tts.voice = left.length ? `custom:${left[0].id}` : DEFAULT_TTS_VOICE;
|
|
1744
|
-
try { persistConfig(cfg, configPath()); } catch { /* best effort */ }
|
|
1745
|
-
}
|
|
1746
|
-
return sendJson(res, 200, { deleted, voice: cfg.tts?.voice });
|
|
1747
|
-
}
|
|
1748
|
-
}
|
|
1749
|
-
|
|
1750
|
-
// POST /tts — { text, voice?, speed? } → audio/wav — and its OpenAI-compatible
|
|
1751
|
-
// twin POST /v1/audio/speech ({ input, voice, speed, response_format }), so any
|
|
1752
|
-
// OpenAI client or tunnel can drive local speech with no ChatPanel-specific code.
|
|
1753
|
-
// Both go through ONE handler: two routes must never drift into two behaviours.
|
|
1754
|
-
//
|
|
1755
|
-
// Deliberately NOT redacted. Every other stage in the voice pipeline redacts at
|
|
1756
|
-
// the model-send chokepoint because the text is about to leave the machine;
|
|
1757
|
-
// synthesis is local, so there is nothing to protect it from — and reading
|
|
1758
|
-
// "[[PERSON_1]]" aloud to the person who wrote it is a bug, not privacy.
|
|
1759
|
-
if ((pathname === '/tts' || pathname === '/v1/audio/speech') && req.method === 'POST') {
|
|
1760
|
-
if (cfg.tts?.enabled === false) return sendJson(res, 503, { error: { message: 'tts is disabled in gateway config', type: 'tts_disabled' } });
|
|
1761
|
-
let body = null;
|
|
1762
|
-
try { body = JSON.parse((await readBody(req, cfg.maxBodyBytes)).toString('utf8')); } catch { body = null; }
|
|
1763
|
-
// `input` is OpenAI's field name, `text` is ours — accept either on both routes.
|
|
1764
|
-
const text = body && typeof (body.input ?? body.text) === 'string' ? String(body.input ?? body.text).trim() : '';
|
|
1765
|
-
if (!text) return sendJson(res, 400, { error: { message: 'text is required', type: 'bad_request' } });
|
|
1766
|
-
if (text.length > MAX_TTS_CHARS) return sendJson(res, 413, { error: { message: `text too long (max ${MAX_TTS_CHARS} chars)`, type: 'too_long' } });
|
|
1767
|
-
const speed = Number.isFinite(body.speed) ? Math.min(2, Math.max(0.5, body.speed)) : 1;
|
|
1768
|
-
const dest = ttsDestination(cfg);
|
|
1769
|
-
// A remote destination has its own voice namespace (an ElevenLabs voice id is
|
|
1770
|
-
// not a Kokoro one), so the local catalog check would reject every valid id.
|
|
1771
|
-
const rawVoice = body && typeof body.voice === 'string' && body.voice.trim() ? body.voice.trim() : null;
|
|
1772
|
-
const voice = rawVoice || (dest ? dest.voice : (cfg.tts?.voice || DEFAULT_TTS_VOICE));
|
|
1773
|
-
// A REMOTE destination has its own voice namespace, so it is validated here;
|
|
1774
|
-
// local voices cannot be resolved until the model is loaded, because which
|
|
1775
|
-
// KIND of voice is valid depends on the architecture. See below.
|
|
1776
|
-
if (dest && !isValidRemoteVoice(voice)) {
|
|
1777
|
-
return sendJson(res, 400, { error: { message: 'unknown or invalid voice', type: 'bad_voice' } });
|
|
1778
|
-
}
|
|
1779
|
-
// We synthesize WAV only. Say so rather than returning WAV bytes under an mp3
|
|
1780
|
-
// content-type — a client that trusts the header would play noise.
|
|
1781
|
-
const fmt = body && typeof body.response_format === 'string' ? body.response_format.toLowerCase() : 'wav';
|
|
1782
|
-
if (fmt !== 'wav' && fmt !== 'pcm') return sendJson(res, 400, { error: { message: `unsupported response_format "${fmt}" — this gateway synthesizes wav`, type: 'bad_format' } });
|
|
1783
|
-
try {
|
|
1784
|
-
// Remote destination: the caller's own auth goes upstream, the text is
|
|
1785
|
-
// redacted first unless this destination explicitly opted out, and the
|
|
1786
|
-
// vendor's own audio format is passed straight through rather than
|
|
1787
|
-
// re-wrapped — we did not synthesize it and must not claim its container.
|
|
1788
|
-
if (dest) {
|
|
1789
|
-
const { audio, contentType, redacted } = await synthesizeRemote({
|
|
1790
|
-
dest, text, voice, speed,
|
|
1791
|
-
auth: req.headers.authorization || req.headers['xi-api-key'] || '',
|
|
1792
|
-
redaction: cfg.redaction,
|
|
1793
|
-
isPro: await resolvePro(cfg.pro?.entitlementToken),
|
|
1794
|
-
});
|
|
1795
|
-
res.writeHead(200, {
|
|
1796
|
-
'Content-Type': contentType,
|
|
1797
|
-
'Content-Length': String(audio.length),
|
|
1798
|
-
'Cache-Control': 'no-store',
|
|
1799
|
-
// Say what actually left. A caller that asked for privacy can verify it,
|
|
1800
|
-
// and one that turned it off can see that it is off.
|
|
1801
|
-
'X-Tts-Provider': dest.kind,
|
|
1802
|
-
'X-Tts-Redacted': String(redacted),
|
|
1803
|
-
});
|
|
1804
|
-
return res.end(audio);
|
|
1805
|
-
}
|
|
1806
|
-
const ok = await ttsEngine.ready({
|
|
1807
|
-
onLog: (m) => console.log(m),
|
|
1808
|
-
allowDownload: cfg.tts?.allowDownload !== false,
|
|
1809
|
-
model: cfg.tts?.model || resolveDefaultModel(rawOrtAvailable()),
|
|
1810
|
-
dtype: cfg.tts?.dtype || 'auto',
|
|
1811
|
-
});
|
|
1812
|
-
if (!ok) return sendJson(res, 503, { error: { message: ttsEngine.health().error || 'tts model not ready', type: 'tts_unavailable' } });
|
|
1813
|
-
// Voices are resolved AFTER the model is up, because what counts as a valid
|
|
1814
|
-
// voice is a property of the architecture: Kokoro takes a style-bank name,
|
|
1815
|
-
// SpeechT5 takes a recorded embedding, VITS takes neither. Resolving first
|
|
1816
|
-
// meant a `custom:` voice could reach a freshly-loaded Kokoro and fail deep
|
|
1817
|
-
// in the engine with "invalid voice id".
|
|
1818
|
-
const picked = resolveTtsVoice({
|
|
1819
|
-
requested: rawVoice, configured: voice, engine: ttsEngine, voices: ttsVoices,
|
|
1820
|
-
isPocketVoice, isKnownVoice, isValidVoiceId,
|
|
1821
|
-
defaultVoice: DEFAULT_TTS_VOICE, defaultPocketVoice: DEFAULT_POCKET_VOICE,
|
|
1822
|
-
});
|
|
1823
|
-
if (!picked.ok) return sendJson(res, picked.status, { error: { message: picked.message, type: picked.type } });
|
|
1824
|
-
const { voice: useVoice, customId, speakerEmbedding } = picked;
|
|
1825
|
-
|
|
1826
|
-
const pcm = await ttsEngine.synth(text, { voice: useVoice, speed, speakerEmbedding });
|
|
1827
|
-
// The ACTIVE model's rate, not the constant: a VITS/MMS model emits 16 kHz
|
|
1828
|
-
// and writing it into a 24 kHz header plays it fast and chipmunked.
|
|
1829
|
-
const rate = ttsEngine.sampleRate();
|
|
1830
|
-
const out = fmt === 'pcm' ? Buffer.from(new Float32Array(pcm).buffer) : ttsEngine.toWav(pcm, rate);
|
|
1831
|
-
res.writeHead(200, {
|
|
1832
|
-
'Content-Type': fmt === 'pcm' ? 'application/octet-stream' : 'audio/wav',
|
|
1833
|
-
'Content-Length': String(out.length),
|
|
1834
|
-
'Cache-Control': 'no-store',
|
|
1835
|
-
'X-Tts-Sample-Rate': String(rate),
|
|
1836
|
-
// Say which voice actually spoke, so a caller (or a person debugging one)
|
|
1837
|
-
// can check the setting took. Single-speaker models have nothing to say.
|
|
1838
|
-
...(customId || ttsEngine.isPocket() || ttsEngine.supportsVoices() ? { 'X-Tts-Voice': useVoice } : {}),
|
|
1839
|
-
});
|
|
1840
|
-
return res.end(out);
|
|
1841
|
-
} catch (e) {
|
|
1842
|
-
return sendJson(res, 500, { error: { message: e.message, type: 'tts_failed' } });
|
|
1843
|
-
}
|
|
1844
|
-
}
|
|
1845
|
-
|
|
1846
|
-
if (pathname === '/stt/sessions' && req.method === 'POST') {
|
|
1847
|
-
if (cfg.stt?.enabled === false) return sendJson(res, 403, { error: { message: 'STT disabled in gateway config', type: 'stt_disabled' } });
|
|
1848
|
-
let body = null;
|
|
1849
|
-
try { body = JSON.parse((await readBody(req, cfg.maxBodyBytes)).toString('utf8') || '{}'); } catch { body = null; }
|
|
1850
|
-
// Kick the model load on first use (single-flight; downloads once). The
|
|
1851
|
-
// client follows progress on the session's SSE stream.
|
|
1852
|
-
if (!sttEngine.isReady()) {
|
|
1853
|
-
sttEngine.init({ model: cfg.stt?.model || DEFAULT_STT_MODEL, allowDownload: cfg.stt?.allowDownload !== false, dtype: cfg.stt?.dtype || undefined, onLog: (m) => console.log(m) });
|
|
1854
|
-
}
|
|
1855
|
-
// Diarization is another OPTIONAL stage: load its model only when a session
|
|
1856
|
-
// asks for it (never on the dictation path).
|
|
1857
|
-
const wantDiarize = body?.diarize === true && cfg.stt?.diarize !== false;
|
|
1858
|
-
if (wantDiarize && !diarizeEngine.isReady()) {
|
|
1859
|
-
diarizeEngine.init({ allowDownload: cfg.stt?.allowDownload !== false, onLog: (m) => console.log(m) });
|
|
1860
|
-
}
|
|
1861
|
-
try {
|
|
1862
|
-
// `redact: true` chains the OPTIONAL redaction hop onto finals (STT → NER,
|
|
1863
|
-
// same composable model as everything else: any stage, with or without).
|
|
1864
|
-
// `diarize: true` (+ optional `speakerLabel` to pin the mic channel to a
|
|
1865
|
-
// name) attaches a speaker to each final.
|
|
1866
|
-
// `endSilenceMs` (additive) lets a voice conversation wait longer for a
|
|
1867
|
-
// sentence to finish than dictation into a text box needs to.
|
|
1868
|
-
const { id } = sttEngine.createSession({ lang: body?.lang, redact: body?.redact === true, diarize: wantDiarize, speakerLabel: body?.speakerLabel, endSilenceMs: body?.endSilenceMs });
|
|
1869
|
-
return sendJson(res, 201, { id, state: sttEngine.state() });
|
|
1870
|
-
} catch (e) {
|
|
1871
|
-
return sendJson(res, e.code === 'too_many_sessions' ? 429 : 500, { error: { message: e.message, type: e.code || 'stt_error' } });
|
|
1872
|
-
}
|
|
1873
|
-
}
|
|
1874
|
-
{
|
|
1875
|
-
const m = pathname.match(/^\/stt\/sessions\/([0-9a-f-]{36})(\/audio|\/events)?$/);
|
|
1876
|
-
if (m) {
|
|
1877
|
-
const sid = m[1];
|
|
1878
|
-
if (m[2] === '/audio' && req.method === 'POST') {
|
|
1879
|
-
try {
|
|
1880
|
-
const raw = await readBody(req, cfg.maxBodyBytes);
|
|
1881
|
-
sttEngine.pushAudio(sid, sttEngine.toFloat32(raw));
|
|
1882
|
-
return sendJson(res, 200, { ok: true, state: sttEngine.state() });
|
|
1883
|
-
} catch (e) {
|
|
1884
|
-
return sendJson(res, e.code === 'no_session' ? 404 : 400, { error: { message: e.message, type: e.code || 'stt_error' } });
|
|
1885
|
-
}
|
|
1886
|
-
}
|
|
1887
|
-
if (m[2] === '/events' && req.method === 'GET') {
|
|
1888
|
-
const sess = sttEngine.getSession(sid);
|
|
1889
|
-
if (!sess) return sendJson(res, 404, { error: { message: 'no such session', type: 'no_session' } });
|
|
1890
|
-
res.writeHead(200, { 'content-type': 'text/event-stream', 'cache-control': 'no-cache', connection: 'keep-alive' });
|
|
1891
|
-
const send = (ev) => res.write(`data: ${JSON.stringify(ev)}\n\n`);
|
|
1892
|
-
// Optional STT → NER hop: redact FINALS through the same shared guard as
|
|
1893
|
-
// chat traffic (one implementation, composed — never a second redactor).
|
|
1894
|
-
// Interims stay raw (transient, loopback-only). NOTE: the vault is
|
|
1895
|
-
// discarded, so these placeholders are permanent — that's the point.
|
|
1896
|
-
const sttIsPro = sess.redact ? await resolvePro(cfg.pro?.entitlementToken) : true;
|
|
1897
|
-
const maybeRedact = async (ev) => {
|
|
1898
|
-
if (ev.type !== 'final' || !sess.redact) return ev;
|
|
1899
|
-
try {
|
|
1900
|
-
let t = ev.text;
|
|
1901
|
-
await redactSegments([segment(() => t, (v) => { t = v; })], cfg.redaction, { isPro: sttIsPro });
|
|
1902
|
-
return { ...ev, text: t };
|
|
1903
|
-
} catch { return ev; } // fail-open: raw text is still local-only
|
|
1904
|
-
};
|
|
1905
|
-
// While the model is loading/downloading, stream progress so the UI can
|
|
1906
|
-
// show "downloading 43%" instead of dead air on first-ever dictation.
|
|
1907
|
-
send({ type: 'state', state: sttEngine.state() });
|
|
1908
|
-
const progressTimer = setInterval(() => {
|
|
1909
|
-
const st = sttEngine.state();
|
|
1910
|
-
if (st === 'downloading' || st === 'loading') { send({ type: 'progress', state: st, ...(sttEngine.progress() || {}) }); return; }
|
|
1911
|
-
if (st === 'error') { send({ type: 'error', code: 'model_failed', message: sttEngine.health().error || 'model failed to load', fatal: true }); clearInterval(progressTimer); return; }
|
|
1912
|
-
// STT ready — if diarization is on, surface ITS one-time download too, so
|
|
1913
|
-
// "who said what" doesn't silently lag while the speaker model fetches.
|
|
1914
|
-
if (sess.diarize) {
|
|
1915
|
-
const ds = diarizeEngine.state();
|
|
1916
|
-
if (ds === 'downloading' || ds === 'loading') { send({ type: 'diarize-progress', state: ds, ...(diarizeEngine.progress() || {}) }); return; }
|
|
1917
|
-
}
|
|
1918
|
-
send({ type: 'state', state: st }); clearInterval(progressTimer);
|
|
1919
|
-
}, 500);
|
|
1920
|
-
progressTimer.unref?.();
|
|
1921
|
-
// Redaction is async — chain events so finals can't overtake interims.
|
|
1922
|
-
let evChain = Promise.resolve();
|
|
1923
|
-
const unsub = sttEngine.subscribe(sid, (ev) => {
|
|
1924
|
-
evChain = evChain.then(async () => {
|
|
1925
|
-
send(await maybeRedact(ev));
|
|
1926
|
-
if (ev.type === 'end') { clearInterval(progressTimer); res.end(); }
|
|
1927
|
-
}).catch(() => {});
|
|
1928
|
-
});
|
|
1929
|
-
req.on('close', () => { clearInterval(progressTimer); unsub?.(); });
|
|
1930
|
-
return;
|
|
1931
|
-
}
|
|
1932
|
-
if (!m[2] && req.method === 'DELETE') {
|
|
1933
|
-
await sttEngine.endSession(sid);
|
|
1934
|
-
return sendJson(res, 200, { ok: true });
|
|
1935
|
-
}
|
|
1936
|
-
}
|
|
1937
|
-
}
|
|
1938
|
-
if (pathname === '/logs' && req.method === 'GET') {
|
|
1939
|
-
return sendJson(res, 200, { entries: [...recentRequests].reverse() }); // newest first; counts only, unless logDetail enriches each entry
|
|
1940
|
-
}
|
|
1941
|
-
if (pathname === '/config' && req.method === 'GET') {
|
|
1942
|
-
const proUnlocked = await resolvePro(cfg.pro?.entitlementToken);
|
|
1943
|
-
return sendJson(res, 200, publicConfig(cfg, { proUnlocked }));
|
|
1944
|
-
}
|
|
1945
|
-
if (pathname === '/config' && req.method === 'POST') {
|
|
1946
|
-
let patch = null;
|
|
1947
|
-
try { patch = JSON.parse((await readBody(req, cfg.maxBodyBytes)).toString('utf8')); } catch { patch = null; }
|
|
1948
|
-
if (!patch || typeof patch !== 'object') return sendJson(res, 400, { error: 'invalid config patch' });
|
|
1949
|
-
applyConfigPatch(cfg, patch);
|
|
1950
|
-
try { persistConfig(cfg, configPath()); } catch (e) { return sendJson(res, 500, { error: `could not persist config: ${e.message}` }); }
|
|
1951
|
-
// The bundled NER engine only auto-loads at startup. If the user just switched
|
|
1952
|
-
// detection BACK to the bundled engine (or it never loaded because an external
|
|
1953
|
-
// detector was configured at boot), load it now so it doesn't stay "not running"
|
|
1954
|
-
// until a restart. (An external detector needs no engine.) Fire-and-forget.
|
|
1955
|
-
const det = cfg.redaction?.detection;
|
|
1956
|
-
const usingBundled = !det || !det.backend || det.backend === 'off';
|
|
1957
|
-
const st = nerEngine.state();
|
|
1958
|
-
if (cfg.ner?.autostart && usingBundled && st !== 'ready' && st !== 'loading' && st !== 'downloading') {
|
|
1959
|
-
nerEngine.setModel(cfg.ner.model, { onLog: (m) => console.log(m) }).then((ok) => {
|
|
1960
|
-
if (ok && cfg.ner?.enableFullTier && cfg.redaction.tier !== 'full') cfg.redaction.tier = 'full';
|
|
1961
|
-
});
|
|
1962
|
-
}
|
|
1963
|
-
const proUnlocked = await resolvePro(cfg.pro?.entitlementToken);
|
|
1964
|
-
return sendJson(res, 200, publicConfig(cfg, { proUnlocked }));
|
|
1965
|
-
}
|
|
1966
|
-
|
|
1967
|
-
// THE SKILLS ON THIS MACHINE, asked of the gateway rather than the bridge.
|
|
1968
|
-
//
|
|
1969
|
-
// The bridge is what reads the user's disk, so this proxies it — but a client should
|
|
1970
|
-
// have ONE address for everything. A client that talks to the gateway for models and the
|
|
1971
|
-
// bridge for skills has to know both are up, hold both tokens, and handle two failure
|
|
1972
|
-
// modes for one screen; and the direct-to-bridge path is the one with no policy in front
|
|
1973
|
-
// of it, so making it necessary for a feature is how it becomes the habit.
|
|
1974
|
-
if (req.method === 'GET' && pathname === '/skills') {
|
|
1975
|
-
const base = await resolveBridgeUrl(cfg);
|
|
1976
|
-
if (!base) return sendJson(res, 503, { error: { message: 'no bridge is configured', type: 'no_bridge' } });
|
|
1977
|
-
const token = readBridgeToken(cfg.bridge?.token);
|
|
1978
|
-
try {
|
|
1979
|
-
const r = await fetch(`${base}/skills`, {
|
|
1980
|
-
headers: { Accept: 'application/json', ...(token ? { Authorization: `Bearer ${token}` } : {}) },
|
|
1981
|
-
signal: AbortSignal.timeout(8000),
|
|
1982
|
-
});
|
|
1983
|
-
const data = await r.json().catch(() => ({}));
|
|
1984
|
-
if (!r.ok) return sendJson(res, r.status, { error: { message: data?.error || `bridge ${r.status}`, type: 'bridge_error' } });
|
|
1985
|
-
return sendJson(res, 200, { skills: Array.isArray(data?.skills) ? data.skills : [] });
|
|
1986
|
-
} catch (e) {
|
|
1987
|
-
return sendJson(res, 502, { error: { message: `bridge unreachable: ${e.message}`, type: 'bridge_unreachable' } });
|
|
1988
|
-
}
|
|
1989
|
-
}
|
|
1990
|
-
|
|
1991
|
-
// ONE skill, with the prompt the list deliberately leaves out.
|
|
1992
|
-
//
|
|
1993
|
-
// /skills answers `promptChars` — a COUNT — because a list of ninety-five skills carrying
|
|
1994
|
-
// ninety-five prompt bodies is a megabyte nobody asked for. A client that wants to scope a
|
|
1995
|
-
// task to a skill needs the body itself, and the only other way to get it was to go
|
|
1996
|
-
// straight at the bridge, which is the habit the /skills comment above exists to prevent.
|
|
1997
|
-
//
|
|
1998
|
-
// The id is passed through as ONE path segment, encoded. A skill id is a file name on the
|
|
1999
|
-
// user's disk, so letting a slash or a `..` reach the bridge's reader would be asking it
|
|
2000
|
-
// to open something else; the bridge validates too, and this is the half we own.
|
|
2001
|
-
if (req.method === 'GET' && /^\/skills\/[^/]+$/.test(pathname)) {
|
|
2002
|
-
const id = decodeURIComponent(pathname.slice('/skills/'.length));
|
|
2003
|
-
if (!id || id === '.' || id === '..' || id.includes('/') || id.includes('\\')) {
|
|
2004
|
-
return sendJson(res, 400, { error: { message: 'not a skill id', type: 'invalid_request' } });
|
|
2005
|
-
}
|
|
2006
|
-
const base = await resolveBridgeUrl(cfg);
|
|
2007
|
-
if (!base) return sendJson(res, 503, { error: { message: 'no bridge is configured', type: 'no_bridge' } });
|
|
2008
|
-
const token = readBridgeToken(cfg.bridge?.token);
|
|
2009
|
-
try {
|
|
2010
|
-
const r = await fetch(`${base}/skills/${encodeURIComponent(id)}`, {
|
|
2011
|
-
headers: { Accept: 'application/json', ...(token ? { Authorization: `Bearer ${token}` } : {}) },
|
|
2012
|
-
signal: AbortSignal.timeout(8000),
|
|
2013
|
-
});
|
|
2014
|
-
const data = await r.json().catch(() => ({}));
|
|
2015
|
-
if (!r.ok) return sendJson(res, r.status, { error: { message: data?.error || `bridge ${r.status}`, type: 'bridge_error' } });
|
|
2016
|
-
return sendJson(res, 200, { skill: data?.skill || null });
|
|
2017
|
-
} catch (e) {
|
|
2018
|
-
return sendJson(res, 502, { error: { message: `bridge unreachable: ${e.message}`, type: 'bridge_unreachable' } });
|
|
2019
|
-
}
|
|
2020
|
-
}
|
|
2021
|
-
|
|
2022
|
-
// Model discovery — aggregate every destination's models.
|
|
2023
|
-
if (req.method === 'GET' && /\/models$/.test(pathname)) {
|
|
2024
|
-
return sendJson(res, 200, await aggregateModelsAsync(cfg));
|
|
2025
|
-
}
|
|
2026
|
-
|
|
2027
|
-
// Anything under a LOCAL namespace that reached here matched no route, which
|
|
2028
|
-
// almost always means the caller is newer than this gateway. Falling through to
|
|
2029
|
-
// the model proxy makes that arrive as "upstream fetch failed", pointing the
|
|
2030
|
-
// user at their model provider for a feature their gateway simply does not
|
|
2031
|
-
// have yet — so these 404 with the actual reason instead.
|
|
2032
|
-
if (LOCAL_NAMESPACES.some((ns) => pathname === ns || pathname.startsWith(`${ns}/`))) {
|
|
2033
|
-
return sendJson(res, 404, {
|
|
2034
|
-
error: {
|
|
2035
|
-
message: `this gateway (${VERSION}) has no ${pathname} — update it to use this feature`,
|
|
2036
|
-
type: 'unknown_endpoint',
|
|
2037
|
-
},
|
|
2038
|
-
});
|
|
2039
|
-
}
|
|
2040
|
-
|
|
2041
|
-
const r = route(pathname, req.headers, cfg);
|
|
2042
|
-
let raw;
|
|
2043
|
-
try {
|
|
2044
|
-
raw = await readBody(req, cfg.maxBodyBytes);
|
|
2045
|
-
} catch (e) {
|
|
2046
|
-
sendJson(res, e.code === 413 ? 413 : 400, { error: e.code === 413 ? 'payload too large' : 'bad request' });
|
|
2047
|
-
req.destroy(); // stop reading an oversized/aborted upload; don't leave the socket half-open
|
|
2048
|
-
return;
|
|
2049
|
-
}
|
|
2050
|
-
|
|
2051
|
-
// Redact the request body for the known chat endpoints.
|
|
2052
|
-
let vault = null;
|
|
2053
|
-
let body = null;
|
|
2054
|
-
let outBody = raw;
|
|
2055
|
-
let redactedCount = 0;
|
|
2056
|
-
let sanitizedCount = 0;
|
|
2057
|
-
let narrowedTools = 0;
|
|
2058
|
-
let redactionOff = false;
|
|
2059
|
-
let isPro = true;
|
|
2060
|
-
// Off the hot path: only build a trace when logging is on, so it adds nothing
|
|
2061
|
-
// when off (no clock reads, no record, no console line).
|
|
2062
|
-
const trace = (cfg.logRequests && r.redactable && req.method === 'POST') ? mkTrace(recordRequest) : null;
|
|
2063
|
-
if (r.redactable && req.method === 'POST' && raw.length) {
|
|
2064
|
-
try { body = JSON.parse(raw.toString('utf8')); } catch { body = null; }
|
|
2065
|
-
if (body && isRelayResume(body, r.kind)) {
|
|
2066
|
-
// Relay tool-result follow-up: do NOT redact here — the parked session
|
|
2067
|
-
// redacts the tool result + restores the reply with ITS vault. Pass raw.
|
|
2068
|
-
outBody = raw;
|
|
2069
|
-
} else if (body) {
|
|
2070
|
-
// Auto-narrow tools to the top-K most relevant for this turn (speed) —
|
|
2071
|
-
// same shared ranker as the extension's AUTO mode. Only MCP-named tools
|
|
2072
|
-
// are narrowed; the client's core tools (bash/read/edit…) are always kept,
|
|
2073
|
-
// unless tools.narrowAll is set. Mutates body.tools BEFORE redaction so
|
|
2074
|
-
// both the API forward and the bridge relay see the trimmed set.
|
|
2075
|
-
const tcfg = cfg.tools || {};
|
|
2076
|
-
if (tcfg.autoNarrow !== false && Array.isArray(body.tools) && body.tools.length) {
|
|
2077
|
-
const cap = Number(tcfg.maxPerTurn) > 0 ? Number(tcfg.maxPerTurn) : DEFAULT_GATEWAY_TOOL_CAP;
|
|
2078
|
-
const keep = tcfg.narrowAll ? null : (t) => !MCP_NAME_RE.test(toolName(t));
|
|
2079
|
-
const before = body.tools.length;
|
|
2080
|
-
body.tools = narrowSpecs(body.tools, latestUserText(body, r.kind), { cap, keep, name: toolName, description: toolDesc });
|
|
2081
|
-
narrowedTools = before - body.tools.length;
|
|
2082
|
-
}
|
|
2083
|
-
// Free users get full-tier redaction within a fixed lifetime allowance —
|
|
2084
|
-
// checked here, consumed below once a redaction actually happens. Over the
|
|
2085
|
-
// cap returns 402.
|
|
2086
|
-
isPro = await resolvePro(cfg.pro?.entitlementToken);
|
|
2087
|
-
const allow = checkQuota(cfg, isPro);
|
|
2088
|
-
if (!allow.allowed) {
|
|
2089
|
-
return sendJson(res, 402, { error: {
|
|
2090
|
-
message: `ChatPanel Gateway free trial used up (${allow.cap} redactions). Add a ChatPanel Pro entitlement token to unlock unlimited full-tier redaction (names/orgs).`,
|
|
2091
|
-
type: 'free_limit_reached',
|
|
2092
|
-
} });
|
|
2093
|
-
}
|
|
2094
|
-
// REDACTION OFF, FOR THIS REQUEST, BECAUSE THE USER SAID SO. A note task that reads
|
|
2095
|
-
// "write about NVIDIA GPUs" had NVIDIA replaced with an organisation placeholder, and
|
|
2096
|
-
// the model — seeing only [[ORG_1]] — guessed a different company and wrote about
|
|
2097
|
-
// that. The policy is right for the corpus and wrong for the user's own instruction,
|
|
2098
|
-
// and only the user can tell which a given turn is. So an AUTHENTICATED local client
|
|
2099
|
-
// (the desktop, the extension — both hold the gateway token) may send
|
|
2100
|
-
// `X-ChatPanel-Redaction: off`; the trace records it so the ledger says "redaction
|
|
2101
|
-
// was off for this turn" rather than "0 redactions", which would read as "nothing to
|
|
2102
|
-
// redact". Anonymous callers cannot switch it off: that is what the token is for.
|
|
2103
|
-
redactionOff = String(req.headers['x-chatpanel-redaction'] || '').trim().toLowerCase() === 'off' && isAdminAuthorized(req);
|
|
2104
|
-
// The detector must be up BEFORE the text is redacted, not after someone notices it
|
|
2105
|
-
// wasn't. redactSegments consults the engine and falls open when it is not ready, so
|
|
2106
|
-
// a gateway whose engine never autostarted sent names through at full tier without a
|
|
2107
|
-
// word. Cheap after the first call: ready → a state check, absent weights → nothing.
|
|
2108
|
-
if (!redactionOff) await ensureNer(cfg);
|
|
2109
|
-
const segs = redactionOff ? [] : r.adapter.collectSegments(body, cfg.redaction);
|
|
2110
|
-
const ac = new AbortController();
|
|
2111
|
-
res.on('close', () => { if (!res.writableFinished) ac.abort(); });
|
|
2112
|
-
const rd0 = trace ? trace.clock() : 0;
|
|
2113
|
-
// Redact at the configured tier for everyone (free users get name/org
|
|
2114
|
-
// redaction within their allowance); the custom dictionary stays capped for
|
|
2115
|
-
// free (isPro decides that inside).
|
|
2116
|
-
const { vault: v, count, sanitized } = redactionOff ? { vault: null, count: 0, sanitized: 0 } : await redactSegments(segs, cfg.redaction, {
|
|
2117
|
-
signal: ac.signal,
|
|
2118
|
-
isPro,
|
|
2119
|
-
// A detector is the only hop that sees the request BEFORE redaction. It is guarded
|
|
2120
|
-
// (SSRF) but was not visible: /v1/observability/access is where a user answers
|
|
2121
|
-
// "what left my machine", and this was the one thing missing from it.
|
|
2122
|
-
onEgress: (e) => accessLog.push(makeAccessEvent({
|
|
2123
|
-
ts: Date.now(),
|
|
2124
|
-
client: 'redaction',
|
|
2125
|
-
tool: `detect:${e.backend}@${e.host || 'local'}`,
|
|
2126
|
-
ok: e.ok,
|
|
2127
|
-
ms: e.ms,
|
|
2128
|
-
error: e.error,
|
|
2129
|
-
})),
|
|
2130
|
-
});
|
|
2131
|
-
if (trace) trace.lap('redact', rd0);
|
|
2132
|
-
vault = v;
|
|
2133
|
-
redactedCount = count;
|
|
2134
|
-
sanitizedCount = sanitized || 0;
|
|
2135
|
-
// Consume one lifetime free credit only when we actually redacted
|
|
2136
|
-
// something, then persist. (No-op / no write for Pro.)
|
|
2137
|
-
if (!isPro && count > 0) {
|
|
2138
|
-
consume(cfg, isPro);
|
|
2139
|
-
try { persistConfig(cfg, configPath()); } catch { /* best effort — usage is advisory */ }
|
|
2140
|
-
}
|
|
2141
|
-
// When tools are armed, tell the model placeholders are auto-restored for
|
|
2142
|
-
// tools (so privacy-aware models USE them instead of refusing). Injected
|
|
2143
|
-
// AFTER redaction so the note isn't itself redacted. Covers BOTH the API
|
|
2144
|
-
// forward and the relay (which reads system from this same body).
|
|
2145
|
-
if (!redactionOff && Array.isArray(body.tools) && body.tools.length && typeof r.adapter.injectSystemNote === 'function') {
|
|
2146
|
-
// A relayed CLI agent brings tools of its own that run PAST this proxy and get the
|
|
2147
|
-
// placeholder literally; an API model has only the tools in this request. The note
|
|
2148
|
-
// has to say which is which, so the destination is looked up here — the same
|
|
2149
|
-
// resolution as below, on the same hint, just earlier. No destination means the
|
|
2150
|
-
// legacy bridge path, which is an agent.
|
|
2151
|
-
const early = resolveDestination(body?.model, cfg, r.kind, {
|
|
2152
|
-
destination: String(req.headers['x-chatpanel-destination'] || body?.chatpanel?.destination || '').trim(),
|
|
2153
|
-
});
|
|
2154
|
-
const ownTools = !(early && early.type === 'api');
|
|
2155
|
-
r.adapter.injectSystemNote(body, placeholderToolNote({ toolData: cfg.tools?.toolData, ownTools }));
|
|
2156
|
-
} else if (!redactionOff && count > 0 && typeof r.adapter.injectSystemNote === 'function') {
|
|
2157
|
-
// No tools, but something WAS replaced: the model still meets [[LOCATION_1]] and, told
|
|
2158
|
-
// nothing, a coding agent stops to ask what the "unresolved placeholder" means.
|
|
2159
|
-
r.adapter.injectSystemNote(body, placeholderNote());
|
|
2160
|
-
}
|
|
2161
|
-
outBody = Buffer.from(JSON.stringify(body), 'utf8');
|
|
2162
|
-
}
|
|
2163
|
-
}
|
|
2164
|
-
|
|
2165
|
-
// THE shared tool harness — same one the extension uses. The gateway only needs
|
|
2166
|
-
// ② (tool args): restore to real for the client to run, or keep the redacted
|
|
2167
|
-
// token for remote MCP tools when tools.toolData is "redactRemote". Results are
|
|
2168
|
-
// re-redacted by the NEXT request's normal redaction, so ③ isn't needed here.
|
|
2169
|
-
const harness = makeToolHarness({ vault, toolData: cfg.tools?.toolData });
|
|
2170
|
-
|
|
2171
|
-
// Route by the requested model → a destination (agent via the bridge, or an
|
|
2172
|
-
// API we forward to). Falls back to the legacy backend when none configured.
|
|
2173
|
-
// ChatPanel's own routing envelope, never the provider's business. A caller that knows
|
|
2174
|
-
// WHICH destination it means says so here instead of hoping a model id is unique — 39 ids
|
|
2175
|
-
// on a three-provider machine already collide once you ignore case, and two providers
|
|
2176
|
-
// offering the same id exactly is ordinary. Without this, `dests.find(...)` picks whichever
|
|
2177
|
-
// destination happens to come first and the call goes out on the wrong provider's key.
|
|
2178
|
-
// ChatPanel's routing metadata travels in HEADERS, not in the request body.
|
|
2179
|
-
//
|
|
2180
|
-
// It started as a `chatpanel` field on the JSON body, and NVIDIA answered "unsupported
|
|
2181
|
-
// parameters" — OpenAI-compatible providers validate the body strictly and reject fields
|
|
2182
|
-
// they do not know, while ignoring headers they do not know. A body field also breaks
|
|
2183
|
-
// against any gateway older than the one that strips it, which is every gateway already
|
|
2184
|
-
// installed. The body belongs to the provider; this hop gets its own channel.
|
|
2185
|
-
//
|
|
2186
|
-
// The legacy body field is still honoured (and removed) so a client that has not updated
|
|
2187
|
-
// yet keeps working instead of 400ing at the provider.
|
|
2188
|
-
const legacy = (body && typeof body.chatpanel === 'object' && body.chatpanel) || null;
|
|
2189
|
-
if (legacy) {
|
|
2190
|
-
delete body.chatpanel;
|
|
2191
|
-
outBody = Buffer.from(JSON.stringify(body), 'utf8');
|
|
2192
|
-
}
|
|
2193
|
-
const hint = {
|
|
2194
|
-
destination: String(req.headers['x-chatpanel-destination'] || legacy?.destination || '').trim(),
|
|
2195
|
-
reach: String(req.headers['x-chatpanel-reach'] || legacy?.reach || '').trim(),
|
|
2196
|
-
// A TEAM ROLE'S RUN, for the bridge (pillars §14.2): `{ grants, workspace, connectionId }`
|
|
2197
|
-
// — URI-encoded JSON in a header (the body belongs to the provider), the legacy body
|
|
2198
|
-
// field also honoured. Only the bridge path reads it; an API destination never sees it.
|
|
2199
|
-
run: readRunHint(req.headers['x-chatpanel-run'], legacy?.run),
|
|
2200
|
-
};
|
|
2201
|
-
const dest = resolveDestination(body?.model, cfg, r.kind, { destination: hint.destination });
|
|
2202
|
-
// An EXPLICIT destination that does not resolve is an error, not an invitation to fall
|
|
2203
|
-
// back. Falling back would send a credential-bearing call to a provider the user did not
|
|
2204
|
-
// choose — the silent-misroute version of the bug this field exists to prevent.
|
|
2205
|
-
if (hint.destination && (!dest || dest.id !== hint.destination)) {
|
|
2206
|
-
trace?.commit();
|
|
2207
|
-
return sendJson(res, 404, {
|
|
2208
|
-
error: {
|
|
2209
|
-
message: `no destination "${hint.destination}" is configured on this gateway`,
|
|
2210
|
-
type: 'unknown_destination',
|
|
2211
|
-
known: listDestinations(cfg).map((d) => d.id),
|
|
2212
|
-
},
|
|
2213
|
-
});
|
|
2214
|
-
}
|
|
2215
|
-
if (trace) {
|
|
2216
|
-
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') };
|
|
2217
|
-
}
|
|
2218
|
-
if (dest && dest.type === 'api') {
|
|
2219
|
-
if (!dest.baseUrl) { trace?.commit(); return sendJson(res, 502, { error: `destination "${dest.id}" has no baseUrl` }); }
|
|
2220
|
-
if (isSelfUrl(dest.baseUrl, cfg)) {
|
|
2221
|
-
trace?.commit();
|
|
2222
|
-
return sendJson(res, 508, { error: { message: `destination "${dest.id}" points back at the gateway (${dest.baseUrl}) — refusing to forward (would loop).`, type: 'loop_detected' } });
|
|
2223
|
-
}
|
|
2224
|
-
return handleApi(req, res, { ...r, pathname, search: url.search, base: dest.baseUrl, destKey: dest.apiKey, destProtocol: dest.protocol, harness, trace }, outBody, vault);
|
|
2225
|
-
}
|
|
2226
|
-
return handleBridge(req, res, { ...r, pathname, agentOverride: dest?.agent, harness, trace, run: hint.run }, body, vault, cfg, isPro);
|
|
2227
|
-
});
|
|
2228
|
-
}
|
|
2229
|
-
|
|
2230
|
-
/** `{ grants[], workspace{ repo, projectId, jobId, base? }, connectionId }` from the header or the legacy field — shaped, never a token. */
|
|
2231
|
-
function readRunHint(header, legacy) {
|
|
2232
|
-
let raw = legacy && typeof legacy === 'object' ? legacy : null;
|
|
2233
|
-
if (!raw && header) { try { raw = JSON.parse(decodeURIComponent(String(header))); } catch { raw = null; } }
|
|
2234
|
-
if (!raw || typeof raw !== 'object') return null;
|
|
2235
|
-
const out = {};
|
|
2236
|
-
if (Array.isArray(raw.grants)) out.grants = raw.grants.map((g) => String(g).slice(0, 80)).slice(0, 32);
|
|
2237
|
-
if (raw.workspace && typeof raw.workspace === 'object' && raw.workspace.repo) {
|
|
2238
|
-
const w = raw.workspace;
|
|
2239
|
-
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) } : {}) };
|
|
2240
|
-
}
|
|
2241
|
-
if (raw.connectionId) out.connectionId = String(raw.connectionId).slice(0, 64);
|
|
2242
|
-
return Object.keys(out).length ? out : null;
|
|
2243
|
-
}
|
|
2244
|
-
|
|
2245
|
-
let bridgeSupervisor = null; // the running gateway's bridge controller (bridge-supervisor.js), for /health and shutdown
|
|
2246
|
-
|
|
2247
|
-
export function start(cfg = loadConfig()) {
|
|
2248
|
-
installTimestampedConsole(); // every gateway log line gets a clock — before anything logs
|
|
2249
|
-
ensureGatewayToken(); // M2: load/create the admin-route token (best-effort)
|
|
2250
|
-
const server = createGateway(cfg);
|
|
2251
|
-
const ner = startNer(cfg); // may mutate cfg.redaction when it comes up
|
|
2252
|
-
// Re-validate the stored entitlement online on an interval; clears it and drops
|
|
2253
|
-
// the gateway to Free when the worker reports it invalid (see
|
|
2254
|
-
// entitlement-refresh.js).
|
|
2255
|
-
const entitlement = startEntitlementRefresh(cfg);
|
|
2256
|
-
// Fail LOUD on a port clash instead of crashing with a raw stack trace. We bind a
|
|
2257
|
-
// FIXED port (4320) so the extension / install.sh / OpenCode can always find us; if
|
|
2258
|
-
// something else already holds it, tell the user exactly how to recover (pick a new
|
|
2259
|
-
// port, restart, and point the extension's Gateway tab at it) rather than silently
|
|
2260
|
-
// dying or drifting to a random port.
|
|
2261
|
-
server.on('error', (e) => {
|
|
2262
|
-
if (e && e.code === 'EADDRINUSE') {
|
|
2263
|
-
console.error(`Port ${cfg.port} is already in use — another app (or a second gateway) has it.`);
|
|
2264
|
-
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.`);
|
|
2265
|
-
process.exit(1);
|
|
2266
|
-
}
|
|
2267
|
-
console.error(`Gateway server error: ${e?.message || e}`);
|
|
2268
|
-
process.exit(1);
|
|
2269
|
-
});
|
|
2270
|
-
server.listen(cfg.port, cfg.host, () => {
|
|
2271
|
-
console.log(`ChatPanel Privacy Gateway v${VERSION} on http://${cfg.host}:${cfg.port}`);
|
|
2272
|
-
console.log(` backend : ${cfg.backend}` + (cfg.backend === 'bridge' ? ` (agent: ${cfg.bridge.agent}, via ${cfg.bridge.url})` : ''));
|
|
2273
|
-
// THE GATEWAY CARRIES THE BRIDGE (bridge-supervisor.js): adopt one that already answers
|
|
2274
|
-
// (the desktop's, a standalone, launchd's), else start the embedded copy as a child and
|
|
2275
|
-
// keep it up. One install for the user; two processes on purpose. Best-effort and
|
|
2276
|
-
// non-fatal: the gateway runs without a bridge, it just has no local agents.
|
|
2277
|
-
ensureBridge(cfg).then((c) => { bridgeSupervisor = c; }).catch((e) => console.log(` bridge : not supervised (${e?.message || e})`));
|
|
2278
|
-
console.log(` redaction: ${cfg.redaction.tier}` + (cfg.redaction.detection?.backend && cfg.redaction.detection.backend !== 'off'
|
|
2279
|
-
? ` + ${cfg.redaction.detection.backend} detector` : (cfg.ner?.autostart ? ' (+ NER starting…)' : '')));
|
|
2280
|
-
// M7: a non-loopback bind exposes the gateway on the LAN, where the per-request
|
|
2281
|
-
// loopback Host check is trivially satisfied by a spoofed `Host: 127.0.0.1`. The
|
|
2282
|
-
// /v1 data plane forwards with the client's own key, but make the exposure LOUD.
|
|
2283
|
-
if (!isLoopbackHost(cfg.host)) {
|
|
2284
|
-
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.`);
|
|
2285
|
-
}
|
|
2286
|
-
});
|
|
2287
|
-
// If the user handed off a backup key, refresh the warm store from the encrypted
|
|
2288
|
-
// rotating archive in the background — so the gateway stays current even when the
|
|
2289
|
-
// extension never runs. Best-effort; never blocks startup or crashes it.
|
|
2290
|
-
if (hasBackupSecret()) {
|
|
2291
|
-
ingestBackups(historyStore, loadBackupSecret())
|
|
2292
|
-
.then((r) => { if (r?.ok) console.log(` warm : seeded ${r.ingested} records from ${r.file}`); })
|
|
2293
|
-
.catch(() => {});
|
|
2294
|
-
}
|
|
2295
|
-
const shutdown = () => { ner?.stop(); entitlement.stop(); bridgeSupervisor?.stop(); server.close(() => process.exit(0)); };
|
|
2296
|
-
process.on('SIGINT', shutdown);
|
|
2297
|
-
process.on('SIGTERM', shutdown);
|
|
2298
|
-
return server;
|
|
2299
|
-
}
|
|
19
|
+
`),m=a.redact?await X(t.pro?.entitlementToken):!0,f=async b=>{if(b.type!=="final"||!a.redact)return b;try{let T=b.text;return await de([Ee(()=>T,z=>{T=z})],t.redaction,{isPro:m}),{...b,text:T}}catch{return b}};l({type:"state",state:E.state()});const y=setInterval(()=>{const b=E.state();if(b==="downloading"||b==="loading"){l({type:"progress",state:b,...E.progress()||{}});return}if(b==="error"){l({type:"error",code:"model_failed",message:E.health().error||"model failed to load",fatal:!0}),clearInterval(y);return}if(a.diarize){const T=P.state();if(T==="downloading"||T==="loading"){l({type:"diarize-progress",state:T,...P.progress()||{}});return}}l({type:"state",state:b}),clearInterval(y)},500);y.unref?.();let h=Promise.resolve();const g=E.subscribe(n,b=>{h=h.then(async()=>{l(await f(b)),b.type==="end"&&(clearInterval(y),o.end())}).catch(()=>{})});r.on("close",()=>{clearInterval(y),g?.()});return}if(!e[2]&&r.method==="DELETE")return await E.endSession(n),s(o,200,{ok:!0})}}if(c==="/logs"&&r.method==="GET")return s(o,200,{entries:[...i].reverse()});if(c==="/config"&&r.method==="GET"){const e=await X(t.pro?.entitlementToken);return s(o,200,ze(t,{proUnlocked:e}))}if(c==="/config"&&r.method==="POST"){let e=null;try{e=JSON.parse((await v(r,t.maxBodyBytes)).toString("utf8"))}catch{e=null}if(!e||typeof e!="object")return s(o,400,{error:"invalid config patch"});po(t,e);try{q(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",l=N.state();t.ner?.autostart&&a&&l!=="ready"&&l!=="loading"&&l!=="downloading"&&N.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 X(t.pro?.entitlementToken);return s(o,200,ze(t,{proUnlocked:m}))}if(r.method==="GET"&&c==="/skills"){const e=await re(t);if(!e)return s(o,503,{error:{message:"no bridge is configured",type:"no_bridge"}});const n=ne(t.bridge?.token);try{const a=await fetch(`${e}/skills`,{headers:{Accept:"application/json",...n?{Authorization:`Bearer ${n}`}:{}},signal:AbortSignal.timeout(8e3)}),l=await a.json().catch(()=>({}));return a.ok?s(o,200,{skills:Array.isArray(l?.skills)?l.skills:[]}):s(o,a.status,{error:{message:l?.error||`bridge ${a.status}`,type:"bridge_error"}})}catch(a){return s(o,502,{error:{message:`bridge unreachable: ${a.message}`,type:"bridge_unreachable"}})}}if(r.method==="GET"&&/^\/skills\/[^/]+$/.test(c)){const e=decodeURIComponent(c.slice(8));if(!e||e==="."||e===".."||e.includes("/")||e.includes("\\"))return s(o,400,{error:{message:"not a skill id",type:"invalid_request"}});const n=await re(t);if(!n)return s(o,503,{error:{message:"no bridge is configured",type:"no_bridge"}});const a=ne(t.bridge?.token);try{const l=await fetch(`${n}/skills/${encodeURIComponent(e)}`,{headers:{Accept:"application/json",...a?{Authorization:`Bearer ${a}`}:{}},signal:AbortSignal.timeout(8e3)}),m=await l.json().catch(()=>({}));return l.ok?s(o,200,{skill:m?.skill||null}):s(o,l.status,{error:{message:m?.error||`bridge ${l.status}`,type:"bridge_error"}})}catch(l){return s(o,502,{error:{message:`bridge unreachable: ${l.message}`,type:"bridge_unreachable"}})}}if(r.method==="GET"&&/\/models$/.test(c))return s(o,200,await ho(t));if(Lo.some(e=>c===e||c.startsWith(`${e}/`)))return s(o,404,{error:{message:`this gateway (${K}) has no ${c} — update it to use this feature`,type:"unknown_endpoint"}});const S=Po(c,r.headers,t);let w;try{w=await v(r,t.maxBodyBytes)}catch(e){s(o,e.code===413?413:400,{error:e.code===413?"payload too large":"bad request"}),r.destroy();return}let O=null,p=null,M=w,A=0,D=0,F=0,R=!1,I=!0;const B=t.logRequests&&S.redactable&&r.method==="POST"?Ao(d):null;if(S.redactable&&r.method==="POST"&&w.length){try{p=JSON.parse(w.toString("utf8"))}catch{p=null}if(p&&$o(p,S.kind))M=w;else if(p){const e=t.tools||{};if(e.autoNarrow!==!1&&Array.isArray(p.tools)&&p.tools.length){const g=Number(e.maxPerTurn)>0?Number(e.maxPerTurn):ko,b=e.narrowAll?null:z=>!So.test(Ke(z)),T=p.tools.length;p.tools=yt(p.tools,To(p,S.kind),{cap:g,keep:b,name:Ke,description:vo}),F=T-p.tools.length}I=await X(t.pro?.entitlementToken);const n=co(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"&&W(r),R||await pe(t);const a=R?[]:S.adapter.collectSegments(p,t.redaction),l=new AbortController;o.on("close",()=>{o.writableFinished||l.abort()});const m=B?B.clock():0,{vault:f,count:y,sanitized:h}=R?{vault:null,count:0,sanitized:0}:await de(a,t.redaction,{signal:l.signal,isPro:I,onEgress:g=>Se.push(He({ts:Date.now(),client:"redaction",tool:`detect:${g.backend}@${g.host||"local"}`,ok:g.ok,ms:g.ms,error:g.error}))});if(B&&B.lap("redact",m),O=f,A=y,D=h||0,!I&&y>0){uo(t,I);try{q(t,Q())}catch{}}if(!R&&Array.isArray(p.tools)&&p.tools.length&&typeof S.adapter.injectSystemNote=="function"){const g=Je(p?.model,t,S.kind,{destination:String(r.headers["x-chatpanel-destination"]||p?.chatpanel?.destination||"").trim()}),b=!(g&&g.type==="api");S.adapter.injectSystemNote(p,ft({toolData:t.tools?.toolData,ownTools:b}))}else!R&&y>0&&typeof S.adapter.injectSystemNote=="function"&&S.adapter.injectSystemNote(p,gt());M=Buffer.from(JSON.stringify(p),"utf8")}}const _=ht({vault:O,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:Vo(r.headers["x-chatpanel-run"],j?.run)},x=Je(p?.model,t,S.kind,{destination:H.destination});return H.destination&&(!x||x.id!==H.destination)?(B?.commit(),s(o,404,{error:{message:`no destination "${H.destination}" is configured on this gateway`,type:"unknown_destination",known:fo(t).map(e=>e.id)}})):(B&&(B.meta={t:Date.now(),model:p?.model||null,dest:x?x.id:null,type:x?x.type:null,redacted:A,sanitized:D,narrowed:F,detail:qe(O,t.logDetail),redaction:R?"off":t.redaction.tier||"basic"}),x&&x.type==="api"?x.baseUrl?No(x.baseUrl,t)?(B?.commit(),s(o,508,{error:{message:`destination "${x.id}" points back at the gateway (${x.baseUrl}) — refusing to forward (would loop).`,type:"loop_detected"}})):Go(r,o,{...S,pathname:c,search:u.search,base:x.baseUrl,destKey:x.apiKey,destProtocol:x.protocol,harness:_,trace:B},M,O):(B?.commit(),s(o,502,{error:`destination "${x.id}" has no baseUrl`})):jo(r,o,{...S,pathname:c,agentOverride:x?.agent,harness:_,trace:B,run:H.run},p,O,t,I))})}function Vo(t,i){let d=i&&typeof i=="object"?i:null;if(!d&&t)try{d=JSON.parse(decodeURIComponent(String(t)))}catch{d=null}if(!d||typeof d!="object")return null;const r={};if(Array.isArray(d.grants)&&(r.grants=d.grants.map(o=>String(o).slice(0,80)).slice(0,32)),d.workspace&&typeof d.workspace=="object"&&d.workspace.repo){const o=d.workspace;r.workspace={repo:String(o.repo).slice(0,400),projectId:String(o.projectId||"").slice(0,120),jobId:String(o.jobId||"").slice(0,120),...o.base?{base:String(o.base).slice(0,120)}:{}}}return d.connectionId&&(r.connectionId=String(d.connectionId).slice(0,64)),Object.keys(r).length?r:null}let ce=null;function Pr(t=Oe()){xt(),wt(),Ae();const i=zo(t),d=Et(t),r=it(t);i.on("error",u=>{u&&u.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: ${u?.message||u}`),process.exit(1)}),i.listen(t.port,t.host,()=>{console.log(`ChatPanel Privacy Gateway v${K} on http://${t.host}:${t.port}`),console.log(` backend : ${t.backend}`+(t.backend==="bridge"?` (agent: ${t.bridge.agent}, via ${t.bridge.url})`:"")),Rt(t).then(u=>{ce=u}).catch(u=>console.log(` bridge : not supervised (${u?.message||u})`)),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…)":"")),Xe(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.`)}),De()&&he($,Ce()).then(u=>{u?.ok&&console.log(` warm : seeded ${u.ingested} records from ${u.file}`)}).catch(()=>{});const o=()=>{d?.stop(),r.stop(),ce?.stop(),i.close(()=>process.exit(0))};return process.on("SIGINT",o),process.on("SIGTERM",o),i}export{K as VERSION,zo as createGateway,Io as joinUpstream,ve as parseAgentModel,Pr as start};
|