@chatpanel/gateway 0.61.0 → 0.64.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@chatpanel/gateway",
3
- "version": "0.61.0",
3
+ "version": "0.64.0",
4
4
  "description": "Local privacy gateway — redacts PII out of OpenAI/Anthropic API traffic before it reaches a model, then restores it in the reply. Point opencode, codex, aider, Claude Code, etc. at it.",
5
5
  "type": "module",
6
6
  "bin": {
@@ -23,7 +23,7 @@
23
23
  "dependencies": {
24
24
  "@anthropic-ai/sandbox-runtime": "^0.0.77",
25
25
  "@chatpanel/bridge": "^0.32.2",
26
- "@chatpanel/events": "^0.278.0",
26
+ "@chatpanel/events": "^0.295.0",
27
27
  "@chatpanel/pii": "^0.12.0",
28
28
  "@huggingface/transformers": "^4.2.0",
29
29
  "defuddle": "^0.19.4",
package/src/egress.js CHANGED
@@ -1,2 +1,2 @@
1
- import{isBlockedHost as f}from"@chatpanel/pii";const b=()=>new Date().toISOString();function g(e){try{const t=typeof e=="string"?new URL(e):e instanceof URL?e:new URL(e?.url);return{host:t.hostname,port:t.port||(t.protocol==="https:"?"443":t.protocol==="http:"?"80":""),scheme:t.protocol.replace(":","")}}catch{return null}}const u=e=>{const t=String(e||"").toLowerCase();return t==="localhost"||t.endsWith(".localhost")||t==="::1"||t==="[::1]"?!0:f(t,{allowLoopback:!1,allowPrivate:!1})&&!f(t,{allowLoopback:!0,allowPrivate:!0})};function v({clock:e=b}={}){const t=new Map;return{record(r){const a=g(r);if(!a||!a.host)return;const h=`${a.scheme}://${a.host}:${a.port}`,l=e(),s=t.get(h);if(s){s.count+=1,s.lastAt=l;return}t.set(h,{host:a.host,port:a.port,scheme:a.scheme,local:u(a.host),count:1,firstAt:l,lastAt:l})},snapshot(){return[...t.values()].sort((r,a)=>r.local===a.local?a.count-r.count:r.local?1:-1)},reset(){t.clear()}}}let w=null;function E(e=globalThis,{allow:t=null}={}){if(e.__chatpanelEgress)return t&&e.__chatpanelEgress.setGate(t),e.__chatpanelEgress;const r=v();let a=t;r.setGate=l=>{a=l},r.blocked=[];const h=e.fetch;return typeof h=="function"&&(e.fetch=function(s,p){let o=null;try{o=g(s),r.record(s)}catch{}if(a&&o?.host){let i=!0;try{i=a(`${o.scheme}://${o.host}:${o.port}`,{local:u(o.host)})}catch{i=!0}if(!i){const n=`${o.host}:${o.port}`;r.blocked.includes(n)||r.blocked.push(n);const c=new Error(`egress to ${o.host} is blocked by your organisation’s policy`);return c.code="EGRESS_POLICY",Promise.reject(c)}}return h.call(this,s,p)}),e.__chatpanelEgress=r,e===globalThis&&(w=r),r}function k(){return w||(globalThis.__chatpanelEgress??null)}function d(e){try{return new URL(e).host}catch{return String(e||"")}}function $(e={},t=process.env){const r=[],a=(o,i,{when:n="always",off:c=null,local:m=!1,data:y=""}={})=>{o&&r.push({host:o,purpose:i,when:n,off:c,local:m,data:y})};if(a("api.chatpanel.net","Pro entitlement: issues and refreshes the signed licence token",{when:"when a Pro token is present (pro.entitlementToken)",off:"free tier — no token, no call",data:"the install id and the current token; never chat content"}),a("dl.chatpanel.net","model weights (NER, dictation, read-aloud) and the installer",{when:"first use of a local model, or an update",off:"ner.enabled / stt.enabled / tts.enabled = false",data:"the model id being downloaded"}),a("huggingface.co","model weights when dl.chatpanel.net does not carry the model",{when:"a custom model id, or a mirror miss",off:"the same switches as dl.chatpanel.net",data:"the model id being downloaded"}),t.CHATPANEL_ORT_DIR||a("registry.npmjs.org","the native ONNX runtime the standalone binary loads, fetched once",{when:"first start of a binary install that has no native runtime yet; never on npm/Node",off:"CHATPANEL_ORT_DIR=<dir> — point it at a copy you placed yourself, and nothing is fetched",data:"nothing — a versioned package tarball"}),e.link?.enabled!==!1){let o="link.chatpanel.net";try{e.link?.relayUrl&&(o=new URL(e.link.relayUrl).host)}catch{}a(o,"ChatPanel Link: the relay a paired phone reaches this gateway through",{when:"only after a phone is paired (Settings › Link your phone), and while pairing",off:"link.enabled = false, or remove every paired phone",data:"a room id, an admission token, and end-to-end encrypted frames the relay cannot read"})}a("the page you ask to read","web retrieval: POST /v1/read fetches ONE public page as Markdown, on request",{when:"a client calls /v1/read (the extension’s reader slot, the desktop, the CLI)",off:"nothing to switch off — no read happens unless a client asks for that page",data:"a GET of that page with a browser User-Agent; never a cookie, never a token, never chat content"});const h=e.search?.searxng?.url||"";if(h){let o=h;try{o=new URL(h).host}catch{}a(o,"web search: your SearXNG (POST /v1/search) — the query, after layer-1 redaction",{when:"a client searches and search.provider is auto (SearXNG up) or searxng",off:'search.searxng.url = ""',data:"the search query with emails, cards, keys and dictionary terms removed; never chat content",local:/^(localhost|127\.|\[::1\]|10\.|192\.168\.)/.test(o)})}if(e.search?.provider!=="searxng"&&(a("www.startpage.com","web search: the built-in results-page search, first engine",{when:"a client searches and no SearXNG answers (search.provider auto) or search.provider is serp",off:'search.provider = "searxng" with a SearXNG configured',data:"the search query with emails, cards, keys and dictionary terms removed"}),a("html.duckduckgo.com","web search: the built-in results-page search, fallback engine",{when:"Startpage returned nothing",off:"the same switch as www.startpage.com",data:"the same query"})),e.read?.remote?.url){let o=e.read.remote.url;try{o=new URL(e.read.remote.url).host}catch{}a(o,"web retrieval: the remote reader (r.jina.ai-shaped) for pages a fetch cannot render",{when:'a read names provider "remote", or read.provider is "remote"',off:'read.remote.url = ""',data:"the URL of the page being read; the key you configured",local:/^(localhost|127\.|\[::1\])/.test(o)})}const l={rerank:{what:"ranking: POST /v1/rerank — the query and the candidate texts",data:"the query and the documents to order; layer-1 redaction is the client’s duty before they reach here; never chat history"},decide:{what:"decisions: POST /v1/decide — the text judged and the typed questions",data:"the state text and the questions; never chat history"},stt:{what:"transcription: every committed segment of audio, as a WAV, to POST /audio/transcriptions",data:"the audio itself — what was said, by whom; the text that comes back is what the redaction hop sees"},embed:{what:"embeddings: POST /v1/embeddings — the text being indexed or searched",data:"the text embedded — notes, chats, meetings when semantic search indexes them; the query when it searches"}};for(const[o,i]of Object.entries(l)){const n=e.capabilities?.[o];if(!n?.url||n.provider==="embedded")continue;let c=n.url;try{c=new URL(n.url).host}catch{}a(c,`${i.what}${n.service?` (the ${n.service} container, started under Settings › Runtime)`:` (${n.adapter} at the address you configured)`}`,{when:`a client calls /v1/${o}`,off:n.service?`stop the ${n.service} service under Settings › Runtime`:`capabilities.${o} = null`,data:`${i.data}${n.token?"; the token you configured":""}`,local:/^(localhost|127\.|\[::1\]|10\.|192\.168\.)/.test(c)})}t.CHATPANEL_SELF_UPDATE!=="off"&&(a("registry.npmjs.org","update check: is a newer gateway published?",{when:"on /status, throttled; npm installs only",off:"CHATPANEL_SELF_UPDATE=off",data:"nothing — a read of the package manifest"}),a("api.github.com","update check for the standalone binary",{when:"on /status, throttled; binary installs only",off:"CHATPANEL_SELF_UPDATE=off",data:"nothing — a read of the latest release"}));for(const[o,i]of Object.entries(e.upstreams||{}))i?.baseUrl&&a(d(i.baseUrl),`model upstream "${o}" — chat requests (after redaction) go here`,{when:`a request addressed to ${o}`,off:`upstreams.${o}.baseUrl`,local:u(d(i.baseUrl).split(":")[0]),data:"the conversation, with PII replaced by placeholders when redaction is on"});for(const o of e.destinations||[])o?.baseUrl&&a(d(o.baseUrl),`destination "${o.id||o.type}" — chat requests (after redaction) go here`,{when:`a request addressed to ${o.id||"it"}`,off:"destinations[]",local:u(d(o.baseUrl).split(":")[0]),data:"the conversation, with PII replaced by placeholders when redaction is on"});a("(the endpoint the client passes through)","a client can address any endpoint per request (BYO); the gateway proxies to it after redaction",{when:"the extension or desktop sends a request with its own endpoint",off:"the client’s own endpoint settings",data:"the conversation, with PII replaced by placeholders when redaction is on"}),e.ner?.url&&a(d(e.ner.url),"external NER detector (redaction) — a sidecar you configured",{when:"every redacted request",off:"ner.url",local:u(d(e.ner.url).split(":")[0]),data:"the text being redacted"});const s=e.tts||{};if(s.provider==="openai"||s.provider==="elevenlabs"){const o=s.remote?.baseUrl?d(s.remote.baseUrl):s.provider==="elevenlabs"?"api.elevenlabs.io":"api.openai.com";a(o,`remote read-aloud voice (${s.provider})`,{when:"a read-aloud request",off:"tts.provider = local",data:s.remote?.redact===!1?"the text being spoken, unredacted (tts.remote.redact = false)":"the text being spoken, with PII replaced by placeholders"})}const p=e.bridge?.url||"http://127.0.0.1:4319";return a(d(p),"the local bridge — your CLI agents (Claude Code, Codex, …)",{when:"a request addressed to an agent",off:"bridge.url",local:!0,data:"the conversation; the agent then reaches its own vendor with your own login"}),r}function x(e,{ledger:t=k(),version:r="",startedAt:a=null,env:h=process.env,managed:l=null}={}){return{ok:!0,version:r,since:a?new Date(a).toISOString():null,...l?{managed:l,blocked:t?.blocked||[]}:{},scope:"this gateway process’s own outbound requests. Not covered: the embedded bridge (a separate process), the CLI agents it runs (they reach their vendors with your logins), and a client’s direct calls that bypass the gateway.",observed:t?t.snapshot():[],declared:$(e,h)}}function S(e){const t=[];t.push(`ChatPanel Gateway ${e.version||""} — egress audit`.trim()),e.since&&t.push(`observed since ${e.since}`),t.push(""),t.push("OBSERVED — hosts this process has actually contacted"),e.observed?.length||t.push(" (none yet)");for(const r of e.observed||[])t.push(` ${r.local?"[local] ":""}${r.scheme}://${r.host}:${r.port} ×${r.count} last ${r.lastAt}`);t.push(""),t.push("DECLARED — hosts this configuration allows, and why");for(const r of e.declared||[])t.push(` ${r.local?"[local] ":""}${r.host}`),t.push(` ${r.purpose}`),t.push(` when: ${r.when}${r.off?` · off: ${r.off}`:""}`),r.data&&t.push(` sends: ${r.data}`);return e.managed&&(t.push(""),t.push(`POLICY — ${e.managed.name||e.managed.org||"managed"} (${e.managed.signed?"signed":"unsigned file"}, hash ${String(e.managed.policyHash||"").slice(0,12)}…)`),t.push(` enforcing: ${Object.entries(e.managed.enforces||{}).filter(([,r])=>r).map(([r,a])=>a===!0?r:`${r}=${a}`).join(", ")||"nothing yet"}`),t.push(` refused this session: ${e.blocked?.length?e.blocked.join(", "):"none"}`)),t.push(""),t.push(`Scope: ${e.scope}`),t.push("Verify it yourself: any hostname not listed above that appears in your firewall or proxy log for this process is a bug — report it (security@chatpanel.net)."),t.join(`
2
- `)}export{v as createEgressLedger,$ as declaredEgress,x as egressAudit,k as egressLedger,S as formatAudit,E as installEgressLedger};
1
+ import{isBlockedHost as f}from"@chatpanel/pii";const b=()=>new Date().toISOString();function w(e){try{const t=typeof e=="string"?new URL(e):e instanceof URL?e:new URL(e?.url),r=t.protocol.replace(":","");return{host:t.hostname,port:t.port||{https:"443",wss:"443",http:"80",ws:"80"}[r]||"",scheme:r}}catch{return null}}const p=e=>{const t=String(e||"").toLowerCase();return t==="localhost"||t.endsWith(".localhost")||t==="::1"||t==="[::1]"?!0:f(t,{allowLoopback:!1,allowPrivate:!1})&&!f(t,{allowLoopback:!0,allowPrivate:!0})};function v({clock:e=b}={}){const t=new Map;return{record(r){const o=w(r);if(!o||!o.host)return;const h=`${o.scheme}://${o.host}:${o.port}`,l=e(),i=t.get(h);if(i){i.count+=1,i.lastAt=l;return}t.set(h,{host:o.host,port:o.port,scheme:o.scheme,local:p(o.host),count:1,firstAt:l,lastAt:l})},snapshot(){return[...t.values()].sort((r,o)=>r.local===o.local?o.count-r.count:r.local?1:-1)},reset(){t.clear()}}}let g=null;function E(e=globalThis,{allow:t=null}={}){if(e.__chatpanelEgress)return t&&e.__chatpanelEgress.setGate(t),e.__chatpanelEgress;const r=v();let o=t;r.setGate=c=>{o=c},r.blocked=[];const h=c=>{let a=null;try{a=w(c),r.record(c)}catch{}if(!o||!a?.host)return null;let s=!0;try{s=o(`${a.scheme}://${a.host}:${a.port}`,{local:p(a.host)})}catch{s=!0}if(s)return null;const n=`${a.host}:${a.port}`;r.blocked.includes(n)||r.blocked.push(n);const d=new Error(`egress to ${a.host} is blocked by your organisation’s policy`);return d.code="EGRESS_POLICY",d},l=e.fetch;typeof l=="function"&&(e.fetch=function(a,s){const n=h(a);return n?Promise.reject(n):l.call(this,a,s)});const i=e.WebSocket;return typeof i=="function"&&(e.WebSocket=new Proxy(i,{construct(c,a,s){const n=h(a[0]);if(n)throw n;return Reflect.construct(c,a,s)}})),e.__chatpanelEgress=r,e===globalThis&&(g=r),r}function k(){return g||(globalThis.__chatpanelEgress??null)}function u(e){try{return new URL(e).host}catch{return String(e||"")}}function $(e={},t=process.env){const r=[],o=(a,s,{when:n="always",off:d=null,local:y=!1,data:m=""}={})=>{a&&r.push({host:a,purpose:s,when:n,off:d,local:y,data:m})};if(o("api.chatpanel.net","Pro entitlement: issues and refreshes the signed licence token",{when:"when a Pro token is present (pro.entitlementToken)",off:"free tier — no token, no call",data:"the install id and the current token; never chat content"}),o("dl.chatpanel.net","model weights (NER, dictation, read-aloud) and the installer",{when:"first use of a local model, or an update",off:"ner.enabled / stt.enabled / tts.enabled = false",data:"the model id being downloaded"}),o("huggingface.co","model weights when dl.chatpanel.net does not carry the model",{when:"a custom model id, or a mirror miss",off:"the same switches as dl.chatpanel.net",data:"the model id being downloaded"}),t.CHATPANEL_ORT_DIR||o("registry.npmjs.org","the native ONNX runtime the standalone binary loads, fetched once",{when:"first start of a binary install that has no native runtime yet; never on npm/Node",off:"CHATPANEL_ORT_DIR=<dir> — point it at a copy you placed yourself, and nothing is fetched",data:"nothing — a versioned package tarball"}),e.link?.enabled!==!1){let a="link.chatpanel.net";try{e.link?.relayUrl&&(a=new URL(e.link.relayUrl).host)}catch{}o(a,"ChatPanel Link: the relay a paired phone reaches this gateway through",{when:"only after a phone is paired (Settings › Link your phone), and while pairing",off:"link.enabled = false, or remove every paired phone",data:"a room id, an admission token, and end-to-end encrypted frames the relay cannot read"})}o("the page you ask to read","web retrieval: POST /v1/read fetches ONE public page as Markdown, on request",{when:"a client calls /v1/read (the extension’s reader slot, the desktop, the CLI)",off:"nothing to switch off — no read happens unless a client asks for that page",data:"a GET of that page with a browser User-Agent; never a cookie, never a token, never chat content"});const h=e.search?.searxng?.url||"";if(h){let a=h;try{a=new URL(h).host}catch{}o(a,"web search: your SearXNG (POST /v1/search) — the query, after layer-1 redaction",{when:"a client searches and search.provider is auto (SearXNG up) or searxng",off:'search.searxng.url = ""',data:"the search query with emails, cards, keys and dictionary terms removed; never chat content",local:/^(localhost|127\.|\[::1\]|10\.|192\.168\.)/.test(a)})}if(e.search?.provider!=="searxng"&&(o("www.startpage.com","web search: the built-in results-page search, first engine",{when:"a client searches and no SearXNG answers (search.provider auto) or search.provider is serp",off:'search.provider = "searxng" with a SearXNG configured',data:"the search query with emails, cards, keys and dictionary terms removed"}),o("html.duckduckgo.com","web search: the built-in results-page search, fallback engine",{when:"Startpage returned nothing",off:"the same switch as www.startpage.com",data:"the same query"})),e.read?.remote?.url){let a=e.read.remote.url;try{a=new URL(e.read.remote.url).host}catch{}o(a,"web retrieval: the remote reader (r.jina.ai-shaped) for pages a fetch cannot render",{when:'a read names provider "remote", or read.provider is "remote"',off:'read.remote.url = ""',data:"the URL of the page being read; the key you configured",local:/^(localhost|127\.|\[::1\])/.test(a)})}const l={rerank:{what:"ranking: POST /v1/rerank — the query and the candidate texts",data:"the query and the documents to order; layer-1 redaction is the client’s duty before they reach here; never chat history"},decide:{what:"decisions: POST /v1/decide — the text judged and the typed questions",data:"the state text and the questions; never chat history"},stt:{what:"transcription: every committed segment of audio, as a WAV, to POST /audio/transcriptions",data:"the audio itself — what was said, by whom; the text that comes back is what the redaction hop sees"},embed:{what:"embeddings: POST /v1/embeddings — the text being indexed or searched",data:"the text embedded — notes, chats, meetings when semantic search indexes them; the query when it searches"}};for(const[a,s]of Object.entries(l)){const n=e.capabilities?.[a];if(!n?.url||n.provider==="embedded")continue;let d=n.url;try{d=new URL(n.url).host}catch{}o(d,`${s.what}${n.service?` (the ${n.service} container, started under Settings › Runtime)`:` (${n.adapter} at the address you configured)`}`,{when:`a client calls /v1/${a}`,off:n.service?`stop the ${n.service} service under Settings › Runtime`:`capabilities.${a} = null`,data:`${s.data}${n.token?"; the token you configured":""}`,local:/^(localhost|127\.|\[::1\]|10\.|192\.168\.)/.test(d)})}t.CHATPANEL_SELF_UPDATE!=="off"&&(o("registry.npmjs.org","update check: is a newer gateway published?",{when:"on /status, throttled; npm installs only",off:"CHATPANEL_SELF_UPDATE=off",data:"nothing — a read of the package manifest"}),o("api.github.com","update check for the standalone binary",{when:"on /status, throttled; binary installs only",off:"CHATPANEL_SELF_UPDATE=off",data:"nothing — a read of the latest release"}));for(const[a,s]of Object.entries(e.upstreams||{}))s?.baseUrl&&o(u(s.baseUrl),`model upstream "${a}" — chat requests (after redaction) go here`,{when:`a request addressed to ${a}`,off:`upstreams.${a}.baseUrl`,local:p(u(s.baseUrl).split(":")[0]),data:"the conversation, with PII replaced by placeholders when redaction is on"});for(const a of e.destinations||[])a?.baseUrl&&o(u(a.baseUrl),`destination "${a.id||a.type}" — chat requests (after redaction) go here`,{when:`a request addressed to ${a.id||"it"}`,off:"destinations[]",local:p(u(a.baseUrl).split(":")[0]),data:"the conversation, with PII replaced by placeholders when redaction is on"});o("(the endpoint the client passes through)","a client can address any endpoint per request (BYO); the gateway proxies to it after redaction",{when:"the extension or desktop sends a request with its own endpoint",off:"the client’s own endpoint settings",data:"the conversation, with PII replaced by placeholders when redaction is on"}),e.ner?.url&&o(u(e.ner.url),"external NER detector (redaction) — a sidecar you configured",{when:"every redacted request",off:"ner.url",local:p(u(e.ner.url).split(":")[0]),data:"the text being redacted"});const i=e.tts||{};if(i.provider==="openai"||i.provider==="elevenlabs"){const a=i.remote?.baseUrl?u(i.remote.baseUrl):i.provider==="elevenlabs"?"api.elevenlabs.io":"api.openai.com";o(a,`remote read-aloud voice (${i.provider})`,{when:"a read-aloud request",off:"tts.provider = local",data:i.remote?.redact===!1?"the text being spoken, unredacted (tts.remote.redact = false)":"the text being spoken, with PII replaced by placeholders"})}const c=e.bridge?.url||"http://127.0.0.1:4319";return o(u(c),"the local bridge — your CLI agents (Claude Code, Codex, …)",{when:"a request addressed to an agent",off:"bridge.url",local:!0,data:"the conversation; the agent then reaches its own vendor with your own login"}),r}function S(e,{ledger:t=k(),version:r="",startedAt:o=null,env:h=process.env,managed:l=null}={}){return{ok:!0,version:r,since:o?new Date(o).toISOString():null,...l?{managed:l,blocked:t?.blocked||[]}:{},scope:"this gateway process’s own outbound requests and sockets. Not covered: the embedded bridge (a separate process), the CLI agents it runs (they reach their vendors with your logins), and a client’s direct calls that bypass the gateway.",observed:t?t.snapshot():[],declared:$(e,h)}}function x(e){const t=[];t.push(`ChatPanel Gateway ${e.version||""} — egress audit`.trim()),e.since&&t.push(`observed since ${e.since}`),t.push(""),t.push("OBSERVED — hosts this process has actually contacted"),e.observed?.length||t.push(" (none yet)");for(const r of e.observed||[])t.push(` ${r.local?"[local] ":""}${r.scheme}://${r.host}:${r.port} ×${r.count} last ${r.lastAt}`);t.push(""),t.push("DECLARED — hosts this configuration allows, and why");for(const r of e.declared||[])t.push(` ${r.local?"[local] ":""}${r.host}`),t.push(` ${r.purpose}`),t.push(` when: ${r.when}${r.off?` · off: ${r.off}`:""}`),r.data&&t.push(` sends: ${r.data}`);return e.managed&&(t.push(""),t.push(`POLICY — ${e.managed.name||e.managed.org||"managed"} (${e.managed.signed?"signed":"unsigned file"}, hash ${String(e.managed.policyHash||"").slice(0,12)}…)`),t.push(` enforcing: ${Object.entries(e.managed.enforces||{}).filter(([,r])=>r).map(([r,o])=>o===!0?r:`${r}=${o}`).join(", ")||"nothing yet"}`),t.push(` refused this session: ${e.blocked?.length?e.blocked.join(", "):"none"}`)),t.push(""),t.push(`Scope: ${e.scope}`),t.push("Verify it yourself: any hostname not listed above that appears in your firewall or proxy log for this process is a bug — report it (security@chatpanel.net)."),t.join(`
2
+ `)}export{v as createEgressLedger,$ as declaredEgress,S as egressAudit,k as egressLedger,x as formatAudit,E as installEgressLedger};
package/src/link-host.js CHANGED
@@ -1 +1 @@
1
- import{readFileSync as z,writeFileSync as G,renameSync as H,mkdirSync as Y,chmodSync as W}from"node:fs";import{dirname as Q,join as X}from"node:path";import I from"node:os";import{createLinkEndpoint as Z}from"@chatpanel/events/link-connect.js";import{noiseCrypto as q}from"@chatpanel/events/link-noise.js";import{pairingUri as ee,admissionToken as B,admissionVerifier as F,toB64url as v,fromB64url as O}from"@chatpanel/events/link-protocol.js";import{qrSvg as te}from"@chatpanel/events/qr.js";const ne="https://link.chatpanel.net",R=10*6e4,oe=3e4,N=[1e3,2e3,5e3,1e4,3e4,6e4],re=40,ae=16e3,se=[/^\/v1\/models(?:\/|$|\?)/,/^\/v1\/chat\/completions$/,/^\/v1\/messages$/,/^\/v1\/audio\/(?:transcriptions|speech)$/,/^\/v1\/history\/(?:search|smart-search|get|list|related|status)(?:$|\?)/,/^\/v1\/memory\/(?:recall|list|remember)(?:$|\?)/,/^\/v1\/(?:research|search|read|rerank|decide|capabilities|fusions)(?:$|\?)/,/^\/v1\/status$/],ie=p=>se.some(m=>m.test(String(p||"")));function ce(){return X(I.homedir(),".chatpanel","link.json")}function le(p){try{const m=JSON.parse(z(p,"utf8"));return{v:1,key:m.key||null,rooms:Array.isArray(m.rooms)?m.rooms:[]}}catch{return{v:1,key:null,rooms:[]}}}function D(p,m){Y(Q(p),{recursive:!0});const k=`${p}.tmp`;G(k,JSON.stringify(m,null,2),{mode:384});try{W(k,384)}catch{}H(k,p)}function ke({relay:p=ne,name:m=I.hostname(),dispatch:k,path:E=ce(),fetch:j=globalThis.fetch,WebSocket:J=globalThis.WebSocket,now:y=()=>Date.now(),random:U=d=>globalThis.crypto.getRandomValues(new Uint8Array(d)),crypto:A=q(),log:$=()=>{}}={}){const d=new URL(p).origin;if(!/^https:/.test(d)&&!/^http:\/\/127\.0\.0\.1(?::\d+)?$/.test(d))throw new Error("link: the relay must be https");let c=le(E);const u=new Map;let f=null;async function T(){return f||(c.key?f=await A.keyPairFromPrivate(O(c.key)):(f=await A.generateKeyPair(),c.key=v(f.raw),D(E,c)),f)}const b=e=>c.rooms.find(t=>t.room===e)||null,K=()=>D(E,c),_=async(e,t,o,r)=>{try{return await j(`${d}/v1/room/${e}`,{method:t,headers:{authorization:`Bearer ${o}`,...r?{"content-type":"application/json"}:{}},body:r?JSON.stringify(r):void 0})}catch(s){const a=s?.cause?.code||"",n=a==="ENOTFOUND"?"this computer cannot look up its name (a VPN or DNS that does not know it yet)":a?`${a}`:s?.message||"no answer";throw new Error(`cannot reach the Link relay at ${new URL(d).host}: ${n}`)}};async function V(e,t,o){if(!ie(t.path))return await o.head(403,{"content-type":"application/json"}),await o.write(JSON.stringify({error:{message:"link: a paired phone may not call this",type:"forbidden"}})),o.end();const r=t.method==="GET"?void 0:await t.body.bytes(),s=await k({method:t.method,path:t.path,headers:t.headers,body:r,device:e.room}),a={};if(s.headers?.forEach?.((n,i)=>{a[i]=n}),await o.head(s.status,a),s.body){let n=[],i=0,g=y();const w=async()=>{if(!i)return;const h=new Uint8Array(i);let l=0;for(const S of n)h.set(S,l),l+=S.length;n=[],i=0,g=y(),await o.write(h)};for await(const h of s.body){if(o.cancelled)break;const l=h instanceof Uint8Array?h:new TextEncoder().encode(String(h));n.push(l),i+=l.length,(i>=ae||y()-g>=re)&&await w()}await w()}return o.end()}async function x(e){const t=u.get(e.room)||{attempts:0,stopped:!1,online:!1};if(u.set(e.room,t),t.stopped)return;const o=await T(),r=e.pending&&e.pending.expiresAt>y()?e.pending:null;if(!e.phoneKey&&!r){L(e.room,"the pairing code expired");return}const s=`${d.replace(/^http/,"ws")}/v1/room/${e.room}`;let a;try{a=new J(s,["chatpanel-link.v1",e.token])}catch(n){M(e,n?.message);return}a.binaryType="arraybuffer",t.ws=a,t.endpoint=Z({side:"laptop",keyPair:o,crypto:A,psk:e.phoneKey?null:O(r.psk),peerKey:e.phoneKey?O(e.phoneKey):null,sendBytes:n=>{try{a.send(n)}catch{}},onRequest:(n,i)=>V(e,n,i),onSession:(n,i)=>{t.online=!0,t.attempts=0,e.lastSeen=y(),i.paired&&(e.phoneKey=v(i.peerKey),e.name=i.name||e.name||"Phone",e.pairedAt=y(),e.pending=null,$(`link: paired ${e.name}`)),K()},onEnd:()=>{t.online=!1}}),a.onopen=()=>{if(t.stopped||u.get(e.room)!==t){try{a.close(1e3,"stopped")}catch{}return}clearInterval(t.keepalive),t.keepalive=setInterval(()=>{try{a.send("ping")}catch{}},oe),t.keepalive.unref?.()},a.onmessage=n=>typeof n.data=="string"?t.endpoint.onText(n.data):t.endpoint.onBinary(new Uint8Array(n.data)),a.onclose=n=>{if(clearInterval(t.keepalive),t.online=!1,t.endpoint?.close("socket closed"),!t.stopped){if(n?.code===4003||n?.code===4004){P(e.room,"the relay removed the room");return}M(e,n?.code===4001?"replaced":`closed ${n?.code||""}`,n?.code===4001?5:null)}},a.onerror=()=>{}}function M(e,t,o=null){const r=u.get(e.room);if(!r||r.stopped)return;const s=o??Math.min(r.attempts,N.length-1);r.attempts++,clearTimeout(r.timer),r.timer=setTimeout(()=>x(e),N[s]),r.timer.unref?.(),$(`link: ${t}; again in ${N[s]/1e3}s`)}function C(e){const t=u.get(e);if(t){t.stopped=!0,clearTimeout(t.timer),clearInterval(t.keepalive),t.endpoint?.close("stopped");try{t.ws?.close(1e3,"stopped")}catch{}u.delete(e)}}function L(e,t){const o=b(e);o&&!o.phoneKey&&_(e,"DELETE",o.token).catch(()=>{}),P(e,t)}function P(e,t){C(e),c.rooms=c.rooms.filter(o=>o.room!==e),K(),$(`link: ${t}`)}return{async pair({name:e=m}={}){const t=await T(),o=U(16),r=U(32),s=v(o),a=await B(r,o,"laptop"),n=await B(r,o,"phone"),i=await _(s,"PUT",a,{laptop:await F(a),phone:await F(n)});if(i.status!==200&&i.status!==201)throw new Error(`link: the relay refused the room (${i.status})`);for(const l of c.rooms.filter(S=>!S.phoneKey))L(l.room,"a new pairing code replaced this one");const g=y()+R,w={room:s,token:a,phoneKey:null,name:"",pairedAt:null,lastSeen:null,pending:{psk:v(r),expiresAt:g}};c.rooms.push(w),K();const h=ee({relay:d,room:o,key:t.publicKey,secret:r,name:String(e||"").slice(0,60)});return x(w),setTimeout(()=>{const l=b(s);l&&!l.phoneKey&&L(s,"the pairing code expired")},R+1e3).unref?.(),{uri:h,svg:te(h,{ecc:"M"}),expiresAt:g,room:s}},status(){return{relay:d,devices:c.rooms.filter(e=>e.phoneKey).map(e=>({id:e.room,name:e.name||"Phone",pairedAt:e.pairedAt,lastSeen:e.lastSeen,online:!!u.get(e.room)?.online})),pairing:c.rooms.filter(e=>!e.phoneKey&&e.pending?.expiresAt>y()).map(e=>({id:e.room,expiresAt:e.pending.expiresAt,connected:!!u.get(e.room)?.online}))[0]||null}},async remove(e){const t=b(e);if(!t)return!1;try{await _(e,"DELETE",t.token)}catch{}return P(e,"removed"),!0},async start(){if(c.rooms.length){await T();for(const e of c.rooms)x(e)}},stop(){for(const e of[...u.keys()])C(e)},get publicKey(){return f?.publicKey||null}}}export{se as COMPANION_PATHS,ne as DEFAULT_RELAY,R as PAIRING_TTL_MS,ie as companionMay,ke as createLinkHost,ce as defaultLinkPath};
1
+ import{readFileSync as q,writeFileSync as ee,renameSync as te,mkdirSync as ne,chmodSync as oe}from"node:fs";import{dirname as re,join as ae}from"node:path";import B from"node:os";import{createLinkEndpoint as se}from"@chatpanel/events/link-connect.js";import{noiseCrypto as ie}from"@chatpanel/events/link-noise.js";import{pairingUri as ce,admissionToken as j,admissionVerifier as J,toB64url as $,fromB64url as I}from"@chatpanel/events/link-protocol.js";import{qrSvg as le}from"@chatpanel/events/qr.js";import{verifyEntitlement as pe,licenseFromPayload as de,can as me,FEATURE_TIER as V}from"@chatpanel/events/entitlement.js";const ue="https://link.chatpanel.net",G=10*6e4,fe=3e4,R=[1e3,2e3,5e3,1e4,3e4,6e4],he=40,ye=16e3,ke=/(^|\n): ?ping\n\n/g,ge=4,we=[/^\/v1\/models(?:\/|$|\?)/,/^\/v1\/chat\/completions$/,/^\/v1\/messages$/,/^\/v1\/audio\/(?:transcriptions|speech)$/,/^\/v1\/history\/(?:search|smart-search|get|list|related|status)(?:$|\?)/,/^\/v1\/history\/(?:records|stream)(?:$|\?)/,/^\/v1\/memory\/(?:recall|list|remember)(?:$|\?)/,/^\/v1\/(?:research|search|read|rerank|decide|capabilities|fusions)(?:$|\?)/,/^\/v1\/status$/],Ee=l=>we.some(i=>i.test(String(l||""))),H="x-chatpanel-entitlement",z="x-chatpanel-install",Y=(l,i)=>{for(const[m,y]of Object.entries(l||{}))if(m.toLowerCase()===i)return String(y||"");return""};async function Se(l,{now:i=Date.now()}={}){if(!V.link||V.link==="free")return!1;const m=Y(l,H),y=Y(l,z);if(!m||!y)return!1;const A=await pe(m,y,{now:i});return!!A&&me(de(A,{at:i}),"link",0,i)}function Te(){return ae(B.homedir(),".chatpanel","link.json")}function ve(l){try{const i=JSON.parse(q(l,"utf8"));return{v:1,key:i.key||null,rooms:Array.isArray(i.rooms)?i.rooms:[]}}catch{return{v:1,key:null,rooms:[]}}}function W(l,i){ne(re(l),{recursive:!0});const m=`${l}.tmp`;ee(m,JSON.stringify(i,null,2),{mode:384});try{oe(m,384)}catch{}te(m,l)}function Ne({relay:l=ue,name:i=B.hostname(),dispatch:m,path:y=Te(),fetch:A=globalThis.fetch,WebSocket:Q=globalThis.WebSocket,now:u=()=>Date.now(),random:U=f=>globalThis.crypto.getRandomValues(new Uint8Array(f)),crypto:_=ie(),log:x=()=>{},mayLink:X=Se}={}){const f=new URL(l).origin;if(!/^https:/.test(f)&&!/^http:\/\/127\.0\.0\.1(?::\d+)?$/.test(f))throw new Error("link: the relay must be https");let p=ve(y);const h=new Map;let g=null;async function b(){return g||(p.key?g=await _.keyPairFromPrivate(I(p.key)):(g=await _.generateKeyPair(),p.key=$(g.raw),W(y,p)),g)}const L=e=>p.rooms.find(t=>t.room===e)||null,P=()=>W(y,p),K=async(e,t,n,a)=>{try{return await A(`${f}/v1/room/${e}`,{method:t,headers:{authorization:`Bearer ${n}`,...a?{"content-type":"application/json"}:{}},body:a?JSON.stringify(a):void 0})}catch(c){const r=c?.cause?.code||"",o=r==="ENOTFOUND"?"this computer cannot look up its name (a VPN or DNS that does not know it yet)":r?`${r}`:c?.message||"no answer";throw new Error(`cannot reach the Link relay at ${new URL(f).host}: ${o}`)}};async function Z(e,t,n){if(!Ee(t.path))return await n.head(403,{"content-type":"application/json"}),await n.write(JSON.stringify({error:{message:"link: a paired phone may not call this",type:"forbidden"}})),n.end();if(!await X(t.headers,{now:u()}))return await n.head(402,{"content-type":"application/json"}),await n.write(JSON.stringify({error:{message:"ChatPanel Link needs Pro on this phone — upgrade on the phone, or restore its Pro under Settings › Plan",type:"pro_required"}})),n.end();const a={};for(const[s,d]of Object.entries(t.headers||{}))s.toLowerCase()!==H&&s.toLowerCase()!==z&&(a[s]=d);const c=t.method==="GET"?void 0:await t.body.bytes(),r=await m({method:t.method,path:t.path,headers:a,body:c,device:e.room}),o={};if(r.headers?.forEach?.((s,d)=>{o[d]=s}),await n.head(r.status,o),r.body){let s=[],d=0,S=u();const T=async()=>{if(!d)return;const k=new Uint8Array(d);let w=0;for(const v of s)k.set(v,w),w+=v.length;s=[],d=0,S=u(),await n.write(k)},E=/event-stream/.test(String(r.headers?.get?.("content-type")||""));for await(const k of r.body){if(n.cancelled)break;let w=k instanceof Uint8Array?k:new TextEncoder().encode(String(k));if(E){const v=new TextDecoder().decode(w);if(v.includes(": ping")){const F=v.replace(ke,"$1");if(!F)continue;w=new TextEncoder().encode(F)}}s.push(w),d+=w.length,(d>=ye||u()-S>=he)&&await T()}await T()}return n.end()}async function N(e){const t=h.get(e.room)||{attempts:0,stopped:!1,online:!1};if(h.set(e.room,t),t.stopped)return;const n=await b(),a=e.pending&&e.pending.expiresAt>u()?e.pending:null;if(!e.phoneKey&&!a){O(e.room,"the pairing code expired");return}const c=`${f.replace(/^http/,"ws")}/v1/room/${e.room}`;let r;try{r=new Q(c,["chatpanel-link.v1",e.token])}catch(o){D(e,o?.message);return}r.binaryType="arraybuffer",t.ws=r,t.endpoint=se({side:"laptop",keyPair:n,crypto:_,psk:e.phoneKey?null:I(a.psk),peerKey:e.phoneKey?I(e.phoneKey):null,sendBytes:o=>{try{r.send(o)}catch{}},onRequest:(o,s)=>Z(e,o,s),onSession:(o,s)=>{t.online=!0,t.attempts=0,e.lastSeen=u(),s.paired&&(e.phoneKey=$(s.peerKey),e.name=s.name||e.name||"Phone",e.pairedAt=u(),e.pending=null,x(`link: paired ${e.name}`)),P()},onEnd:()=>{t.online=!1}}),r.onopen=()=>{if(t.stopped||h.get(e.room)!==t){try{r.close(1e3,"stopped")}catch{}return}clearInterval(t.keepalive),t.keepalive=setInterval(()=>{try{r.send("ping")}catch{}},fe),t.keepalive.unref?.()},r.onmessage=o=>typeof o.data=="string"?t.endpoint.onText(o.data):t.endpoint.onBinary(new Uint8Array(o.data)),r.onclose=o=>{if(clearInterval(t.keepalive),t.online=!1,t.endpoint?.close("socket closed"),!t.stopped){if(o?.code===4003||o?.code===4004){C(e.room,"the relay removed the room");return}D(e,o?.code===4001?"replaced":o?.code===4008?"over the relay's budget":`closed ${o?.code||""}`,o?.code===4001?5:o?.code===4008?ge:null)}},r.onerror=()=>{}}function D(e,t,n=null){const a=h.get(e.room);if(!a||a.stopped)return;const c=n??Math.min(a.attempts,R.length-1);a.attempts++,clearTimeout(a.timer),a.timer=setTimeout(()=>N(e),R[c]),a.timer.unref?.(),x(`link: ${t}; again in ${R[c]/1e3}s`)}function M(e){const t=h.get(e);if(t){t.stopped=!0,clearTimeout(t.timer),clearInterval(t.keepalive),t.endpoint?.close("stopped");try{t.ws?.close(1e3,"stopped")}catch{}h.delete(e)}}function O(e,t){const n=L(e);n&&!n.phoneKey&&K(e,"DELETE",n.token).catch(()=>{}),C(e,t)}function C(e,t){M(e),p.rooms=p.rooms.filter(n=>n.room!==e),P(),x(`link: ${t}`)}return{async pair({name:e=i}={}){const t=await b(),n=U(16),a=U(32),c=$(n),r=await j(a,n,"laptop"),o=await j(a,n,"phone"),s=await K(c,"PUT",r,{laptop:await J(r),phone:await J(o)});if(s.status!==200&&s.status!==201)throw new Error(`link: the relay refused the room (${s.status})`);for(const E of p.rooms.filter(k=>!k.phoneKey))O(E.room,"a new pairing code replaced this one");const d=u()+G,S={room:c,token:r,phoneKey:null,name:"",pairedAt:null,lastSeen:null,pending:{psk:$(a),expiresAt:d}};p.rooms.push(S),P();const T=ce({relay:f,room:n,key:t.publicKey,secret:a,name:String(e||"").slice(0,60)});return N(S),setTimeout(()=>{const E=L(c);E&&!E.phoneKey&&O(c,"the pairing code expired")},G+1e3).unref?.(),{uri:T,svg:le(T,{ecc:"M"}),expiresAt:d,room:c}},status(){return{relay:f,devices:p.rooms.filter(e=>e.phoneKey).map(e=>({id:e.room,name:e.name||"Phone",pairedAt:e.pairedAt,lastSeen:e.lastSeen,online:!!h.get(e.room)?.online})),pairing:p.rooms.filter(e=>!e.phoneKey&&e.pending?.expiresAt>u()).map(e=>({id:e.room,expiresAt:e.pending.expiresAt,connected:!!h.get(e.room)?.online}))[0]||null}},async remove(e){const t=L(e);if(!t)return!1;try{await K(e,"DELETE",t.token)}catch{}return C(e,"removed"),!0},async start(){if(p.rooms.length){await b();for(const e of p.rooms)N(e)}},stop(){for(const e of[...h.keys()])M(e)},get publicKey(){return g?.publicKey||null}}}export{we as COMPANION_PATHS,ue as DEFAULT_RELAY,H as ENTITLEMENT_HEADER,z as INSTALL_HEADER,G as PAIRING_TTL_MS,Ee as companionMay,Ne as createLinkHost,Te as defaultLinkPath,Se as phoneMayLink};
@@ -1,9 +1,9 @@
1
- const s=d=>Number.isFinite(Number(d))?Number(d):0,A=d=>Math.max(s(d?.updatedAt),s(d?.deletedAt));class N{constructor(i){this.db=i}init(){return this.db.exec(`CREATE TABLE IF NOT EXISTS library(
1
+ import{mergeNoteRecords as S}from"@chatpanel/events/note-merge.js";const d=s=>Number.isFinite(Number(s))?Number(s):0,y=20,_=new Set(["rev","host","at","baseRev"]);function R(s){return Array.isArray(s)?`[${s.map(R).join(",")}]`:s&&typeof s=="object"?`{${Object.keys(s).filter(t=>!_.has(t)&&!(t==="deletedAt"&&!s[t])).sort().map(t=>`${JSON.stringify(t)}:${R(s[t])}`).join(",")}}`:JSON.stringify(s??null)}const v=(s,t)=>R(s)===R(t),g=s=>Math.max(d(s?.updatedAt),d(s?.deletedAt));class M{constructor(t){this.db=t}init(){this.db.exec(`CREATE TABLE IF NOT EXISTS library(
2
2
  id TEXT PRIMARY KEY, kind TEXT NOT NULL, title TEXT NOT NULL DEFAULT '',
3
3
  updated_at INTEGER NOT NULL DEFAULT 0, deleted_at INTEGER NOT NULL DEFAULT 0,
4
4
  host TEXT NOT NULL DEFAULT '', seq INTEGER NOT NULL DEFAULT 0, at INTEGER NOT NULL DEFAULT 0,
5
5
  record TEXT, sealed TEXT, bytes INTEGER NOT NULL DEFAULT 0,
6
6
  stamp INTEGER NOT NULL DEFAULT 0
7
- )`),this.db.exec("CREATE INDEX IF NOT EXISTS library_since ON library(stamp, id)"),this}get size(){return this.db.get("SELECT COUNT(*) c FROM library WHERE deleted_at = 0")?.c||0}get newest(){return this.db.get("SELECT MAX(stamp) m FROM library")?.m||0}stamp(i){const a=this.db.get("SELECT id, updated_at, deleted_at, at FROM library WHERE id = ?",[i]);return a?{id:a.id,updatedAt:a.updated_at,deletedAt:a.deleted_at,at:a.at}:null}_wins(i,a,u,r){const t=this.stamp(i);if(!t)return!0;const e=Math.max(s(a),s(u)),n=Math.max(s(t.updatedAt),s(t.deletedAt));return e!==n?e>n:s(r)>s(t.at)}upsert(i,{host:a="",seq:u=0,at:r=Date.now()}={}){const t=[];this.db.exec("BEGIN");try{for(const e of i||[]){if(!e||typeof e.id!="string"||!e.id.includes(":"))continue;const n=s(e.updatedAt),l=s(e.deletedAt);if(!n&&!l||!this._wins(e.id,n,l,r))continue;const E=l?null:JSON.stringify(e);this.db.run(`INSERT OR REPLACE INTO library(id, kind, title, updated_at, deleted_at, host, seq, at, record, sealed, bytes, stamp)
8
- VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, NULL, ?, ?)`,[e.id,e.kind||e.id.split(":")[0],String(e.title||""),n,l,String(a||""),s(u),s(r),E,E?E.length:0,Math.max(n,l)]),t.push(e.id)}this.db.exec("COMMIT")}catch(e){throw this.db.exec("ROLLBACK"),e}return t}async upsertEntries(i,{open:a=async()=>null}={}){const u=[];let r=0;for(const t of i||[]){if(!t||typeof t.id!="string"||!t.stamp)continue;const e=s(t.stamp.updatedAt),n=s(t.stamp.deletedAt);if(!e&&!n||!this._wins(t.id,e,n,t.at))continue;if(n){this.upsert([{id:t.id,kind:t.id.split(":")[0],updatedAt:e,deletedAt:n}],{host:t.host,seq:t.seq,at:t.at}),u.push(t.id);continue}let l=null;try{l=await a(t)}catch{l=null}if(l&&typeof l=="object")this.upsert([{...l,id:t.id,updatedAt:s(l.updatedAt)||e,deletedAt:0}],{host:t.host,seq:t.seq,at:t.at});else{const E=JSON.stringify(t.blob||null);this.db.run(`INSERT OR REPLACE INTO library(id, kind, title, updated_at, deleted_at, host, seq, at, record, sealed, bytes, stamp)
9
- VALUES(?, ?, '', ?, 0, ?, ?, ?, NULL, ?, ?, ?)`,[t.id,t.id.split(":")[0],e,String(t.host||""),s(t.seq),s(t.at),E,E.length,e]),r+=1}u.push(t.id)}return{written:u,sealed:r}}get(i){return L(this.db.get("SELECT * FROM library WHERE id = ?",[i]))}since({since:i=0,cursor:a="",limit:u=200,kind:r=null}={}){const t=Math.min(1e3,Math.max(1,s(u)||200));let e=s(i),n="";if(a){const T=String(a).indexOf(":");T>0&&(e=s(a.slice(0,T)),n=a.slice(T+1))}const l=[a?"(stamp > ? OR (stamp = ? AND id > ?))":"stamp > ?"],E=a?[e,e,n]:[e];r&&(l.push("kind = ?"),E.push(String(r)));const c=this.db.all(`SELECT * FROM library WHERE ${l.join(" AND ")} ORDER BY stamp ASC, id ASC LIMIT ?`,[...E,t+1]),o=c.length>t,h=o?c.slice(0,t):c,p=h.at(-1);return{records:h.map(L),next:o&&p?`${p.stamp}:${p.id}`:null}}stamps(){return this.db.all("SELECT id, updated_at, deleted_at FROM library").map(i=>({id:i.id,updatedAt:i.updated_at,deletedAt:i.deleted_at}))}clear(){const i=this.db.get("SELECT COUNT(*) c FROM library")?.c||0;return this.db.exec("DELETE FROM library"),i}}function L(d){if(!d)return null;if(d.deleted_at)return{id:d.id,kind:d.kind,updatedAt:d.updated_at,deletedAt:d.deleted_at,host:d.host,at:d.at};if(d.record)try{return{...JSON.parse(d.record),host:d.host,at:d.at}}catch{}let i=null;try{i=d.sealed?JSON.parse(d.sealed):null}catch{i=null}return{id:d.id,kind:d.kind,updatedAt:d.updated_at,deletedAt:0,sealed:i,host:d.host,at:d.at}}export{N as LosslessStore};
7
+ )`),this.db.exec("CREATE INDEX IF NOT EXISTS library_since ON library(stamp, id)");try{this.db.exec("ALTER TABLE library ADD COLUMN rev INTEGER NOT NULL DEFAULT 0")}catch{}this.db.exec("CREATE INDEX IF NOT EXISTS library_rev ON library(rev)"),this.db.exec("CREATE TABLE IF NOT EXISTS note_versions(id TEXT NOT NULL, rev INTEGER NOT NULL, host TEXT NOT NULL DEFAULT '', record TEXT NOT NULL, PRIMARY KEY(id, rev))"),this._rev=this.db.get("SELECT MAX(rev) m FROM library")?.m||0;const t=this.db.all("SELECT id FROM library WHERE rev = 0 ORDER BY stamp ASC, id ASC");if(t.length){this.db.exec("BEGIN");try{for(const i of t)this.db.run("UPDATE library SET rev = ? WHERE id = ?",[++this._rev,i.id]);this.db.exec("COMMIT")}catch(i){throw this.db.exec("ROLLBACK"),i}}return this}get rev(){return this._rev||0}get size(){return this.db.get("SELECT COUNT(*) c FROM library WHERE deleted_at = 0")?.c||0}get newest(){return this.db.get("SELECT MAX(stamp) m FROM library")?.m||0}stamp(t){const i=this.db.get("SELECT id, updated_at, deleted_at, at, rev FROM library WHERE id = ?",[t]);return i?{id:i.id,updatedAt:i.updated_at,deletedAt:i.deleted_at,at:i.at,rev:i.rev}:null}_wins(t,i,c,a){const e=this.stamp(t);if(!e)return!0;const r=Math.max(d(i),d(c)),n=Math.max(d(e.updatedAt),d(e.deletedAt));return r!==n?r>n:d(a)>d(e.at)}upsert(t,i={}){return this.write(t,i).written}write(t,{host:i="",seq:c=0,at:a=Date.now(),merge:e=!1}={}){const r=[],n={},l=[],E=[];this.db.exec("BEGIN");try{for(const h of t||[]){if(!h||typeof h.id!="string"||!h.id.includes(":"))continue;const{baseRev:T,...o}=h;let p=d(o.updatedAt),u=d(o.deletedAt);if(!p&&!u)continue;if(T!=null){const A=this.stamp(o.id);if(d(A?.rev)!==d(T)){const L=e&&!u?this._mergeNote(o,d(T),a):null;if(!L){l.push(this.get(o.id));continue}const b=this._put(L,{host:i,seq:c,at:a});r.push(o.id),n[o.id]=b,E.push({...L,rev:b});continue}const N=A?Math.max(d(A.updatedAt),d(A.deletedAt))+1:0;u&&u<N?u=N:!u&&p<N&&(p=N),o.updatedAt=p,u&&(o.deletedAt=u)}else{if(!this._wins(o.id,p,u,a))continue;const A=this.stamp(o.id);if(A&&Math.max(d(A.updatedAt),d(A.deletedAt))===Math.max(p,u)&&v(this.get(o.id),o))continue}const O=this._put(o,{host:i,seq:c,at:a});r.push(o.id),n[o.id]=O}this.db.exec("COMMIT")}catch(h){throw this.db.exec("ROLLBACK"),this._rev=this.db.get("SELECT MAX(rev) m FROM library")?.m||0,h}return{written:r,revs:n,conflicts:l.filter(Boolean),merged:E}}_put(t,{host:i="",seq:c=0,at:a=0}={}){const e=d(t.updatedAt),r=d(t.deletedAt),n=r?null:JSON.stringify(t),l=++this._rev,E=t.kind||t.id.split(":")[0];return this.db.run(`INSERT OR REPLACE INTO library(id, kind, title, updated_at, deleted_at, host, seq, at, record, sealed, bytes, stamp, rev)
8
+ VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, NULL, ?, ?, ?)`,[t.id,E,String(t.title||""),e,r,String(i||""),d(c),d(a),n,n?n.length:0,Math.max(e,r),l]),E==="note"&&n&&(this.db.run("INSERT OR REPLACE INTO note_versions(id, rev, host, record) VALUES(?, ?, ?, ?)",[t.id,l,String(i||""),n]),this.db.run("DELETE FROM note_versions WHERE id = ? AND rev NOT IN (SELECT rev FROM note_versions WHERE id = ? ORDER BY rev DESC LIMIT ?)",[t.id,t.id,y])),l}noteVersions(t){return this.db.all("SELECT rev, host, record FROM note_versions WHERE id = ? ORDER BY rev DESC",[t]).map(i=>{try{return{rev:i.rev,host:i.host,record:JSON.parse(i.record)}}catch{return null}}).filter(Boolean)}_mergeNote(t,i,c){const a=this.get(t.id);if(!a||a.deletedAt||(a.kind||t.id.split(":")[0])!=="note")return null;const e=this.db.get("SELECT record FROM note_versions WHERE id = ? AND rev = ?",[t.id,i]);let r=null;try{r=e?JSON.parse(e.record):null}catch{r=null}if(!r)return null;const{host:n,at:l,rev:E,...h}=a,{record:T}=S({base:{title:r.title??"",tags:r.tags??[],markdown:r.body?.markdown??""},ours:t,theirs:h,now:Math.max(d(c),d(a.updatedAt),d(t.updatedAt))+1});return T}async upsertEntries(t,{open:i=async()=>null}={}){const c=[];let a=0;for(const e of t||[]){if(!e||typeof e.id!="string"||!e.stamp)continue;const r=d(e.stamp.updatedAt),n=d(e.stamp.deletedAt);if(!r&&!n||!this._wins(e.id,r,n,e.at))continue;if(n){this.upsert([{id:e.id,kind:e.id.split(":")[0],updatedAt:r,deletedAt:n}],{host:e.host,seq:e.seq,at:e.at}),c.push(e.id);continue}let l=null;try{l=await i(e)}catch{l=null}if(l&&typeof l=="object")this.upsert([{...l,id:e.id,updatedAt:d(l.updatedAt)||r,deletedAt:0}],{host:e.host,seq:e.seq,at:e.at});else{const E=JSON.stringify(e.blob||null);this.db.run(`INSERT OR REPLACE INTO library(id, kind, title, updated_at, deleted_at, host, seq, at, record, sealed, bytes, stamp, rev)
9
+ VALUES(?, ?, '', ?, 0, ?, ?, ?, NULL, ?, ?, ?, ?)`,[e.id,e.id.split(":")[0],r,String(e.host||""),d(e.seq),d(e.at),E,E.length,r,++this._rev]),a+=1}c.push(e.id)}return{written:c,sealed:a}}get(t){return f(this.db.get("SELECT * FROM library WHERE id = ?",[t]))}since({since:t=0,cursor:i="",limit:c=200,kind:a=null,bytes:e=0,afterRev:r=null}={}){const n=Math.min(1e3,Math.max(1,d(c)||200));if(r!=null&&r!=="")return this._sinceRev(d(r),n,a,d(e));let l=d(t),E="";if(i){const N=String(i).indexOf(":");N>0&&(l=d(i.slice(0,N)),E=i.slice(N+1))}const h=[i?"(stamp > ? OR (stamp = ? AND id > ?))":"stamp > ?"],T=i?[l,l,E]:[l];a&&(h.push("kind = ?"),T.push(String(a)));const o=this.db.all(`SELECT * FROM library WHERE ${h.join(" AND ")} ORDER BY stamp ASC, id ASC LIMIT ?`,[...T,n+1]);let p=o.length>n,u=p?o.slice(0,n):o;const O=d(e);if(O>0){let N=0;const L=u.findIndex((b,m)=>(N+=d(b.bytes),m>0&&N>O));L>0&&(u=u.slice(0,L),p=!0)}const A=u.at(-1);return{records:u.map(f),next:p&&A?`${A.stamp}:${A.id}`:null}}_sinceRev(t,i,c,a){const e=["rev > ?"],r=[t];c&&(e.push("kind = ?"),r.push(String(c)));const n=this.db.all(`SELECT * FROM library WHERE ${e.join(" AND ")} ORDER BY rev ASC LIMIT ?`,[...r,i+1]);let l=n.length>i,E=l?n.slice(0,i):n;if(a>0){let h=0;const T=E.findIndex((o,p)=>(h+=d(o.bytes),p>0&&h>a));T>0&&(E=E.slice(0,T),l=!0)}return{records:E.map(f),next:l&&E.length?String(E.at(-1).rev):null,rev:this.rev}}stamps(){return this.db.all("SELECT id, updated_at, deleted_at FROM library").map(t=>({id:t.id,updatedAt:t.updated_at,deletedAt:t.deleted_at}))}clear(){const t=this.db.get("SELECT COUNT(*) c FROM library")?.c||0;return this.db.exec("DELETE FROM library"),t}}function f(s){if(!s)return null;const t=d(s.rev);if(s.deleted_at)return{id:s.id,kind:s.kind,updatedAt:s.updated_at,deletedAt:s.deleted_at,host:s.host,at:s.at,rev:t};if(s.record)try{return{...JSON.parse(s.record),host:s.host,at:s.at,rev:t}}catch{}let i=null;try{i=s.sealed?JSON.parse(s.sealed):null}catch{i=null}return{id:s.id,kind:s.kind,updatedAt:s.updated_at,deletedAt:0,sealed:i,host:s.host,at:s.at,rev:t}}export{M as LosslessStore,y as NOTE_VERSIONS_KEPT,v as sameContent};
package/src/server.js CHANGED
@@ -1,48 +1,48 @@
1
- import{createServer as co}from"node:http";import{loadConfig as vt}from"./config.js";import{startEntitlementRefresh as uo,maybeRevalidate as mo}from"./entitlement-refresh.js";import{redactSegments as De,segment as Qe}from"./redact.js";import{pipeRestoredStream as po,pipeRestoredOpenAIStream as ho,makeTokenRestorer as kt,restoreDeep as yo}from"./stream.js";import{restoreText as fo,gatedDictionary as go,narrowSpecs as wo,makeToolHarness as bo,placeholderToolNote as vo,placeholderNote as ko,assertEndpointUrl as So,capRunOptions as To,isPaired as xo}from"@chatpanel/pii";import{ensureGatewayToken as Oe,currentGatewayToken as Ye,isAdminAuthorized as z,callerTrustOf as Re,setPinnedExtensionIds as Oo,issuePairingCode as _o,claimPairingCode as Eo}from"./gateway-token.js";import{installEgressLedger as $o,egressAudit as Po}from"./egress.js";import{initPolicy as Ao,activePolicy as No,applyPolicyToConfig as St,managedSummary as _e,PolicyLoadError as Bo}from"./policy.js";import{routeAllowed as Tt,agentAllowed as Mo,egressAllowed as Co}from"@chatpanel/events/policy.js";import{resolveBridgeUrl as Ee}from"./bridge.js";import{secureFetch as Ie}from"./secure-fetch.js";import{fetchCard as je,forgetCard as Do,sendMessage as Ro,streamMessage as Io,getTask as jo,cancelTask as Lo,knownAgents as Jo,A2AError as xt}from"./a2a.js";import{streamBridgeChat as Ot,readBridgeToken as $e,openBridgeChat as zo,acceptedBridgeToken as Go}from"./bridge.js";import{createRelaySession as Ho,getRelaySession as _t,endRelaySession as Pe,pumpBridgeStream as Uo,deliverToolResult as Vo,toolsToSpecs as Fo,wantsApprovals as Wo,parseToolCallId as Et,touchRelaySession as Ze}from"./toolrelay.js";import{shaperFor as Xe}from"./shape.js";import{startNer as Ko,ensureNer as Le,unionForThisMachine as Qo,skippedCompanions as Yo}from"./ner.js";import{recommendDetector as $t}from"@chatpanel/pii/detector-router.js";import{installTimestampedConsole as Zo}from"./log.js";import{saveBackupSecret as Xo,clearBackupSecret as qo,loadBackupSecret as qe,hasBackupSecret as Pt}from"./history-store.js";import{createMemoryStore as er}from"./memory-store.js";import{createPrefsStore as tr}from"./prefs-store.js";import{agentCardFor as or,runHintFor as rr}from"@chatpanel/events/agent-run-hint.js";import{researchStore as nr,researchResponse as sr}from"./research.js";import{createTeamStore as ar,loadOrCreateKey as et}from"./team-store.js";import{createScorecardStore as ir}from"./scorecard-store.js";import{createEngineLedgerStore as lr}from"./engine-ledger-store.js";import{createProjectStore as dr}from"./project-store.js";import{applicationsFor as cr,recruitPass as ur}from"./recruiting.js";import{ensureBridge as mr,holderOf as pr,compareVersions as hr}from"./bridge-supervisor.js";import{checkForUpdate as yr,updateStatus as fr,startUpdate as gr,updateJob as wr}from"./update.js";import{createHistoryStore as br}from"./sqlite-store.js";import{createEventStore as vr}from"./event-store.js";import{ingestCloudEvents as kr,cursorOf as At}from"./event-sync.js";import{eventStats as Sr,projectYear as Tr}from"./event-stats.js";import{toCloudEvent as tt}from"./cloudevents.js";import{fusionsDocument as xr,resolveFusionModel as Or}from"./fusions.js";import{ingestBackups as ot}from"./backup-ingest.js";import{toSearchRecord as _r}from"@chatpanel/events/library.js";import{deriveBackupKey as Er,openRecord as $r,keyCache as Pr,nodeCodec as Ar}from"@chatpanel/events/backup-envelope.js";import Nr from"node:zlib";import*as A from"./ner-engine.js";import Nt from"node:os";import{capabilitiesDocument as Br,handleDetect as Mr}from"./capabilities.js";import{createExtractService as Cr}from"./extract/service.js";import{workerSandbox as Dr,disposeWorkerSandbox as Rr}from"./worker-sandbox.js";import{createRuntime as Ir}from"./runtime.js";import{createCapabilityProxy as jr}from"./capability-proxy.js";import{createEmbeddedCapabilities as Lr}from"./capability-embedded.js";import{EMBEDDED_MODELS as Jr,EMBEDDED_IDS as zr}from"./embedded-models.js";import{handleExtract as Gr}from"./extract/handler.js";import{MAX_DOCUMENT_BYTES as Hr}from"./extract-capability.js";import{createReader as Ur}from"./retrieval/read.js";import{createBrowserRelayHost as Vr}from"./browser-relay.js";import{createLinkHost as Fr,DEFAULT_RELAY as Wr}from"./link-host.js";import{createSearcher as Kr,toJinaSearch as Qr,SEARCH_DEFAULTS as Yr}from"./retrieval/search.js";import{createSearxng as Zr}from"./retrieval/search-searxng.js";import{toJinaText as Xr}from"./read-document.js";import*as D from"./stt-engine.js";import*as P from"./diarize-engine.js";import{DIARIZE_MODEL_CATALOG as qr,DEFAULT_DIARIZE_MODEL as en,isKnownDiarizeModel as Bt}from"./diarize-models.js";import{providerOf as rt}from"./providers.js";import{createRemoteTranscriber as Mt}from"./stt-remote.js";import{parseMultipart as tn,decodeAudioFile as on}from"./audio-file.js";import{MODEL_CATALOG as Ct,isKnownModel as Dt,isValidCustomModelId as Rt,recommendFor as rn}from"./models.js";import{STT_MODEL_CATALOG as nn,isKnownSttModel as sn,isValidCustomSttId as an,DEFAULT_STT_MODEL as Je,STT_DTYPES as ln,isValidDtype as dn}from"./stt-models.js";import*as $ from"./tts-engine.js";import{TTS_MODEL_CATALOG as It,TTS_VOICES as cn,isKnownTtsModel as un,isValidCustomTtsId as mn,isKnownVoice as jt,isValidVoiceId as Lt,DEFAULT_TTS_MODEL as Jt,DEFAULT_TTS_VOICE as fe,TTS_DTYPES as pn,isValidTtsDtype as hn,MAX_TTS_CHARS as zt,ttsModelHasCustomVoices as yn,resolveDefaultModel as Gt,POCKET_VOICES as fn,DEFAULT_POCKET_VOICE as ze,isPocketVoice as Ge,ttsModelEngine as He}from"./tts-models.js";import{ttsDestination as gn,synthesizeRemote as wn,isValidRemoteVoice as bn}from"./tts-remote.js";import{rawOrtAvailable as nt}from"./ort.js";import*as Z from"./tts-voices.js";import{resolveTtsVoice as vn}from"./tts-voice-resolve.js";import{resolvePro as we,checkQuota as kn,consume as Sn,usage as Tn}from"./freegate.js";import{publicConfig as Ht,applyConfigPatch as xn,registryChildEnv as On,applyNerModelSelection as Ut,persistConfig as pe,configPath as ne,bridgeAgentOptions as Vt,PERMISSION_MODES as _n,sandboxEnvFor as En}from"./configstore.js";import Ft from"node:path";import{resolveDestination as st,aggregateModelsAsync as $n,listDestinations as Pn,ensureModelCatalog as An,agentOwnsModel as Nn}from"./router.js";import{makeAccessEvent as Wt}from"./observability.js";import{createPersistentAccessLog as Bn}from"./access-log-store.js";import{planQueries as Mn,multiSearch as Cn}from"./rrf.js";import*as at from"./openai.js";import*as Kt from"./responses.js";import*as it from"./anthropic.js";import{closeAndExit as Dn}from"./shutdown.js";import{VERSION as K}from"./version.js";import{VERSION as Aa}from"./version.js";const B=await br(),he=new Set;function Ue({ids:t=[]}={}){const d=B.lossless;if(!d||!he.size)return;const c=JSON.stringify({newest:d.newest,size:d.size,ids:t.slice(0,50),at:Date.now()});for(const m of he)try{m.write(`event: records
1
+ import{createServer as co}from"node:http";import{loadConfig as vt}from"./config.js";import{startEntitlementRefresh as uo,maybeRevalidate as mo}from"./entitlement-refresh.js";import{redactSegments as Re,segment as Qe}from"./redact.js";import{pipeRestoredStream as po,pipeRestoredOpenAIStream as ho,makeTokenRestorer as kt,restoreDeep as yo}from"./stream.js";import{restoreText as fo,gatedDictionary as go,narrowSpecs as wo,makeToolHarness as bo,placeholderToolNote as vo,placeholderNote as ko,assertEndpointUrl as So,capRunOptions as To,isPaired as xo}from"@chatpanel/pii";import{ensureGatewayToken as _e,currentGatewayToken as Ye,isAdminAuthorized as G,callerTrustOf as Ie,setPinnedExtensionIds as Oo,issuePairingCode as _o,claimPairingCode as Eo}from"./gateway-token.js";import{installEgressLedger as $o,egressAudit as Po}from"./egress.js";import{initPolicy as Ao,activePolicy as No,applyPolicyToConfig as St,managedSummary as Ee,PolicyLoadError as Bo}from"./policy.js";import{routeAllowed as Tt,agentAllowed as Mo,egressAllowed as Co}from"@chatpanel/events/policy.js";import{resolveBridgeUrl as $e}from"./bridge.js";import{secureFetch as je}from"./secure-fetch.js";import{fetchCard as Le,forgetCard as Do,sendMessage as Ro,streamMessage as Io,getTask as jo,cancelTask as Lo,knownAgents as Jo,A2AError as xt}from"./a2a.js";import{streamBridgeChat as Ot,readBridgeToken as Pe,openBridgeChat as zo,acceptedBridgeToken as Go}from"./bridge.js";import{createRelaySession as Ho,getRelaySession as _t,endRelaySession as Ae,pumpBridgeStream as Uo,deliverToolResult as Vo,toolsToSpecs as Fo,wantsApprovals as Wo,parseToolCallId as Et,touchRelaySession as Ze}from"./toolrelay.js";import{shaperFor as Xe}from"./shape.js";import{startNer as Ko,ensureNer as Je,unionForThisMachine as Qo,skippedCompanions as Yo}from"./ner.js";import{recommendDetector as $t}from"@chatpanel/pii/detector-router.js";import{installTimestampedConsole as Zo}from"./log.js";import{saveBackupSecret as Xo,clearBackupSecret as qo,loadBackupSecret as qe,hasBackupSecret as Pt}from"./history-store.js";import{createMemoryStore as er}from"./memory-store.js";import{createPrefsStore as tr}from"./prefs-store.js";import{agentCardFor as or,runHintFor as rr}from"@chatpanel/events/agent-run-hint.js";import{researchStore as nr,researchResponse as ar}from"./research.js";import{createTeamStore as sr,loadOrCreateKey as et}from"./team-store.js";import{createScorecardStore as ir}from"./scorecard-store.js";import{createEngineLedgerStore as lr}from"./engine-ledger-store.js";import{createProjectStore as dr}from"./project-store.js";import{applicationsFor as cr,recruitPass as ur}from"./recruiting.js";import{ensureBridge as mr,holderOf as pr,compareVersions as hr}from"./bridge-supervisor.js";import{checkForUpdate as yr,updateStatus as fr,startUpdate as gr,updateJob as wr}from"./update.js";import{createHistoryStore as br}from"./sqlite-store.js";import{createEventStore as vr}from"./event-store.js";import{ingestCloudEvents as kr,cursorOf as At}from"./event-sync.js";import{eventStats as Sr,projectYear as Tr}from"./event-stats.js";import{toCloudEvent as tt}from"./cloudevents.js";import{fusionsDocument as xr,resolveFusionModel as Or}from"./fusions.js";import{ingestBackups as ot}from"./backup-ingest.js";import{toSearchRecord as _r}from"@chatpanel/events/library.js";import{deriveBackupKey as Er,openRecord as $r,keyCache as Pr,nodeCodec as Ar}from"@chatpanel/events/backup-envelope.js";import Nr from"node:zlib";import*as A from"./ner-engine.js";import Nt from"node:os";import{capabilitiesDocument as Br,handleDetect as Mr}from"./capabilities.js";import{createExtractService as Cr}from"./extract/service.js";import{workerSandbox as Dr,disposeWorkerSandbox as Rr}from"./worker-sandbox.js";import{createRuntime as Ir}from"./runtime.js";import{createCapabilityProxy as jr}from"./capability-proxy.js";import{createEmbeddedCapabilities as Lr}from"./capability-embedded.js";import{EMBEDDED_MODELS as Jr,EMBEDDED_IDS as zr}from"./embedded-models.js";import{handleExtract as Gr}from"./extract/handler.js";import{MAX_DOCUMENT_BYTES as Hr}from"./extract-capability.js";import{createReader as Ur}from"./retrieval/read.js";import{createBrowserRelayHost as Vr}from"./browser-relay.js";import{createLinkHost as Fr,DEFAULT_RELAY as Wr}from"./link-host.js";import{createSearcher as Kr,toJinaSearch as Qr,SEARCH_DEFAULTS as Yr}from"./retrieval/search.js";import{createSearxng as Zr}from"./retrieval/search-searxng.js";import{toJinaText as Xr}from"./read-document.js";import*as R from"./stt-engine.js";import*as P from"./diarize-engine.js";import{DIARIZE_MODEL_CATALOG as qr,DEFAULT_DIARIZE_MODEL as en,isKnownDiarizeModel as Bt}from"./diarize-models.js";import{providerOf as rt}from"./providers.js";import{createRemoteTranscriber as Mt}from"./stt-remote.js";import{parseMultipart as tn,decodeAudioFile as on}from"./audio-file.js";import{MODEL_CATALOG as Ct,isKnownModel as Dt,isValidCustomModelId as Rt,recommendFor as rn}from"./models.js";import{STT_MODEL_CATALOG as nn,isKnownSttModel as an,isValidCustomSttId as sn,DEFAULT_STT_MODEL as ze,STT_DTYPES as ln,isValidDtype as dn}from"./stt-models.js";import*as $ from"./tts-engine.js";import{TTS_MODEL_CATALOG as It,TTS_VOICES as cn,isKnownTtsModel as un,isValidCustomTtsId as mn,isKnownVoice as jt,isValidVoiceId as Lt,DEFAULT_TTS_MODEL as Jt,DEFAULT_TTS_VOICE as fe,TTS_DTYPES as pn,isValidTtsDtype as hn,MAX_TTS_CHARS as zt,ttsModelHasCustomVoices as yn,resolveDefaultModel as Gt,POCKET_VOICES as fn,DEFAULT_POCKET_VOICE as Ge,isPocketVoice as He,ttsModelEngine as Ue}from"./tts-models.js";import{ttsDestination as gn,synthesizeRemote as wn,isValidRemoteVoice as bn}from"./tts-remote.js";import{rawOrtAvailable as nt}from"./ort.js";import*as X from"./tts-voices.js";import{resolveTtsVoice as vn}from"./tts-voice-resolve.js";import{resolvePro as we,checkQuota as kn,consume as Sn,usage as Tn}from"./freegate.js";import{publicConfig as Ht,applyConfigPatch as xn,registryChildEnv as On,applyNerModelSelection as Ut,persistConfig as he,configPath as se,bridgeAgentOptions as Vt,PERMISSION_MODES as _n,sandboxEnvFor as En}from"./configstore.js";import Ft from"node:path";import{resolveDestination as at,aggregateModelsAsync as $n,listDestinations as Pn,ensureModelCatalog as An,agentOwnsModel as Nn}from"./router.js";import{makeAccessEvent as Wt}from"./observability.js";import{createPersistentAccessLog as Bn}from"./access-log-store.js";import{planQueries as Mn,multiSearch as Cn}from"./rrf.js";import*as st from"./openai.js";import*as Kt from"./responses.js";import*as it from"./anthropic.js";import{closeAndExit as Dn}from"./shutdown.js";import{VERSION as K}from"./version.js";import{VERSION as As}from"./version.js";const M=await br(),ye=new Set;function Ve({ids:t=[]}={}){const d=M.lossless;if(!d||!ye.size)return;const c=JSON.stringify({newest:d.newest,rev:d.rev,size:d.size,ids:t.slice(0,50),at:Date.now()});for(const m of ye)try{m.write(`event: records
2
2
  data: ${c}
3
3
 
4
- `)}catch{he.delete(m)}}setInterval(()=>{for(const t of he)try{t.write(`: ping
4
+ `)}catch{ye.delete(m)}}setInterval(()=>{for(const t of ye)try{t.write(`: ping
5
5
 
6
- `)}catch{he.delete(t)}},25e3).unref?.();const W=await vr(),be=new Set;W?.watch(t=>{if(!be.size)return;const d=`event: cloudevent
6
+ `)}catch{ye.delete(t)}},25e3).unref?.();const W=await vr(),be=new Set;W?.watch(t=>{if(!be.size)return;const d=`event: cloudevent
7
7
  data: ${JSON.stringify(tt(t))}
8
8
 
9
9
  `;for(const c of be)try{c.write(d)}catch{be.delete(c)}}),setInterval(()=>{for(const t of be)try{t.write(`: ping
10
10
 
11
- `)}catch{be.delete(t)}},25e3).unref?.();const oe=await er(),te=tr(),Se=ir({key:et()}),Te=lr({key:et()}),X=dr({key:et()}),V=ar({scorecards:Se,engines:Te}),lt=new Set,Qt=(t,d)=>{for(const m of lt)try{m({applied:t,by:d,revision:te.revision})}catch{}const c=JSON.stringify({revision:te.revision,applied:(t||[]).slice(0,50),by:d||"",at:Date.now()});for(const m of he)try{m.write(`event: prefs
11
+ `)}catch{be.delete(t)}},25e3).unref?.();const re=await er(),oe=tr(),Se=ir({key:et()}),Te=lr({key:et()}),q=dr({key:et()}),F=sr({scorecards:Se,engines:Te}),lt=new Set,Qt=(t,d)=>{for(const m of lt)try{m({applied:t,by:d,revision:oe.revision})}catch{}const c=JSON.stringify({revision:oe.revision,applied:(t||[]).slice(0,50),by:d||"",at:Date.now()});for(const m of ye)try{m.write(`event: prefs
12
12
  data: ${c}
13
13
 
14
- `)}catch{he.delete(m)}},dt=Bn(),Yt=new Set(["codex","claude","opencode","pi","kiro","antigravity","hermes"]),Rn=16,In=/^mcp[_-]/i,Zt=t=>t&&t.function&&t.function.name||t&&t.name||"",jn=t=>t&&t.function&&t.function.description||t&&t.description||"";function Xt(t){return typeof t=="string"?t:Array.isArray(t)?t.map(d=>typeof d=="string"?d:d&&(d.text||d.content)||"").join(" "):""}function Ln(t,d){if(!t)return"";if(d==="responses"){const m=t.input;return typeof m=="string"?m:Array.isArray(m)?m.map(h=>Xt(h&&(h.content??h))).join(" "):""}const c=Array.isArray(t.messages)?t.messages:[];for(let m=c.length-1;m>=0;m--)if(c[m]&&c[m].role==="user")return Xt(c[m].content);return""}const qt=new Set(["host","connection","content-length","transfer-encoding","accept-encoding","content-encoding","keep-alive"]);function ct(t){if(!t)return!1;const d=t.replace(/:\d+$/,"").replace(/^\[|\]$/g,"");return d==="localhost"||d==="127.0.0.1"||d==="::1"}function Jn(t,d){return!t||/^chrome-extension:\/\//.test(t)||/^moz-extension:\/\//.test(t)||/^http:\/\/(localhost|127\.0\.0\.1|\[::1\])(:\d+)?$/.test(t)?!0:Array.isArray(d.allowedOrigins)&&d.allowedOrigins.includes(t)}function zn(t,d){t.setHeader("Access-Control-Allow-Origin",d||"*"),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 eo=Date.now();function Gn(t){if(!t)return"";const d={redact:"redact",upstream:"model",stream:"stream",restore:"restore",total:"total"};return Object.keys(t).map(c=>`${d[c]||c} ${t[c]}ms`).join(" · ")}function Hn(t){const d=/^(model|harness):([^/]+)(?:\/(.+))?$/.exec(String(t||""));return d?{kind:d[1],id:d[2],...d[3]?{model:d[3]}:{}}:null}function Un(t){const d=performance.now(),c={};let m=!1;const h=(g,E)=>{c[g]=Math.round(E*10)/10};return{meta:{},timings:c,mark:h,lap(g,E){h(g,performance.now()-E)},clock(){return performance.now()},commit(){if(m)return;m=!0,h("total",performance.now()-d);const g={...this.meta,timings:c};setImmediate(()=>{t(g),console.log(`[gateway] model=${g.model||"-"} → ${g.dest?`${g.dest}(${g.type})`:"none"} · ${g.redaction==="off"?"redaction OFF (client request)":`redacted ${g.redacted||0}`}${g.sanitized?` · scrubbed ${g.sanitized} hidden`:""}${g.narrowed?` · narrowed -${g.narrowed}`:""} · ${Gn(c)}`)})}}}function to(t,d){if(!t||!t.byToken||d!=="types"&&d!=="values")return;const c=[];for(const[m,h]of t.byToken){const g=/^\[\[([A-Z][A-Z0-9]*)_\d+\]\]$/.exec(m),E=g?g[1]:"PII",w=m.replace(/^\[\[|\]\]$/g,"");c.push(d==="values"?{token:w,type:E,value:h}:{token:w,type:E})}return c}function Vn(t,d,c){return it.matches(t)||"anthropic-version"in d?{kind:"anthropic",adapter:it,redactable:it.matches(t),base:c.upstreams?.anthropic?.baseUrl}:Kt.matches(t)?{kind:"responses",adapter:Kt,redactable:!0,base:c.upstreams?.openai?.baseUrl}:{kind:"openai",adapter:at,redactable:at.matches(t),base:c.upstreams?.openai?.baseUrl}}function ut(t,d){const c=String(t||"");if(Yt.has(c))return{agent:c,agentModel:""};const m=c.indexOf("/");if(m>0){const h=c.slice(0,m);if(Yt.has(h))return{agent:h,agentModel:c.slice(m+1)}}return{agent:d.bridge.agent,agentModel:""}}function oo(t,d){return ut(t,d).agent}function Fn(t,d){if(d!=="openai"||!t)return!1;const c=at.extractLatestToolResult(t);if(!c)return!1;const m=Et(c.tool_call_id);return!!(m&&_t(m.gwId))}function Wn(t,d){try{const c=new URL(t),m=c.hostname.replace(/^\[|\]$/g,""),h=m==="127.0.0.1"||m==="localhost"||m==="::1",g=c.port||(c.protocol==="https:"?"443":"80");return h&&String(g)===String(d.port)}catch{return!1}}async function T(t,d){const c=[];let m=0;for await(const h of t){if(m+=h.length,d&&m>d){const g=new Error("payload too large");throw g.code=413,g}c.push(h)}return Buffer.concat(c)}function s(t,d,c){t.writeHead(d,{"content-type":"application/json"}),t.end(JSON.stringify(c))}function ro(t){const d=t.redaction?.detection?.url;return!d||t.redaction?.detection?.backend==="off"?null:d}function mt(t){const d=t?.redaction?.detection,c=t?.redaction?.tier==="full"?"full":"basic";if(d&&d.backend&&d.backend!=="off")return{source:"external",backend:d.backend,state:"external",model:d.model||null,ready:!0,tier:c,coverage:c==="full"?"names":"patterns"};const m=A.health(),h=m.ok&&c==="full";return{source:"bundled",state:m.state,model:m.model||t?.ner?.model||null,installed:A.modelOnDisk(t?.ner?.model||void 0),error:m.error||null,ready:h,tier:c,coverage:h?"names":"patterns"}}async function no(t){if(A.state()!=="off"){const c=A.health();return{configured:c.configured,ok:c.ok,state:c.state,model:c.model,error:c.error||null,url:c.configured?`http://${t.host}:${t.port}/ner`:null,stats:c.stats,companions:c.companions}}const d=ro(t);if(!d)return{configured:!1,ok:!1,url:null,model:null};try{const c=await Ie(d.replace(/\/ner\/?$/,"")+"/health",{signal:AbortSignal.timeout(2e3)});if(!c.ok)return{configured:!0,ok:!1,url:d,model:null};const m=await c.json().catch(()=>({}));return{configured:!0,ok:!0,url:d,model:m.model||null}}catch{return{configured:!0,ok:!1,url:d,model:null}}}function Kn(t,d){const c={};for(const[m,h]of Object.entries(t)){const g=m.toLowerCase();g.startsWith("x-chatpanel-")||qt.has(g)||(c[m]=h)}c["accept-encoding"]="identity";try{c.host=new URL(d).host}catch{}return c}async function so(t,d,c,m){const h=kt(d.vault),g=pt();t.on("close",()=>{t.writableFinished||Pe(d.id)});const E=m?m.clock():0;let w=E,O=!0;const M=()=>{m&&O&&(m.lap("upstream",E),w=m.clock(),O=!1)};await Uo(d,{onText:v=>{M(),Ze(d.id);const C=h.push(v);C&&t.write(c.sseDelta(C))},onToolRequest:({name:v,restoredArgs:C,toolId:j})=>{M(),Ze(d.id);const G=h.flush();G&&t.write(c.sseDelta(G)),t.write(c.sseToolCalls([{id:j,name:v,arguments:JSON.stringify(C)}])),t.write(c.sseToolFinish(g.value)),m&&m.lap("stream",w),t.end(),m?.commit()},onDone:()=>{const v=h.flush();v&&t.write(c.sseDelta(v)),t.write(c.sseTail(g.value)),m&&m.lap("stream",w),t.end(),Pe(d.id),m?.commit()},onError:v=>{t.write(`data: ${JSON.stringify({error:{message:v.message,type:"bridge_error"}})}
14
+ `)}catch{ye.delete(m)}},dt=Bn(),Yt=new Set(["codex","claude","opencode","pi","kiro","antigravity","hermes"]),Rn=16,In=/^mcp[_-]/i,Zt=t=>t&&t.function&&t.function.name||t&&t.name||"",jn=t=>t&&t.function&&t.function.description||t&&t.description||"";function Xt(t){return typeof t=="string"?t:Array.isArray(t)?t.map(d=>typeof d=="string"?d:d&&(d.text||d.content)||"").join(" "):""}function Ln(t,d){if(!t)return"";if(d==="responses"){const m=t.input;return typeof m=="string"?m:Array.isArray(m)?m.map(h=>Xt(h&&(h.content??h))).join(" "):""}const c=Array.isArray(t.messages)?t.messages:[];for(let m=c.length-1;m>=0;m--)if(c[m]&&c[m].role==="user")return Xt(c[m].content);return""}const qt=new Set(["host","connection","content-length","transfer-encoding","accept-encoding","content-encoding","keep-alive"]);function ct(t){if(!t)return!1;const d=t.replace(/:\d+$/,"").replace(/^\[|\]$/g,"");return d==="localhost"||d==="127.0.0.1"||d==="::1"}function Jn(t,d){return!t||/^chrome-extension:\/\//.test(t)||/^moz-extension:\/\//.test(t)||/^http:\/\/(localhost|127\.0\.0\.1|\[::1\])(:\d+)?$/.test(t)?!0:Array.isArray(d.allowedOrigins)&&d.allowedOrigins.includes(t)}function zn(t,d){t.setHeader("Access-Control-Allow-Origin",d||"*"),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 eo=Date.now();function Gn(t){if(!t)return"";const d={redact:"redact",upstream:"model",stream:"stream",restore:"restore",total:"total"};return Object.keys(t).map(c=>`${d[c]||c} ${t[c]}ms`).join(" · ")}function Hn(t){const d=/^(model|harness):([^/]+)(?:\/(.+))?$/.exec(String(t||""));return d?{kind:d[1],id:d[2],...d[3]?{model:d[3]}:{}}:null}function Un(t){const d=performance.now(),c={};let m=!1;const h=(g,E)=>{c[g]=Math.round(E*10)/10};return{meta:{},timings:c,mark:h,lap(g,E){h(g,performance.now()-E)},clock(){return performance.now()},commit(){if(m)return;m=!0,h("total",performance.now()-d);const g={...this.meta,timings:c};setImmediate(()=>{t(g),console.log(`[gateway] model=${g.model||"-"} → ${g.dest?`${g.dest}(${g.type})`:"none"} · ${g.redaction==="off"?"redaction OFF (client request)":`redacted ${g.redacted||0}`}${g.sanitized?` · scrubbed ${g.sanitized} hidden`:""}${g.narrowed?` · narrowed -${g.narrowed}`:""} · ${Gn(c)}`)})}}}function to(t,d){if(!t||!t.byToken||d!=="types"&&d!=="values")return;const c=[];for(const[m,h]of t.byToken){const g=/^\[\[([A-Z][A-Z0-9]*)_\d+\]\]$/.exec(m),E=g?g[1]:"PII",w=m.replace(/^\[\[|\]\]$/g,"");c.push(d==="values"?{token:w,type:E,value:h}:{token:w,type:E})}return c}function Vn(t,d,c){return it.matches(t)||"anthropic-version"in d?{kind:"anthropic",adapter:it,redactable:it.matches(t),base:c.upstreams?.anthropic?.baseUrl}:Kt.matches(t)?{kind:"responses",adapter:Kt,redactable:!0,base:c.upstreams?.openai?.baseUrl}:{kind:"openai",adapter:st,redactable:st.matches(t),base:c.upstreams?.openai?.baseUrl}}function ut(t,d){const c=String(t||"");if(Yt.has(c))return{agent:c,agentModel:""};const m=c.indexOf("/");if(m>0){const h=c.slice(0,m);if(Yt.has(h))return{agent:h,agentModel:c.slice(m+1)}}return{agent:d.bridge.agent,agentModel:""}}function oo(t,d){return ut(t,d).agent}function Fn(t,d){if(d!=="openai"||!t)return!1;const c=st.extractLatestToolResult(t);if(!c)return!1;const m=Et(c.tool_call_id);return!!(m&&_t(m.gwId))}function Wn(t,d){try{const c=new URL(t),m=c.hostname.replace(/^\[|\]$/g,""),h=m==="127.0.0.1"||m==="localhost"||m==="::1",g=c.port||(c.protocol==="https:"?"443":"80");return h&&String(g)===String(d.port)}catch{return!1}}async function S(t,d){const c=[];let m=0;for await(const h of t){if(m+=h.length,d&&m>d){const g=new Error("payload too large");throw g.code=413,g}c.push(h)}return Buffer.concat(c)}function a(t,d,c){t.writeHead(d,{"content-type":"application/json"}),t.end(JSON.stringify(c))}function ro(t){const d=t.redaction?.detection?.url;return!d||t.redaction?.detection?.backend==="off"?null:d}function mt(t){const d=t?.redaction?.detection,c=t?.redaction?.tier==="full"?"full":"basic";if(d&&d.backend&&d.backend!=="off")return{source:"external",backend:d.backend,state:"external",model:d.model||null,ready:!0,tier:c,coverage:c==="full"?"names":"patterns"};const m=A.health(),h=m.ok&&c==="full";return{source:"bundled",state:m.state,model:m.model||t?.ner?.model||null,installed:A.modelOnDisk(t?.ner?.model||void 0),error:m.error||null,ready:h,tier:c,coverage:h?"names":"patterns"}}async function no(t){if(A.state()!=="off"){const c=A.health();return{configured:c.configured,ok:c.ok,state:c.state,model:c.model,error:c.error||null,url:c.configured?`http://${t.host}:${t.port}/ner`:null,stats:c.stats,companions:c.companions}}const d=ro(t);if(!d)return{configured:!1,ok:!1,url:null,model:null};try{const c=await je(d.replace(/\/ner\/?$/,"")+"/health",{signal:AbortSignal.timeout(2e3)});if(!c.ok)return{configured:!0,ok:!1,url:d,model:null};const m=await c.json().catch(()=>({}));return{configured:!0,ok:!0,url:d,model:m.model||null}}catch{return{configured:!0,ok:!1,url:d,model:null}}}function Kn(t,d){const c={};for(const[m,h]of Object.entries(t)){const g=m.toLowerCase();g.startsWith("x-chatpanel-")||qt.has(g)||(c[m]=h)}c["accept-encoding"]="identity";try{c.host=new URL(d).host}catch{}return c}async function ao(t,d,c,m){const h=kt(d.vault),g=pt();t.on("close",()=>{t.writableFinished||Ae(d.id)});const E=m?m.clock():0;let w=E,O=!0;const C=()=>{m&&O&&(m.lap("upstream",E),w=m.clock(),O=!1)};await Uo(d,{onText:b=>{C(),Ze(d.id);const D=h.push(b);D&&t.write(c.sseDelta(D))},onToolRequest:({name:b,restoredArgs:D,toolId:L})=>{C(),Ze(d.id);const H=h.flush();H&&t.write(c.sseDelta(H)),t.write(c.sseToolCalls([{id:L,name:b,arguments:JSON.stringify(D)}])),t.write(c.sseToolFinish(g.value)),m&&m.lap("stream",w),t.end(),m?.commit()},onDone:()=>{const b=h.flush();b&&t.write(c.sseDelta(b)),t.write(c.sseTail(g.value)),m&&m.lap("stream",w),t.end(),Ae(d.id),m?.commit()},onError:b=>{t.write(`data: ${JSON.stringify({error:{message:b.message,type:"bridge_error"}})}
15
15
 
16
- `),t.end(),Pe(d.id),m?.commit()},onUsage:v=>g.add(v)})}async function Qn(t,d,{kind:c,adapter:m,agent:h,run:g=null},E,w,O,M,v,C=null,j=null){const{messages:G,system:ue}=m.toTurn(E),{agentModel:se}=ut(E?.model,O),q=Vt(O,{...se?{model:se}:{},...g||{}}),ae=$e(O.bridge.token),R=Xe(c,E?.model||h),ee={tier:O.redaction.tier==="full"?"full":"basic",dictionary:go(O.redaction,M),entities:[]},ie=await Ee(O),n=Ho({vault:w,redactOpts:ee,bridgeUrl:ie,token:ae,harness:C});let o;try{o=await zo({bridgeUrl:ie,agent:h,token:ae,messages:G,system:ue,specs:Fo(v),options:q,signal:void 0,approvals:Wo(v)})}catch(f){return Pe(n.id),j?.commit(),s(d,502,{error:{message:`bridge: ${f.message}`,type:"bridge_error"}})}return n.reader=o.body.getReader(),d.writeHead(200,{"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive"}),d.write(R.sseHead()),so(d,n,R,j)}async function Yn(t,d,c,m,h=null){Ze(d.id),d.rounds=(d.rounds||0)+1;try{const E=h?h.clock():0;await Vo(d,c),h&&h.lap("redact",E)}catch(E){return Pe(d.id),h?.commit(),s(t,502,{error:{message:`tool-result: ${E.message}`,type:"bridge_error"}})}const g=Xe("openai",m||"codex");return t.writeHead(200,{"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive"}),t.write(g.sseHead()),so(t,d,g,h)}function pt(){let t=!1;const d={inputTokens:0,outputTokens:0,cacheReadTokens:0,cacheWriteTokens:0};return{add(c){t=!0;for(const m of Object.keys(d))d[m]+=Math.max(0,Number(c?.[m])||0)},get value(){return t?d:null}}}async function Zn(t,d,{kind:c,adapter:m,redactable:h,pathname:g,agentOverride:E,harness:w,trace:O,run:M=null},v,C,j,G){if(!h)return O?.commit(),s(d,404,{error:`endpoint ${g} not supported by the bridge backend`});if(c==="openai"){const H=m.extractLatestToolResult(v);if(H){const Q=Et(H.tool_call_id),de=Q&&_t(Q.gwId);if(de)return Yn(d,de,H.content,v?.model,O)}const k=m.extractTools(v);if(k.length&&v?.stream===!0)return Qn(t,d,{kind:c,adapter:m,agent:E||oo(v?.model,j),run:M},v,C,j,G,k,w,O)}const{messages:ue,system:se}=m.toTurn(v),q=E||oo(v?.model,j),ae=v?.stream===!0,R=Xe(c,v?.model||q),ee=$e(j.bridge.token),ie=new AbortController;d.on("close",()=>{d.writableFinished||ie.abort()});const{agentModel:n}=ut(v?.model,j),o={bridgeUrl:await Ee(j),agent:q,token:ee,messages:ue,system:se,signal:ie.signal,options:Vt(j,{...n?{model:n}:{},...M||{}})};if(!ae)try{let H="";const k=pt(),Q=O?O.clock():0;await Ot(o,ve=>{H+=ve},null,ve=>k.add(ve)),O&&O.lap("upstream",Q);const de=O?O.clock():0,Ne=R.full(fo(H,C),k.value);return O&&O.lap("restore",de),d.writeHead(200,{"content-type":R.contentType}),d.end(Ne),O?.commit()}catch(H){return O?.commit(),s(d,502,{error:{message:`bridge backend failed: ${H.message}`,type:"bridge_error"}})}d.writeHead(200,{"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive"}),d.write(R.sseHead());const f=kt(C),i=O?O.clock():0;let L=i;const le=pt();try{let H=!0;await Ot(o,Q=>{O&&H&&(O.lap("upstream",i),L=O.clock(),H=!1);const de=f.push(Q);de&&d.write(R.sseDelta(de))},R.sseActivity?Q=>{try{d.write(R.sseActivity(yo(Q,C)))}catch{}}:null,Q=>le.add(Q));const k=f.flush();k&&d.write(R.sseDelta(k)),d.write(R.sseTail(le.value))}catch(H){d.write(`data: ${JSON.stringify({error:{message:H.message,type:"bridge_error"}})}
16
+ `),t.end(),Ae(d.id),m?.commit()},onUsage:b=>g.add(b)})}async function Qn(t,d,{kind:c,adapter:m,agent:h,run:g=null},E,w,O,C,b,D=null,L=null){const{messages:H,system:pe}=m.toTurn(E),{agentModel:ie}=ut(E?.model,O),ee=Vt(O,{...ie?{model:ie}:{},...g||{}}),le=Pe(O.bridge.token),I=Xe(c,E?.model||h),te={tier:O.redaction.tier==="full"?"full":"basic",dictionary:go(O.redaction,C),entities:[]},de=await $e(O),n=Ho({vault:w,redactOpts:te,bridgeUrl:de,token:le,harness:D});let o;try{o=await zo({bridgeUrl:de,agent:h,token:le,messages:H,system:pe,specs:Fo(b),options:ee,signal:void 0,approvals:Wo(b)})}catch(f){return Ae(n.id),L?.commit(),a(d,502,{error:{message:`bridge: ${f.message}`,type:"bridge_error"}})}return n.reader=o.body.getReader(),d.writeHead(200,{"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive"}),d.write(I.sseHead()),ao(d,n,I,L)}async function Yn(t,d,c,m,h=null){Ze(d.id),d.rounds=(d.rounds||0)+1;try{const E=h?h.clock():0;await Vo(d,c),h&&h.lap("redact",E)}catch(E){return Ae(d.id),h?.commit(),a(t,502,{error:{message:`tool-result: ${E.message}`,type:"bridge_error"}})}const g=Xe("openai",m||"codex");return t.writeHead(200,{"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive"}),t.write(g.sseHead()),ao(t,d,g,h)}function pt(){let t=!1;const d={inputTokens:0,outputTokens:0,cacheReadTokens:0,cacheWriteTokens:0};return{add(c){t=!0;for(const m of Object.keys(d))d[m]+=Math.max(0,Number(c?.[m])||0)},get value(){return t?d:null}}}async function Zn(t,d,{kind:c,adapter:m,redactable:h,pathname:g,agentOverride:E,harness:w,trace:O,run:C=null},b,D,L,H){if(!h)return O?.commit(),a(d,404,{error:`endpoint ${g} not supported by the bridge backend`});if(c==="openai"){const U=m.extractLatestToolResult(b);if(U){const Q=Et(U.tool_call_id),ue=Q&&_t(Q.gwId);if(ue)return Yn(d,ue,U.content,b?.model,O)}const v=m.extractTools(b);if(v.length&&b?.stream===!0)return Qn(t,d,{kind:c,adapter:m,agent:E||oo(b?.model,L),run:C},b,D,L,H,v,w,O)}const{messages:pe,system:ie}=m.toTurn(b),ee=E||oo(b?.model,L),le=b?.stream===!0,I=Xe(c,b?.model||ee),te=Pe(L.bridge.token),de=new AbortController;d.on("close",()=>{d.writableFinished||de.abort()});const{agentModel:n}=ut(b?.model,L),o={bridgeUrl:await $e(L),agent:ee,token:te,messages:pe,system:ie,signal:de.signal,options:Vt(L,{...n?{model:n}:{},...C||{}})};if(!le)try{let U="";const v=pt(),Q=O?O.clock():0;await Ot(o,ve=>{U+=ve},null,ve=>v.add(ve)),O&&O.lap("upstream",Q);const ue=O?O.clock():0,Be=I.full(fo(U,D),v.value);return O&&O.lap("restore",ue),d.writeHead(200,{"content-type":I.contentType}),d.end(Be),O?.commit()}catch(U){return O?.commit(),a(d,502,{error:{message:`bridge backend failed: ${U.message}`,type:"bridge_error"}})}d.writeHead(200,{"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive"}),d.write(I.sseHead());const f=kt(D),i=O?O.clock():0;let J=i;const ce=pt();try{let U=!0;await Ot(o,Q=>{O&&U&&(O.lap("upstream",i),J=O.clock(),U=!1);const ue=f.push(Q);ue&&d.write(I.sseDelta(ue))},I.sseActivity?Q=>{try{d.write(I.sseActivity(yo(Q,D)))}catch{}}:null,Q=>ce.add(Q));const v=f.flush();v&&d.write(I.sseDelta(v)),d.write(I.sseTail(ce.value))}catch(U){d.write(`data: ${JSON.stringify({error:{message:U.message,type:"bridge_error"}})}
17
17
 
18
- `)}O&&O.lap("stream",L),d.end(),O?.commit()}function Xn(t,d,c=""){const m=String(t||"").replace(/\/+$/,""),h=String(d||"").split("/")[1];return h&&m.endsWith(`/${h}`)?m.slice(0,-(h.length+1))+d+c:m+d+c}const qn=9e4;function es(t,d,c){if(d===c)return t;const m=d/c,h=new Float32Array(Math.floor(t.length/m));for(let g=0;g<h.length;g++){const E=g*m,w=Math.floor(E),O=Math.min(t.length-1,w+1),M=E-w;h[g]=t[w]*(1-M)+t[O]*M}return h}const ts=["/tts","/stt","/ner","/diarize","/skills","/agent-defs","/a2a","/redact","/config","/logs","/status","/admin","/v1/browser","/v1/link"];function ht(t,{installing:d=!1}={}){return t.stt?.diarize===!1?"off":d&&t.stt?.allowDownload!==!1?"download":"ondisk"}async function ce(t,d,c,m,{method:h="GET",timeoutMs:g=8e3,pick:E=w=>w}={}){const w=await Ee(c);if(!w)return s(d,503,{error:{message:"no bridge is configured",type:"no_bridge"}});const O=$e(c.bridge?.token),M=h!=="GET"&&h!=="DELETE";try{const v=M?(await T(t,c.maxBodyBytes)).toString("utf8"):"",C=await fetch(`${w}${m}`,{method:h,headers:{Accept:"application/json",...M?{"content-type":"application/json"}:{},...O?{Authorization:`Bearer ${O}`}:{}},...M?{body:v||"{}"}:{},signal:AbortSignal.timeout(g)}),j=await C.json().catch(()=>({}));return C.ok?s(d,200,E(j)):s(d,C.status,{error:{message:j?.error||`bridge ${C.status}`,type:"bridge_error"}})}catch(v){return s(d,502,{error:{message:`bridge unreachable: ${v.message}`,type:"bridge_unreachable"}})}}function yt(t){return!t||t==="."||t===".."||t.includes("/")||t.includes("\\")}function xe(t,d){const c=new URLSearchParams;for(const g of t.searchParams.getAll("dir"))g&&c.append("dir",g);const m=t.searchParams.get("workdir")||String(d?.bridge?.workingDir||"").trim();m&&c.set("workdir",m);const h=c.toString();return h?`?${h}`:""}async function os(t,d,{adapter:c,kind:m,pathname:h,search:g,base:E,destKey:w,destProtocol:O,harness:M,trace:v},C,j){let G;const ue=v?v.clock():0;try{const R=Kn(t.headers,E);w&&(O==="anthropic"?(R["x-api-key"]=w,delete R.authorization):R.authorization=`Bearer ${w}`);const ee=So(Xn(E,h,g)).toString();G=await fetch(ee,{method:t.method,headers:R,body:["GET","HEAD"].includes(t.method)?void 0:C})}catch(R){return v?.commit(),s(d,502,{error:`upstream fetch failed: ${R.message}`})}const se=G.headers.get("content-type")||"",q={};if(G.headers.forEach((R,ee)=>{qt.has(ee.toLowerCase())||(q[ee]=R)}),se.includes("text/event-stream")&&G.body){v&&v.lap("upstream",ue);const R=v?v.clock():0;d.writeHead(G.status,q);const ee=m==="openai"?ho(G.body,d,j,M):po(G.body,d,j);return Promise.resolve(ee).finally(()=>{v&&v.lap("stream",R),v?.commit()})}const ae=Buffer.from(await G.arrayBuffer());if(v&&v.lap("upstream",ue),j&&se.includes("application/json"))try{const R=v?v.clock():0,ee=c.restoreResponse(JSON.parse(ae.toString("utf8")),j,M);return v&&v.lap("restore",R),d.writeHead(G.status,{...q,"content-type":"application/json"}),d.end(Buffer.from(JSON.stringify(ee),"utf8")),v?.commit()}catch{}d.writeHead(G.status,q),d.end(ae),v?.commit()}function rs(t=vt()){const d=Vr({version:K}),c=t.link?.enabled===!1?null:Fr({relay:t.link?.relayUrl||Wr,...t.link?.path?{path:t.link.path}:{},dispatch:({method:n,path:o,headers:f,body:i,device:L})=>fetch(`http://127.0.0.1:${t.port}${o}`,{method:n,body:i,headers:{...f,"x-chatpanel-token":Ye()||Oe(),"x-chatpanel-link-device":String(L||"")}}),log:n=>console.log(` ${n}`)});t.stt?.diarizeModel&&t.stt.diarizeModel!==P.activeModel()&&(Bt(t.stt.diarizeModel)?P.setModel(t.stt.diarizeModel,{log:n=>console.log(n)}):console.warn(`[diarize] config names an unknown speaker model (${t.stt.diarizeModel}) — using ${en}`));let m=null;const h=()=>{if(!m){const n=t.read||{};m=Ur({remote:n.remote?.url?{url:n.remote.url,key:n.remote.key||""}:null,defaultProvider:n.provider||"defuddle"})}return m};let g=null;const E=()=>(g||(g=Cr({wrap:(n,o,f,i)=>Dr().wrap(n,o,f,i),onLog:n=>console.warn(`[extract worker] ${n}`)})),g);let w={at:0,fn:()=>"unknown"},O=null;async function M(){if(Date.now()-w.at<1e4)return w.fn;let n=new Map;try{const i=await C().health();for(const[L,le]of Object.entries(i)){const H=(t.destinations||[]).filter(k=>k?.service===L).flatMap(k=>[k.id,...k.models||[]]);for(const k of[L,...H])n.set(k,le)}}catch{n=new Map}const o=i=>n.get(i)||"unknown",f=new Map((t.destinations||[]).filter(i=>i?.service).map(i=>[i.id,i.service]));return o.window=i=>{try{return C().contextWindow(f.get(i)||i)}catch{return null}},o.card=i=>{try{return C().modelCard(f.get(i)||i)}catch{return null}},o.sig=JSON.stringify([...n.entries()].sort()),w={at:Date.now(),fn:o},w.fn}let v=null;const C=()=>(v||(v=Ir({cfg:t,bridgeHealth:async()=>{const n=await Ee(t);if(!n)return null;const o=$e(t.bridge?.token),f=await fetch(`${n}/health`,{headers:{Accept:"application/json",...o?{Authorization:`Bearer ${o}`}:{}},signal:AbortSignal.timeout(4e3)});return f.ok?f.json():null},persist:()=>{try{pe(t,ne())}catch(n){console.warn(`[runtime] could not persist config: ${n.message}`)}},stateDir:Ft.join(Ft.dirname(ne()),"runtime"),workers:()=>{const n=g?.status();return n?.running?[{id:"extract",kind:"worker",engine:"extract",command:"extract worker",label:"document extractor",pid:n.pid,sandbox:n.sandbox,refused:[]}]:[]},log:n=>console.log(n)})),v),j=Number(t.runtime?.idleMinutes),G=Lr({warmMs:(Number.isFinite(j)&&j>=0?j:10)*6e4,log:n=>console.log(n)}),ue=jr({cfg:t,wake:(n,o)=>C().wake(n,o),embedded:G}),se=()=>{t.search?.searxng?.url&&C().wake("searxng").catch(()=>{})};let q=null;const ae=()=>{if(!q){const n=t.search||{},o=n.searxng?.url?Zr({url:n.searxng.url,token:n.searxng.token||"",engines:n.searxng.engines||"",safesearch:n.searxng.safesearch??null}):null;q=Kr({reader:h(),searxng:o,defaultProvider:n.provider||"auto",redact:async f=>{let i=f;return await De([Qe(()=>i,L=>{i=L})],{...t.redaction,tier:"basic"},{isPro:!0}),i}})}return q};Oo(t.allowedExtensionIds||[]);const R=[],ee=n=>{R.push(n),R.length>50&&R.shift()},ie=co(async(n,o)=>{const f=new URL(n.url,"http://127.0.0.1"),i=f.pathname;if(!ct(n.headers.host))return s(o,403,{error:"loopback only"});if(!Jn(n.headers.origin,t))return s(o,403,{error:"origin not allowed"});if(n.headers.origin&&zn(o,n.headers.origin),n.method==="OPTIONS")return o.writeHead(204),o.end();if(i==="/admin/token"&&n.method==="POST")return z(n)?s(o,200,{token:Oe()}):s(o,403,{error:"admin: extension origin or gateway token required"});if(i==="/pair/code"&&n.method==="POST"){if(!z(n))return s(o,403,{error:"pair/code: extension origin or gateway token required"});const e=_o();return console.log("[gateway] pairing code issued — valid for 5 minutes, one use"),s(o,200,{ok:!0,...e})}if(i==="/pair"&&n.method==="POST"){let e=null;try{e=JSON.parse((await T(n,t.maxBodyBytes)).toString("utf8"))}catch{e=null}const r=Eo(e?.code);if(!r.ok)return console.log(`[gateway] pairing refused (${r.reason}) from ${Re(n)} caller`),s(o,403,{error:r.reason});console.log(`[gateway] paired a ${Re(n)} client${n.headers.origin?` (${n.headers.origin})`:""}`);const{token:a,refused:l}=await Go(t);return l&&console.log(`[gateway] pairing: the bridge at ${l.url}${l.version?` (v${l.version})`:""} accepts none of the tokens this gateway holds — not handing one over`),s(o,200,{ok:!0,token:Ye()||Oe(),...a?{bridgeToken:a}:{},...l?{bridgeRefused:l}:{}})}if(i==="/whoami"&&n.method==="POST"){const e=Re(n);return s(o,200,{ok:!0,trust:e,paired:xo(e),version:K})}if(i==="/audit"&&n.method==="GET")return z(n)?s(o,200,Po(t,{version:K,startedAt:eo,managed:_e()})):s(o,403,{error:"audit: extension origin or gateway token required"});if((i==="/config"||i==="/logs"||i==="/update"&&n.method!=="GET")&&!z(n))return s(o,403,{error:"admin route: extension origin or gateway token required"});if(i==="/update"&&n.method==="GET"){const e=await yr(K,{force:f.searchParams.get("force")==="1"}).catch(r=>({current:K,updateAvailable:!1,error:String(r?.message||r)}));return s(o,200,{ok:!0,update:e,job:wr()})}if(i==="/update"&&n.method==="POST"){const e=gr(K);return s(o,e.already?409:202,{ok:!0,job:e})}if((i==="/v1/history/key"||i==="/v1/history/ingest-backup")&&n.method==="POST"&&!z(n))return s(o,403,{error:{message:"history key route: extension origin or gateway token required",type:"forbidden"}});if(i==="/v1/history/records"&&n.method==="PUT"&&!z(n))return s(o,403,{error:{message:"history write — extension origin or gateway token required",type:"forbidden"}});if((i==="/v1/history/ingest"||i==="/v1/history/clear")&&n.method==="POST"&&!z(n))return s(o,403,{error:{message:"history write — extension origin or gateway token required",type:"forbidden"}});if((i==="/v1/memory/remember"||i==="/v1/memory/forget"||i==="/v1/memory/sync"||i==="/v1/memory/clear")&&n.method==="POST"&&!z(n))return s(o,403,{error:{message:"memory write — extension origin or gateway token required",type:"forbidden"}});if((i==="/v1/prefs"||i.startsWith("/v1/prefs/")||i.startsWith("/v1/teams")||i.startsWith("/v1/agents")||i.startsWith("/v1/projects"))&&!z(n))return s(o,403,{error:{message:"prefs: extension origin or gateway token required",type:"forbidden"}});if((i==="/v1/browser"||i.startsWith("/v1/browser/"))&&!z(n))return s(o,403,{error:{message:"browser: extension origin or gateway token required",type:"forbidden"}});if((i==="/v1/link"||i.startsWith("/v1/link/"))&&!z(n))return s(o,403,{error:{message:"link: extension origin or gateway token required",type:"forbidden"}});if((i==="/v1/events"||i.startsWith("/v1/events/"))&&!z(n))return s(o,403,{error:{message:"events: extension origin or gateway token required",type:"forbidden"}});if(i.startsWith("/v1/observability")&&!z(n))return s(o,403,{error:{message:"observability: extension origin or gateway token required",type:"forbidden"}});if(n.method==="GET"&&i==="/health"){const e=D.health(),r=$.health();return s(o,200,{ok:!0,version:K,backend:t.backend,tier:t.redaction.tier,pairing:!0,..._e()?{managed:_e()}:{},...process.env.CHATPANEL_MANAGED_BY?{managedBy:String(process.env.CHATPANEL_MANAGED_BY).slice(0,32)}:{},...Ae?{bridge:Ae.status()}:Ve?{bridge:Ve}:{},search:{provider:t.search?.provider||"auto",searxng:!!t.search?.searxng?.url},stt:{enabled:t.stt?.enabled!==!1,state:e.state,ready:e.ok,model:e.model||t.stt?.model||Je,runtime:e.runtime,dtype:e.dtype},tts:{enabled:t.tts?.enabled!==!1,state:r.state,ready:r.ok,model:r.model||t.tts?.model||Jt,voice:t.tts?.voice||fe,runtime:r.runtime,dtype:r.dtype},events:W?{count:W.count(),hosts:W.hosts().length}:null,browser:d.health()})}if(i==="/status"&&n.method==="GET"){mo(t);const e=await we(t.pro?.entitlementToken),r=await no(t);return s(o,200,{ok:!0,version:K,backend:t.backend,tier:t.redaction.tier,search:{provider:t.search?.provider||"auto",searxng:!!t.search?.searxng?.url},..._e()?{managed:_e()}:{},...process.env.CHATPANEL_MANAGED_BY?{managedBy:String(process.env.CHATPANEL_MANAGED_BY).slice(0,32)}:{},ner:{autostart:!!t.ner?.autostart,configured:r.configured,ready:r.ok,model:r.model,url:r.url},detector:mt(t),pro:{unlocked:e},usage:Tn(t),uptimeSeconds:Math.floor((Date.now()-eo)/1e3),update:fr(K)})}if(i==="/v1/history/ingest"&&n.method==="POST")try{const e=JSON.parse((await T(n,t.maxBodyBytes)).toString("utf8"))||{},r=B.bulk({upserts:Array.isArray(e.upserts)?e.upserts:[],removes:Array.isArray(e.removes)?e.removes:[]});return s(o,200,{ok:!0,size:r})}catch(e){return s(o,400,{error:{message:`ingest failed: ${e.message}`,type:"ingest_error"}})}if(i==="/v1/prefs"&&n.method==="GET"){const e=String(f.searchParams.get("section")||"");return f.searchParams.get("stamps")?s(o,200,{ok:!0,revision:te.revision,stamps:te.stamps()}):s(o,200,{ok:!0,revision:te.revision,sections:te.get(e)})}if(i==="/v1/prefs"&&(n.method==="POST"||n.method==="PUT"))try{const e=JSON.parse((await T(n,t.maxBodyBytes)).toString("utf8"))||{},r=te.put(e.sections||{},{by:e.by||""});return r.applied.length&&Qt(r.applied,e.by||""),s(o,200,{ok:!0,...r})}catch(e){return s(o,400,{error:{message:`prefs write failed: ${e.message}`,type:"prefs_error"}})}if(i==="/v1/prefs"&&n.method==="DELETE"){const e=String(f.searchParams.get("section")||""),r=e?te.remove(e):!1;return r&&Qt([e],""),s(o,200,{ok:!0,removed:r})}if(i==="/v1/prefs/events"&&n.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)}
18
+ `)}O&&O.lap("stream",J),d.end(),O?.commit()}function Xn(t,d,c=""){const m=String(t||"").replace(/\/+$/,""),h=String(d||"").split("/")[1];return h&&m.endsWith(`/${h}`)?m.slice(0,-(h.length+1))+d+c:m+d+c}const qn=9e4;function ea(t,d,c){if(d===c)return t;const m=d/c,h=new Float32Array(Math.floor(t.length/m));for(let g=0;g<h.length;g++){const E=g*m,w=Math.floor(E),O=Math.min(t.length-1,w+1),C=E-w;h[g]=t[w]*(1-C)+t[O]*C}return h}const ta=["/tts","/stt","/ner","/diarize","/skills","/agent-defs","/a2a","/redact","/config","/logs","/status","/admin","/v1/browser","/v1/link"];function ht(t,{installing:d=!1}={}){return t.stt?.diarize===!1?"off":d&&t.stt?.allowDownload!==!1?"download":"ondisk"}async function me(t,d,c,m,{method:h="GET",timeoutMs:g=8e3,pick:E=w=>w}={}){const w=await $e(c);if(!w)return a(d,503,{error:{message:"no bridge is configured",type:"no_bridge"}});const O=Pe(c.bridge?.token),C=h!=="GET"&&h!=="DELETE";try{const b=C?(await S(t,c.maxBodyBytes)).toString("utf8"):"",D=await fetch(`${w}${m}`,{method:h,headers:{Accept:"application/json",...C?{"content-type":"application/json"}:{},...O?{Authorization:`Bearer ${O}`}:{}},...C?{body:b||"{}"}:{},signal:AbortSignal.timeout(g)}),L=await D.json().catch(()=>({}));return D.ok?a(d,200,E(L)):a(d,D.status,{error:{message:L?.error||`bridge ${D.status}`,type:"bridge_error"}})}catch(b){return a(d,502,{error:{message:`bridge unreachable: ${b.message}`,type:"bridge_unreachable"}})}}function yt(t){return!t||t==="."||t===".."||t.includes("/")||t.includes("\\")}function xe(t,d){const c=new URLSearchParams;for(const g of t.searchParams.getAll("dir"))g&&c.append("dir",g);const m=t.searchParams.get("workdir")||String(d?.bridge?.workingDir||"").trim();m&&c.set("workdir",m);const h=c.toString();return h?`?${h}`:""}async function oa(t,d,{adapter:c,kind:m,pathname:h,search:g,base:E,destKey:w,destProtocol:O,harness:C,trace:b},D,L){let H;const pe=b?b.clock():0;try{const I=Kn(t.headers,E);w&&(O==="anthropic"?(I["x-api-key"]=w,delete I.authorization):I.authorization=`Bearer ${w}`);const te=So(Xn(E,h,g)).toString();H=await fetch(te,{method:t.method,headers:I,body:["GET","HEAD"].includes(t.method)?void 0:D})}catch(I){return b?.commit(),a(d,502,{error:`upstream fetch failed: ${I.message}`})}const ie=H.headers.get("content-type")||"",ee={};if(H.headers.forEach((I,te)=>{qt.has(te.toLowerCase())||(ee[te]=I)}),ie.includes("text/event-stream")&&H.body){b&&b.lap("upstream",pe);const I=b?b.clock():0;d.writeHead(H.status,ee);const te=m==="openai"?ho(H.body,d,L,C):po(H.body,d,L);return Promise.resolve(te).finally(()=>{b&&b.lap("stream",I),b?.commit()})}const le=Buffer.from(await H.arrayBuffer());if(b&&b.lap("upstream",pe),L&&ie.includes("application/json"))try{const I=b?b.clock():0,te=c.restoreResponse(JSON.parse(le.toString("utf8")),L,C);return b&&b.lap("restore",I),d.writeHead(H.status,{...ee,"content-type":"application/json"}),d.end(Buffer.from(JSON.stringify(te),"utf8")),b?.commit()}catch{}d.writeHead(H.status,ee),d.end(le),b?.commit()}function ra(t=vt()){const d=Vr({version:K}),c=t.link?.enabled===!1?null:Fr({relay:t.link?.relayUrl||Wr,...t.link?.path?{path:t.link.path}:{},dispatch:({method:n,path:o,headers:f,body:i,device:J})=>fetch(`http://127.0.0.1:${t.port}${o}`,{method:n,body:i,headers:{...f,"x-chatpanel-token":Ye()||_e(),"x-chatpanel-link-device":String(J||"")}}),log:n=>console.log(` ${n}`)});t.stt?.diarizeModel&&t.stt.diarizeModel!==P.activeModel()&&(Bt(t.stt.diarizeModel)?P.setModel(t.stt.diarizeModel,{log:n=>console.log(n)}):console.warn(`[diarize] config names an unknown speaker model (${t.stt.diarizeModel}) — using ${en}`));let m=null;const h=()=>{if(!m){const n=t.read||{};m=Ur({remote:n.remote?.url?{url:n.remote.url,key:n.remote.key||""}:null,defaultProvider:n.provider||"defuddle"})}return m};let g=null;const E=()=>(g||(g=Cr({wrap:(n,o,f,i)=>Dr().wrap(n,o,f,i),onLog:n=>console.warn(`[extract worker] ${n}`)})),g);let w={at:0,fn:()=>"unknown"},O=null;async function C(){if(Date.now()-w.at<1e4)return w.fn;let n=new Map;try{const i=await D().health();for(const[J,ce]of Object.entries(i)){const U=(t.destinations||[]).filter(v=>v?.service===J).flatMap(v=>[v.id,...v.models||[]]);for(const v of[J,...U])n.set(v,ce)}}catch{n=new Map}const o=i=>n.get(i)||"unknown",f=new Map((t.destinations||[]).filter(i=>i?.service).map(i=>[i.id,i.service]));return o.window=i=>{try{return D().contextWindow(f.get(i)||i)}catch{return null}},o.card=i=>{try{return D().modelCard(f.get(i)||i)}catch{return null}},o.sig=JSON.stringify([...n.entries()].sort()),w={at:Date.now(),fn:o},w.fn}let b=null;const D=()=>(b||(b=Ir({cfg:t,bridgeHealth:async()=>{const n=await $e(t);if(!n)return null;const o=Pe(t.bridge?.token),f=await fetch(`${n}/health`,{headers:{Accept:"application/json",...o?{Authorization:`Bearer ${o}`}:{}},signal:AbortSignal.timeout(4e3)});return f.ok?f.json():null},persist:()=>{try{he(t,se())}catch(n){console.warn(`[runtime] could not persist config: ${n.message}`)}},stateDir:Ft.join(Ft.dirname(se()),"runtime"),workers:()=>{const n=g?.status();return n?.running?[{id:"extract",kind:"worker",engine:"extract",command:"extract worker",label:"document extractor",pid:n.pid,sandbox:n.sandbox,refused:[]}]:[]},log:n=>console.log(n)})),b),L=Number(t.runtime?.idleMinutes),H=Lr({warmMs:(Number.isFinite(L)&&L>=0?L:10)*6e4,log:n=>console.log(n)}),pe=jr({cfg:t,wake:(n,o)=>D().wake(n,o),embedded:H}),ie=()=>{t.search?.searxng?.url&&D().wake("searxng").catch(()=>{})};let ee=null;const le=()=>{if(!ee){const n=t.search||{},o=n.searxng?.url?Zr({url:n.searxng.url,token:n.searxng.token||"",engines:n.searxng.engines||"",safesearch:n.searxng.safesearch??null}):null;ee=Kr({reader:h(),searxng:o,defaultProvider:n.provider||"auto",redact:async f=>{let i=f;return await Re([Qe(()=>i,J=>{i=J})],{...t.redaction,tier:"basic"},{isPro:!0}),i}})}return ee};Oo(t.allowedExtensionIds||[]);const I=[],te=n=>{I.push(n),I.length>50&&I.shift()},de=co(async(n,o)=>{const f=new URL(n.url,"http://127.0.0.1"),i=f.pathname;if(!ct(n.headers.host))return a(o,403,{error:"loopback only"});if(!Jn(n.headers.origin,t))return a(o,403,{error:"origin not allowed"});if(n.headers.origin&&zn(o,n.headers.origin),n.method==="OPTIONS")return o.writeHead(204),o.end();if(i==="/admin/token"&&n.method==="POST")return G(n)?a(o,200,{token:_e()}):a(o,403,{error:"admin: extension origin or gateway token required"});if(i==="/pair/code"&&n.method==="POST"){if(!G(n))return a(o,403,{error:"pair/code: extension origin or gateway token required"});const e=_o();return console.log("[gateway] pairing code issued — valid for 5 minutes, one use"),a(o,200,{ok:!0,...e})}if(i==="/pair"&&n.method==="POST"){let e=null;try{e=JSON.parse((await S(n,t.maxBodyBytes)).toString("utf8"))}catch{e=null}const r=Eo(e?.code);if(!r.ok)return console.log(`[gateway] pairing refused (${r.reason}) from ${Ie(n)} caller`),a(o,403,{error:r.reason});console.log(`[gateway] paired a ${Ie(n)} client${n.headers.origin?` (${n.headers.origin})`:""}`);const{token:s,refused:l}=await Go(t);return l&&console.log(`[gateway] pairing: the bridge at ${l.url}${l.version?` (v${l.version})`:""} accepts none of the tokens this gateway holds — not handing one over`),a(o,200,{ok:!0,token:Ye()||_e(),...s?{bridgeToken:s}:{},...l?{bridgeRefused:l}:{}})}if(i==="/whoami"&&n.method==="POST"){const e=Ie(n);return a(o,200,{ok:!0,trust:e,paired:xo(e),version:K})}if(i==="/audit"&&n.method==="GET")return G(n)?a(o,200,Po(t,{version:K,startedAt:eo,managed:Ee()})):a(o,403,{error:"audit: extension origin or gateway token required"});if((i==="/config"||i==="/logs"||i==="/update"&&n.method!=="GET")&&!G(n))return a(o,403,{error:"admin route: extension origin or gateway token required"});if(i==="/update"&&n.method==="GET"){const e=await yr(K,{force:f.searchParams.get("force")==="1"}).catch(r=>({current:K,updateAvailable:!1,error:String(r?.message||r)}));return a(o,200,{ok:!0,update:e,job:wr()})}if(i==="/update"&&n.method==="POST"){const e=gr(K);return a(o,e.already?409:202,{ok:!0,job:e})}if((i==="/v1/history/key"||i==="/v1/history/ingest-backup")&&n.method==="POST"&&!G(n))return a(o,403,{error:{message:"history key route: extension origin or gateway token required",type:"forbidden"}});if(i==="/v1/history/records"&&n.method==="PUT"&&!G(n))return a(o,403,{error:{message:"history write — extension origin or gateway token required",type:"forbidden"}});if((i==="/v1/history/ingest"||i==="/v1/history/clear")&&n.method==="POST"&&!G(n))return a(o,403,{error:{message:"history write — extension origin or gateway token required",type:"forbidden"}});if((i==="/v1/memory/remember"||i==="/v1/memory/forget"||i==="/v1/memory/sync"||i==="/v1/memory/clear")&&n.method==="POST"&&!G(n))return a(o,403,{error:{message:"memory write — extension origin or gateway token required",type:"forbidden"}});if((i==="/v1/prefs"||i.startsWith("/v1/prefs/")||i.startsWith("/v1/teams")||i.startsWith("/v1/agents")||i.startsWith("/v1/projects"))&&!G(n))return a(o,403,{error:{message:"prefs: extension origin or gateway token required",type:"forbidden"}});if((i==="/v1/browser"||i.startsWith("/v1/browser/"))&&!G(n))return a(o,403,{error:{message:"browser: extension origin or gateway token required",type:"forbidden"}});if((i==="/v1/link"||i.startsWith("/v1/link/"))&&!G(n))return a(o,403,{error:{message:"link: extension origin or gateway token required",type:"forbidden"}});if((i==="/v1/events"||i.startsWith("/v1/events/"))&&!G(n))return a(o,403,{error:{message:"events: extension origin or gateway token required",type:"forbidden"}});if(i.startsWith("/v1/observability")&&!G(n))return a(o,403,{error:{message:"observability: extension origin or gateway token required",type:"forbidden"}});if(n.method==="GET"&&i==="/health"){const e=R.health(),r=$.health();return a(o,200,{ok:!0,version:K,backend:t.backend,tier:t.redaction.tier,pairing:!0,...Ee()?{managed:Ee()}:{},...process.env.CHATPANEL_MANAGED_BY?{managedBy:String(process.env.CHATPANEL_MANAGED_BY).slice(0,32)}:{},...Ne?{bridge:Ne.status()}:Fe?{bridge:Fe}:{},search:{provider:t.search?.provider||"auto",searxng:!!t.search?.searxng?.url},stt:{enabled:t.stt?.enabled!==!1,state:e.state,ready:e.ok,model:e.model||t.stt?.model||ze,runtime:e.runtime,dtype:e.dtype},tts:{enabled:t.tts?.enabled!==!1,state:r.state,ready:r.ok,model:r.model||t.tts?.model||Jt,voice:t.tts?.voice||fe,runtime:r.runtime,dtype:r.dtype},events:W?{count:W.count(),hosts:W.hosts().length}:null,browser:d.health()})}if(i==="/status"&&n.method==="GET"){mo(t);const e=await we(t.pro?.entitlementToken),r=await no(t);return a(o,200,{ok:!0,version:K,backend:t.backend,tier:t.redaction.tier,search:{provider:t.search?.provider||"auto",searxng:!!t.search?.searxng?.url},...Ee()?{managed:Ee()}:{},...process.env.CHATPANEL_MANAGED_BY?{managedBy:String(process.env.CHATPANEL_MANAGED_BY).slice(0,32)}:{},ner:{autostart:!!t.ner?.autostart,configured:r.configured,ready:r.ok,model:r.model,url:r.url},detector:mt(t),pro:{unlocked:e},usage:Tn(t),uptimeSeconds:Math.floor((Date.now()-eo)/1e3),update:fr(K)})}if(i==="/v1/history/ingest"&&n.method==="POST")try{const e=JSON.parse((await S(n,t.maxBodyBytes)).toString("utf8"))||{},r=M.bulk({upserts:Array.isArray(e.upserts)?e.upserts:[],removes:Array.isArray(e.removes)?e.removes:[]});return a(o,200,{ok:!0,size:r})}catch(e){return a(o,400,{error:{message:`ingest failed: ${e.message}`,type:"ingest_error"}})}if(i==="/v1/prefs"&&n.method==="GET"){const e=String(f.searchParams.get("section")||"");return f.searchParams.get("stamps")?a(o,200,{ok:!0,revision:oe.revision,stamps:oe.stamps()}):a(o,200,{ok:!0,revision:oe.revision,sections:oe.get(e)})}if(i==="/v1/prefs"&&(n.method==="POST"||n.method==="PUT"))try{const e=JSON.parse((await S(n,t.maxBodyBytes)).toString("utf8"))||{},r=oe.put(e.sections||{},{by:e.by||""});return r.applied.length&&Qt(r.applied,e.by||""),a(o,200,{ok:!0,...r})}catch(e){return a(o,400,{error:{message:`prefs write failed: ${e.message}`,type:"prefs_error"}})}if(i==="/v1/prefs"&&n.method==="DELETE"){const e=String(f.searchParams.get("section")||""),r=e?oe.remove(e):!1;return r&&Qt([e],""),a(o,200,{ok:!0,removed:r})}if(i==="/v1/prefs/events"&&n.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)}
19
19
 
20
- `);e({type:"hello",revision:te.revision,stamps:te.stamps()});const r=l=>e({type:"changed",...l});lt.add(r);const a=setInterval(()=>{try{o.write(`: keep-alive
20
+ `);e({type:"hello",revision:oe.revision,stamps:oe.stamps()});const r=l=>e({type:"changed",...l});lt.add(r);const s=setInterval(()=>{try{o.write(`: keep-alive
21
21
 
22
- `)}catch{}},25e3);o.on("close",()=>{lt.delete(r),clearInterval(a)});return}if(i==="/v1/projects"&&n.method==="GET")return s(o,200,{ok:!0,projects:X.list({limit:f.searchParams.get("limit")||50,status:f.searchParams.get("status")||""})});if(i==="/v1/projects/jobs"&&n.method==="GET")return s(o,200,{ok:!0,jobs:X.openJobs()});if(i==="/v1/projects"&&n.method==="POST")try{const e=JSON.parse((await T(n,t.maxBodyBytes)).toString("utf8"))||{};return s(o,200,{ok:!0,project:X.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(i);if(e){const r=e[1],a=e[2]||"",l=e[3]||"",u=e[4]||"",S=()=>s(o,404,{error:{message:`no project ${r}`,type:"not_found"}});if(u){const y=X.get(r);if(!y)return S();const x=y.jobs.find(p=>p.id===l);if(!x)return s(o,404,{error:{message:`no job ${l}`,type:"not_found"}});const b={cfg:t,prefsStore:te,scorecards:Se,engines:Te};if(u==="/applications"&&n.method==="GET"){const p=await cr(x,{...b,reach:f.searchParams.get("reach")||"any",chatModel:f.searchParams.get("chatModel")||null});return s(o,200,{ok:!0,job:x,...p})}if(u==="/recruit"&&n.method==="POST"){if(!["open","evaluating"].includes(x.status))return s(o,400,{error:{message:`job ${l} is ${x.status}; only an open job is recruited`,type:"project_error"}});try{const p=JSON.parse((await T(n,t.maxBodyBytes)).toString("utf8"))||{},_=String(p.by||"evaluator").slice(0,80),J=await ur(x,{...b,record:y,reach:p.reach||"any",chatModel:p.chatModel||null,evaluation:p.evaluation||null,text:p.text??null,by:_});let I=null;for(const F of J.events)F.type==="job.updated"?I=X.updateJob(r,l,F.job,{by:F.by||_}):I=X.append(r,[F]);return s(o,200,{ok:!0,project:I,decision:J.decision,applications:J.applications,evaluation:J.evaluation})}catch(p){return s(o,400,{error:{message:`recruit: ${p.message}`,type:"project_error"}})}}return s(o,405,{error:{message:"method not allowed",type:"project_error"}})}if(!a&&n.method==="GET"){const y=X.get(r,{events:f.searchParams.get("events")==="1"});return y?s(o,200,{ok:!0,project:y}):S()}if(!a&&n.method==="DELETE")return s(o,200,{ok:!0,removed:X.remove(r)});if(n.method==="POST"&&(a==="/events"||a.startsWith("/jobs")))try{const y=JSON.parse((await T(n,t.maxBodyBytes)).toString("utf8"))||{},x=String(y.by||"person").slice(0,80),b=a==="/events"?X.append(r,y.events||[]):l?X.updateJob(r,l,y.patch||y,{by:x}):X.postJob(r,y.job||y,{by:x});return s(o,200,{ok:!0,project:b})}catch(y){return s(o,y.message.startsWith("no ")?404:400,{error:{message:`project: ${y.message}`,type:"project_error"}})}if(a==="/events"&&n.method==="GET"){if(!X.get(r))return S();o.writeHead(200,{"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive"});const y=_=>o.write(`data: ${JSON.stringify(_)}
22
+ `)}catch{}},25e3);o.on("close",()=>{lt.delete(r),clearInterval(s)});return}if(i==="/v1/projects"&&n.method==="GET")return a(o,200,{ok:!0,projects:q.list({limit:f.searchParams.get("limit")||50,status:f.searchParams.get("status")||""})});if(i==="/v1/projects/jobs"&&n.method==="GET")return a(o,200,{ok:!0,jobs:q.openJobs()});if(i==="/v1/projects"&&n.method==="POST")try{const e=JSON.parse((await S(n,t.maxBodyBytes)).toString("utf8"))||{};return a(o,200,{ok:!0,project:q.create({id:e.id||e.project?.id,project:e.project||null,by:e.by})})}catch(e){return a(o,400,{error:{message:`project: ${e.message}`,type:"project_error"}})}{const e=/^\/v1\/projects\/([a-zA-Z0-9_-]{1,64})(\/events|\/jobs(?:\/([a-zA-Z0-9_-]{1,64})(\/applications|\/recruit)?)?)?$/.exec(i);if(e){const r=e[1],s=e[2]||"",l=e[3]||"",u=e[4]||"",k=()=>a(o,404,{error:{message:`no project ${r}`,type:"not_found"}});if(u){const y=q.get(r);if(!y)return k();const x=y.jobs.find(p=>p.id===l);if(!x)return a(o,404,{error:{message:`no job ${l}`,type:"not_found"}});const T={cfg:t,prefsStore:oe,scorecards:Se,engines:Te};if(u==="/applications"&&n.method==="GET"){const p=await cr(x,{...T,reach:f.searchParams.get("reach")||"any",chatModel:f.searchParams.get("chatModel")||null});return a(o,200,{ok:!0,job:x,...p})}if(u==="/recruit"&&n.method==="POST"){if(!["open","evaluating"].includes(x.status))return a(o,400,{error:{message:`job ${l} is ${x.status}; only an open job is recruited`,type:"project_error"}});try{const p=JSON.parse((await S(n,t.maxBodyBytes)).toString("utf8"))||{},_=String(p.by||"evaluator").slice(0,80),N=await ur(x,{...T,record:y,reach:p.reach||"any",chatModel:p.chatModel||null,evaluation:p.evaluation||null,text:p.text??null,by:_});let j=null;for(const Y of N.events)Y.type==="job.updated"?j=q.updateJob(r,l,Y.job,{by:Y.by||_}):j=q.append(r,[Y]);return a(o,200,{ok:!0,project:j,decision:N.decision,applications:N.applications,evaluation:N.evaluation})}catch(p){return a(o,400,{error:{message:`recruit: ${p.message}`,type:"project_error"}})}}return a(o,405,{error:{message:"method not allowed",type:"project_error"}})}if(!s&&n.method==="GET"){const y=q.get(r,{events:f.searchParams.get("events")==="1"});return y?a(o,200,{ok:!0,project:y}):k()}if(!s&&n.method==="DELETE")return a(o,200,{ok:!0,removed:q.remove(r)});if(n.method==="POST"&&(s==="/events"||s.startsWith("/jobs")))try{const y=JSON.parse((await S(n,t.maxBodyBytes)).toString("utf8"))||{},x=String(y.by||"person").slice(0,80),T=s==="/events"?q.append(r,y.events||[]):l?q.updateJob(r,l,y.patch||y,{by:x}):q.postJob(r,y.job||y,{by:x});return a(o,200,{ok:!0,project:T})}catch(y){return a(o,y.message.startsWith("no ")?404:400,{error:{message:`project: ${y.message}`,type:"project_error"}})}if(s==="/events"&&n.method==="GET"){if(!q.get(r))return k();o.writeHead(200,{"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive"});const y=_=>o.write(`data: ${JSON.stringify(_)}
23
23
 
24
- `);let x=f.searchParams.has("after")?Number(f.searchParams.get("after")):-1;y({seq:-1,type:"hello",at:Date.now(),payload:{project:X.get(r),after:x}});const b=X.watch(r,_=>{_.seq>x&&(x=_.seq,y(_))});for(const _ of X.eventsSince(r,x))x=_.seq,y(_);const p=setInterval(()=>{try{o.write(`: keep
24
+ `);let x=f.searchParams.has("after")?Number(f.searchParams.get("after")):-1;y({seq:-1,type:"hello",at:Date.now(),payload:{project:q.get(r),after:x}});const T=q.watch(r,_=>{_.seq>x&&(x=_.seq,y(_))});for(const _ of q.eventsSince(r,x))x=_.seq,y(_);const p=setInterval(()=>{try{o.write(`: keep
25
25
 
26
- `)}catch{}},25e3);n.on("close",()=>{clearInterval(p),b()});return}}}if(i==="/v1/agents/scorecards"&&n.method==="GET")return s(o,200,{ok:!0,agents:Se.list()});{const e=/^\/v1\/agents\/([a-zA-Z0-9_.:@+-]{1,120})\/scorecard$/.exec(i);if(e){const r=decodeURIComponent(e[1]);if(n.method==="GET")return s(o,200,{ok:!0,...await Se.get(r)});if(n.method==="POST")try{const a=JSON.parse((await T(n,t.maxBodyBytes)).toString("utf8"))||{},l=await Se.append({agentId:r,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(Se.chains.get(r)||[],{...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(i==="/v1/capabilities"&&n.method==="GET")return s(o,200,Br(t,{version:K,reader:m,searcher:q,extract:E(),proxy:ue}));if(i==="/v1/fusions"&&n.method==="GET"){const e={active:A.health().model||t.ner?.model||null,companions:A.companions()};let r=null;try{r=await C().status()}catch{r=null}return s(o,200,xr({cfg:t,ner:e,runtimeDoc:r}))}if(i==="/v1/runtime"&&n.method==="GET"){const e=Object.fromEntries(zr.map(r=>{const a=rt(t,r);return[r,{provider:a.kind,model:a.kind==="embedded"?a.model:null,models:Jr[r],threads:G.threads,...a.kind==="embedded"?G.health(r,a.model):{}}]}));return s(o,200,{...await C().status(),inProcess:e})}{const e=/^\/v1\/runtime\/(engines|services)\/([a-z0-9-]+)$/.exec(i);if(e&&n.method==="POST"){if(!z(n))return s(o,403,{error:"runtime: extension origin or gateway token required"});let r={};try{r=JSON.parse((await T(n,t.maxBodyBytes)).toString("utf8")||"{}")}catch{r={}}const a=String(r.action||"start"),l=C(),u=e[1]==="engines"?a==="start"?await l.startEngine(e[2]):{ok:!1,error:`unknown action ${a}`}:a==="start"?await l.startService(e[2]):a==="stop"?await l.stopService(e[2]):a==="model"?await l.setModel(e[2],r.model):a==="tune"?await l.setTunings(e[2],r.tunings):a==="profile"?await l.setProfile(e[2],r.profile):a==="pull"?await l.pullModel(e[2]):a==="install"?await l.installRunner(e[2]):a==="cancel"?l.cancelJob(e[2]):{ok:!1,error:`unknown action ${a}`};return s(o,u.ok?200:400,u)}}if((i==="/v1/rerank"||i==="/v1/decide")&&n.method==="POST"){const e=i.slice(4);let r;try{r=JSON.parse((await T(n,t.maxBodyBytes)).toString("utf8"))}catch{return s(o,400,{error:{message:`${e}: body must be JSON`,type:"invalid_request"}})}const a=await ue.call(e,r);return s(o,a.status,a.body)}if(i==="/v1/detect"&&n.method==="POST"){let e;try{e=JSON.parse((await T(n,t.maxBodyBytes)).toString("utf8"))}catch{return s(o,400,{error:{message:"detect: body must be JSON",type:"invalid_request"}})}try{const r=await Mr(e,{ensure:()=>Le(t),model:A.health().model});return s(o,r.status,r.body)}catch(r){return s(o,500,{error:{message:`detect: ${r.message}`,type:"detector_error"}})}}if(i==="/v1/extract"&&n.method==="POST"){let e;try{e=JSON.parse((await T(n,Math.max(t.maxBodyBytes,Math.ceil(Hr*4/3)+1024))).toString("utf8"))}catch{return s(o,400,{error:{message:"extract: body must be JSON",type:"invalid_request"}})}const r=await Gr(e,{service:E()});return s(o,r.status,r.body)}if(i==="/v1/read"&&n.method==="POST"){let e;try{e=JSON.parse((await T(n,t.maxBodyBytes)).toString("utf8"))}catch{return s(o,400,{error:{message:"read: body must be JSON",type:"invalid_request"}})}const r=await h().read(e);return s(o,r.status,r.body)}if(i==="/v1/search"&&n.method==="POST"){let e;try{e=JSON.parse((await T(n,t.maxBodyBytes)).toString("utf8"))}catch{return s(o,400,{error:{message:"search: body must be JSON",type:"invalid_request"}})}se();const r=await ae().search(e);return s(o,r.status,r.body)}if(/^\/v1\/search\/./.test(i)&&n.method==="GET"){let e;try{e=decodeURIComponent(i.slice(11))}catch{e=i.slice(11)}const r=f.searchParams.has("read")?Math.max(0,Math.min(10,Number(f.searchParams.get("read"))||0)):Yr.aliasRead;se();const a=await ae().search({q:e,read:r,limit:Math.max(r,5)});return s(o,a.status,a.status===200?Qr(a.body):a.body)}if(/^\/v1\/read\/./.test(i)&&n.method==="GET"){const e=String(n.url||"").slice(9),r=/^https?:\/\//i.test(e)?e:decodeURIComponent(e),a=/application\/json/i.test(n.headers.accept||""),l=/^text$/i.test(n.headers["x-return-format"]||"")?"text":"markdown",u=await h().read({url:r,format:l});return u.status!==200||a?s(o,u.status,u.status===200?{code:200,status:2e4,data:u.body}:u.body):(o.writeHead(200,{"content-type":"text/plain; charset=utf-8","x-chatpanel-provider":u.body.provider}),o.end(Xr(u.body)))}if(i==="/v1/engines"&&n.method==="GET"){const e=Number(f.searchParams.get("minCalls"))||void 0;return s(o,200,{ok:!0,engines:Te.list({minCalls:e})})}{const e=/^\/v1\/engines\/(.+)\/(card|entries)$/.exec(i);if(e){const r=decodeURIComponent(e[1]).slice(0,300);if(e[2]==="card"&&n.method==="GET"){const a=Number(f.searchParams.get("minCalls"))||void 0;return s(o,200,{ok:!0,...await Te.get(r,{entries:f.searchParams.get("entries")==="1",minCalls:a})})}if(e[2]==="entries"&&n.method==="POST")try{const a=JSON.parse((await T(n,t.maxBodyBytes)).toString("utf8"))||{},l=a.engine||Hn(r);if(!l)return s(o,400,{error:{message:"model-ledger: engine required",type:"model_ledger_error"}});const u=await Te.append({...a,engine:l,kind:a.kind||"call"});return u.key!==r?s(o,400,{error:{message:`model-ledger: entry is for ${u.key}, not ${r}`,type:"model_ledger_error"}}):s(o,200,{ok:!0,entry:u})}catch(a){return s(o,400,{error:{message:`model-ledger: ${a.message}`,type:"model_ledger_error"}})}}}if(i==="/v1/teams/stream"&&n.method==="GET"){o.writeHead(200,{"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive"});const e=l=>{try{o.write(`data: ${JSON.stringify(l)}
26
+ `)}catch{}},25e3);n.on("close",()=>{clearInterval(p),T()});return}}}if(i==="/v1/agents/scorecards"&&n.method==="GET")return a(o,200,{ok:!0,agents:Se.list()});{const e=/^\/v1\/agents\/([a-zA-Z0-9_.:@+-]{1,120})\/scorecard$/.exec(i);if(e){const r=decodeURIComponent(e[1]);if(n.method==="GET")return a(o,200,{ok:!0,...await Se.get(r)});if(n.method==="POST")try{const s=JSON.parse((await S(n,t.maxBodyBytes)).toString("utf8"))||{},l=await Se.append({agentId:r,kind:"rating",runId:s.runId,taskId:s.taskId,jobId:s.jobId,rating:{by:String(s.by||"person").slice(0,40),score:s.score,note:s.note,about:s.about},refs:s.refs});return Te.fromRating(Se.chains.get(r)||[],{...l,jobKind:s.jobKind?String(s.jobKind).slice(0,60):void 0}),a(o,200,{ok:!0,entry:l})}catch(s){return a(o,400,{error:{message:`scorecard: ${s.message}`,type:"scorecard_error"}})}}}if(i==="/v1/capabilities"&&n.method==="GET")return a(o,200,Br(t,{version:K,reader:m,searcher:ee,extract:E(),proxy:pe}));if(i==="/v1/fusions"&&n.method==="GET"){const e={active:A.health().model||t.ner?.model||null,companions:A.companions()};let r=null;try{r=await D().status()}catch{r=null}return a(o,200,xr({cfg:t,ner:e,runtimeDoc:r}))}if(i==="/v1/runtime"&&n.method==="GET"){const e=Object.fromEntries(zr.map(r=>{const s=rt(t,r);return[r,{provider:s.kind,model:s.kind==="embedded"?s.model:null,models:Jr[r],threads:H.threads,...s.kind==="embedded"?H.health(r,s.model):{}}]}));return a(o,200,{...await D().status(),inProcess:e})}{const e=/^\/v1\/runtime\/(engines|services)\/([a-z0-9-]+)$/.exec(i);if(e&&n.method==="POST"){if(!G(n))return a(o,403,{error:"runtime: extension origin or gateway token required"});let r={};try{r=JSON.parse((await S(n,t.maxBodyBytes)).toString("utf8")||"{}")}catch{r={}}const s=String(r.action||"start"),l=D(),u=e[1]==="engines"?s==="start"?await l.startEngine(e[2]):{ok:!1,error:`unknown action ${s}`}:s==="start"?await l.startService(e[2]):s==="stop"?await l.stopService(e[2]):s==="model"?await l.setModel(e[2],r.model):s==="tune"?await l.setTunings(e[2],r.tunings):s==="profile"?await l.setProfile(e[2],r.profile):s==="pull"?await l.pullModel(e[2]):s==="install"?await l.installRunner(e[2]):s==="cancel"?l.cancelJob(e[2]):{ok:!1,error:`unknown action ${s}`};return a(o,u.ok?200:400,u)}}if((i==="/v1/rerank"||i==="/v1/decide")&&n.method==="POST"){const e=i.slice(4);let r;try{r=JSON.parse((await S(n,t.maxBodyBytes)).toString("utf8"))}catch{return a(o,400,{error:{message:`${e}: body must be JSON`,type:"invalid_request"}})}const s=await pe.call(e,r);return a(o,s.status,s.body)}if(i==="/v1/detect"&&n.method==="POST"){let e;try{e=JSON.parse((await S(n,t.maxBodyBytes)).toString("utf8"))}catch{return a(o,400,{error:{message:"detect: body must be JSON",type:"invalid_request"}})}try{const r=await Mr(e,{ensure:()=>Je(t),model:A.health().model});return a(o,r.status,r.body)}catch(r){return a(o,500,{error:{message:`detect: ${r.message}`,type:"detector_error"}})}}if(i==="/v1/extract"&&n.method==="POST"){let e;try{e=JSON.parse((await S(n,Math.max(t.maxBodyBytes,Math.ceil(Hr*4/3)+1024))).toString("utf8"))}catch{return a(o,400,{error:{message:"extract: body must be JSON",type:"invalid_request"}})}const r=await Gr(e,{service:E()});return a(o,r.status,r.body)}if(i==="/v1/read"&&n.method==="POST"){let e;try{e=JSON.parse((await S(n,t.maxBodyBytes)).toString("utf8"))}catch{return a(o,400,{error:{message:"read: body must be JSON",type:"invalid_request"}})}const r=await h().read(e);return a(o,r.status,r.body)}if(i==="/v1/search"&&n.method==="POST"){let e;try{e=JSON.parse((await S(n,t.maxBodyBytes)).toString("utf8"))}catch{return a(o,400,{error:{message:"search: body must be JSON",type:"invalid_request"}})}ie();const r=await le().search(e);return a(o,r.status,r.body)}if(/^\/v1\/search\/./.test(i)&&n.method==="GET"){let e;try{e=decodeURIComponent(i.slice(11))}catch{e=i.slice(11)}const r=f.searchParams.has("read")?Math.max(0,Math.min(10,Number(f.searchParams.get("read"))||0)):Yr.aliasRead;ie();const s=await le().search({q:e,read:r,limit:Math.max(r,5)});return a(o,s.status,s.status===200?Qr(s.body):s.body)}if(/^\/v1\/read\/./.test(i)&&n.method==="GET"){const e=String(n.url||"").slice(9),r=/^https?:\/\//i.test(e)?e:decodeURIComponent(e),s=/application\/json/i.test(n.headers.accept||""),l=/^text$/i.test(n.headers["x-return-format"]||"")?"text":"markdown",u=await h().read({url:r,format:l});return u.status!==200||s?a(o,u.status,u.status===200?{code:200,status:2e4,data:u.body}:u.body):(o.writeHead(200,{"content-type":"text/plain; charset=utf-8","x-chatpanel-provider":u.body.provider}),o.end(Xr(u.body)))}if(i==="/v1/engines"&&n.method==="GET"){const e=Number(f.searchParams.get("minCalls"))||void 0;return a(o,200,{ok:!0,engines:Te.list({minCalls:e})})}{const e=/^\/v1\/engines\/(.+)\/(card|entries)$/.exec(i);if(e){const r=decodeURIComponent(e[1]).slice(0,300);if(e[2]==="card"&&n.method==="GET"){const s=Number(f.searchParams.get("minCalls"))||void 0;return a(o,200,{ok:!0,...await Te.get(r,{entries:f.searchParams.get("entries")==="1",minCalls:s})})}if(e[2]==="entries"&&n.method==="POST")try{const s=JSON.parse((await S(n,t.maxBodyBytes)).toString("utf8"))||{},l=s.engine||Hn(r);if(!l)return a(o,400,{error:{message:"model-ledger: engine required",type:"model_ledger_error"}});const u=await Te.append({...s,engine:l,kind:s.kind||"call"});return u.key!==r?a(o,400,{error:{message:`model-ledger: entry is for ${u.key}, not ${r}`,type:"model_ledger_error"}}):a(o,200,{ok:!0,entry:u})}catch(s){return a(o,400,{error:{message:`model-ledger: ${s.message}`,type:"model_ledger_error"}})}}}if(i==="/v1/teams/stream"&&n.method==="GET"){o.writeHead(200,{"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive"});const e=l=>{try{o.write(`data: ${JSON.stringify(l)}
27
27
 
28
- `)}catch{}};e({type:"hello",at:Date.now()});const r=V.watchAll(l=>e({type:"run",id:l.id,removed:!!l.removed})),a=setInterval(()=>{try{o.write(`: keep-alive
28
+ `)}catch{}};e({type:"hello",at:Date.now()});const r=F.watchAll(l=>e({type:"run",id:l.id,removed:!!l.removed})),s=setInterval(()=>{try{o.write(`: keep-alive
29
29
 
30
- `)}catch{}},25e3);o.on("close",()=>{r(),clearInterval(a)});return}if(i==="/v1/teams/runs"&&n.method==="GET")return s(o,200,{ok:!0,runs:V.list({limit:f.searchParams.get("limit")||50,team:f.searchParams.get("team")||""})});if(i==="/v1/teams/runs"&&n.method==="POST")try{const e=JSON.parse((await T(n,t.maxBodyBytes)).toString("utf8"))||{};return s(o,200,{ok:!0,run:V.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(i);if(e){const r=e[1],a=e[2]||"";if(!a&&n.method==="GET"){const l=V.get(r,{events:f.searchParams.get("events")==="1"});return l?s(o,200,{ok:!0,run:l}):s(o,404,{error:{message:`no run ${r}`,type:"not_found"}})}if(!a&&n.method==="DELETE")return V.stop(r),s(o,200,{ok:!0,removed:V.remove(r)});if(a==="/stop"&&n.method==="POST"){const l=V.stop(r);return l?s(o,200,{ok:!0,run:l}):s(o,404,{error:{message:`no run ${r}`,type:"not_found"}})}if(a==="/checkpoint"&&n.method==="GET")try{return s(o,200,{ok:!0,checkpoint:V.checkpoint(r)})}catch(l){return s(o,404,{error:{message:`team run: ${l.message}`,type:"team_error"}})}if((a==="/handoff"||a==="/claim")&&n.method==="POST")try{const l=JSON.parse((await T(n,t.maxBodyBytes)).toString("utf8"))||{},u=a==="/handoff"?V.handoff(r,{taskId:l.taskId,model:l.model,by:l.by,reason:l.reason}):V.claim(r,{client:l.client});return s(o,200,{ok:!0,run:u})}catch(l){return s(o,l.message.startsWith("no ")?404:400,{error:{message:`team run: ${l.message}`,type:"team_error"}})}if(a.startsWith("/threads/")&&n.method==="DELETE")try{return s(o,200,{ok:!0,run:V.removeThread(r,{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")&&n.method==="POST")try{const l=JSON.parse((await T(n,t.maxBodyBytes)).toString("utf8"))||{},u=String(l.by||"person").slice(0,40),S=a==="/answer"?V.answer(r,{threadId:l.threadId,text:l.text,by:u}):a==="/decide"?V.decide(r,{postId:l.postId,status:l.status,by:u}):V.post(r,{threadId:l.threadId,text:l.text,by:u,kind:l.kind,replyTo:l.replyTo});return s(o,200,{ok:!0,run:S})}catch(l){return s(o,l.message.startsWith("no ")?404:400,{error:{message:`team run: ${l.message}`,type:"team_error"}})}if(a==="/events"&&n.method==="POST")try{const l=JSON.parse((await T(n,t.maxBodyBytes)).toString("utf8"))||{};return s(o,200,{ok:!0,run:V.append(r,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"&&n.method==="GET"){if(!V.get(r))return s(o,404,{error:{message:`no run ${r}`,type:"not_found"}});o.writeHead(200,{"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive"});const l=b=>o.write(`data: ${JSON.stringify(b)}
30
+ `)}catch{}},25e3);o.on("close",()=>{r(),clearInterval(s)});return}if(i==="/v1/teams/runs"&&n.method==="GET")return a(o,200,{ok:!0,runs:F.list({limit:f.searchParams.get("limit")||50,team:f.searchParams.get("team")||""})});if(i==="/v1/teams/runs"&&n.method==="POST")try{const e=JSON.parse((await S(n,t.maxBodyBytes)).toString("utf8"))||{};return a(o,200,{ok:!0,run:F.create({id:e.id,client:e.client,team:e.team,request:e.request})})}catch(e){return a(o,400,{error:{message:`team run: ${e.message}`,type:"team_error"}})}{const e=/^\/v1\/teams\/runs\/([a-zA-Z0-9_-]{4,64})(\/events|\/stop|\/answer|\/decide|\/post|\/handoff|\/checkpoint|\/claim|\/threads\/[a-zA-Z0-9_:-]{1,80})?$/.exec(i);if(e){const r=e[1],s=e[2]||"";if(!s&&n.method==="GET"){const l=F.get(r,{events:f.searchParams.get("events")==="1"});return l?a(o,200,{ok:!0,run:l}):a(o,404,{error:{message:`no run ${r}`,type:"not_found"}})}if(!s&&n.method==="DELETE")return F.stop(r),a(o,200,{ok:!0,removed:F.remove(r)});if(s==="/stop"&&n.method==="POST"){const l=F.stop(r);return l?a(o,200,{ok:!0,run:l}):a(o,404,{error:{message:`no run ${r}`,type:"not_found"}})}if(s==="/checkpoint"&&n.method==="GET")try{return a(o,200,{ok:!0,checkpoint:F.checkpoint(r)})}catch(l){return a(o,404,{error:{message:`team run: ${l.message}`,type:"team_error"}})}if((s==="/handoff"||s==="/claim")&&n.method==="POST")try{const l=JSON.parse((await S(n,t.maxBodyBytes)).toString("utf8"))||{},u=s==="/handoff"?F.handoff(r,{taskId:l.taskId,model:l.model,by:l.by,reason:l.reason}):F.claim(r,{client:l.client});return a(o,200,{ok:!0,run:u})}catch(l){return a(o,l.message.startsWith("no ")?404:400,{error:{message:`team run: ${l.message}`,type:"team_error"}})}if(s.startsWith("/threads/")&&n.method==="DELETE")try{return a(o,200,{ok:!0,run:F.removeThread(r,{threadId:s.slice(9),by:"person"})})}catch(l){return a(o,l.message.startsWith("no ")?404:400,{error:{message:`team run: ${l.message}`,type:"team_error"}})}if((s==="/answer"||s==="/decide"||s==="/post")&&n.method==="POST")try{const l=JSON.parse((await S(n,t.maxBodyBytes)).toString("utf8"))||{},u=String(l.by||"person").slice(0,40),k=s==="/answer"?F.answer(r,{threadId:l.threadId,text:l.text,by:u}):s==="/decide"?F.decide(r,{postId:l.postId,status:l.status,by:u}):F.post(r,{threadId:l.threadId,text:l.text,by:u,kind:l.kind,replyTo:l.replyTo});return a(o,200,{ok:!0,run:k})}catch(l){return a(o,l.message.startsWith("no ")?404:400,{error:{message:`team run: ${l.message}`,type:"team_error"}})}if(s==="/events"&&n.method==="POST")try{const l=JSON.parse((await S(n,t.maxBodyBytes)).toString("utf8"))||{};return a(o,200,{ok:!0,run:F.append(r,l.events||[])})}catch(l){return a(o,l.message.startsWith("no run")?404:400,{error:{message:`team run: ${l.message}`,type:"team_error"}})}if(s==="/events"&&n.method==="GET"){if(!F.get(r))return a(o,404,{error:{message:`no run ${r}`,type:"not_found"}});o.writeHead(200,{"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive"});const l=T=>o.write(`data: ${JSON.stringify(T)}
31
31
 
32
- `),u=f.searchParams.has("after")?Number(f.searchParams.get("after")):NaN;let S=Number.isFinite(u)?u:-1;l({seq:-1,type:"hello",at:Date.now(),payload:{run:V.get(r),after:S}});const y=V.watch(r,b=>{b.seq==null?l(b):b.seq>S&&(S=b.seq,l(b))});for(const b of V.eventsSince(r,S))S=b.seq,l(b);const x=setInterval(()=>{try{o.write(`: keep-alive
32
+ `),u=f.searchParams.has("after")?Number(f.searchParams.get("after")):NaN;let k=Number.isFinite(u)?u:-1;l({seq:-1,type:"hello",at:Date.now(),payload:{run:F.get(r),after:k}});const y=F.watch(r,T=>{T.seq==null?l(T):T.seq>k&&(k=T.seq,l(T))});for(const T of F.eventsSince(r,k))k=T.seq,l(T);const x=setInterval(()=>{try{o.write(`: keep-alive
33
33
 
34
- `)}catch{}},25e3);o.on("close",()=>{y(),clearInterval(x)});return}}}if(i==="/v1/memory/list"&&n.method==="GET")return s(o,200,{ok:!0,size:oe.size,memories:oe.list()});if(i==="/v1/memory/recall"&&n.method==="POST")try{const e=JSON.parse((await T(n,t.maxBodyBytes)).toString("utf8"))||{},r=oe.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:oe.size,...r})}catch(e){return s(o,400,{error:{message:`recall failed: ${e.message}`,type:"memory_error"}})}if(i==="/v1/memory/remember"&&n.method==="POST")try{const e=JSON.parse((await T(n,t.maxBodyBytes)).toString("utf8"))||{},r=oe.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:r.action,record:r.record,replaced:r.replaces||null,size:oe.size})}catch(e){return s(o,400,{error:{message:e.message,type:"memory_error"}})}if(i==="/v1/memory/forget"&&n.method==="POST")try{const e=JSON.parse((await T(n,t.maxBodyBytes)).toString("utf8"))||{},{removed:r}=oe.forget(String(e.query||""));return s(o,200,{ok:!0,removed:r,size:oe.size})}catch(e){return s(o,400,{error:{message:e.message,type:"memory_error"}})}if(i==="/v1/memory/sync"&&n.method==="POST")try{const e=JSON.parse((await T(n,t.maxBodyBytes)).toString("utf8"))||{},r=oe.bulk({upserts:Array.isArray(e.upserts)?e.upserts:[],removes:Array.isArray(e.removes)?e.removes:[]});return s(o,200,{ok:!0,...r,memories:oe.list()})}catch(e){return s(o,400,{error:{message:`memory sync failed: ${e.message}`,type:"memory_error"}})}if(i==="/v1/memory/clear"&&n.method==="POST")return s(o,200,{ok:!0,dropped:oe.clear(),size:oe.size});if(i==="/v1/history/clear"&&n.method==="POST"){const e=B.clear();return s(o,200,{ok:!0,dropped:e,size:B.size})}if(i==="/v1/history/search"&&n.method==="POST")try{const e=JSON.parse((await T(n,t.maxBodyBytes)).toString("utf8"))||{},r=B.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:B.size,newest:B.newest,results:r})}catch(e){return s(o,400,{error:{message:`search failed: ${e.message}`,type:"search_error"}})}if(i==="/v1/history/smart-search"&&n.method==="POST")try{const e=JSON.parse((await T(n,t.maxBodyBytes)).toString("utf8"))||{},r=String(e.question||e.query||""),a=Mn(r,{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},u=Math.min(30,Math.max(5,Number(e.limit)||10)*2),S=await Cn(a,x=>B.search(x,{limit:u,...l}),{limit:Math.min(50,Math.max(1,Number(e.limit)||10))}),y=l.type?S:[...S.filter(x=>x.type==="brief"),...S.filter(x=>x.type!=="brief")];return s(o,200,{ok:!0,size:B.size,newest:B.newest,queries:a,results:y})}catch(e){return s(o,400,{error:{message:`smart search failed: ${e.message}`,type:"search_error"}})}if(i==="/v1/research"&&n.method==="POST"){let e;try{e=JSON.parse((await T(n,t.maxBodyBytes)).toString("utf8")||"{}")||{}}catch{return s(o,400,{error:{message:"research: the body must be JSON",type:"invalid_request_error"}})}const r=String(e.question||"").trim();if(!r)return s(o,400,{error:{message:"research: `question` is required",type:"invalid_request_error"}});const a=typeof e.model=="string"?e.model.trim():"";if(a&&!z(n))return s(o,403,{error:{message:"research with a model: extension origin or gateway token required",type:"forbidden"}});const l=`http://127.0.0.1:${n.socket.localPort}`,u=a?async(b,{maxTokens:p=220}={})=>{const _=new AbortController,J=setTimeout(()=>_.abort(),3e4);try{const I=Ye()||Oe(),F=await fetch(`${l}/v1/chat/completions`,{method:"POST",signal:_.signal,headers:{"content-type":"application/json",...I?{Authorization:`Bearer ${I}`}:{},"X-ChatPanel-Client":"research"},body:JSON.stringify({model:a,messages:[{role:"user",content:b}],stream:!1,max_tokens:p,temperature:.2})}),me=await F.json().catch(()=>({}));return F.ok?String(me?.choices?.[0]?.message?.content||""):""}finally{clearTimeout(J)}}:null,S=te.get("identity")?.identity?.value||{},y=e.previous&&typeof e.previous=="object"&&e.previous.plan&&typeof e.previous.plan=="object"?{plan:e.previous.plan,top:typeof e.previous.top=="string"?e.previous.top:null,answer:String(e.previous.answer||"").slice(0,4e3)}:null,x=await nr(r,{store:B,memories:oe.list(),complete:u,previous:y,self:String(S.selfName||"").trim(),excludeId:typeof e.excludeId=="string"?e.excludeId:null,parallel:3});return s(o,200,sr(r,x,{size:B.size,newest:B.newest}))}if(i==="/v1/history/related"&&n.method==="GET"){const e=String(f.searchParams.get("id")||""),r=Math.min(30,Math.max(1,Number(f.searchParams.get("limit"))||5));return s(o,200,{ok:!0,results:B.related(e,{limit:r})})}if(i==="/v1/history/status"&&n.method==="GET")return s(o,200,{ok:!0,size:B.size,newest:B.newest,bytes:B.bytes,lossless:B.lossless?{records:B.lossless.size,newest:B.lossless.newest}:null});if(i==="/v1/observability"&&n.method==="GET"){const e=Math.min(500,Math.max(1,Number(f.searchParams.get("limit"))||200));return s(o,200,{ok:!0,storage:{warm:{records:B.size,bytes:B.bytes,newest:B.newest}},access:dt.snapshot(e)})}if(i==="/v1/observability/access"&&n.method==="POST")try{const e=JSON.parse((await T(n,t.maxBodyBytes)).toString("utf8"))||{},r=dt.push(Wt({ts:Date.now(),...e}));return s(o,200,{ok:!0,event:r})}catch(e){return s(o,400,{error:{message:`access log failed: ${e.message}`,type:"observability_error"}})}if(i==="/v1/history/records"&&n.method==="PUT"){const e=B.lossless;if(!e)return s(o,501,{error:{message:"lossless records need the SQLite warm store",type:"unavailable"}});try{const r=JSON.parse((await T(n,t.maxBodyBytes)).toString("utf8"))||{},a=String(r.host||"").slice(0,80),l=Number(r.at)||Date.now(),u=[];let S=0;const y={upserts:[],removes:[]},x=b=>{if(!b||b.deletedAt){b?.id&&y.removes.push(b.id);return}try{const p=_r(b);p&&y.upserts.push(p)}catch{}};if(Array.isArray(r.records)){const b=e.upsert(r.records,{host:a,at:l});u.push(...b);for(const p of r.records)b.includes(p?.id)&&x(p)}if(Array.isArray(r.entries)){const b=qe(),p=b?Pr((I,F)=>Er(b,{salt:I,iterations:F})):null,_=async I=>{if(!p||!I.blob)return null;const F=await p(I.blob),me=I.blob.compression&&I.blob.compression!=="none"?Ar(Nr,I.blob.compression):null;return $r(I.blob,F,{codec:me})},J=await e.upsertEntries(r.entries,{open:_});u.push(...J.written),S+=J.sealed;for(const I of J.written)x(e.get(I))}return(y.upserts.length||y.removes.length)&&B.bulk(y),u.length&&Ue({ids:u}),s(o,200,{ok:!0,written:u.length,ids:u,sealed:S,size:e.size})}catch(r){return s(o,400,{error:{message:`records failed: ${r.message}`,type:"ingest_error"}})}}if(i==="/v1/events"&&n.method==="POST"){if(!W)return s(o,501,{error:{message:"the event log needs SQLite",type:"unavailable"}});try{const e=JSON.parse((await T(n,t.maxBodyBytes)).toString("utf8"))||{},r=Array.isArray(e)?e:e.events;if(!Array.isArray(r))return s(o,400,{error:{message:"events: an array of CloudEvents (or { events: [...] }) required",type:"invalid_request_error"}});if(r.length>2e3)return s(o,413,{error:{message:"events: at most 2000 per batch",type:"invalid_request_error"}});const a=kr(W,r);return s(o,200,{ok:!0,appended:a.appended,duplicates:a.duplicates,rejected:a.rejected,cursor:W.cursor()})}catch(e){return s(o,400,{error:{message:`events: ${e?.message||e}`,type:"invalid_request_error"}})}}if(i==="/v1/events/cursor"&&n.method==="GET")return W?s(o,200,{ok:!0,cursor:W.cursor(),count:W.count()}):s(o,501,{error:{message:"the event log needs SQLite",type:"unavailable"}});if(i==="/v1/events/stats"&&n.method==="GET"){if(!W)return s(o,501,{error:{message:"the event log needs SQLite",type:"unavailable"}});const e=Sr(W.all());return s(o,200,{ok:!0,stats:e,year:Tr(e)})}if(i==="/v1/events"&&n.method==="GET"){if(!W)return s(o,501,{error:{message:"the event log needs SQLite",type:"unavailable"}});let e={};try{e=At(JSON.parse(f.searchParams.get("cursor")||"{}"))}catch{return s(o,400,{error:{message:"events: cursor must be JSON { host: seq }",type:"invalid_request_error"}})}const r=W.since(e,{limit:Number(f.searchParams.get("limit"))||void 0,host:f.searchParams.get("host")||null});return s(o,200,{ok:!0,events:r.events.map(a=>tt(a)),cursor:r.cursor,more:r.more})}if(i==="/v1/events/stream"&&n.method==="GET"){if(!W)return s(o,501,{error:{message:"the event log needs SQLite",type:"unavailable"}});let e=null;if(f.searchParams.has("cursor"))try{e=At(JSON.parse(f.searchParams.get("cursor")||"{}"))}catch{e={}}if(o.writeHead(200,{"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive"}),o.write(`event: hello
34
+ `)}catch{}},25e3);o.on("close",()=>{y(),clearInterval(x)});return}}}if(i==="/v1/memory/list"&&n.method==="GET")return a(o,200,{ok:!0,size:re.size,memories:re.list()});if(i==="/v1/memory/recall"&&n.method==="POST")try{const e=JSON.parse((await S(n,t.maxBodyBytes)).toString("utf8"))||{},r=re.recall({text:String(e.text||""),scopes:Array.isArray(e.scopes)&&e.scopes.length?e.scopes.map(String):["global"],limit:Number(e.limit)||0,maxChars:Number(e.maxChars)||0});return a(o,200,{ok:!0,size:re.size,...r})}catch(e){return a(o,400,{error:{message:`recall failed: ${e.message}`,type:"memory_error"}})}if(i==="/v1/memory/remember"&&n.method==="POST")try{const e=JSON.parse((await S(n,t.maxBodyBytes)).toString("utf8"))||{},r=re.remember({text:String(e.text||""),kind:e.kind?String(e.kind):"fact",scope:e.scope?String(e.scope):"global",tags:Array.isArray(e.tags)?e.tags.map(String):[],source:{via:String(e.source?.via||"mcp"),surface:String(e.source?.surface||"mcp"),agent:String(e.source?.agent||""),ref:String(e.source?.ref||"")}});return a(o,200,{ok:!0,action:r.action,record:r.record,replaced:r.replaces||null,size:re.size})}catch(e){return a(o,400,{error:{message:e.message,type:"memory_error"}})}if(i==="/v1/memory/forget"&&n.method==="POST")try{const e=JSON.parse((await S(n,t.maxBodyBytes)).toString("utf8"))||{},{removed:r}=re.forget(String(e.query||""));return a(o,200,{ok:!0,removed:r,size:re.size})}catch(e){return a(o,400,{error:{message:e.message,type:"memory_error"}})}if(i==="/v1/memory/sync"&&n.method==="POST")try{const e=JSON.parse((await S(n,t.maxBodyBytes)).toString("utf8"))||{},r=re.bulk({upserts:Array.isArray(e.upserts)?e.upserts:[],removes:Array.isArray(e.removes)?e.removes:[]});return a(o,200,{ok:!0,...r,memories:re.list()})}catch(e){return a(o,400,{error:{message:`memory sync failed: ${e.message}`,type:"memory_error"}})}if(i==="/v1/memory/clear"&&n.method==="POST")return a(o,200,{ok:!0,dropped:re.clear(),size:re.size});if(i==="/v1/history/clear"&&n.method==="POST"){const e=M.clear();return a(o,200,{ok:!0,dropped:e,size:M.size})}if(i==="/v1/history/search"&&n.method==="POST")try{const e=JSON.parse((await S(n,t.maxBodyBytes)).toString("utf8"))||{},r=M.search(String(e.query||""),{limit:Number(e.limit)||10,offset:Math.max(0,Number(e.offset)||0),type:e.type?String(e.type):null,since:e.since!=null?Number(e.since):null,before:e.before!=null?Number(e.before):null});return a(o,200,{ok:!0,size:M.size,newest:M.newest,results:r})}catch(e){return a(o,400,{error:{message:`search failed: ${e.message}`,type:"search_error"}})}if(i==="/v1/history/smart-search"&&n.method==="POST")try{const e=JSON.parse((await S(n,t.maxBodyBytes)).toString("utf8"))||{},r=String(e.question||e.query||""),s=Mn(r,{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},u=Math.min(30,Math.max(5,Number(e.limit)||10)*2),k=await Cn(s,x=>M.search(x,{limit:u,...l}),{limit:Math.min(50,Math.max(1,Number(e.limit)||10))}),y=l.type?k:[...k.filter(x=>x.type==="brief"),...k.filter(x=>x.type!=="brief")];return a(o,200,{ok:!0,size:M.size,newest:M.newest,queries:s,results:y})}catch(e){return a(o,400,{error:{message:`smart search failed: ${e.message}`,type:"search_error"}})}if(i==="/v1/research"&&n.method==="POST"){let e;try{e=JSON.parse((await S(n,t.maxBodyBytes)).toString("utf8")||"{}")||{}}catch{return a(o,400,{error:{message:"research: the body must be JSON",type:"invalid_request_error"}})}const r=String(e.question||"").trim();if(!r)return a(o,400,{error:{message:"research: `question` is required",type:"invalid_request_error"}});const s=typeof e.model=="string"?e.model.trim():"";if(s&&!G(n))return a(o,403,{error:{message:"research with a model: extension origin or gateway token required",type:"forbidden"}});const l=`http://127.0.0.1:${n.socket.localPort}`,u=s?async(T,{maxTokens:p=220}={})=>{const _=new AbortController,N=setTimeout(()=>_.abort(),3e4);try{const j=Ye()||_e(),Y=await fetch(`${l}/v1/chat/completions`,{method:"POST",signal:_.signal,headers:{"content-type":"application/json",...j?{Authorization:`Bearer ${j}`}:{},"X-ChatPanel-Client":"research"},body:JSON.stringify({model:s,messages:[{role:"user",content:T}],stream:!1,max_tokens:p,temperature:.2})}),ae=await Y.json().catch(()=>({}));return Y.ok?String(ae?.choices?.[0]?.message?.content||""):""}finally{clearTimeout(N)}}:null,k=oe.get("identity")?.identity?.value||{},y=e.previous&&typeof e.previous=="object"&&e.previous.plan&&typeof e.previous.plan=="object"?{plan:e.previous.plan,top:typeof e.previous.top=="string"?e.previous.top:null,answer:String(e.previous.answer||"").slice(0,4e3)}:null,x=await nr(r,{store:M,memories:re.list(),complete:u,previous:y,self:String(k.selfName||"").trim(),excludeId:typeof e.excludeId=="string"?e.excludeId:null,parallel:3});return a(o,200,ar(r,x,{size:M.size,newest:M.newest}))}if(i==="/v1/history/related"&&n.method==="GET"){const e=String(f.searchParams.get("id")||""),r=Math.min(30,Math.max(1,Number(f.searchParams.get("limit"))||5));return a(o,200,{ok:!0,results:M.related(e,{limit:r})})}if(i==="/v1/history/status"&&n.method==="GET")return a(o,200,{ok:!0,size:M.size,newest:M.newest,bytes:M.bytes,lossless:M.lossless?{records:M.lossless.size,newest:M.lossless.newest}:null});if(i==="/v1/observability"&&n.method==="GET"){const e=Math.min(500,Math.max(1,Number(f.searchParams.get("limit"))||200));return a(o,200,{ok:!0,storage:{warm:{records:M.size,bytes:M.bytes,newest:M.newest}},access:dt.snapshot(e)})}if(i==="/v1/observability/access"&&n.method==="POST")try{const e=JSON.parse((await S(n,t.maxBodyBytes)).toString("utf8"))||{},r=dt.push(Wt({ts:Date.now(),...e}));return a(o,200,{ok:!0,event:r})}catch(e){return a(o,400,{error:{message:`access log failed: ${e.message}`,type:"observability_error"}})}if(i==="/v1/history/records"&&n.method==="PUT"){const e=M.lossless;if(!e)return a(o,501,{error:{message:"lossless records need the SQLite warm store",type:"unavailable"}});try{const r=JSON.parse((await S(n,t.maxBodyBytes)).toString("utf8"))||{},s=String(r.host||"").slice(0,80),l=Number(r.at)||Date.now(),u=[];let k=0,y={},x=[],T=[];const p={upserts:[],removes:[]},_=N=>{if(!N||N.deletedAt){N?.id&&p.removes.push(N.id);return}try{const j=_r(N);j&&p.upserts.push(j)}catch{}};if(Array.isArray(r.records)){const N=e.write(r.records,{host:s,at:l,merge:r.merge===!0});u.push(...N.written),y=N.revs,x=N.conflicts,T=N.merged;for(const j of N.written)_(e.get(j))}if(Array.isArray(r.entries)){const N=qe(),j=N?Pr((V,z)=>Er(N,{salt:V,iterations:z})):null,Y=async V=>{if(!j||!V.blob)return null;const z=await j(V.blob),Oe=V.blob.compression&&V.blob.compression!=="none"?Ar(Nr,V.blob.compression):null;return $r(V.blob,z,{codec:Oe})},ae=await e.upsertEntries(r.entries,{open:Y});u.push(...ae.written),k+=ae.sealed;for(const V of ae.written)_(e.get(V))}return(p.upserts.length||p.removes.length)&&M.bulk(p),u.length&&Ve({ids:u}),a(o,200,{ok:!0,written:u.length,ids:u,revs:y,conflicts:x,merged:T,sealed:k,size:e.size,rev:e.rev})}catch(r){return a(o,400,{error:{message:`records failed: ${r.message}`,type:"ingest_error"}})}}if(i==="/v1/events"&&n.method==="POST"){if(!W)return a(o,501,{error:{message:"the event log needs SQLite",type:"unavailable"}});try{const e=JSON.parse((await S(n,t.maxBodyBytes)).toString("utf8"))||{},r=Array.isArray(e)?e:e.events;if(!Array.isArray(r))return a(o,400,{error:{message:"events: an array of CloudEvents (or { events: [...] }) required",type:"invalid_request_error"}});if(r.length>2e3)return a(o,413,{error:{message:"events: at most 2000 per batch",type:"invalid_request_error"}});const s=kr(W,r);return a(o,200,{ok:!0,appended:s.appended,duplicates:s.duplicates,rejected:s.rejected,cursor:W.cursor()})}catch(e){return a(o,400,{error:{message:`events: ${e?.message||e}`,type:"invalid_request_error"}})}}if(i==="/v1/events/cursor"&&n.method==="GET")return W?a(o,200,{ok:!0,cursor:W.cursor(),count:W.count()}):a(o,501,{error:{message:"the event log needs SQLite",type:"unavailable"}});if(i==="/v1/events/stats"&&n.method==="GET"){if(!W)return a(o,501,{error:{message:"the event log needs SQLite",type:"unavailable"}});const e=Sr(W.all());return a(o,200,{ok:!0,stats:e,year:Tr(e)})}if(i==="/v1/events"&&n.method==="GET"){if(!W)return a(o,501,{error:{message:"the event log needs SQLite",type:"unavailable"}});let e={};try{e=At(JSON.parse(f.searchParams.get("cursor")||"{}"))}catch{return a(o,400,{error:{message:"events: cursor must be JSON { host: seq }",type:"invalid_request_error"}})}const r=W.since(e,{limit:Number(f.searchParams.get("limit"))||void 0,host:f.searchParams.get("host")||null});return a(o,200,{ok:!0,events:r.events.map(s=>tt(s)),cursor:r.cursor,more:r.more})}if(i==="/v1/events/stream"&&n.method==="GET"){if(!W)return a(o,501,{error:{message:"the event log needs SQLite",type:"unavailable"}});let e=null;if(f.searchParams.has("cursor"))try{e=At(JSON.parse(f.searchParams.get("cursor")||"{}"))}catch{e={}}if(o.writeHead(200,{"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive"}),o.write(`event: hello
35
35
  data: ${JSON.stringify({cursor:W.cursor(),count:W.count(),version:K})}
36
36
 
37
- `),be.add(o),n.on("close",()=>be.delete(o)),e){let r={cursor:e,more:!0};for(;r.more;){r=W.since(r.cursor);for(const a of r.events)o.write(`event: cloudevent
38
- data: ${JSON.stringify(tt(a))}
37
+ `),be.add(o),n.on("close",()=>be.delete(o)),e){let r={cursor:e,more:!0};for(;r.more;){r=W.since(r.cursor);for(const s of r.events)o.write(`event: cloudevent
38
+ data: ${JSON.stringify(tt(s))}
39
39
 
40
- `)}}return}if(i==="/v1/link"&&n.method==="GET")return s(o,200,c?{enabled:!0,...c.status()}:{enabled:!1,devices:[],pairing:null});if(i==="/v1/link/pair"&&n.method==="POST"){if(!c)return s(o,409,{error:{message:"link is off (link.enabled: false)",type:"disabled"}});if(n.headers["x-chatpanel-link-device"])return s(o,403,{error:{message:"a paired phone cannot pair another",type:"forbidden"}});let e={};try{e=JSON.parse((await T(n,t.maxBodyBytes)).toString("utf8")||"{}")||{}}catch{e={}}try{return s(o,200,await c.pair({name:String(e?.name||"").slice(0,60)||void 0}))}catch(r){return s(o,502,{error:{message:r?.message||String(r),type:"relay"}})}}if(i.startsWith("/v1/link/devices/")&&n.method==="DELETE"){if(!c)return s(o,404,{error:{message:"link is off",type:"disabled"}});const e=decodeURIComponent(i.slice(17));return await c.remove(e)?s(o,200,{ok:!0}):s(o,404,{error:{message:"no such device",type:"not_found"}})}if(i==="/v1/browser"&&n.method==="GET")return s(o,200,d.status());if(i==="/v1/browser/stream"&&n.method==="GET"){d.stream(n,o);return}if((i==="/v1/browser/call"||i==="/v1/browser/announce"||i==="/v1/browser/result")&&n.method==="POST"){let e;try{e=JSON.parse((await T(n,t.maxBodyBytes)).toString("utf8"))}catch{return s(o,400,{error:{message:"browser: body must be JSON",type:"invalid_request"}})}const r=i==="/v1/browser/call"?await d.call(e,n):i==="/v1/browser/announce"?d.announce(e):d.result(e);return s(o,r.status,r.body)}if(i==="/v1/history/stream"&&n.method==="GET"){const e=B.lossless;if(!e)return s(o,501,{error:{message:"lossless records need the SQLite warm store",type:"unavailable"}});o.writeHead(200,{"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive"}),o.write(`event: hello
41
- data: ${JSON.stringify({newest:e.newest,size:e.size,version:K,prefsRevision:te.revision})}
40
+ `)}}return}if(i==="/v1/link"&&n.method==="GET")return a(o,200,c?{enabled:!0,...c.status()}:{enabled:!1,devices:[],pairing:null});if(i==="/v1/link/pair"&&n.method==="POST"){if(!c)return a(o,409,{error:{message:"link is off (link.enabled: false)",type:"disabled"}});if(n.headers["x-chatpanel-link-device"])return a(o,403,{error:{message:"a paired phone cannot pair another",type:"forbidden"}});let e={};try{e=JSON.parse((await S(n,t.maxBodyBytes)).toString("utf8")||"{}")||{}}catch{e={}}try{return a(o,200,await c.pair({name:String(e?.name||"").slice(0,60)||void 0}))}catch(r){return a(o,502,{error:{message:r?.message||String(r),type:"relay"}})}}if(i.startsWith("/v1/link/devices/")&&n.method==="DELETE"){if(!c)return a(o,404,{error:{message:"link is off",type:"disabled"}});const e=decodeURIComponent(i.slice(17));return await c.remove(e)?a(o,200,{ok:!0}):a(o,404,{error:{message:"no such device",type:"not_found"}})}if(i==="/v1/browser"&&n.method==="GET")return a(o,200,d.status());if(i==="/v1/browser/stream"&&n.method==="GET"){d.stream(n,o);return}if((i==="/v1/browser/call"||i==="/v1/browser/announce"||i==="/v1/browser/result")&&n.method==="POST"){let e;try{e=JSON.parse((await S(n,t.maxBodyBytes)).toString("utf8"))}catch{return a(o,400,{error:{message:"browser: body must be JSON",type:"invalid_request"}})}const r=i==="/v1/browser/call"?await d.call(e,n):i==="/v1/browser/announce"?d.announce(e):d.result(e);return a(o,r.status,r.body)}if(i==="/v1/history/stream"&&n.method==="GET"){const e=M.lossless;if(!e)return a(o,501,{error:{message:"lossless records need the SQLite warm store",type:"unavailable"}});o.writeHead(200,{"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive"}),o.write(`event: hello
41
+ data: ${JSON.stringify({newest:e.newest,rev:e.rev,size:e.size,version:K,prefsRevision:oe.revision})}
42
42
 
43
- `),he.add(o),n.on("close",()=>he.delete(o));return}if(i==="/v1/history/records"&&n.method==="GET"){const e=B.lossless;if(!e)return s(o,501,{error:{message:"lossless records need the SQLite warm store",type:"unavailable"}});const r=e.since({since:Number(f.searchParams.get("since"))||0,cursor:f.searchParams.get("cursor")||"",limit:Number(f.searchParams.get("limit"))||200,kind:f.searchParams.get("kind")||null});return s(o,200,{ok:!0,...r,size:e.size,newest:e.newest})}if(i==="/v1/history/list"&&n.method==="GET"){const e=Math.min(500,Math.max(1,Number(f.searchParams.get("limit"))||50)),r=Math.max(0,Number(f.searchParams.get("offset"))||0),a=f.searchParams.get("type")||null;return s(o,200,{ok:!0,...B.list({limit:e,offset:r,type:a})})}if(i==="/v1/history/get"&&n.method==="GET"){const e=f.searchParams.get("maxChars")!=null?Math.max(1,Number(f.searchParams.get("maxChars"))||0):null,r=Math.max(0,Number(f.searchParams.get("offset"))||0),a=B.get(String(f.searchParams.get("id")||""),{maxChars:e,offset:r});return a?s(o,200,{ok:!0,record:a}):s(o,404,{error:{message:"no such record",type:"not_found"}})}if(i==="/v1/history/key"&&n.method==="GET")return s(o,200,{ok:!0,hasKey:Pt()});if(i==="/v1/history/key"&&n.method==="POST")try{const e=JSON.parse((await T(n,t.maxBodyBytes)).toString("utf8"))||{};e.passphrase?Xo(String(e.passphrase)):qo();const r=e.passphrase?await ot(B,String(e.passphrase)):{ok:!0,ingested:0};return r.ok&&r.whole&&Ue(),s(o,200,{ok:!0,hasKey:!!e.passphrase,...r})}catch(e){return s(o,400,{error:{message:`key handoff failed: ${e.message}`,type:"key_error"}})}if(i==="/v1/history/ingest-backup"&&n.method==="POST")try{const e=await ot(B,qe());return e.ok&&e.whole&&Ue(),s(o,e.ok?200:409,e)}catch(e){return s(o,400,{error:{message:`backup ingest failed: ${e.message}`,type:"ingest_error"}})}if(i==="/ner"){if(n.method==="GET"){const e=await no(t);return s(o,e.ok?200:503,e)}if(n.method==="POST"){if(await Le(t),A.state()!=="off"){if(!A.isReady()){const r=A.health();return s(o,503,{error:{message:r.state==="error"?`NER model failed to load: ${r.error||"unknown error"}`:`NER model is ${r.state} — not ready yet`,type:r.state==="error"?"ner_error":"ner_loading"},state:r.state,model:r.model})}try{const r=await T(n,t.maxBodyBytes);let a="";try{a=JSON.parse(r.toString("utf8"))?.text||""}catch{}const l=await A.detect(a);return s(o,200,{entities:l})}catch(r){return s(o,500,{error:{message:`NER error: ${r.message}`,type:"ner_error"}})}}const e=ro(t);if(!e){const r=A.modelOnDisk(t.ner?.model||void 0);return s(o,503,{error:{message:r?"the bundled detector could not start — deterministic-only redaction":"no entity detector is installed — deterministic-only redaction (install one from Gateway settings)",type:r?"ner_error":"ner_not_installed"},state:A.state(),model:t.ner?.model||null})}try{const r=await T(n,t.maxBodyBytes),a=await Ie(e,{method:"POST",headers:{"content-type":"application/json"},body:r,signal:AbortSignal.timeout(8e3)}),l=await a.text();return o.writeHead(a.status,{"content-type":"application/json"}),o.end(l)}catch(r){return s(o,502,{error:{message:`NER unreachable: ${r.message}`,type:"ner_unreachable"}})}}}if(i==="/redact"&&n.method==="POST"){let e="";try{e=String(JSON.parse((await T(n,t.maxBodyBytes)).toString("utf8"))?.text||"")}catch{e=""}if(!e)return s(o,200,{text:"",count:0,sanitized:0,entities:[],detector:mt(t)});try{let r=e;const a=await we(t.pro?.entitlementToken);await Le(t);const l=await De([Qe(()=>r,u=>{r=u})],t.redaction,{isPro:a});return s(o,200,{text:r,count:l.count||0,sanitized:l.sanitized||0,tier:t.redaction?.tier==="full"?"full":"basic",entities:to(l.vault,"types")||[],detector:mt(t)})}catch(r){return s(o,500,{error:{message:`redaction preview failed: ${r.message}`,type:"redact_error"}})}}if(i==="/ner/models"){if(n.method==="GET"){const e=A.health().model||t.ner?.model||null,r=Math.round(Nt.totalmem()/1048576),a=rn(Ct,{totalRamMB:r}).map(l=>({...l,installed:A.modelOnDisk(l.id)}));for(const l of[e,...A.modelsOnDisk()])!l||a.some(u=>u.id===l)||a.push({id:l,label:l,lang:"—",custom:!0,installed:A.modelOnDisk(l),note:"Custom model (from Hugging Face)."});return s(o,200,{active:e,companions:A.companions(),union:Array.isArray(t.ner?.union)?t.ner.union:[],machine:{totalRamMB:r},skipped:Yo(),recommendation:$t(a,{totalRamMB:r},[]),state:A.state(),progress:A.progress(),available:a})}if(n.method==="POST"){let e=null;try{e=JSON.parse((await T(n,t.maxBodyBytes)).toString("utf8"))}catch{e=null}if(e&&e.recommended===!0){const a=Math.round(Nt.totalmem()/1048576),l=$t(Ct.map(u=>({...u,installed:A.modelOnDisk(u.id)})),{totalRamMB:a},[]);e={id:l.primary,union:l.union}}const r=e&&typeof e.id=="string"?e.id.trim():null;if(e&&Array.isArray(e.union)){const a=[...new Set(e.union.map(u=>String(u||"").trim()).filter(Boolean))];for(const u of a)if(!(Dt(u)||Rt(u)))return s(o,400,{error:{message:`unknown or invalid model id in union: ${u}`,type:"bad_model"}});const l=r||t.ner?.model||A.health().model;t.ner=t.ner||{allowDownload:!0,enableFullTier:!0},t.ner.union=a.filter(u=>u!==l),r&&Ut(t,r);try{pe(t,ne())}catch{}return(async()=>{r&&await A.setModel(r,{onLog:S=>console.log(S)});const u=Qo(t.ner,{log:S=>console.log(S)});for(const S of A.companions())u.includes(S.model)||await A.removeCompanion(S.model);for(const S of u)await A.addCompanion(S,{onLog:y=>console.log(y),allowDownload:t.ner.allowDownload!==!1});A.setUnionOrder(u)})().catch(u=>console.log(`[ner] union update failed: ${u.message}`)),s(o,202,{accepted:!0,active:l,union:t.ner.union,companions:A.companions(),state:A.state()})}if(!r||!(Dt(r)||Rt(r)))return s(o,400,{error:{message:"unknown or invalid model id",type:"bad_model"}});Ut(t,r);try{pe(t,ne())}catch{}return A.setModel(r,{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:r,state:A.state(),progress:A.progress()})}}if(i==="/stt/models"){if(n.method==="GET"){const e=D.health().model||t.stt?.model||Je,r=nn.map(a=>({...a,installed:D.modelOnDisk(a.id)}));return e&&!r.some(a=>a.id===e)&&r.push({id:e,label:e,lang:"—",tier:"custom",custom:!0,installed:D.modelOnDisk(e),note:"Custom model (from Hugging Face)."}),s(o,200,{active:e,state:D.state(),progress:D.progress(),available:r,dtype:t.stt?.dtype||"auto",loadedDtype:D.health().dtype,runtime:D.health().runtime,dtypes:ln})}if(n.method==="POST"){let e=null;try{e=JSON.parse((await T(n,t.maxBodyBytes)).toString("utf8"))}catch{e=null}const r=e&&typeof e.id=="string"?e.id.trim():null;if(!r||!(sn(r)||an(r)))return s(o,400,{error:{message:"unknown or invalid model id",type:"bad_model"}});const a=typeof e.dtype=="string"&&dn(e.dtype)?e.dtype:void 0;t.stt?t.stt.model=r:t.stt={enabled:!0,model:r,allowDownload:!0},a&&(t.stt.dtype=a==="auto"?null:a);try{pe(t,ne())}catch{}return D.setModel(r,{onLog:l=>console.log(l),dtype:a||t.stt.dtype||"auto",warmMs:t.stt.warmMs,speaker:ht(t,{installing:!0})}),s(o,202,{accepted:!0,active:r,dtype:t.stt.dtype||"auto",state:D.state(),progress:D.progress(),speaker:{id:P.activeModel(),state:P.state(),installed:P.modelOnDisk()}})}}if(i==="/diarize/model"){if(n.method==="GET"){const e=P.activeModel(),r=qr.map(a=>({...a,installed:P.modelOnDisk(a.id)})).sort((a,l)=>(l.id===e?1:0)-(a.id===e?1:0));return s(o,200,{active:e,state:P.state(),threshold:P.activeThreshold(),progress:P.progress(),available:r})}if(n.method==="POST"){let e=null;try{e=JSON.parse((await T(n,t.maxBodyBytes)).toString("utf8")||"{}")}catch{e=null}const r=e&&typeof e.id=="string"?e.id.trim():null;if(r){if(!Bt(r))return s(o,400,{error:{message:"unknown speaker model id",type:"bad_model"}});if(!await P.setModel(r,{log:a=>console.log(a)}))return s(o,409,{error:{message:"a diarizing session is using the current speaker model — try again when it ends",type:"model_busy"}});t.stt?t.stt.diarizeModel=r:t.stt={enabled:!0,diarize:!0,diarizeModel:r};try{pe(t,ne())}catch{}return P.init({allowDownload:t.stt?.allowDownload!==!1,warmMs:t.stt?.warmMs,onLog:a=>console.log(a)}),s(o,202,{accepted:!0,active:P.activeModel(),state:P.state(),threshold:P.activeThreshold(),progress:P.progress()})}return P.download({onLog:a=>console.log(a)}),s(o,202,{accepted:!0,active:P.activeModel(),state:P.state(),threshold:P.activeThreshold(),progress:P.progress()})}}if(i==="/tts/models"){if(n.method==="GET"){const e=$.health().model||t.tts?.model||Gt(nt()),r=nt(),a=It.find(u=>u.id===e)||null,l=It.map(u=>({...u,installed:$.modelOnDisk(u.id),unavailable:u.requiresNative&&!r?"needs the npm gateway — the standalone binary cannot load this engine":void 0}));return e&&!l.some(u=>u.id===e)&&l.push({id:e,label:e,lang:"—",tier:"custom",custom:!0,installed:$.modelOnDisk(e),note:"Custom model (from Hugging Face)."}),s(o,200,{active:e,state:$.state(),progress:$.progress(),available:l,voice:t.tts?.voice||(He(e)==="pocket-tts"?ze:fe),arch:$.arch(),supportsVoices:$.arch()?$.supportsVoices():a?a.arch==="style-tts2"&&!!a.voices:!0,supportsCustomVoices:$.arch()?$.supportsCustomVoices():!!a?.customVoices,sampleRate:$.sampleRate(),voices:$.isPocket()||!$.arch()&&He(e)==="pocket-tts"?($.builtinVoices().length?$.builtinVoices():fn).map(u=>({id:u,label:u[0].toUpperCase()+u.slice(1),lang:"en",installed:$.builtinVoices().includes(u)})):$.arch()&&$.arch()!=="style-tts2"?[]:cn.map(u=>({...u,installed:$.voiceOnDisk(u.id,e)})),dtype:t.tts?.dtype||"auto",loadedDtype:$.health().dtype,runtime:$.health().runtime,dtypes:pn})}if(n.method==="POST"){let e=null;try{e=JSON.parse((await T(n,t.maxBodyBytes)).toString("utf8"))}catch{e=null}const r=e&&typeof e.id=="string"?e.id.trim():null;if(r&&!(un(r)||mn(r)))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 u=Z.parseCustomVoice(a);if(!(u?!!Z.getVoice(u):Ge(a)||jt(a)&&Lt(a)))return s(o,400,{error:{message:"unknown or invalid voice",type:"bad_voice"}})}const l=e&&typeof e.dtype=="string"&&hn(e.dtype)?e.dtype:void 0;if(t.tts||(t.tts={enabled:!0,model:Jt,voice:fe,allowDownload:!0}),r&&(t.tts.model=r),a&&(t.tts.voice=a),r&&!a){const u=yn(r),S=Z.parseCustomVoice(t.tts.voice||""),y=!!(S&&Z.getVoice(S));if(u&&!y)if(He(r)==="pocket-tts")t.tts.voice=ze;else{const b=Z.listVoices();t.tts.voice=b.length?`custom:${b[0].id}`:""}else!u&&y&&(t.tts.voice=fe);const x=He(r)==="pocket-tts";x&&!Z.parseCustomVoice(t.tts.voice||"")&&!Ge(t.tts.voice)&&(t.tts.voice=ze),!x&&Ge(t.tts.voice)&&(t.tts.voice=fe)}l&&(t.tts.dtype=l==="auto"?null:l);try{pe(t,ne())}catch{}return r&&$.setModel(r,{onLog:u=>console.log(u),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:$.state(),progress:$.progress()})}}if(i==="/tts/voices"){if(n.method==="GET")return s(o,200,{voices:Z.listVoices(),usable:$.supportsCustomVoices(),embedder:P.activeModel(),embedderReady:P.isReady()});if(n.method==="POST"){let e=null;try{e=JSON.parse((await T(n,t.maxBodyBytes)).toString("utf8"))}catch{e=null}const r=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(!Z.getVoice(l))return s(o,404,{error:{message:"no such saved voice",type:"bad_voice"}});if(!a){if(!r)return s(o,400,{error:{message:"a name is required",type:"bad_request"}});try{return s(o,200,{...Z.renameVoice(l,r),usable:$.supportsCustomVoices()})}catch(u){return s(o,400,{error:{message:u.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(!r)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 p=P.download({onLog:I=>console.log(I)}),_=Symbol("timeout"),J=await Promise.race([p.then(()=>null).catch(I=>I),new Promise(I=>setTimeout(()=>I(_),qn))]);if(J===_||!P.isReady())return s(o,503,{error:{message:J===_?"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 u=Float32Array.from(a),S=await P.embed(u);let y=null;try{const p=await $.pocketForEncoding({allowDownload:t.tts?.allowDownload!==!1,log:_=>console.log(_)});p&&(y=await p.encodeVoice(es(u,16e3,24e3)))}catch(p){console.log(`[tts] pocket conditioning unavailable for this voice (${p.message})`)}const x=l?Z.replaceVoice(l,{vec:S,pocket:y}):Z.saveVoice({name:r,vec:S,pocket:y}),b=l&&r&&r!==x.name?Z.renameVoice(l,r):x;return console.log(`[tts] ${l?"re-recorded":"saved"} custom voice "${b.name}" (${(x.kinds||[]).join(" + ")}, sample discarded)`),s(o,l?200:201,{...x,...b,usable:$.supportsCustomVoices()})}catch(u){return s(o,400,{error:{message:u.message,type:"save_failed"}})}}if(n.method==="DELETE"){const e=f.searchParams.get("id")||"",r=Z.deleteVoice(e);if(r&&t.tts?.voice===`custom:${e}`){const a=Z.listVoices();t.tts.voice=a.length?`custom:${a[0].id}`:fe;try{pe(t,ne())}catch{}}return s(o,200,{deleted:r,voice:t.tts?.voice})}}if((i==="/tts"||i==="/v1/audio/speech")&&n.method==="POST"){if(t.tts?.enabled===!1)return s(o,503,{error:{message:"tts is disabled in gateway config",type:"tts_disabled"}});let e=null;try{e=JSON.parse((await T(n,t.maxBodyBytes)).toString("utf8"))}catch{e=null}const r=e&&typeof(e.input??e.text)=="string"?String(e.input??e.text).trim():"";if(!r)return s(o,400,{error:{message:"text is required",type:"bad_request"}});if(r.length>zt)return s(o,413,{error:{message:`text too long (max ${zt} chars)`,type:"too_long"}});const a=Number.isFinite(e.speed)?Math.min(2,Math.max(.5,e.speed)):1,l=gn(t),u=e&&typeof e.voice=="string"&&e.voice.trim()?e.voice.trim():null,S=u||(l?l.voice:t.tts?.voice||fe);if(l&&!bn(S))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:ye,contentType:U,redacted:Ke}=await wn({dest:l,text:r,voice:S,speed:a,auth:n.headers.authorization||n.headers["xi-api-key"]||"",redaction:t.redaction,isPro:await we(t.pro?.entitlementToken)});return o.writeHead(200,{"Content-Type":U,"Content-Length":String(ye.length),"Cache-Control":"no-store","X-Tts-Provider":l.kind,"X-Tts-Redacted":String(Ke)}),o.end(ye)}if(!await $.ready({onLog:ye=>console.log(ye),allowDownload:t.tts?.allowDownload!==!1,model:t.tts?.model||Gt(nt()),dtype:t.tts?.dtype||"auto"}))return s(o,503,{error:{message:$.health().error||"tts model not ready",type:"tts_unavailable"}});const b=vn({requested:u,configured:S,engine:$,voices:Z,isPocketVoice:Ge,isKnownVoice:jt,isValidVoiceId:Lt,defaultVoice:fe,defaultPocketVoice:ze});if(!b.ok)return s(o,b.status,{error:{message:b.message,type:b.type}});const{voice:p,customId:_,speakerEmbedding:J}=b,I=await $.synth(r,{voice:p,speed:a,speakerEmbedding:J}),F=$.sampleRate(),me=y==="pcm"?Buffer.from(new Float32Array(I).buffer):$.toWav(I,F);return o.writeHead(200,{"Content-Type":y==="pcm"?"application/octet-stream":"audio/wav","Content-Length":String(me.length),"Cache-Control":"no-store","X-Tts-Sample-Rate":String(F),..._||$.isPocket()||$.supportsVoices()?{"X-Tts-Voice":p}:{}}),o.end(me)}catch(x){return s(o,500,{error:{message:x.message,type:"tts_failed"}})}}if(i==="/v1/audio/transcriptions"&&n.method==="POST"){if(t.stt?.enabled===!1)return s(o,403,{error:{message:"STT disabled in gateway config",type:"stt_disabled"}});let e;try{e=tn(await T(n,Math.max(t.maxBodyBytes||0,64*1024*1024)),n.headers["content-type"])}catch(p){return s(o,p.code===413?413:415,{error:{message:p.message,type:"bad_request"}})}const r=p=>e.find(_=>_.name===p&&!_.filename)?.data.toString("utf8").trim()||"",a=e.find(p=>p.name==="file"&&p.filename)||e.find(p=>p.filename);if(!a?.data?.length)return s(o,400,{error:{message:"a `file` part is required",type:"bad_request"}});let l;try{l=await on(a.data)}catch(p){return s(o,p.code===415?415:500,{error:{message:p.message,type:"unsupported_media"}})}const u=["json","text","verbose_json"].includes(r("response_format"))?r("response_format"):"json",S=rt(t,"stt");let y=null;if(S.kind==="remote"||S.kind==="container")try{y=Mt(S,{fetchImpl:Ie})}catch(p){return s(o,500,{error:{message:`stt provider: ${p.message}`,type:"bad_provider"}})}!y&&!D.isReady()&&D.init({model:t.stt?.model||Je,allowDownload:t.stt?.allowDownload!==!1,dtype:t.stt?.dtype||void 0,warmMs:t.stt?.warmMs,speaker:ht(t),onLog:p=>console.log(p)});const x=r("diarize")==="true"&&t.stt?.diarize!==!1;x&&!P.isReady()&&P.init({allowDownload:t.stt?.allowDownload!==!1,warmMs:t.stt?.warmMs,onLog:p=>console.log(p)});const b=Date.now();try{const{id:p}=D.createSession({lang:r("language")||void 0,diarize:x,interims:!1,remote:y}),_=[];let J=null;D.subscribe(p,U=>{U.type==="final"&&U.text?_.push(U):U.type==="language"&&(J=U.lang)});const I=16e3*5;for(let U=0;U<l.pcm.length;U+=I)D.pushAudio(p,l.pcm.subarray(U,Math.min(l.pcm.length,U+I)));await D.endSession(p);let F=0;const me=_.map((U,Ke)=>{const io=F,lo=(U.durationMs||0)/1e3;return F+=lo,{id:Ke,start:Math.round(io*100)/100,end:Math.round(F*100)/100,text:U.text,...U.speaker?{speaker:U.speaker}:{}}}),ye=me.map(U=>U.text).join(" ").replace(/\s+/g," ").trim();return u==="text"?(o.writeHead(200,{"content-type":"text/plain; charset=utf-8"}),o.end(ye)):u==="verbose_json"?s(o,200,{task:"transcribe",language:J||r("language")||null,duration:Math.round(l.seconds*100)/100,text:ye,segments:me,provider:S.kind,took_ms:Date.now()-b}):s(o,200,{text:ye})}catch(p){return s(o,p.code==="too_many_sessions"?429:500,{error:{message:p.message,type:p.code||"stt_error"}})}}if(i==="/stt/sessions"&&n.method==="POST"){if(t.stt?.enabled===!1)return s(o,403,{error:{message:"STT disabled in gateway config",type:"stt_disabled"}});let e=null;try{e=JSON.parse((await T(n,t.maxBodyBytes)).toString("utf8")||"{}")}catch{e=null}const r=rt(t,"stt");let a=null;if(r.kind==="remote"||r.kind==="container")try{a=Mt(r,{fetchImpl:Ie})}catch(u){return s(o,500,{error:{message:`stt provider: ${u.message}`,type:"bad_provider"}})}!a&&!D.isReady()&&D.init({model:t.stt?.model||Je,allowDownload:t.stt?.allowDownload!==!1,dtype:t.stt?.dtype||void 0,warmMs:t.stt?.warmMs,speaker:ht(t),onLog:u=>console.log(u)});const l=e?.diarize===!0&&t.stt?.diarize!==!1;l&&!P.isReady()&&P.init({allowDownload:t.stt?.allowDownload!==!1,warmMs:t.stt?.warmMs,onLog:u=>console.log(u)});try{const{id:u}=D.createSession({lang:e?.lang,redact:e?.redact===!0,diarize:l,speakerLabel:e?.speakerLabel,endSilenceMs:e?.endSilenceMs,interims:e?.interims!==!1,remote:a});return s(o,201,{id:u,state:D.state()})}catch(u){return s(o,u.code==="too_many_sessions"?429:500,{error:{message:u.message,type:u.code||"stt_error"}})}}{const e=i.match(/^\/stt\/sessions\/([0-9a-f-]{36})(\/audio|\/events)?$/);if(e){const r=e[1];if(e[2]==="/audio"&&n.method==="POST")try{const a=await T(n,t.maxBodyBytes);return D.pushAudio(r,D.toFloat32(a)),s(o,200,{ok:!0,state:D.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"&&n.method==="GET"){const a=D.getSession(r);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=p=>o.write(`data: ${JSON.stringify(p)}
43
+ `),ye.add(o),n.on("close",()=>ye.delete(o));return}if(i==="/v1/history/records"&&n.method==="GET"){const e=M.lossless;if(!e)return a(o,501,{error:{message:"lossless records need the SQLite warm store",type:"unavailable"}});const r=e.since({since:Number(f.searchParams.get("since"))||0,cursor:f.searchParams.get("cursor")||"",limit:Number(f.searchParams.get("limit"))||200,kind:f.searchParams.get("kind")||null,bytes:Number(f.searchParams.get("bytes"))||0,afterRev:f.searchParams.has("after_rev")?Number(f.searchParams.get("after_rev"))||0:null});return a(o,200,{ok:!0,...r,size:e.size,newest:e.newest})}if(i==="/v1/history/list"&&n.method==="GET"){const e=Math.min(500,Math.max(1,Number(f.searchParams.get("limit"))||50)),r=Math.max(0,Number(f.searchParams.get("offset"))||0),s=f.searchParams.get("type")||null;return a(o,200,{ok:!0,...M.list({limit:e,offset:r,type:s})})}if(i==="/v1/history/get"&&n.method==="GET"){const e=f.searchParams.get("maxChars")!=null?Math.max(1,Number(f.searchParams.get("maxChars"))||0):null,r=Math.max(0,Number(f.searchParams.get("offset"))||0),s=M.get(String(f.searchParams.get("id")||""),{maxChars:e,offset:r});return s?a(o,200,{ok:!0,record:s}):a(o,404,{error:{message:"no such record",type:"not_found"}})}if(i==="/v1/history/key"&&n.method==="GET")return a(o,200,{ok:!0,hasKey:Pt()});if(i==="/v1/history/key"&&n.method==="POST")try{const e=JSON.parse((await S(n,t.maxBodyBytes)).toString("utf8"))||{};e.passphrase?Xo(String(e.passphrase)):qo();const r=e.passphrase?await ot(M,String(e.passphrase)):{ok:!0,ingested:0};return r.ok&&r.whole&&Ve(),a(o,200,{ok:!0,hasKey:!!e.passphrase,...r})}catch(e){return a(o,400,{error:{message:`key handoff failed: ${e.message}`,type:"key_error"}})}if(i==="/v1/history/ingest-backup"&&n.method==="POST")try{const e=await ot(M,qe());return e.ok&&e.whole&&Ve(),a(o,e.ok?200:409,e)}catch(e){return a(o,400,{error:{message:`backup ingest failed: ${e.message}`,type:"ingest_error"}})}if(i==="/ner"){if(n.method==="GET"){const e=await no(t);return a(o,e.ok?200:503,e)}if(n.method==="POST"){if(await Je(t),A.state()!=="off"){if(!A.isReady()){const r=A.health();return a(o,503,{error:{message:r.state==="error"?`NER model failed to load: ${r.error||"unknown error"}`:`NER model is ${r.state} — not ready yet`,type:r.state==="error"?"ner_error":"ner_loading"},state:r.state,model:r.model})}try{const r=await S(n,t.maxBodyBytes);let s="";try{s=JSON.parse(r.toString("utf8"))?.text||""}catch{}const l=await A.detect(s);return a(o,200,{entities:l})}catch(r){return a(o,500,{error:{message:`NER error: ${r.message}`,type:"ner_error"}})}}const e=ro(t);if(!e){const r=A.modelOnDisk(t.ner?.model||void 0);return a(o,503,{error:{message:r?"the bundled detector could not start — deterministic-only redaction":"no entity detector is installed — deterministic-only redaction (install one from Gateway settings)",type:r?"ner_error":"ner_not_installed"},state:A.state(),model:t.ner?.model||null})}try{const r=await S(n,t.maxBodyBytes),s=await je(e,{method:"POST",headers:{"content-type":"application/json"},body:r,signal:AbortSignal.timeout(8e3)}),l=await s.text();return o.writeHead(s.status,{"content-type":"application/json"}),o.end(l)}catch(r){return a(o,502,{error:{message:`NER unreachable: ${r.message}`,type:"ner_unreachable"}})}}}if(i==="/redact"&&n.method==="POST"){let e="";try{e=String(JSON.parse((await S(n,t.maxBodyBytes)).toString("utf8"))?.text||"")}catch{e=""}if(!e)return a(o,200,{text:"",count:0,sanitized:0,entities:[],detector:mt(t)});try{let r=e;const s=await we(t.pro?.entitlementToken);await Je(t);const l=await Re([Qe(()=>r,u=>{r=u})],t.redaction,{isPro:s});return a(o,200,{text:r,count:l.count||0,sanitized:l.sanitized||0,tier:t.redaction?.tier==="full"?"full":"basic",entities:to(l.vault,"types")||[],detector:mt(t)})}catch(r){return a(o,500,{error:{message:`redaction preview failed: ${r.message}`,type:"redact_error"}})}}if(i==="/ner/models"){if(n.method==="GET"){const e=A.health().model||t.ner?.model||null,r=Math.round(Nt.totalmem()/1048576),s=rn(Ct,{totalRamMB:r}).map(l=>({...l,installed:A.modelOnDisk(l.id)}));for(const l of[e,...A.modelsOnDisk()])!l||s.some(u=>u.id===l)||s.push({id:l,label:l,lang:"—",custom:!0,installed:A.modelOnDisk(l),note:"Custom model (from Hugging Face)."});return a(o,200,{active:e,companions:A.companions(),union:Array.isArray(t.ner?.union)?t.ner.union:[],machine:{totalRamMB:r},skipped:Yo(),recommendation:$t(s,{totalRamMB:r},[]),state:A.state(),progress:A.progress(),available:s})}if(n.method==="POST"){let e=null;try{e=JSON.parse((await S(n,t.maxBodyBytes)).toString("utf8"))}catch{e=null}if(e&&e.recommended===!0){const s=Math.round(Nt.totalmem()/1048576),l=$t(Ct.map(u=>({...u,installed:A.modelOnDisk(u.id)})),{totalRamMB:s},[]);e={id:l.primary,union:l.union}}const r=e&&typeof e.id=="string"?e.id.trim():null;if(e&&Array.isArray(e.union)){const s=[...new Set(e.union.map(u=>String(u||"").trim()).filter(Boolean))];for(const u of s)if(!(Dt(u)||Rt(u)))return a(o,400,{error:{message:`unknown or invalid model id in union: ${u}`,type:"bad_model"}});const l=r||t.ner?.model||A.health().model;t.ner=t.ner||{allowDownload:!0,enableFullTier:!0},t.ner.union=s.filter(u=>u!==l),r&&Ut(t,r);try{he(t,se())}catch{}return(async()=>{r&&await A.setModel(r,{onLog:k=>console.log(k)});const u=Qo(t.ner,{log:k=>console.log(k)});for(const k of A.companions())u.includes(k.model)||await A.removeCompanion(k.model);for(const k of u)await A.addCompanion(k,{onLog:y=>console.log(y),allowDownload:t.ner.allowDownload!==!1});A.setUnionOrder(u)})().catch(u=>console.log(`[ner] union update failed: ${u.message}`)),a(o,202,{accepted:!0,active:l,union:t.ner.union,companions:A.companions(),state:A.state()})}if(!r||!(Dt(r)||Rt(r)))return a(o,400,{error:{message:"unknown or invalid model id",type:"bad_model"}});Ut(t,r);try{he(t,se())}catch{}return A.setModel(r,{onLog:s=>console.log(s)}).then(s=>{s&&t.ner?.enableFullTier&&t.redaction.tier!=="full"&&(t.redaction.tier="full")}),a(o,202,{accepted:!0,active:r,state:A.state(),progress:A.progress()})}}if(i==="/stt/models"){if(n.method==="GET"){const e=R.health().model||t.stt?.model||ze,r=nn.map(s=>({...s,installed:R.modelOnDisk(s.id)}));return e&&!r.some(s=>s.id===e)&&r.push({id:e,label:e,lang:"—",tier:"custom",custom:!0,installed:R.modelOnDisk(e),note:"Custom model (from Hugging Face)."}),a(o,200,{active:e,state:R.state(),progress:R.progress(),available:r,dtype:t.stt?.dtype||"auto",loadedDtype:R.health().dtype,runtime:R.health().runtime,dtypes:ln})}if(n.method==="POST"){let e=null;try{e=JSON.parse((await S(n,t.maxBodyBytes)).toString("utf8"))}catch{e=null}const r=e&&typeof e.id=="string"?e.id.trim():null;if(!r||!(an(r)||sn(r)))return a(o,400,{error:{message:"unknown or invalid model id",type:"bad_model"}});const s=typeof e.dtype=="string"&&dn(e.dtype)?e.dtype:void 0;t.stt?t.stt.model=r:t.stt={enabled:!0,model:r,allowDownload:!0},s&&(t.stt.dtype=s==="auto"?null:s);try{he(t,se())}catch{}return R.setModel(r,{onLog:l=>console.log(l),dtype:s||t.stt.dtype||"auto",warmMs:t.stt.warmMs,speaker:ht(t,{installing:!0})}),a(o,202,{accepted:!0,active:r,dtype:t.stt.dtype||"auto",state:R.state(),progress:R.progress(),speaker:{id:P.activeModel(),state:P.state(),installed:P.modelOnDisk()}})}}if(i==="/diarize/model"){if(n.method==="GET"){const e=P.activeModel(),r=qr.map(s=>({...s,installed:P.modelOnDisk(s.id)})).sort((s,l)=>(l.id===e?1:0)-(s.id===e?1:0));return a(o,200,{active:e,state:P.state(),threshold:P.activeThreshold(),progress:P.progress(),available:r})}if(n.method==="POST"){let e=null;try{e=JSON.parse((await S(n,t.maxBodyBytes)).toString("utf8")||"{}")}catch{e=null}const r=e&&typeof e.id=="string"?e.id.trim():null;if(r){if(!Bt(r))return a(o,400,{error:{message:"unknown speaker model id",type:"bad_model"}});if(!await P.setModel(r,{log:s=>console.log(s)}))return a(o,409,{error:{message:"a diarizing session is using the current speaker model — try again when it ends",type:"model_busy"}});t.stt?t.stt.diarizeModel=r:t.stt={enabled:!0,diarize:!0,diarizeModel:r};try{he(t,se())}catch{}return P.init({allowDownload:t.stt?.allowDownload!==!1,warmMs:t.stt?.warmMs,onLog:s=>console.log(s)}),a(o,202,{accepted:!0,active:P.activeModel(),state:P.state(),threshold:P.activeThreshold(),progress:P.progress()})}return P.download({onLog:s=>console.log(s)}),a(o,202,{accepted:!0,active:P.activeModel(),state:P.state(),threshold:P.activeThreshold(),progress:P.progress()})}}if(i==="/tts/models"){if(n.method==="GET"){const e=$.health().model||t.tts?.model||Gt(nt()),r=nt(),s=It.find(u=>u.id===e)||null,l=It.map(u=>({...u,installed:$.modelOnDisk(u.id),unavailable:u.requiresNative&&!r?"needs the npm gateway — the standalone binary cannot load this engine":void 0}));return e&&!l.some(u=>u.id===e)&&l.push({id:e,label:e,lang:"—",tier:"custom",custom:!0,installed:$.modelOnDisk(e),note:"Custom model (from Hugging Face)."}),a(o,200,{active:e,state:$.state(),progress:$.progress(),available:l,voice:t.tts?.voice||(Ue(e)==="pocket-tts"?Ge:fe),arch:$.arch(),supportsVoices:$.arch()?$.supportsVoices():s?s.arch==="style-tts2"&&!!s.voices:!0,supportsCustomVoices:$.arch()?$.supportsCustomVoices():!!s?.customVoices,sampleRate:$.sampleRate(),voices:$.isPocket()||!$.arch()&&Ue(e)==="pocket-tts"?($.builtinVoices().length?$.builtinVoices():fn).map(u=>({id:u,label:u[0].toUpperCase()+u.slice(1),lang:"en",installed:$.builtinVoices().includes(u)})):$.arch()&&$.arch()!=="style-tts2"?[]:cn.map(u=>({...u,installed:$.voiceOnDisk(u.id,e)})),dtype:t.tts?.dtype||"auto",loadedDtype:$.health().dtype,runtime:$.health().runtime,dtypes:pn})}if(n.method==="POST"){let e=null;try{e=JSON.parse((await S(n,t.maxBodyBytes)).toString("utf8"))}catch{e=null}const r=e&&typeof e.id=="string"?e.id.trim():null;if(r&&!(un(r)||mn(r)))return a(o,400,{error:{message:"unknown or invalid model id",type:"bad_model"}});const s=e&&typeof e.voice=="string"?e.voice.trim():null;if(s){const u=X.parseCustomVoice(s);if(!(u?!!X.getVoice(u):He(s)||jt(s)&&Lt(s)))return a(o,400,{error:{message:"unknown or invalid voice",type:"bad_voice"}})}const l=e&&typeof e.dtype=="string"&&hn(e.dtype)?e.dtype:void 0;if(t.tts||(t.tts={enabled:!0,model:Jt,voice:fe,allowDownload:!0}),r&&(t.tts.model=r),s&&(t.tts.voice=s),r&&!s){const u=yn(r),k=X.parseCustomVoice(t.tts.voice||""),y=!!(k&&X.getVoice(k));if(u&&!y)if(Ue(r)==="pocket-tts")t.tts.voice=Ge;else{const T=X.listVoices();t.tts.voice=T.length?`custom:${T[0].id}`:""}else!u&&y&&(t.tts.voice=fe);const x=Ue(r)==="pocket-tts";x&&!X.parseCustomVoice(t.tts.voice||"")&&!He(t.tts.voice)&&(t.tts.voice=Ge),!x&&He(t.tts.voice)&&(t.tts.voice=fe)}l&&(t.tts.dtype=l==="auto"?null:l);try{he(t,se())}catch{}return r&&$.setModel(r,{onLog:u=>console.log(u),dtype:l||t.tts.dtype||"auto"}),a(o,202,{accepted:!0,active:t.tts.model,voice:t.tts.voice,dtype:t.tts.dtype||"auto",state:$.state(),progress:$.progress()})}}if(i==="/tts/voices"){if(n.method==="GET")return a(o,200,{voices:X.listVoices(),usable:$.supportsCustomVoices(),embedder:P.activeModel(),embedderReady:P.isReady()});if(n.method==="POST"){let e=null;try{e=JSON.parse((await S(n,t.maxBodyBytes)).toString("utf8"))}catch{e=null}const r=e&&typeof e.name=="string"?e.name.trim():"",s=e&&Array.isArray(e.pcm)?e.pcm:null,l=e&&typeof e.id=="string"?e.id.trim():"";if(l){if(!X.getVoice(l))return a(o,404,{error:{message:"no such saved voice",type:"bad_voice"}});if(!s){if(!r)return a(o,400,{error:{message:"a name is required",type:"bad_request"}});try{return a(o,200,{...X.renameVoice(l,r),usable:$.supportsCustomVoices()})}catch(u){return a(o,400,{error:{message:u.message,type:"rename_failed"}})}}if(s.length<16e3)return a(o,400,{error:{message:"need at least 1 second of 16 kHz mono audio",type:"sample_too_short"}})}else if(!r)return a(o,400,{error:{message:"a name is required",type:"bad_request"}});if(!s||s.length<16e3)return a(o,400,{error:{message:"need at least 1 second of 16 kHz mono audio",type:"sample_too_short"}});try{if(!P.isReady()){const p=P.download({onLog:j=>console.log(j)}),_=Symbol("timeout"),N=await Promise.race([p.then(()=>null).catch(j=>j),new Promise(j=>setTimeout(()=>j(_),qn))]);if(N===_||!P.isReady())return a(o,503,{error:{message:N===_?"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 u=Float32Array.from(s),k=await P.embed(u);let y=null;try{const p=await $.pocketForEncoding({allowDownload:t.tts?.allowDownload!==!1,log:_=>console.log(_)});p&&(y=await p.encodeVoice(ea(u,16e3,24e3)))}catch(p){console.log(`[tts] pocket conditioning unavailable for this voice (${p.message})`)}const x=l?X.replaceVoice(l,{vec:k,pocket:y}):X.saveVoice({name:r,vec:k,pocket:y}),T=l&&r&&r!==x.name?X.renameVoice(l,r):x;return console.log(`[tts] ${l?"re-recorded":"saved"} custom voice "${T.name}" (${(x.kinds||[]).join(" + ")}, sample discarded)`),a(o,l?200:201,{...x,...T,usable:$.supportsCustomVoices()})}catch(u){return a(o,400,{error:{message:u.message,type:"save_failed"}})}}if(n.method==="DELETE"){const e=f.searchParams.get("id")||"",r=X.deleteVoice(e);if(r&&t.tts?.voice===`custom:${e}`){const s=X.listVoices();t.tts.voice=s.length?`custom:${s[0].id}`:fe;try{he(t,se())}catch{}}return a(o,200,{deleted:r,voice:t.tts?.voice})}}if((i==="/tts"||i==="/v1/audio/speech")&&n.method==="POST"){if(t.tts?.enabled===!1)return a(o,503,{error:{message:"tts is disabled in gateway config",type:"tts_disabled"}});let e=null;try{e=JSON.parse((await S(n,t.maxBodyBytes)).toString("utf8"))}catch{e=null}const r=e&&typeof(e.input??e.text)=="string"?String(e.input??e.text).trim():"";if(!r)return a(o,400,{error:{message:"text is required",type:"bad_request"}});if(r.length>zt)return a(o,413,{error:{message:`text too long (max ${zt} chars)`,type:"too_long"}});const s=Number.isFinite(e.speed)?Math.min(2,Math.max(.5,e.speed)):1,l=gn(t),u=e&&typeof e.voice=="string"&&e.voice.trim()?e.voice.trim():null,k=u||(l?l.voice:t.tts?.voice||fe);if(l&&!bn(k))return a(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 a(o,400,{error:{message:`unsupported response_format "${y}" — this gateway synthesizes wav`,type:"bad_format"}});try{if(l){const{audio:V,contentType:z,redacted:Oe}=await wn({dest:l,text:r,voice:k,speed:s,auth:n.headers.authorization||n.headers["xi-api-key"]||"",redaction:t.redaction,isPro:await we(t.pro?.entitlementToken)});return o.writeHead(200,{"Content-Type":z,"Content-Length":String(V.length),"Cache-Control":"no-store","X-Tts-Provider":l.kind,"X-Tts-Redacted":String(Oe)}),o.end(V)}if(!await $.ready({onLog:V=>console.log(V),allowDownload:t.tts?.allowDownload!==!1,model:t.tts?.model||Gt(nt()),dtype:t.tts?.dtype||"auto"}))return a(o,503,{error:{message:$.health().error||"tts model not ready",type:"tts_unavailable"}});const T=vn({requested:u,configured:k,engine:$,voices:X,isPocketVoice:He,isKnownVoice:jt,isValidVoiceId:Lt,defaultVoice:fe,defaultPocketVoice:Ge});if(!T.ok)return a(o,T.status,{error:{message:T.message,type:T.type}});const{voice:p,customId:_,speakerEmbedding:N}=T,j=await $.synth(r,{voice:p,speed:s,speakerEmbedding:N}),Y=$.sampleRate(),ae=y==="pcm"?Buffer.from(new Float32Array(j).buffer):$.toWav(j,Y);return o.writeHead(200,{"Content-Type":y==="pcm"?"application/octet-stream":"audio/wav","Content-Length":String(ae.length),"Cache-Control":"no-store","X-Tts-Sample-Rate":String(Y),..._||$.isPocket()||$.supportsVoices()?{"X-Tts-Voice":p}:{}}),o.end(ae)}catch(x){return a(o,500,{error:{message:x.message,type:"tts_failed"}})}}if(i==="/v1/audio/transcriptions"&&n.method==="POST"){if(t.stt?.enabled===!1)return a(o,403,{error:{message:"STT disabled in gateway config",type:"stt_disabled"}});let e;try{e=tn(await S(n,Math.max(t.maxBodyBytes||0,64*1024*1024)),n.headers["content-type"])}catch(p){return a(o,p.code===413?413:415,{error:{message:p.message,type:"bad_request"}})}const r=p=>e.find(_=>_.name===p&&!_.filename)?.data.toString("utf8").trim()||"",s=e.find(p=>p.name==="file"&&p.filename)||e.find(p=>p.filename);if(!s?.data?.length)return a(o,400,{error:{message:"a `file` part is required",type:"bad_request"}});let l;try{l=await on(s.data)}catch(p){return a(o,p.code===415?415:500,{error:{message:p.message,type:"unsupported_media"}})}const u=["json","text","verbose_json"].includes(r("response_format"))?r("response_format"):"json",k=rt(t,"stt");let y=null;if(k.kind==="remote"||k.kind==="container")try{y=Mt(k,{fetchImpl:je})}catch(p){return a(o,500,{error:{message:`stt provider: ${p.message}`,type:"bad_provider"}})}!y&&!R.isReady()&&R.init({model:t.stt?.model||ze,allowDownload:t.stt?.allowDownload!==!1,dtype:t.stt?.dtype||void 0,warmMs:t.stt?.warmMs,speaker:ht(t),onLog:p=>console.log(p)});const x=r("diarize")==="true"&&t.stt?.diarize!==!1;x&&!P.isReady()&&P.init({allowDownload:t.stt?.allowDownload!==!1,warmMs:t.stt?.warmMs,onLog:p=>console.log(p)});const T=Date.now();try{const{id:p}=R.createSession({lang:r("language")||void 0,diarize:x,interims:!1,remote:y}),_=[];let N=null;R.subscribe(p,z=>{z.type==="final"&&z.text?_.push(z):z.type==="language"&&(N=z.lang)});const j=16e3*5;for(let z=0;z<l.pcm.length;z+=j)R.pushAudio(p,l.pcm.subarray(z,Math.min(l.pcm.length,z+j)));await R.endSession(p);let Y=0;const ae=_.map((z,Oe)=>{const io=Y,lo=(z.durationMs||0)/1e3;return Y+=lo,{id:Oe,start:Math.round(io*100)/100,end:Math.round(Y*100)/100,text:z.text,...z.speaker?{speaker:z.speaker}:{}}}),V=ae.map(z=>z.text).join(" ").replace(/\s+/g," ").trim();return u==="text"?(o.writeHead(200,{"content-type":"text/plain; charset=utf-8"}),o.end(V)):u==="verbose_json"?a(o,200,{task:"transcribe",language:N||r("language")||null,duration:Math.round(l.seconds*100)/100,text:V,segments:ae,provider:k.kind,took_ms:Date.now()-T}):a(o,200,{text:V})}catch(p){return a(o,p.code==="too_many_sessions"?429:500,{error:{message:p.message,type:p.code||"stt_error"}})}}if(i==="/stt/sessions"&&n.method==="POST"){if(t.stt?.enabled===!1)return a(o,403,{error:{message:"STT disabled in gateway config",type:"stt_disabled"}});let e=null;try{e=JSON.parse((await S(n,t.maxBodyBytes)).toString("utf8")||"{}")}catch{e=null}const r=rt(t,"stt");let s=null;if(r.kind==="remote"||r.kind==="container")try{s=Mt(r,{fetchImpl:je})}catch(u){return a(o,500,{error:{message:`stt provider: ${u.message}`,type:"bad_provider"}})}!s&&!R.isReady()&&R.init({model:t.stt?.model||ze,allowDownload:t.stt?.allowDownload!==!1,dtype:t.stt?.dtype||void 0,warmMs:t.stt?.warmMs,speaker:ht(t),onLog:u=>console.log(u)});const l=e?.diarize===!0&&t.stt?.diarize!==!1;l&&!P.isReady()&&P.init({allowDownload:t.stt?.allowDownload!==!1,warmMs:t.stt?.warmMs,onLog:u=>console.log(u)});try{const{id:u}=R.createSession({lang:e?.lang,redact:e?.redact===!0,diarize:l,speakerLabel:e?.speakerLabel,endSilenceMs:e?.endSilenceMs,interims:e?.interims!==!1,remote:s});return a(o,201,{id:u,state:R.state()})}catch(u){return a(o,u.code==="too_many_sessions"?429:500,{error:{message:u.message,type:u.code||"stt_error"}})}}{const e=i.match(/^\/stt\/sessions\/([0-9a-f-]{36})(\/audio|\/events)?$/);if(e){const r=e[1];if(e[2]==="/audio"&&n.method==="POST")try{const s=await S(n,t.maxBodyBytes);return R.pushAudio(r,R.toFloat32(s)),a(o,200,{ok:!0,state:R.state()})}catch(s){return a(o,s.code==="no_session"?404:400,{error:{message:s.message,type:s.code||"stt_error"}})}if(e[2]==="/events"&&n.method==="GET"){const s=R.getSession(r);if(!s)return a(o,404,{error:{message:"no such session",type:"no_session"}});o.writeHead(200,{"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive"});const l=p=>o.write(`data: ${JSON.stringify(p)}
44
44
 
45
- `),u=a.redact?await we(t.pro?.entitlementToken):!0,S=async p=>{if(p.type!=="final"||!a.redact)return p;try{let _=p.text;return await De([Qe(()=>_,J=>{_=J})],t.redaction,{isPro:u}),{...p,text:_}}catch{return p}};l({type:"state",state:a.remote?"ready":D.state()});const y=setInterval(()=>{const p=a.remote?"ready":D.state();if(p==="downloading"||p==="loading"){l({type:"progress",state:p,...D.progress()||{}});return}if(p==="error"){l({type:"error",code:"model_failed",message:D.health().error||"model failed to load",fatal:!0}),clearInterval(y);return}if(a.diarize){const _=P.state();if(_==="downloading"||_==="loading"){l({type:"diarize-progress",state:_,...P.progress()||{}});return}}l({type:"state",state:p}),clearInterval(y)},500);y.unref?.();let x=Promise.resolve();const b=D.subscribe(r,p=>{x=x.then(async()=>{l(await S(p)),p.type==="end"&&(clearInterval(y),o.end())}).catch(()=>{})});n.on("close",()=>{clearInterval(y),b?.()});return}if(!e[2]&&n.method==="DELETE")return await D.endSession(r),s(o,200,{ok:!0})}}if(i==="/logs"&&n.method==="GET")return s(o,200,{entries:[...R].reverse()});if(i==="/config"&&n.method==="GET"){const e=await we(t.pro?.entitlementToken);return s(o,200,Ht(t,{proUnlocked:e}))}if(i==="/config"&&n.method==="POST"){let e=null;try{e=JSON.parse((await T(n,t.maxBodyBytes)).toString("utf8"))}catch{e=null}if(!e||typeof e!="object")return s(o,400,{error:"invalid config patch"});const r=JSON.stringify(t.sandbox||null);try{xn(t,e)}catch(y){if(y?.code==="SHAPE")return s(o,400,{error:y.message});throw y}St(t),JSON.stringify(t.sandbox||null)!==r&&Ae?.restart("sandbox settings changed");try{pe(t,ne())}catch(y){return s(o,500,{error:`could not persist config: ${y.message}`})}const a=t.redaction?.detection,l=!a||!a.backend||a.backend==="off",u=A.state();t.ner?.autostart&&l&&u!=="ready"&&u!=="loading"&&u!=="downloading"&&A.setModel(t.ner.model,{onLog:y=>console.log(y)}).then(y=>{y&&t.ner?.enableFullTier&&t.redaction.tier!=="full"&&(t.redaction.tier="full")});const S=await we(t.pro?.entitlementToken);return s(o,200,Ht(t,{proUnlocked:S}))}if(n.method==="GET"&&i==="/skills")return ce(n,o,t,`/skills${xe(f,t)}`,{pick:e=>({skills:Array.isArray(e?.skills)?e.skills:[]})});if(n.method==="GET"&&i==="/skills-quarantined")return ce(n,o,t,`/skills-quarantined${xe(f,t)}`,{pick:e=>({quarantined:Array.isArray(e?.quarantined)?e.quarantined:[]})});if(i==="/skills"&&n.method==="POST")return z(n)?ce(n,o,t,"/skills",{method:"POST",timeoutMs:15e3}):s(o,403,{error:{message:"writing a skill: extension origin or gateway token required",type:"forbidden"}});if(/^\/skills\/[^/]+$/.test(i)&&n.method==="DELETE"){const e=decodeURIComponent(i.slice(8));return yt(e)?s(o,400,{error:{message:"not a skill id",type:"invalid_request"}}):z(n)?ce(n,o,t,`/skills/${encodeURIComponent(e)}`,{method:"DELETE"}):s(o,403,{error:{message:"deleting a skill: extension origin or gateway token required",type:"forbidden"}})}if(/^\/skills\/[^/]+\/file\/.+/.test(i)&&n.method==="PUT"){const e=/^\/skills\/([^/]+)\/file\/(.+)$/.exec(i),r=decodeURIComponent(e[1]);return yt(r)||/(^|\/)\.\.(\/|$)/.test(decodeURIComponent(e[2]))?s(o,400,{error:{message:"not a skill file",type:"invalid_request"}}):z(n)?ce(n,o,t,`/skills/${encodeURIComponent(r)}/file/${e[2]}`,{method:"PUT",timeoutMs:15e3}):s(o,403,{error:{message:"writing a skill file: extension origin or gateway token required",type:"forbidden"}})}if(n.method==="GET"&&i==="/agent-defs")return ce(n,o,t,`/agent-defs${xe(f,t)}`,{pick:e=>({agents:Array.isArray(e?.agents)?e.agents:[],...e?.quarantined?{quarantined:e.quarantined}:{},...e?.problems?{problems:e.problems}:{}})});if(n.method==="GET"&&/^\/agent-defs\/[^/]+$/.test(i)){const e=decodeURIComponent(i.slice(12));return yt(e)?s(o,400,{error:{message:"not an agent id",type:"invalid_request"}}):ce(n,o,t,`/agent-defs/${encodeURIComponent(e)}${xe(f,t)}`)}if(i.startsWith("/a2a/")){if(!z(n))return s(o,403,{error:{message:"a2a: extension origin or gateway token required",type:"forbidden"}});try{if(n.method==="GET"&&i==="/a2a/agents")return s(o,200,{agents:Jo()});if(n.method==="POST"&&i==="/a2a/card"){const e=JSON.parse((await T(n,t.maxBodyBytes)).toString("utf8")||"{}");e.forget&&Do(e.url||"");const r=await je(e.url,{force:!!e.force,auth:String(e.auth||"")});return s(o,200,{ok:!0,card:r.card,fingerprint:r.fingerprint,fresh:r.fresh,changed:!!r.changed,url:r.url})}if(n.method==="POST"&&i==="/a2a/message"){const e=JSON.parse((await T(n,t.maxBodyBytes)).toString("utf8")||"{}"),r=e.card||(await je(e.url,{auth:String(e.auth||"")})).card,a=await Ro({card:r,message:e.message||{messageId:`cp_${Date.now().toString(36)}`,role:"ROLE_USER",parts:[{text:String(e.text||"")}]},auth:String(e.auth||""),returnImmediately:!!e.returnImmediately,contextId:String(e.contextId||""),taskId:String(e.taskId||"")});return s(o,200,{ok:!0,...a})}if(n.method==="POST"&&i==="/a2a/message/stream"){const e=JSON.parse((await T(n,t.maxBodyBytes)).toString("utf8")||"{}"),r=e.card||(await je(e.url,{auth:String(e.auth||"")})).card;o.writeHead(200,{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"});const a=(l,u)=>o.write(`event: ${l}
45
+ `),u=s.redact?await we(t.pro?.entitlementToken):!0,k=async p=>{if(p.type!=="final"||!s.redact)return p;try{let _=p.text;return await Re([Qe(()=>_,N=>{_=N})],t.redaction,{isPro:u}),{...p,text:_}}catch{return p}};l({type:"state",state:s.remote?"ready":R.state()});const y=setInterval(()=>{const p=s.remote?"ready":R.state();if(p==="downloading"||p==="loading"){l({type:"progress",state:p,...R.progress()||{}});return}if(p==="error"){l({type:"error",code:"model_failed",message:R.health().error||"model failed to load",fatal:!0}),clearInterval(y);return}if(s.diarize){const _=P.state();if(_==="downloading"||_==="loading"){l({type:"diarize-progress",state:_,...P.progress()||{}});return}}l({type:"state",state:p}),clearInterval(y)},500);y.unref?.();let x=Promise.resolve();const T=R.subscribe(r,p=>{x=x.then(async()=>{l(await k(p)),p.type==="end"&&(clearInterval(y),o.end())}).catch(()=>{})});n.on("close",()=>{clearInterval(y),T?.()});return}if(!e[2]&&n.method==="DELETE")return await R.endSession(r),a(o,200,{ok:!0})}}if(i==="/logs"&&n.method==="GET")return a(o,200,{entries:[...I].reverse()});if(i==="/config"&&n.method==="GET"){const e=await we(t.pro?.entitlementToken);return a(o,200,Ht(t,{proUnlocked:e}))}if(i==="/config"&&n.method==="POST"){let e=null;try{e=JSON.parse((await S(n,t.maxBodyBytes)).toString("utf8"))}catch{e=null}if(!e||typeof e!="object")return a(o,400,{error:"invalid config patch"});const r=JSON.stringify(t.sandbox||null);try{xn(t,e)}catch(y){if(y?.code==="SHAPE")return a(o,400,{error:y.message});throw y}St(t),JSON.stringify(t.sandbox||null)!==r&&Ne?.restart("sandbox settings changed");try{he(t,se())}catch(y){return a(o,500,{error:`could not persist config: ${y.message}`})}const s=t.redaction?.detection,l=!s||!s.backend||s.backend==="off",u=A.state();t.ner?.autostart&&l&&u!=="ready"&&u!=="loading"&&u!=="downloading"&&A.setModel(t.ner.model,{onLog:y=>console.log(y)}).then(y=>{y&&t.ner?.enableFullTier&&t.redaction.tier!=="full"&&(t.redaction.tier="full")});const k=await we(t.pro?.entitlementToken);return a(o,200,Ht(t,{proUnlocked:k}))}if(n.method==="GET"&&i==="/skills")return me(n,o,t,`/skills${xe(f,t)}`,{pick:e=>({skills:Array.isArray(e?.skills)?e.skills:[]})});if(n.method==="GET"&&i==="/skills-quarantined")return me(n,o,t,`/skills-quarantined${xe(f,t)}`,{pick:e=>({quarantined:Array.isArray(e?.quarantined)?e.quarantined:[]})});if(i==="/skills"&&n.method==="POST")return G(n)?me(n,o,t,"/skills",{method:"POST",timeoutMs:15e3}):a(o,403,{error:{message:"writing a skill: extension origin or gateway token required",type:"forbidden"}});if(/^\/skills\/[^/]+$/.test(i)&&n.method==="DELETE"){const e=decodeURIComponent(i.slice(8));return yt(e)?a(o,400,{error:{message:"not a skill id",type:"invalid_request"}}):G(n)?me(n,o,t,`/skills/${encodeURIComponent(e)}`,{method:"DELETE"}):a(o,403,{error:{message:"deleting a skill: extension origin or gateway token required",type:"forbidden"}})}if(/^\/skills\/[^/]+\/file\/.+/.test(i)&&n.method==="PUT"){const e=/^\/skills\/([^/]+)\/file\/(.+)$/.exec(i),r=decodeURIComponent(e[1]);return yt(r)||/(^|\/)\.\.(\/|$)/.test(decodeURIComponent(e[2]))?a(o,400,{error:{message:"not a skill file",type:"invalid_request"}}):G(n)?me(n,o,t,`/skills/${encodeURIComponent(r)}/file/${e[2]}`,{method:"PUT",timeoutMs:15e3}):a(o,403,{error:{message:"writing a skill file: extension origin or gateway token required",type:"forbidden"}})}if(n.method==="GET"&&i==="/agent-defs")return me(n,o,t,`/agent-defs${xe(f,t)}`,{pick:e=>({agents:Array.isArray(e?.agents)?e.agents:[],...e?.quarantined?{quarantined:e.quarantined}:{},...e?.problems?{problems:e.problems}:{}})});if(n.method==="GET"&&/^\/agent-defs\/[^/]+$/.test(i)){const e=decodeURIComponent(i.slice(12));return yt(e)?a(o,400,{error:{message:"not an agent id",type:"invalid_request"}}):me(n,o,t,`/agent-defs/${encodeURIComponent(e)}${xe(f,t)}`)}if(i.startsWith("/a2a/")){if(!G(n))return a(o,403,{error:{message:"a2a: extension origin or gateway token required",type:"forbidden"}});try{if(n.method==="GET"&&i==="/a2a/agents")return a(o,200,{agents:Jo()});if(n.method==="POST"&&i==="/a2a/card"){const e=JSON.parse((await S(n,t.maxBodyBytes)).toString("utf8")||"{}");e.forget&&Do(e.url||"");const r=await Le(e.url,{force:!!e.force,auth:String(e.auth||"")});return a(o,200,{ok:!0,card:r.card,fingerprint:r.fingerprint,fresh:r.fresh,changed:!!r.changed,url:r.url})}if(n.method==="POST"&&i==="/a2a/message"){const e=JSON.parse((await S(n,t.maxBodyBytes)).toString("utf8")||"{}"),r=e.card||(await Le(e.url,{auth:String(e.auth||"")})).card,s=await Ro({card:r,message:e.message||{messageId:`cp_${Date.now().toString(36)}`,role:"ROLE_USER",parts:[{text:String(e.text||"")}]},auth:String(e.auth||""),returnImmediately:!!e.returnImmediately,contextId:String(e.contextId||""),taskId:String(e.taskId||"")});return a(o,200,{ok:!0,...s})}if(n.method==="POST"&&i==="/a2a/message/stream"){const e=JSON.parse((await S(n,t.maxBodyBytes)).toString("utf8")||"{}"),r=e.card||(await Le(e.url,{auth:String(e.auth||"")})).card;o.writeHead(200,{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"});const s=(l,u)=>o.write(`event: ${l}
46
46
  data: ${JSON.stringify(u)}
47
47
 
48
- `);try{const l=await Io({card:r,message:e.message||{messageId:`cp_${Date.now().toString(36)}`,role:"ROLE_USER",parts:[{text:String(e.text||"")}]},auth:String(e.auth||""),contextId:String(e.contextId||""),taskId:String(e.taskId||""),onEvent:u=>a(u.kind,{kind:u.kind,task:u.task,message:u.message})});a("done",l)}catch(l){a("error",{code:l.code||"ERROR",message:l.message})}return o.end()}if(n.method==="POST"&&i==="/a2a/task"){const e=JSON.parse((await T(n,t.maxBodyBytes)).toString("utf8")||"{}"),r=e.card||(await je(e.url,{auth:String(e.auth||"")})).card,a=e.cancel?await Lo({card:r,id:String(e.id||""),auth:String(e.auth||"")}):await jo({card:r,id:String(e.id||""),auth:String(e.auth||"")});return s(o,200,{ok:!0,...a})}return s(o,404,{error:{message:`no such a2a route: ${i}`,type:"invalid_request"}})}catch(e){const r=e instanceof xt||e?.name==="A2AClientError"?e.code:"ERROR";return s(o,e instanceof xt&&e.code==="UNREACHABLE"?502:400,{error:{message:e.message,type:"a2a_error",code:r}})}}if(n.method==="POST"&&(i==="/agent-defs/export"||i==="/agent-defs/export-plan"))return z(n)?ce(n,o,t,i,{method:"POST",timeoutMs:15e3}):s(o,403,{error:{message:"exporting an agent: extension origin or gateway token required",type:"forbidden"}});if(n.method==="GET"&&/^\/skills\/[^/]+$/.test(i)){const e=decodeURIComponent(i.slice(8));return!e||e==="."||e===".."||e.includes("/")||e.includes("\\")?s(o,400,{error:{message:"not a skill id",type:"invalid_request"}}):ce(n,o,t,`/skills/${encodeURIComponent(e)}${xe(f,t)}`,{pick:r=>({skill:r?.skill||null})})}if(i==="/channels"||/^\/channels\/(connect|pair|unpair|settings|disconnect)$/.test(i)){if(!z(n))return s(o,403,{error:{message:"channels: extension origin or gateway token required",type:"forbidden"}});if(!(i==="/channels"&&n.method==="GET"||i!=="/channels"&&n.method==="POST"))return s(o,405,{error:{message:"method not allowed",type:"invalid_request"}});const e=await Ee(t);if(!e)return s(o,503,{error:{message:"no bridge is configured",type:"no_bridge"}});const r=$e(t.bridge?.token);try{const a=n.method==="POST"?(await T(n,t.maxBodyBytes)).toString("utf8"):"",l=await fetch(`${e}${i}`,{method:n.method,headers:{Accept:"application/json",...n.method==="POST"?{"content-type":"application/json"}:{},...r?{Authorization:`Bearer ${r}`}:{}},...n.method==="POST"?{body:a||"{}"}:{},signal:AbortSignal.timeout(15e3)}),u=await l.json().catch(()=>({}));return s(o,l.status,u)}catch(a){return s(o,502,{error:{message:`bridge unreachable: ${a.message}`,type:"bridge_unreachable"}})}}if(n.method==="GET"&&/^\/skills\/[^/]+\/file\/.+/.test(i)){const e=/^\/skills\/([^/]+)\/file\/(.+)$/.exec(i),r=decodeURIComponent(e[1]),a=e[2];return!r||r==="."||r===".."||r.includes("/")||r.includes("\\")||/(^|\/)\.\.(\/|$)/.test(decodeURIComponent(a))?s(o,400,{error:{message:"not a skill file",type:"invalid_request"}}):ce(n,o,t,`/skills/${encodeURIComponent(r)}/file/${a}${xe(f,t)}`)}if(n.method==="GET"&&/\/models$/.test(i)){const e=await M(),r=e.sig!==void 0&&e.sig!==O;return O=e.sig,s(o,200,await $n(t,{serviceHealth:async()=>e,fresh:r}))}if(ts.some(e=>i===e||i.startsWith(`${e}/`)))return s(o,404,{error:{message:`this gateway (${K}) has no ${i} — update it to use this feature`,type:"unknown_endpoint"}});const L=Vn(i,n.headers,t);let le;try{le=await T(n,t.maxBodyBytes)}catch(e){s(o,e.code===413?413:400,{error:e.code===413?"payload too large":"bad request"}),n.destroy();return}let H=null,k=null,Q=le,de=0,Ne=0,ve=0,ge=!1,ke=!0;const Y=t.logRequests&&L.redactable&&n.method==="POST"?Un(ee):null;if(L.redactable&&n.method==="POST"&&le.length){try{k=JSON.parse(le.toString("utf8"))}catch{k=null}if(k&&Fn(k,L.kind))Q=le;else if(k){const e=t.tools||{};if(e.autoNarrow!==!1&&Array.isArray(k.tools)&&k.tools.length){const b=Number(e.maxPerTurn)>0?Number(e.maxPerTurn):Rn,p=e.narrowAll?null:J=>!In.test(Zt(J)),_=k.tools.length;k.tools=wo(k.tools,Ln(k,L.kind),{cap:b,keep:p,name:Zt,description:jn}),ve=_-k.tools.length}ke=await we(t.pro?.entitlementToken);const r=kn(t,ke);if(!r.allowed)return s(o,402,{error:{message:`ChatPanel Gateway free trial used up (${r.cap} redactions). Add a ChatPanel Pro entitlement token to unlock unlimited full-tier redaction (names/orgs).`,type:"free_limit_reached"}});ge=String(n.headers["x-chatpanel-redaction"]||"").trim().toLowerCase()==="off"&&z(n),ge||await Le(t);const a=ge?[]:L.adapter.collectSegments(k,t.redaction),l=new AbortController;o.on("close",()=>{o.writableFinished||l.abort()});const u=Y?Y.clock():0,{vault:S,count:y,sanitized:x}=ge?{vault:null,count:0,sanitized:0}:await De(a,t.redaction,{signal:l.signal,isPro:ke,onEgress:b=>dt.push(Wt({ts:Date.now(),client:"redaction",tool:`detect:${b.backend}@${b.host||"local"}`,ok:b.ok,ms:b.ms,error:b.error}))});if(Y&&Y.lap("redact",u),H=S,de=y,Ne=x||0,y>0&&o.setHeader("x-chatpanel-redacted",String(y)),!ke&&y>0){Sn(t,ke);try{pe(t,ne())}catch{}}if(!ge&&Array.isArray(k.tools)&&k.tools.length&&typeof L.adapter.injectSystemNote=="function"){const b=st(k?.model,t,L.kind,{destination:String(n.headers["x-chatpanel-destination"]||k?.chatpanel?.destination||"").trim(),down:_=>!!_.service&&w.fn(_.id)==="down"}),p=!(b&&b.type==="api");L.adapter.injectSystemNote(k,vo({toolData:t.tools?.toolData,ownTools:p}))}else!ge&&y>0&&typeof L.adapter.injectSystemNote=="function"&&L.adapter.injectSystemNote(k,ko());Q=Buffer.from(JSON.stringify(k),"utf8")}}const ft=bo({vault:H,toolData:t.tools?.toolData}),Be=k&&typeof k.chatpanel=="object"&&k.chatpanel||null;if(Be&&(delete k.chatpanel,Q=Buffer.from(JSON.stringify(k),"utf8")),typeof k?.model=="string"&&k.model.startsWith("fusion:")){const e=Or(k.model,t,await M());if(e?.error)return Y?.commit(),s(o,400,{error:{message:e.error,type:"fusion"}});e&&(k.model=e.model,Q=Buffer.from(JSON.stringify(k),"utf8"),o.setHeader("x-chatpanel-fusion",`${e.fusion.id} -> ${e.model}`))}const re={destination:String(n.headers["x-chatpanel-destination"]||Be?.destination||"").trim(),reach:String(n.headers["x-chatpanel-reach"]||Be?.reach||"").trim(),run:ao(n.headers["x-chatpanel-run"],Be?.run)},Fe=await M(),gt=e=>!!e.service&&Fe(e.id)==="down";let N=st(k?.model,t,L.kind,{destination:re.destination,down:gt});if(N?.type==="agent"&&k?.model&&!re.destination&&!Nn(N,k.model)&&(await An(t,{serviceHealth:async()=>Fe}),N=st(k?.model,t,L.kind,{destination:re.destination,down:gt})),N?.service&&Fe(N.id)==="down")return Y?.commit(),s(o,503,{error:{message:`${N.id} is not running — the model ${JSON.stringify(k?.model||"")} is served by an engine the Runtime has stopped; start it under Settings › Runtime`,type:"engine_down",service:N.service}});if(re.destination&&(!N||N.id!==re.destination))return Y?.commit(),s(o,404,{error:{message:`no destination "${re.destination}" is configured on this gateway`,type:"unknown_destination",known:Pn(t).map(e=>e.id)}});Y&&(Y.meta={t:Date.now(),model:k?.model||null,dest:N?N.id:null,type:N?N.type:null,redacted:de,sanitized:Ne,narrowed:ve,detail:to(H,t.logDetail),redaction:ge?"off":t.redaction.tier||"basic"});const Me=No();if(Me&&N){const e=N.type==="api"?Tt(Me,{model:k?.model||"",endpoint:N.baseUrl||""}):Mo(Me,N.agent||N.id)?Tt(Me,{model:k?.model||""}):{ok:!1,reason:`agent "${N.agent||N.id}" is not allowed by your organisation’s policy`};if(!e.ok)return Y?.commit(),s(o,403,{error:{message:e.reason,type:"policy",code:"org_policy"}})}if(N&&N.type==="api")return N.baseUrl?Wn(N.baseUrl,t)?(Y?.commit(),s(o,508,{error:{message:`destination "${N.id}" points back at the gateway (${N.baseUrl}) — refusing to forward (would loop).`,type:"loop_detected"}})):os(n,o,{...L,pathname:i,search:f.search,base:N.baseUrl,destKey:N.apiKey,destProtocol:N.protocol,harness:ft,trace:Y},Q,H):(Y?.commit(),s(o,502,{error:`destination "${N.id}" has no baseUrl`}));const We=Re(n),wt=We==="local"&&t.bridge?.openAgentLane?"token":We;if(wt==="local")return Y?.commit(),s(o,401,{error:{message:"agent destinations require the gateway token: send `Authorization: Bearer $(cat ~/.chatpanel/gateway-token)`, or pair this client with `chatpanel-gateway pair`",type:"auth",code:"agent_lane_token_required"}});const bt=Math.max(0,Math.min(8,Number(n.headers["x-chatpanel-ask-depth"])||0));!re.run&&We==="token"&&n.headers["x-chatpanel-link-device"]&&(re.run=ao(null,rr(or(te.get("agentTools").agentTools?.value,N?.agent||k?.model))));const Ce=To({...re.run||{},...re.reach?{reach:re.reach}:{},...bt?{askDepth:bt}:{}},wt);return Ce.reach&&o.setHeader("x-chatpanel-reach-used",Ce.reach),Zn(n,o,{...L,pathname:i,agentOverride:N?.agent,harness:ft,trace:Y,run:Object.keys(Ce).length?Ce:null},k,H,t,ke)});return ie.on("close",()=>{g?.stop("closed"),Rr(),d.close(),c?.stop()}),ie.once("listening",()=>{C()}),ie.linkHost=c,ie}function ao(t,d){let c=d&&typeof d=="object"?d:null;if(!c&&t)try{c=JSON.parse(decodeURIComponent(String(t)))}catch{c=null}if(!c||typeof c!="object")return null;const m={};if(Array.isArray(c.grants)&&(m.grants=c.grants.map(h=>String(h).slice(0,80)).slice(0,32)),c.workspace&&typeof c.workspace=="object"&&c.workspace.repo){const h=c.workspace;m.workspace={repo:String(h.repo).slice(0,400),projectId:String(h.projectId||"").slice(0,120),jobId:String(h.jobId||"").slice(0,120),...h.base?{base:String(h.base).slice(0,120)}:{}}}if(c.connectionId&&(m.connectionId=String(c.connectionId).slice(0,64)),typeof c.workingDir=="string"&&c.workingDir.trim()&&/^([A-Za-z]:[\\/]|\/)/.test(c.workingDir.trim())&&(m.workingDir=c.workingDir.trim().slice(0,1024)),_n.includes(c.permissionMode)&&c.permissionMode!=="default"&&(m.permissionMode=c.permissionMode),c.sandbox&&typeof c.sandbox=="object"){const h=(Array.isArray(c.sandbox.hosts)?c.sandbox.hosts:String(c.sandbox.hosts||"").split(/[\s,;]+/)).map(w=>String(w).trim().toLowerCase().slice(0,253)).filter(Boolean).slice(0,64),g=(Array.isArray(c.sandbox.write)?c.sandbox.write:[]).map(w=>String(w).slice(0,1024)).filter(Boolean).slice(0,32),E=c.sandbox.outside===!0;(h.length||g.length||E)&&(m.sandbox={...h.length?{hosts:h}:{},...g.length?{write:g}:{},...E?{outside:!0}:{}})}return Object.keys(m).length?m:null}let Ae=null,Ve=null;async function Ea(t=vt()){Zo();let d=null;try{d=await Ao()}catch(w){throw w instanceof Bo&&(console.error(`[chatpanel-gateway] org policy: ${w.message}`),process.exit(78)),w}const c=d?.policy||null;c&&(St(t,c),console.log(`[chatpanel-gateway] ${d.label} — ${d.signed?"signed":"unsigned"} policy from ${d.source}`)),$o(globalThis,{allow:c?.egress?(w,{local:O})=>Co(c,w,{local:O}):null}),Oe();const m=rs(t),h=Ko(t),g=uo(t);m.on("error",w=>{if(w&&w.code==="EADDRINUSE"){const O=ct(t.host)?"127.0.0.1":t.host;fetch(`http://${O}:${t.port}/health`,{signal:AbortSignal.timeout(1500)}).then(M=>M.ok?M.json():null).catch(()=>null).then(M=>{if(M?.version&&typeof M.tier=="string"){const v=M.managedBy?` (run by ${M.managedBy})`:"",C=hr(K,M.version);console.error(`ChatPanel Gateway v${M.version} is already running at http://${O}:${t.port}${v} — this one (v${K}) did not start.`),C>0?console.error("To replace it with this version and keep it starting at login: chatpanel-gateway --install"):C<0?console.error(`The running one is NEWER. Nothing to do — this copy (v${K}) is the stale one; \`which -a chatpanel-gateway\` shows where it comes from.`):console.error("It is this same version: nothing to do. `chatpanel-gateway --status` shows how it is started.")}else{const v=pr(t.port);console.error(`Port ${t.port} is held by ${v||"another program"}, which is not a ChatPanel gateway.`),console.error(`Fix: stop that program, or set a different port — edit "port" in ${ne()} (or the extension's Gateway tab) and restart. The extension must point at the same port.`)}process.exit(1)});return}console.error(`Gateway server error: ${w?.message||w}`),process.exit(1)}),m.listen(t.port,t.host,()=>{console.log(`ChatPanel Privacy Gateway v${K} on http://${t.host}:${t.port}`),m.linkHost?.start().catch(w=>console.log(` link : not started (${w?.message||w})`)),console.log(` backend : ${t.backend}`+(t.backend==="bridge"?` (agent: ${t.bridge.agent}, via ${t.bridge.url})`:"")),t.bridge?.openAgentLane&&console.log(" ⚠ agents : bridge.openAgentLane is ON — any local process may drive a CLI agent through this gateway without a token"),Ve={mode:"starting",version:null,pid:null,restarts:0,why:"deciding: adopt the bridge that answers, or start ours"},mr(t,{childEnv:()=>({...En(t),...On(t)})}).then(w=>{Ae=w}).catch(w=>{Ve={mode:"off",version:null,pid:null,restarts:0,why:`not supervised (${w?.message||w})`},console.log(` bridge : not supervised (${w?.message||w})`)}),console.log(` redaction: ${t.redaction.tier}`+(t.redaction.detection?.backend&&t.redaction.detection.backend!=="off"?` + ${t.redaction.detection.backend} detector`:t.ner?.autostart?" (+ NER starting…)":"")),ct(t.host)||console.error(`⚠ SECURITY: gateway bound to NON-LOOPBACK host ${t.host}. It is reachable off-machine, and the loopback Host-header check is spoofable from the LAN. Admin routes still need the token/extension, but prefer binding 127.0.0.1 unless you intend LAN exposure on a trusted network.`)}),Pt()&&ot(B,qe()).then(w=>{w?.ok&&(console.log(` warm : seeded ${w.ingested} records from ${w.file}`),w.whole&&Ue())}).catch(()=>{});const E=()=>{h?.stop(),g.stop(),Ae?.stop(),Dn(m)};return process.on("SIGINT",E),process.on("SIGTERM",E),m}export{Aa as VERSION,rs as createGateway,Xn as joinUpstream,ut as parseAgentModel,Ea as start};
48
+ `);try{const l=await Io({card:r,message:e.message||{messageId:`cp_${Date.now().toString(36)}`,role:"ROLE_USER",parts:[{text:String(e.text||"")}]},auth:String(e.auth||""),contextId:String(e.contextId||""),taskId:String(e.taskId||""),onEvent:u=>s(u.kind,{kind:u.kind,task:u.task,message:u.message})});s("done",l)}catch(l){s("error",{code:l.code||"ERROR",message:l.message})}return o.end()}if(n.method==="POST"&&i==="/a2a/task"){const e=JSON.parse((await S(n,t.maxBodyBytes)).toString("utf8")||"{}"),r=e.card||(await Le(e.url,{auth:String(e.auth||"")})).card,s=e.cancel?await Lo({card:r,id:String(e.id||""),auth:String(e.auth||"")}):await jo({card:r,id:String(e.id||""),auth:String(e.auth||"")});return a(o,200,{ok:!0,...s})}return a(o,404,{error:{message:`no such a2a route: ${i}`,type:"invalid_request"}})}catch(e){const r=e instanceof xt||e?.name==="A2AClientError"?e.code:"ERROR";return a(o,e instanceof xt&&e.code==="UNREACHABLE"?502:400,{error:{message:e.message,type:"a2a_error",code:r}})}}if(n.method==="POST"&&(i==="/agent-defs/export"||i==="/agent-defs/export-plan"))return G(n)?me(n,o,t,i,{method:"POST",timeoutMs:15e3}):a(o,403,{error:{message:"exporting an agent: extension origin or gateway token required",type:"forbidden"}});if(n.method==="GET"&&/^\/skills\/[^/]+$/.test(i)){const e=decodeURIComponent(i.slice(8));return!e||e==="."||e===".."||e.includes("/")||e.includes("\\")?a(o,400,{error:{message:"not a skill id",type:"invalid_request"}}):me(n,o,t,`/skills/${encodeURIComponent(e)}${xe(f,t)}`,{pick:r=>({skill:r?.skill||null})})}if(i==="/channels"||/^\/channels\/(connect|pair|unpair|settings|disconnect)$/.test(i)){if(!G(n))return a(o,403,{error:{message:"channels: extension origin or gateway token required",type:"forbidden"}});if(!(i==="/channels"&&n.method==="GET"||i!=="/channels"&&n.method==="POST"))return a(o,405,{error:{message:"method not allowed",type:"invalid_request"}});const e=await $e(t);if(!e)return a(o,503,{error:{message:"no bridge is configured",type:"no_bridge"}});const r=Pe(t.bridge?.token);try{const s=n.method==="POST"?(await S(n,t.maxBodyBytes)).toString("utf8"):"",l=await fetch(`${e}${i}`,{method:n.method,headers:{Accept:"application/json",...n.method==="POST"?{"content-type":"application/json"}:{},...r?{Authorization:`Bearer ${r}`}:{}},...n.method==="POST"?{body:s||"{}"}:{},signal:AbortSignal.timeout(15e3)}),u=await l.json().catch(()=>({}));return a(o,l.status,u)}catch(s){return a(o,502,{error:{message:`bridge unreachable: ${s.message}`,type:"bridge_unreachable"}})}}if(n.method==="GET"&&/^\/skills\/[^/]+\/file\/.+/.test(i)){const e=/^\/skills\/([^/]+)\/file\/(.+)$/.exec(i),r=decodeURIComponent(e[1]),s=e[2];return!r||r==="."||r===".."||r.includes("/")||r.includes("\\")||/(^|\/)\.\.(\/|$)/.test(decodeURIComponent(s))?a(o,400,{error:{message:"not a skill file",type:"invalid_request"}}):me(n,o,t,`/skills/${encodeURIComponent(r)}/file/${s}${xe(f,t)}`)}if(n.method==="GET"&&/\/models$/.test(i)){const e=await C(),r=e.sig!==void 0&&e.sig!==O;return O=e.sig,a(o,200,await $n(t,{serviceHealth:async()=>e,fresh:r}))}if(ta.some(e=>i===e||i.startsWith(`${e}/`)))return a(o,404,{error:{message:`this gateway (${K}) has no ${i} — update it to use this feature`,type:"unknown_endpoint"}});const J=Vn(i,n.headers,t);let ce;try{ce=await S(n,t.maxBodyBytes)}catch(e){a(o,e.code===413?413:400,{error:e.code===413?"payload too large":"bad request"}),n.destroy();return}let U=null,v=null,Q=ce,ue=0,Be=0,ve=0,ge=!1,ke=!0;const Z=t.logRequests&&J.redactable&&n.method==="POST"?Un(te):null;if(J.redactable&&n.method==="POST"&&ce.length){try{v=JSON.parse(ce.toString("utf8"))}catch{v=null}if(v&&Fn(v,J.kind))Q=ce;else if(v){const e=t.tools||{};if(e.autoNarrow!==!1&&Array.isArray(v.tools)&&v.tools.length){const T=Number(e.maxPerTurn)>0?Number(e.maxPerTurn):Rn,p=e.narrowAll?null:N=>!In.test(Zt(N)),_=v.tools.length;v.tools=wo(v.tools,Ln(v,J.kind),{cap:T,keep:p,name:Zt,description:jn}),ve=_-v.tools.length}ke=await we(t.pro?.entitlementToken);const r=kn(t,ke);if(!r.allowed)return a(o,402,{error:{message:`ChatPanel Gateway free trial used up (${r.cap} redactions). Add a ChatPanel Pro entitlement token to unlock unlimited full-tier redaction (names/orgs).`,type:"free_limit_reached"}});ge=String(n.headers["x-chatpanel-redaction"]||"").trim().toLowerCase()==="off"&&G(n),ge||await Je(t);const s=ge?[]:J.adapter.collectSegments(v,t.redaction),l=new AbortController;o.on("close",()=>{o.writableFinished||l.abort()});const u=Z?Z.clock():0,{vault:k,count:y,sanitized:x}=ge?{vault:null,count:0,sanitized:0}:await Re(s,t.redaction,{signal:l.signal,isPro:ke,onEgress:T=>dt.push(Wt({ts:Date.now(),client:"redaction",tool:`detect:${T.backend}@${T.host||"local"}`,ok:T.ok,ms:T.ms,error:T.error}))});if(Z&&Z.lap("redact",u),U=k,ue=y,Be=x||0,y>0&&o.setHeader("x-chatpanel-redacted",String(y)),!ke&&y>0){Sn(t,ke);try{he(t,se())}catch{}}if(!ge&&Array.isArray(v.tools)&&v.tools.length&&typeof J.adapter.injectSystemNote=="function"){const T=at(v?.model,t,J.kind,{destination:String(n.headers["x-chatpanel-destination"]||v?.chatpanel?.destination||"").trim(),down:_=>!!_.service&&w.fn(_.id)==="down"}),p=!(T&&T.type==="api");J.adapter.injectSystemNote(v,vo({toolData:t.tools?.toolData,ownTools:p}))}else!ge&&y>0&&typeof J.adapter.injectSystemNote=="function"&&J.adapter.injectSystemNote(v,ko());Q=Buffer.from(JSON.stringify(v),"utf8")}}const ft=bo({vault:U,toolData:t.tools?.toolData}),Me=v&&typeof v.chatpanel=="object"&&v.chatpanel||null;if(Me&&(delete v.chatpanel,Q=Buffer.from(JSON.stringify(v),"utf8")),typeof v?.model=="string"&&v.model.startsWith("fusion:")){const e=Or(v.model,t,await C());if(e?.error)return Z?.commit(),a(o,400,{error:{message:e.error,type:"fusion"}});e&&(v.model=e.model,Q=Buffer.from(JSON.stringify(v),"utf8"),o.setHeader("x-chatpanel-fusion",`${e.fusion.id} -> ${e.model}`))}const ne={destination:String(n.headers["x-chatpanel-destination"]||Me?.destination||"").trim(),reach:String(n.headers["x-chatpanel-reach"]||Me?.reach||"").trim(),run:so(n.headers["x-chatpanel-run"],Me?.run)},We=await C(),gt=e=>!!e.service&&We(e.id)==="down";let B=at(v?.model,t,J.kind,{destination:ne.destination,down:gt});if(B?.type==="agent"&&v?.model&&!ne.destination&&!Nn(B,v.model)&&(await An(t,{serviceHealth:async()=>We}),B=at(v?.model,t,J.kind,{destination:ne.destination,down:gt})),B?.service&&We(B.id)==="down")return Z?.commit(),a(o,503,{error:{message:`${B.id} is not running — the model ${JSON.stringify(v?.model||"")} is served by an engine the Runtime has stopped; start it under Settings › Runtime`,type:"engine_down",service:B.service}});if(ne.destination&&(!B||B.id!==ne.destination))return Z?.commit(),a(o,404,{error:{message:`no destination "${ne.destination}" is configured on this gateway`,type:"unknown_destination",known:Pn(t).map(e=>e.id)}});Z&&(Z.meta={t:Date.now(),model:v?.model||null,dest:B?B.id:null,type:B?B.type:null,redacted:ue,sanitized:Be,narrowed:ve,detail:to(U,t.logDetail),redaction:ge?"off":t.redaction.tier||"basic"});const Ce=No();if(Ce&&B){const e=B.type==="api"?Tt(Ce,{model:v?.model||"",endpoint:B.baseUrl||""}):Mo(Ce,B.agent||B.id)?Tt(Ce,{model:v?.model||""}):{ok:!1,reason:`agent "${B.agent||B.id}" is not allowed by your organisation’s policy`};if(!e.ok)return Z?.commit(),a(o,403,{error:{message:e.reason,type:"policy",code:"org_policy"}})}if(B&&B.type==="api")return B.baseUrl?Wn(B.baseUrl,t)?(Z?.commit(),a(o,508,{error:{message:`destination "${B.id}" points back at the gateway (${B.baseUrl}) — refusing to forward (would loop).`,type:"loop_detected"}})):oa(n,o,{...J,pathname:i,search:f.search,base:B.baseUrl,destKey:B.apiKey,destProtocol:B.protocol,harness:ft,trace:Z},Q,U):(Z?.commit(),a(o,502,{error:`destination "${B.id}" has no baseUrl`}));const Ke=Ie(n),wt=Ke==="local"&&t.bridge?.openAgentLane?"token":Ke;if(wt==="local")return Z?.commit(),a(o,401,{error:{message:"agent destinations require the gateway token: send `Authorization: Bearer $(cat ~/.chatpanel/gateway-token)`, or pair this client with `chatpanel-gateway pair`",type:"auth",code:"agent_lane_token_required"}});const bt=Math.max(0,Math.min(8,Number(n.headers["x-chatpanel-ask-depth"])||0));!ne.run&&Ke==="token"&&n.headers["x-chatpanel-link-device"]&&(ne.run=so(null,rr(or(oe.get("agentTools").agentTools?.value,B?.agent||v?.model))));const De=To({...ne.run||{},...ne.reach?{reach:ne.reach}:{},...bt?{askDepth:bt}:{}},wt);return De.reach&&o.setHeader("x-chatpanel-reach-used",De.reach),Zn(n,o,{...J,pathname:i,agentOverride:B?.agent,harness:ft,trace:Z,run:Object.keys(De).length?De:null},v,U,t,ke)});return de.on("close",()=>{g?.stop("closed"),Rr(),d.close(),c?.stop()}),de.once("listening",()=>{D()}),de.linkHost=c,de}function so(t,d){let c=d&&typeof d=="object"?d:null;if(!c&&t)try{c=JSON.parse(decodeURIComponent(String(t)))}catch{c=null}if(!c||typeof c!="object")return null;const m={};if(Array.isArray(c.grants)&&(m.grants=c.grants.map(h=>String(h).slice(0,80)).slice(0,32)),c.workspace&&typeof c.workspace=="object"&&c.workspace.repo){const h=c.workspace;m.workspace={repo:String(h.repo).slice(0,400),projectId:String(h.projectId||"").slice(0,120),jobId:String(h.jobId||"").slice(0,120),...h.base?{base:String(h.base).slice(0,120)}:{}}}if(c.connectionId&&(m.connectionId=String(c.connectionId).slice(0,64)),typeof c.workingDir=="string"&&c.workingDir.trim()&&/^([A-Za-z]:[\\/]|\/)/.test(c.workingDir.trim())&&(m.workingDir=c.workingDir.trim().slice(0,1024)),_n.includes(c.permissionMode)&&c.permissionMode!=="default"&&(m.permissionMode=c.permissionMode),c.sandbox&&typeof c.sandbox=="object"){const h=(Array.isArray(c.sandbox.hosts)?c.sandbox.hosts:String(c.sandbox.hosts||"").split(/[\s,;]+/)).map(w=>String(w).trim().toLowerCase().slice(0,253)).filter(Boolean).slice(0,64),g=(Array.isArray(c.sandbox.write)?c.sandbox.write:[]).map(w=>String(w).slice(0,1024)).filter(Boolean).slice(0,32),E=c.sandbox.outside===!0;(h.length||g.length||E)&&(m.sandbox={...h.length?{hosts:h}:{},...g.length?{write:g}:{},...E?{outside:!0}:{}})}return Object.keys(m).length?m:null}let Ne=null,Fe=null;async function Es(t=vt()){Zo();let d=null;try{d=await Ao()}catch(w){throw w instanceof Bo&&(console.error(`[chatpanel-gateway] org policy: ${w.message}`),process.exit(78)),w}const c=d?.policy||null;c&&(St(t,c),console.log(`[chatpanel-gateway] ${d.label} — ${d.signed?"signed":"unsigned"} policy from ${d.source}`)),$o(globalThis,{allow:c?.egress?(w,{local:O})=>Co(c,w,{local:O}):null}),_e();const m=ra(t),h=Ko(t),g=uo(t);m.on("error",w=>{if(w&&w.code==="EADDRINUSE"){const O=ct(t.host)?"127.0.0.1":t.host;fetch(`http://${O}:${t.port}/health`,{signal:AbortSignal.timeout(1500)}).then(C=>C.ok?C.json():null).catch(()=>null).then(C=>{if(C?.version&&typeof C.tier=="string"){const b=C.managedBy?` (run by ${C.managedBy})`:"",D=hr(K,C.version);console.error(`ChatPanel Gateway v${C.version} is already running at http://${O}:${t.port}${b} — this one (v${K}) did not start.`),D>0?console.error("To replace it with this version and keep it starting at login: chatpanel-gateway --install"):D<0?console.error(`The running one is NEWER. Nothing to do — this copy (v${K}) is the stale one; \`which -a chatpanel-gateway\` shows where it comes from.`):console.error("It is this same version: nothing to do. `chatpanel-gateway --status` shows how it is started.")}else{const b=pr(t.port);console.error(`Port ${t.port} is held by ${b||"another program"}, which is not a ChatPanel gateway.`),console.error(`Fix: stop that program, or set a different port — edit "port" in ${se()} (or the extension's Gateway tab) and restart. The extension must point at the same port.`)}process.exit(1)});return}console.error(`Gateway server error: ${w?.message||w}`),process.exit(1)}),m.listen(t.port,t.host,()=>{console.log(`ChatPanel Privacy Gateway v${K} on http://${t.host}:${t.port}`),m.linkHost?.start().catch(w=>console.log(` link : not started (${w?.message||w})`)),console.log(` backend : ${t.backend}`+(t.backend==="bridge"?` (agent: ${t.bridge.agent}, via ${t.bridge.url})`:"")),t.bridge?.openAgentLane&&console.log(" ⚠ agents : bridge.openAgentLane is ON — any local process may drive a CLI agent through this gateway without a token"),Fe={mode:"starting",version:null,pid:null,restarts:0,why:"deciding: adopt the bridge that answers, or start ours"},mr(t,{childEnv:()=>({...En(t),...On(t)})}).then(w=>{Ne=w}).catch(w=>{Fe={mode:"off",version:null,pid:null,restarts:0,why:`not supervised (${w?.message||w})`},console.log(` bridge : not supervised (${w?.message||w})`)}),console.log(` redaction: ${t.redaction.tier}`+(t.redaction.detection?.backend&&t.redaction.detection.backend!=="off"?` + ${t.redaction.detection.backend} detector`:t.ner?.autostart?" (+ NER starting…)":"")),ct(t.host)||console.error(`⚠ SECURITY: gateway bound to NON-LOOPBACK host ${t.host}. It is reachable off-machine, and the loopback Host-header check is spoofable from the LAN. Admin routes still need the token/extension, but prefer binding 127.0.0.1 unless you intend LAN exposure on a trusted network.`)}),Pt()&&ot(M,qe()).then(w=>{w?.ok&&(console.log(` warm : seeded ${w.ingested} records from ${w.file}`),w.whole&&Ve())}).catch(()=>{});const E=()=>{h?.stop(),g.stop(),Ne?.stop(),Dn(m)};return process.on("SIGINT",E),process.on("SIGTERM",E),m}export{As as VERSION,ra as createGateway,Xn as joinUpstream,ut as parseAgentModel,Es as start};
package/src/update.js CHANGED
@@ -1 +1,3 @@
1
- import J from"node:os";import l from"node:path";import{execFile as b}from"node:child_process";import{chmod as G,rename as P,mkdir as K,readFile as V,writeFile as j,rm as Y}from"node:fs/promises";import{existsSync as W,readFileSync as q,realpathSync as z}from"node:fs";import{restartService as Q,serviceRegistered as y}from"./service.js";const g="@chatpanel/gateway",be="chatpanel/chatpanel-gateway",D="https://dl.chatpanel.net/version/gateway",E=(process.env.CHATPANEL_NPM_REGISTRY||process.env.npm_config_registry||"https://registry.npmjs.org").replace(/\/$/,""),X=`${E}/${g}/latest`,Z=e=>`https://dl.chatpanel.net/gateway/${e.replace(/^chatpanel-gateway-/,"")}`,L=360*60*1e3,N=600*1e3,ee=Math.max(500,Number(process.env.CHATPANEL_UPDATE_TIMEOUT_MS)||5e3),te=15*6e4,k=20*6e4,_=process.env.CHATPANEL_UPDATE_CACHE||l.join(J.homedir(),".chatpanel","gateway-update-check.json"),S=String(process.env.CHATPANEL_SELF_UPDATE||"").toLowerCase()==="off",O={"User-Agent":"chatpanel-gateway-updater"},ne=new Set(["dl.chatpanel.net","github.com","api.github.com","objects.githubusercontent.com","release-assets.githubusercontent.com"]);function ae(e){try{const t=new URL(e);return t.protocol==="https:"&&ne.has(t.hostname)}catch{return!1}}let m={at:0,error:""};function Ee(){m={at:0,error:""}}function T(){const e=l.basename(process.execPath).toLowerCase();return!(e.startsWith("node")||e.startsWith("bun"))}function re(){return process.platform==="darwin"?`chatpanel-gateway-macos-${process.arch==="arm64"?"arm64":"x64"}`:process.platform==="linux"?process.arch==="x64"?"chatpanel-gateway-linux-x64":null:process.platform==="win32"?"chatpanel-gateway-windows-x64.exe":null}function f(e=""){const t=/(\d+(?:\.\d+){0,3})/.exec(e||"");return t?t[1]:null}function R(e,t){const n=String(e).split(".").map(Number),a=String(t).split(".").map(Number);for(let r=0;r<Math.max(n.length,a.length);r+=1){const o=(n[r]||0)-(a[r]||0);if(o)return o>0?1:-1}return 0}async function oe(){try{return JSON.parse(await V(_,"utf8"))}catch{return null}}async function se(e){try{await K(l.dirname(_),{recursive:!0}),await j(_,JSON.stringify(e))}catch{}}async function v(e,t=ee){const n=new AbortController,a=setTimeout(()=>n.abort(),t);try{const r=await fetch(e,{headers:{Accept:"application/json, application/vnd.github+json",...O},signal:n.signal});if(!r.ok)throw new Error(r.status===403&&/github/.test(e)?"GitHub rate limit (60/hour per IP) — try again later":`HTTP ${r.status}`);return await r.json()}catch(r){const o=r?.cause?.code||r?.cause?.message||r?.message||String(r);throw new Error(n.signal.aborted?`the update server did not answer within ${Math.round(t/1e3)}s`:`${new URL(e).hostname}: ${o}`)}finally{clearTimeout(a)}}function x(e=process.argv[1]){let t=e?l.resolve(e):"";try{t=z(t)}catch{}const n=/^(.*[/\\]node_modules[/\\]@chatpanel[/\\]gateway)[/\\]/.exec(t);return n?n[1]:""}function ie(){const e=x();if(!e)return"";try{return String(JSON.parse(q(l.join(e,"package.json"),"utf8")).version||"")}catch{return""}}function $(){const e=l.dirname(process.execPath);return[l.join(e,"..","lib","node_modules","npm","bin","npm-cli.js"),l.join(e,"node_modules","npm","bin","npm-cli.js")].find(n=>W(n))||""}function le(e=process.env,t=process.execPath){const n={...e,npm_config_registry:E,npm_config_fund:"false",npm_config_audit:"false"};delete n.ELECTRON_RUN_AS_NODE;const a=Object.keys(n).find(r=>r.toLowerCase()==="path")||"PATH";return n[a]=[l.dirname(t),...(n[a]||"").split(l.delimiter).filter(Boolean)].filter((r,o,c)=>c.indexOf(r)===o).join(l.delimiter),n}function ce(){import("./prune-install.js").then(({pruneForeignPrebuilds:e,pruneLine:t})=>{const n=t(e({log:a=>console.log(a)}));n&&console.log(`[update]${n}`)}).catch(()=>{})}function de(){return["install","-g",`${g}@latest`,"--ignore-scripts"]}function pe(){const e=$(),t=le(),n=de(),[a,r]=e?[process.execPath,[e,...n]]:["npm",n];return new Promise(o=>{b(a,r,{env:t,timeout:k,maxBuffer:8<<20,windowsHide:!0},(c,p,s)=>{const i=`${p||""}${s||""}`.trim();return c?c.killed&&!i?o({ok:!1,out:`npm was still running after ${Math.round(k/6e4)} minutes and was stopped`}):o({ok:!1,out:i||(e?c.message:"could not run npm: it is not beside the node running this gateway and not on the service's PATH")}):(ce(),o({ok:!0,out:i}))})})}async function H(e,{force:t=!1}={}){const n=T()?"binary":"npm";if(S)return{current:e,latest:null,updateAvailable:!1,mode:n,canSelfUpdate:!1,assetUrl:null,stale:!1,error:"",npmCommand:null,channel:n==="npm"?"npm":"release",service:!1,disabled:!0};const a=re();let r=null,o=null,c=!1,p="",s=0;const i=await oe(),w=i&&i.mode===n,C=()=>{r=w&&i.latest||null,o=w&&i.assetUrl||null,s=w&&i.checkedAt||0,c=!0};if(!t&&w&&Date.now()-i.checkedAt<L)r=i.latest,o=i.assetUrl,s=i.checkedAt;else if(!t&&m.at&&Date.now()-m.at<N)p=m.error,C();else try{if(n==="npm"){let u;try{u=await v(X),r=f(u.version)}catch(B){const U=await v(D);if(r=f(U?.npm?.version)||f(U?.version),!r)throw B}}else{const u=await v(D);r=f(u.version)||f(u.release?.tag),o=a&&(u.release?.assets||[]).includes(a)?Z(a):null}s=Date.now(),await se({checkedAt:s,mode:n,latest:r,assetUrl:o}),m={at:0,error:""}}catch(u){p=u.message,m={at:Date.now(),error:p},C()}const M=!!r&&R(r,e)>0,I=n==="binary"?!!o&&(process.platform!=="win32"||y()):!!x()&&(process.platform!=="win32"||y()&&!!$()),F=n==="npm"?process.platform==="win32"?`chatpanel-gateway --stop; npm i -g ${g}@latest --ignore-scripts; chatpanel-gateway --install`:`npm i -g ${g}@latest --ignore-scripts`:null;return{current:e,latest:r,updateAvailable:M,mode:n,canSelfUpdate:I,assetUrl:o,stale:c,error:p,npmCommand:F,channel:n==="npm"?"npm":"release",service:y(),checkedAt:s}}let h=null,A=null;function _e(e){const t=T()?"binary":"npm";return S?{current:e,latest:null,updateAvailable:!1,mode:t,canSelfUpdate:!1,stale:!1,error:"",npmCommand:null,channel:t==="npm"?"npm":"release",service:!1,disabled:!0}:((!h||(h.stale?!(m.at&&Date.now()-m.at<N):Date.now()-h.seenAt>L))&&!A&&(A=H(e).then(a=>{h={...a,seenAt:Date.now()}}).catch(()=>{}).finally(()=>{A=null})),h?{...h,seenAt:void 0,current:e}:{current:e,latest:null,updateAvailable:!1,mode:t,canSelfUpdate:!1,stale:!0,checking:!0,error:"",npmCommand:null,channel:t==="npm"?"npm":"release",service:y()})}function Se(){h=null,A=null}async function ue(e){const t=process.execPath,n=l.dirname(t),a=l.join(n,`.chatpanel-gateway.new-${Date.now()}`),r=new AbortController,o=setTimeout(()=>r.abort(),te);let c;try{const s=await fetch(e.assetUrl,{headers:O,redirect:"follow",signal:r.signal});if(!s.ok)throw new Error(`download failed (HTTP ${s.status})`);if(!ae(s.url||e.assetUrl))throw new Error(`refused: the download was redirected to ${s.url}, which is not a ChatPanel release host`);c=Buffer.from(await s.arrayBuffer())}finally{clearTimeout(o)}if(c.length<5<<20)throw new Error(`the download was only ${(c.length/1024).toFixed(0)} KB — that is not the gateway, so nothing was replaced`);await j(a,c),process.platform!=="win32"&&await G(a,493),process.platform==="darwin"&&await new Promise(s=>b("xattr",["-c",a],()=>s()));const p=await new Promise(s=>b(a,["--version"],{timeout:6e4,windowsHide:!0},(i,w)=>s(i?"":String(w||"").trim())));if(!f(p))throw await Y(a,{force:!0}),new Error("the downloaded gateway would not run, so it was discarded");return process.platform==="win32"&&await P(t,l.join(n,`chatpanel-gateway.old-${Date.now()}.exe`)),await P(a,t),f(p)}async function me(e){if(S)throw new Error("Self-update is switched off on this gateway (CHATPANEL_SELF_UPDATE=off).");const t=await H(e,{force:!0});if(t.stale)throw new Error(`Could not reach the update server${t.error?` (${t.error})`:""}. Refusing to act on a stale check — try again in a few minutes.`);if(!t.updateAvailable)throw new Error(`Already on the latest ${t.channel} version (v${e}).`);if(!t.canSelfUpdate)throw new Error(t.mode==="npm"?`This gateway cannot update itself here. Run: ${t.npmCommand}`:"No downloadable build for this platform — install it with npm instead.");if(t.mode==="binary")return{from:e,to:await ue(t),mode:"binary"};if(process.platform==="win32")return{from:e,to:t.latest,mode:"npm",deferred:`"${process.execPath}" "${$()}" install -g ${g}@latest --registry=${E} --no-fund --no-audit`};const n=await pe();if(!n.ok)throw new Error(`npm install failed: ${n.out.slice(0,800)}`);const a=ie();if(!a||R(a,e)<=0)throw new Error(`npm ran, but the install at ${x()} is still ${a||"unreadable"} — the service launches a copy npm did not update. Run: ${t.npmCommand}`);return{from:e,to:a,mode:"npm"}}const d={state:"idle",mode:"",from:"",to:"",detail:"",startedAt:0,endedAt:0};function Te(){return{...d}}function ve(e,{restart:t=Q,apply:n=me}={}){return d.state==="installing"||d.state==="restarting"?{...d,already:!0}:(Object.assign(d,{state:"installing",mode:T()?"binary":"npm",from:e,to:"",detail:"",startedAt:Date.now(),endedAt:0}),n(e).then(a=>{Object.assign(d,{state:"restarting",to:a.to,mode:a.mode,detail:a.deferred?`stopping to install v${a.to}, then relaunching`:`v${a.to} is installed; restarting the gateway into it`}),setTimeout(()=>{t({winInstall:a.deferred||""})||Object.assign(d,{state:"done",endedAt:Date.now(),detail:`v${a.to} is installed, but this gateway is not run by a service it can restart. Start it again yourself to run the new version.`})},400)}).catch(a=>{Object.assign(d,{state:"failed",endedAt:Date.now(),detail:String(a?.message||a).slice(0,1200)})}),{...d})}function xe(){Object.assign(d,{state:"idle",mode:"",from:"",to:"",detail:"",startedAt:0,endedAt:0})}export{xe as _resetUpdateJob,Se as _resetUpdateStatus,H as checkForUpdate,R as cmpVersions,ae as downloadHostAllowed,T as isCompiledBinary,de as npmInstallArgs,le as npmInstallEnv,x as npmPackageRoot,Ee as resetUpdateBackoff,me as selfUpdate,ve as startUpdate,Te as updateJob,_e as updateStatus};
1
+ import U from"node:os";import i from"node:path";import{execFile as A}from"node:child_process";import{chmod as G,rename as L,mkdir as K,readFile as V,writeFile as R,rm as W}from"node:fs/promises";import{existsSync as Y,readFileSync as q,realpathSync as z}from"node:fs";import{restartService as Q,serviceRegistered as y}from"./service.js";const g="@chatpanel/gateway",Et="chatpanel/chatpanel-gateway",j="https://dl.chatpanel.net/version/gateway",E=(process.env.CHATPANEL_NPM_REGISTRY||process.env.npm_config_registry||"https://registry.npmjs.org").replace(/\/$/,""),X=`${E}/${g}/latest`,Z=t=>`https://dl.chatpanel.net/gateway/${t.replace(/^chatpanel-gateway-/,"")}`,D=360*60*1e3,N=600*1e3,tt=Math.max(500,Number(process.env.CHATPANEL_UPDATE_TIMEOUT_MS)||5e3),et=15*6e4,k=20*6e4,_=process.env.CHATPANEL_UPDATE_CACHE||i.join(U.homedir(),".chatpanel","gateway-update-check.json"),S=String(process.env.CHATPANEL_SELF_UPDATE||"").toLowerCase()==="off",O={"User-Agent":"chatpanel-gateway-updater"},nt=new Set(["dl.chatpanel.net","github.com","api.github.com","objects.githubusercontent.com","release-assets.githubusercontent.com"]);function at(t){try{const e=new URL(t);return e.protocol==="https:"&&nt.has(e.hostname)}catch{return!1}}let m={at:0,error:""};function _t(){m={at:0,error:""}}function $(){const t=i.basename(process.execPath).toLowerCase();return!(t.startsWith("node")||t.startsWith("bun"))}function rt(){return process.platform==="darwin"?`chatpanel-gateway-macos-${process.arch==="arm64"?"arm64":"x64"}`:process.platform==="linux"?process.arch==="x64"?"chatpanel-gateway-linux-x64":null:process.platform==="win32"?"chatpanel-gateway-windows-x64.exe":null}function f(t=""){const e=/(\d+(?:\.\d+){0,3})/.exec(t||"");return e?e[1]:null}function H(t,e){const n=String(t).split(".").map(Number),a=String(e).split(".").map(Number);for(let r=0;r<Math.max(n.length,a.length);r+=1){const o=(n[r]||0)-(a[r]||0);if(o)return o>0?1:-1}return 0}async function ot(){try{return JSON.parse(await V(_,"utf8"))}catch{return null}}async function st(t){try{await K(i.dirname(_),{recursive:!0}),await R(_,JSON.stringify(t))}catch{}}async function x(t,e=tt){const n=new AbortController,a=setTimeout(()=>n.abort(),e);try{const r=await fetch(t,{headers:{Accept:"application/json, application/vnd.github+json",...O},signal:n.signal});if(!r.ok)throw new Error(r.status===403&&/github/.test(t)?"GitHub rate limit (60/hour per IP) — try again later":`HTTP ${r.status}`);return await r.json()}catch(r){const o=r?.cause?.code||r?.cause?.message||r?.message||String(r);throw new Error(n.signal.aborted?`the update server did not answer within ${Math.round(e/1e3)}s`:`${new URL(t).hostname}: ${o}`)}finally{clearTimeout(a)}}function T(t=process.argv[1]){let e=t?i.resolve(t):"";try{e=z(e)}catch{}const n=/^(.*[/\\]node_modules[/\\]@chatpanel[/\\]gateway)[/\\]/.exec(e);return n?n[1]:""}function it(){const t=T();if(!t)return"";try{return String(JSON.parse(q(i.join(t,"package.json"),"utf8")).version||"")}catch{return""}}function v(){const t=i.dirname(process.execPath);return[i.join(t,"..","lib","node_modules","npm","bin","npm-cli.js"),i.join(t,"node_modules","npm","bin","npm-cli.js")].find(n=>Y(n))||""}function lt(t=process.env,e=process.execPath){const n={...t,npm_config_registry:E,npm_config_fund:"false",npm_config_audit:"false"};delete n.ELECTRON_RUN_AS_NODE;const a=Object.keys(n).find(r=>r.toLowerCase()==="path")||"PATH";return n[a]=[i.dirname(e),...(n[a]||"").split(i.delimiter).filter(Boolean)].filter((r,o,c)=>c.indexOf(r)===o).join(i.delimiter),n}function ct(){import("./prune-install.js").then(({pruneForeignPrebuilds:t,pruneLine:e})=>{const n=e(t({log:a=>console.log(a)}));n&&console.log(`[update]${n}`)}).catch(()=>{})}function pt(){return["install","-g",`${g}@latest`,"--ignore-scripts"]}function dt(t,{home:e=U.homedir(),platform:n=process.platform}={}){if(n==="win32"||!/\b(EACCES|EPERM)\b/.test(t||""))return"";const a=(t.match(/^npm (?:error|ERR!) path (.+)$/m)||[])[1]?.trim()||"",r=a.indexOf(`${i.sep}lib${i.sep}node_modules`),o=r>0?a.slice(0,r):"";return o?o===e||o.startsWith(e+i.sep)?`npm cannot write ${o} — part of it belongs to another user, usually from an earlier \`sudo npm i -g\` (npm's hint about ~/.npm is a different folder). Fix: sudo chown -R "$(whoami)" "${o}" — then update again.`:`npm cannot write ${o}, which belongs to another user. Install the standalone build instead — it needs no npm: curl -fsSL https://dl.chatpanel.net/install.sh | bash`:""}function ut(){const t=v(),e=lt(),n=pt(),[a,r]=t?[process.execPath,[t,...n]]:["npm",n];return new Promise(o=>{A(a,r,{env:e,timeout:k,maxBuffer:8<<20,windowsHide:!0},(c,d,s)=>{const l=`${d||""}${s||""}`.trim();return c?c.killed&&!l?o({ok:!1,out:`npm was still running after ${Math.round(k/6e4)} minutes and was stopped`}):o({ok:!1,out:l||(t?c.message:"could not run npm: it is not beside the node running this gateway and not on the service's PATH")}):(ct(),o({ok:!0,out:l}))})})}async function M(t,{force:e=!1}={}){const n=$()?"binary":"npm";if(S)return{current:t,latest:null,updateAvailable:!1,mode:n,canSelfUpdate:!1,assetUrl:null,stale:!1,error:"",npmCommand:null,channel:n==="npm"?"npm":"release",service:!1,disabled:!0};const a=rt();let r=null,o=null,c=!1,d="",s=0;const l=await ot(),w=l&&l.mode===n,C=()=>{r=w&&l.latest||null,o=w&&l.assetUrl||null,s=w&&l.checkedAt||0,c=!0};if(!e&&w&&Date.now()-l.checkedAt<D)r=l.latest,o=l.assetUrl,s=l.checkedAt;else if(!e&&m.at&&Date.now()-m.at<N)d=m.error,C();else try{if(n==="npm"){let u;try{u=await x(X),r=f(u.version)}catch(J){const P=await x(j);if(r=f(P?.npm?.version)||f(P?.version),!r)throw J}}else{const u=await x(j);r=f(u.version)||f(u.release?.tag),o=a&&(u.release?.assets||[]).includes(a)?Z(a):null}s=Date.now(),await st({checkedAt:s,mode:n,latest:r,assetUrl:o}),m={at:0,error:""}}catch(u){d=u.message,m={at:Date.now(),error:d},C()}const I=!!r&&H(r,t)>0,F=n==="binary"?!!o&&(process.platform!=="win32"||y()):!!T()&&(process.platform!=="win32"||y()&&!!v()),B=n==="npm"?process.platform==="win32"?`chatpanel-gateway --stop; npm i -g ${g}@latest --ignore-scripts; chatpanel-gateway --install`:`npm i -g ${g}@latest --ignore-scripts`:null;return{current:t,latest:r,updateAvailable:I,mode:n,canSelfUpdate:F,assetUrl:o,stale:c,error:d,npmCommand:B,channel:n==="npm"?"npm":"release",service:y(),checkedAt:s}}let h=null,b=null;function St(t){const e=$()?"binary":"npm";return S?{current:t,latest:null,updateAvailable:!1,mode:e,canSelfUpdate:!1,stale:!1,error:"",npmCommand:null,channel:e==="npm"?"npm":"release",service:!1,disabled:!0}:((!h||(h.stale?!(m.at&&Date.now()-m.at<N):Date.now()-h.seenAt>D))&&!b&&(b=M(t).then(a=>{h={...a,seenAt:Date.now()}}).catch(()=>{}).finally(()=>{b=null})),h?{...h,seenAt:void 0,current:t}:{current:t,latest:null,updateAvailable:!1,mode:e,canSelfUpdate:!1,stale:!0,checking:!0,error:"",npmCommand:null,channel:e==="npm"?"npm":"release",service:y()})}function $t(){h=null,b=null}async function mt(t){const e=process.execPath,n=i.dirname(e),a=i.join(n,`.chatpanel-gateway.new-${Date.now()}`),r=new AbortController,o=setTimeout(()=>r.abort(),et);let c;try{const s=await fetch(t.assetUrl,{headers:O,redirect:"follow",signal:r.signal});if(!s.ok)throw new Error(`download failed (HTTP ${s.status})`);if(!at(s.url||t.assetUrl))throw new Error(`refused: the download was redirected to ${s.url}, which is not a ChatPanel release host`);c=Buffer.from(await s.arrayBuffer())}finally{clearTimeout(o)}if(c.length<5<<20)throw new Error(`the download was only ${(c.length/1024).toFixed(0)} KB — that is not the gateway, so nothing was replaced`);await R(a,c),process.platform!=="win32"&&await G(a,493),process.platform==="darwin"&&await new Promise(s=>A("xattr",["-c",a],()=>s()));const d=await new Promise(s=>A(a,["--version"],{timeout:6e4,windowsHide:!0},(l,w)=>s(l?"":String(w||"").trim())));if(!f(d))throw await W(a,{force:!0}),new Error("the downloaded gateway would not run, so it was discarded");return process.platform==="win32"&&await L(e,i.join(n,`chatpanel-gateway.old-${Date.now()}.exe`)),await L(a,e),f(d)}async function ft(t){if(S)throw new Error("Self-update is switched off on this gateway (CHATPANEL_SELF_UPDATE=off).");const e=await M(t,{force:!0});if(e.stale)throw new Error(`Could not reach the update server${e.error?` (${e.error})`:""}. Refusing to act on a stale check — try again in a few minutes.`);if(!e.updateAvailable)throw new Error(`Already on the latest ${e.channel} version (v${t}).`);if(!e.canSelfUpdate)throw new Error(e.mode==="npm"?`This gateway cannot update itself here. Run: ${e.npmCommand}`:"No downloadable build for this platform — install it with npm instead.");if(e.mode==="binary")return{from:t,to:await mt(e),mode:"binary"};if(process.platform==="win32")return{from:t,to:e.latest,mode:"npm",deferred:`"${process.execPath}" "${v()}" install -g ${g}@latest --registry=${E} --no-fund --no-audit`};const n=await ut();if(!n.ok){const r=dt(n.out);throw new Error(r?`${r}
2
+
3
+ npm said: ${n.out.slice(0,600)}`:`npm install failed: ${n.out.slice(0,800)}`)}const a=it();if(!a||H(a,t)<=0)throw new Error(`npm ran, but the install at ${T()} is still ${a||"unreadable"} — the service launches a copy npm did not update. Run: ${e.npmCommand}`);return{from:t,to:a,mode:"npm"}}const p={state:"idle",mode:"",from:"",to:"",detail:"",startedAt:0,endedAt:0};function xt(){return{...p}}function Tt(t,{restart:e=Q,apply:n=ft}={}){return p.state==="installing"||p.state==="restarting"?{...p,already:!0}:(Object.assign(p,{state:"installing",mode:$()?"binary":"npm",from:t,to:"",detail:"",startedAt:Date.now(),endedAt:0}),n(t).then(a=>{Object.assign(p,{state:"restarting",to:a.to,mode:a.mode,detail:a.deferred?`stopping to install v${a.to}, then relaunching`:`v${a.to} is installed; restarting the gateway into it`}),setTimeout(()=>{e({winInstall:a.deferred||""})||Object.assign(p,{state:"done",endedAt:Date.now(),detail:`v${a.to} is installed, but this gateway is not run by a service it can restart. Start it again yourself to run the new version.`})},400)}).catch(a=>{Object.assign(p,{state:"failed",endedAt:Date.now(),detail:String(a?.message||a).slice(0,1200)})}),{...p})}function vt(){Object.assign(p,{state:"idle",mode:"",from:"",to:"",detail:"",startedAt:0,endedAt:0})}export{vt as _resetUpdateJob,$t as _resetUpdateStatus,M as checkForUpdate,H as cmpVersions,at as downloadHostAllowed,$ as isCompiledBinary,pt as npmInstallArgs,lt as npmInstallEnv,T as npmPackageRoot,dt as npmPermissionHint,_t as resetUpdateBackoff,ft as selfUpdate,Tt as startUpdate,xt as updateJob,St as updateStatus};
package/src/version.js CHANGED
@@ -1 +1 @@
1
- const o="0.61.0";export{o as VERSION};
1
+ const o="0.64.0";export{o as VERSION};