@chatpanel/gateway 0.6.109 → 0.7.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +24 -4
- package/bin/chatpanel-gateway-bin.mjs +1 -24
- package/bin/chatpanel-gateway.js +3 -97
- package/package.json +1 -7
- package/src/access-log-store.js +1 -45
- package/src/agent.js +2 -256
- package/src/anthropic.js +3 -83
- package/src/backup-decrypt.js +1 -45
- package/src/backup-ingest.js +6 -120
- package/src/bridge-supervisor.js +3 -212
- package/src/bridge.js +4 -252
- package/src/budget.js +1 -117
- package/src/config.js +1 -209
- package/src/configstore.js +1 -181
- package/src/connect-agents.js +22 -179
- package/src/diarize-engine.js +1 -188
- package/src/egress.js +2 -0
- package/src/engine-ledger-store.js +1 -150
- package/src/engine.js +1 -132
- package/src/entitlement-refresh.js +1 -84
- package/src/entitlement.js +1 -76
- package/src/extraction.js +4 -294
- package/src/freegate.js +1 -47
- package/src/gate.js +1 -75
- package/src/gateway-token.js +1 -60
- package/src/history-store.js +1 -251
- package/src/job.js +3 -148
- package/src/knowledge.js +3 -215
- package/src/local-status.js +6 -102
- package/src/log.js +1 -21
- package/src/mcp-cli.js +19 -113
- package/src/mcp.js +34 -546
- package/src/memory-store.js +1 -176
- package/src/memory.js +2 -642
- package/src/model-integrity.js +1 -82
- package/src/model-ledger.js +1 -229
- package/src/model-runtime.js +1 -37
- package/src/models.js +1 -92
- package/src/ner-engine.js +1 -318
- package/src/ner.js +1 -113
- package/src/observability.js +1 -123
- package/src/openai.js +2 -84
- package/src/ort.js +1 -52
- package/src/parakeet-engine.js +2 -228
- package/src/pocket-tts-engine.js +1 -520
- package/src/prefs-store.js +1 -149
- package/src/project-store.js +1 -139
- package/src/project.js +1 -171
- package/src/recruit.js +3 -424
- package/src/recruiting.js +1 -93
- package/src/redact.js +2 -123
- package/src/responses.js +2 -80
- package/src/router.js +1 -292
- package/src/rrf.js +1 -93
- package/src/scorecard-store.js +1 -92
- package/src/scorecard.js +1 -336
- package/src/search-index.js +2 -134
- package/src/secure-fetch.js +1 -58
- package/src/sentencepiece.js +1 -184
- package/src/server.js +10 -2290
- package/src/service.js +11 -189
- package/src/shape.js +5 -121
- package/src/sqlite-store.js +3 -212
- package/src/stream.js +5 -182
- package/src/structured.js +4 -902
- package/src/stt-engine.js +1 -486
- package/src/stt-models.js +1 -144
- package/src/subject-kinds.js +1 -6
- package/src/subject-name.js +1 -97
- package/src/team-board.js +6 -338
- package/src/team-record.js +1 -226
- package/src/team-store.js +1 -261
- package/src/team.js +1 -303
- package/src/toolrelay.js +3 -122
- package/src/tts-engine.js +1 -453
- package/src/tts-models.js +1 -254
- package/src/tts-remote.js +1 -109
- package/src/tts-voice-resolve.js +1 -78
- package/src/tts-voices.js +1 -192
- package/src/update.js +1 -305
package/src/bridge.js
CHANGED
|
@@ -1,253 +1,5 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
// gateway, with redaction in the middle.
|
|
5
|
-
//
|
|
6
|
-
// gateway → POST http://127.0.0.1:4319/chat { agent, messages, system }
|
|
7
|
-
// ← SSE { type:'delta'|'tool'|'reasoning'|'status'|'done'|'error' }
|
|
8
|
-
//
|
|
9
|
-
// We only surface the model's *text* (delta/done) to the caller; the agent's own
|
|
10
|
-
// tool/reasoning events are its local side effects. Auth uses the bridge's
|
|
11
|
-
// per-install bearer token (~/.chatpanel/bridge-token), the same token a
|
|
12
|
-
// non-browser local client is expected to present.
|
|
1
|
+
import{readFileSync as D,existsSync as j}from"node:fs";import{join as C}from"node:path";import L from"node:os";const A=C(L.homedir(),".chatpanel","bridge-token"),N="http://127.0.0.1:4319",v=1e4;let c={at:0,cfgUrl:"",url:"",fell:!1};async function E(t,e){try{return(await fetch(`${t}/health`,{signal:AbortSignal.timeout(e)})).ok}catch{return!1}}async function k(t,{fallback:e,timeoutMs:r=1500,now:o=Date.now()}={}){e===void 0&&(e=process.env.CHATPANEL_BRIDGE_FALLBACK==="off"?"":N);const s=String(t?.bridge?.url||"").replace(/\/$/,"");if(c.url&&c.cfgUrl===s&&o-c.at<v)return c.url;let n=s||e,l=!1;return e&&n!==e&&!await E(n,r)&&await E(e,r)&&(n=e,l=!0,(!c.fell||c.cfgUrl!==s)&&console.log(`[gateway] bridge.url ${s} is not answering; the bridge on ${e} is — using it (fix the address in Settings to silence this)`)),c={at:o,cfgUrl:s,url:n,fell:l},n}function z(){c={at:0,cfgUrl:"",url:"",fell:!1}}let y=!1;function S(t){try{if(j(t))return D(t,"utf8").trim()}catch{}return""}function F(t,e=A){const r=S(e);return!t||y&&r&&r!==t?r:t}function J(t,e=A){const r=S(e);return!r||r===t?"":(y||(y=!0,console.warn("[gateway] the bridge rejected bridge.token from gateway.config.json; using ~/.chatpanel/bridge-token (the bridge wrote it). Clear the config value to silence this.")),r)}function M(){y=!1}const P=t=>t===401||t===403;async function R(t,e,r,o,s){const n=a=>fetch(`${t.replace(/\/$/,"")}/chat`,{method:"POST",headers:{"content-type":"application/json",...a?{authorization:`Bearer ${a}`}:{}},body:r,signal:o}),l=F(e,s);let f=await n(l);if(P(f.status)){const a=J(l,s);a&&(await f.text().catch(()=>{}),f=await n(a))}return f}function G(t){return typeof t=="string"?t:Array.isArray(t)?t.map(e=>typeof e=="string"?e:typeof e?.text=="string"?e.text:"").filter(Boolean).join(`
|
|
2
|
+
`):""}function _(t){return(t||[]).filter(e=>e&&(e.role==="user"||e.role==="assistant"||e.role==="system")).map(e=>({role:e.role,content:G(e.content)}))}async function W({bridgeUrl:t,agent:e,token:r,messages:o,system:s,specs:n,options:l,signal:f,tokenPath:a}){const u=await R(t,r,JSON.stringify({agent:e,messages:_(o),system:s||"",options:l||{},...Array.isArray(n)&&n.length?{pageTools:{specs:n}}:{}}),f,a);if(!u.ok||!u.body)throw new Error(await $(u));return u}async function $(t){const e=await t.text().catch(()=>"");let r="";try{const o=JSON.parse(e);r=String(o?.error?.message||o?.error||o?.message||"").trim()}catch{}return r?r.slice(0,600):`bridge /chat HTTP ${t.status}${e?`: ${e.slice(0,200)}`:""}`}async function q({bridgeUrl:t,agent:e,token:r,messages:o,system:s,options:n,signal:l,tokenPath:f},a,u=null){const p=await R(t,r,JSON.stringify({agent:e,messages:_(o),system:s||"",options:n||{}}),l,f);if(!p.ok||!p.body)throw new Error(await $(p));const O=p.body.getReader(),U=new TextDecoder;let d="",h="",T=!1,w=null;const b=x=>{for(const m of x.split(`
|
|
3
|
+
`)){const g=m.trim();if(!g.startsWith("data:"))continue;const B=g.slice(5).trim();if(!B||B==="[DONE]")continue;let i;try{i=JSON.parse(B)}catch{continue}i.type==="delta"&&typeof i.text=="string"?(T=!0,h+=i.text,a(i.text)):i.type==="done"?!T&&typeof i.text=="string"&&i.text&&(h+=i.text,a(i.text)):i.type==="error"?w=new Error(i.error||"bridge error"):u&&u(i)}};for(;;){const{done:x,value:m}=await O.read();if(x)break;d+=U.decode(m,{stream:!0});let g;for(;(g=d.indexOf(`
|
|
13
4
|
|
|
14
|
-
|
|
15
|
-
import { join } from 'node:path';
|
|
16
|
-
import os from 'node:os';
|
|
17
|
-
|
|
18
|
-
const DEFAULT_TOKEN_PATH = join(os.homedir(), '.chatpanel', 'bridge-token');
|
|
19
|
-
|
|
20
|
-
export const DEFAULT_BRIDGE_URL = 'http://127.0.0.1:4319';
|
|
21
|
-
const BRIDGE_PROBE_TTL_MS = 10_000;
|
|
22
|
-
let bridgeResolved = { at: 0, cfgUrl: '', url: '', fell: false };
|
|
23
|
-
|
|
24
|
-
async function bridgeAnswers(url, timeoutMs) {
|
|
25
|
-
try {
|
|
26
|
-
const r = await fetch(`${url}/health`, { signal: AbortSignal.timeout(timeoutMs) });
|
|
27
|
-
return r.ok;
|
|
28
|
-
} catch { return false; }
|
|
29
|
-
}
|
|
30
|
-
|
|
31
|
-
/**
|
|
32
|
-
* Where the bridge is, checked rather than believed.
|
|
33
|
-
*
|
|
34
|
-
* The persisted bridge.url was found pointing at an ephemeral port nothing answered on,
|
|
35
|
-
* while the real bridge sat on 4319: every agent showed unavailable, every agent turn failed,
|
|
36
|
-
* and the startup line said so in a log nobody was reading. A configured address that does
|
|
37
|
-
* not answer while the default one does is a stale setting, not a decision, so the default
|
|
38
|
-
* is used and the fall-back is logged. Probed at most every ten seconds.
|
|
39
|
-
*/
|
|
40
|
-
export async function resolveBridgeUrl(cfg, { fallback, timeoutMs = 1500, now = Date.now() } = {}) {
|
|
41
|
-
// CHATPANEL_BRIDGE_FALLBACK=off disables the fallback: the test suite sets it, because a
|
|
42
|
-
// test whose fake bridge has gone away would otherwise find the developer's REAL bridge on
|
|
43
|
-
// 4319 and send its turns to a live coding agent.
|
|
44
|
-
if (fallback === undefined) fallback = process.env.CHATPANEL_BRIDGE_FALLBACK === 'off' ? '' : DEFAULT_BRIDGE_URL;
|
|
45
|
-
const cfgUrl = String(cfg?.bridge?.url || '').replace(/\/$/, '');
|
|
46
|
-
if (bridgeResolved.url && bridgeResolved.cfgUrl === cfgUrl && now - bridgeResolved.at < BRIDGE_PROBE_TTL_MS) return bridgeResolved.url;
|
|
47
|
-
let url = cfgUrl || fallback;
|
|
48
|
-
let fell = false;
|
|
49
|
-
if (fallback && url !== fallback && !(await bridgeAnswers(url, timeoutMs)) && await bridgeAnswers(fallback, timeoutMs)) {
|
|
50
|
-
url = fallback;
|
|
51
|
-
fell = true;
|
|
52
|
-
if (!bridgeResolved.fell || bridgeResolved.cfgUrl !== cfgUrl) console.log(`[gateway] bridge.url ${cfgUrl} is not answering; the bridge on ${fallback} is — using it (fix the address in Settings to silence this)`);
|
|
53
|
-
}
|
|
54
|
-
bridgeResolved = { at: now, cfgUrl, url, fell };
|
|
55
|
-
return url;
|
|
56
|
-
}
|
|
57
|
-
|
|
58
|
-
/** Test seam. */
|
|
59
|
-
export function resetBridgeResolution() { bridgeResolved = { at: 0, cfgUrl: '', url: '', fell: false }; }
|
|
60
|
-
|
|
61
|
-
// Once the bridge has REJECTED the configured token while the file held a different one,
|
|
62
|
-
// the file is what every later call presents. Set by `bridgeTokenRejected`, below.
|
|
63
|
-
let preferFileToken = false;
|
|
64
|
-
|
|
65
|
-
function fileToken(tokenPath) {
|
|
66
|
-
try {
|
|
67
|
-
if (existsSync(tokenPath)) return readFileSync(tokenPath, 'utf8').trim();
|
|
68
|
-
} catch { /* ignore */ }
|
|
69
|
-
return '';
|
|
70
|
-
}
|
|
71
|
-
|
|
72
|
-
/**
|
|
73
|
-
* The bridge token: the config's value first, the file otherwise — until the bridge says
|
|
74
|
-
* the config's value is wrong.
|
|
75
|
-
*
|
|
76
|
-
* `bridge.token` in gateway.config.json is a COPY: the extension's Gateway tab writes its
|
|
77
|
-
* own setting there, and a bridge that regenerates its token leaves the copy behind. The
|
|
78
|
-
* desktop then relayed every Codex turn with the stale copy and got 403 from a bridge ten
|
|
79
|
-
* milliseconds away — an empty streaming bubble, forever. The file is written by the
|
|
80
|
-
* bridge itself, so when the configured token is rejected and the file differs, the file
|
|
81
|
-
* is tried once and, if it works, kept. Nothing is second-guessed before the bridge has
|
|
82
|
-
* actually said no: a pinned token on a loopback bridge stays a pinned token.
|
|
83
|
-
*/
|
|
84
|
-
export function readBridgeToken(cfgToken, tokenPath = DEFAULT_TOKEN_PATH) {
|
|
85
|
-
const file = fileToken(tokenPath);
|
|
86
|
-
if (!cfgToken) return file;
|
|
87
|
-
if (preferFileToken && file && file !== cfgToken) return file;
|
|
88
|
-
return cfgToken;
|
|
89
|
-
}
|
|
90
|
-
|
|
91
|
-
/**
|
|
92
|
-
* Called with the token the bridge just refused. Returns the file's token when it is a
|
|
93
|
-
* different one worth trying — and from then on `readBridgeToken` prefers it — or '' when
|
|
94
|
-
* there is nothing else to try.
|
|
95
|
-
*/
|
|
96
|
-
export function bridgeTokenRejected(rejected, tokenPath = DEFAULT_TOKEN_PATH) {
|
|
97
|
-
const file = fileToken(tokenPath);
|
|
98
|
-
if (!file || file === rejected) return '';
|
|
99
|
-
if (!preferFileToken) {
|
|
100
|
-
preferFileToken = true;
|
|
101
|
-
console.warn('[gateway] the bridge rejected bridge.token from gateway.config.json; using ~/.chatpanel/bridge-token (the bridge wrote it). Clear the config value to silence this.');
|
|
102
|
-
}
|
|
103
|
-
return file;
|
|
104
|
-
}
|
|
105
|
-
|
|
106
|
-
/** Test seam. */
|
|
107
|
-
export function resetBridgeTokenPreference() { preferFileToken = false; }
|
|
108
|
-
|
|
109
|
-
const isAuthFailure = (status) => status === 401 || status === 403;
|
|
110
|
-
|
|
111
|
-
// One POST to /chat, retried once with the file's token when the bridge refuses the one
|
|
112
|
-
// it was given — the stale-copy case above.
|
|
113
|
-
async function postChat(bridgeUrl, token, body, signal, tokenPath) {
|
|
114
|
-
const send = (t) => fetch(`${bridgeUrl.replace(/\/$/, '')}/chat`, {
|
|
115
|
-
method: 'POST',
|
|
116
|
-
headers: { 'content-type': 'application/json', ...(t ? { authorization: `Bearer ${t}` } : {}) },
|
|
117
|
-
body,
|
|
118
|
-
signal,
|
|
119
|
-
});
|
|
120
|
-
// A caller hands over the token it resolved; once a rejection has flipped the
|
|
121
|
-
// preference, the file's token goes first here too.
|
|
122
|
-
const first = readBridgeToken(token, tokenPath);
|
|
123
|
-
let res = await send(first);
|
|
124
|
-
if (isAuthFailure(res.status)) {
|
|
125
|
-
const alt = bridgeTokenRejected(first, tokenPath);
|
|
126
|
-
if (alt) { await res.text().catch(() => {}); res = await send(alt); }
|
|
127
|
-
}
|
|
128
|
-
return res;
|
|
129
|
-
}
|
|
130
|
-
|
|
131
|
-
// Flatten an OpenAI/Anthropic message's content (string | parts[]) to plain text
|
|
132
|
-
// for the bridge, which expects string content. Image parts are dropped here (the
|
|
133
|
-
// bridge takes images separately; wire that later if needed).
|
|
134
|
-
function flattenContent(content) {
|
|
135
|
-
if (typeof content === 'string') return content;
|
|
136
|
-
if (Array.isArray(content)) {
|
|
137
|
-
return content
|
|
138
|
-
.map((p) => (typeof p === 'string' ? p : (typeof p?.text === 'string' ? p.text : '')))
|
|
139
|
-
.filter(Boolean)
|
|
140
|
-
.join('\n');
|
|
141
|
-
}
|
|
142
|
-
return '';
|
|
143
|
-
}
|
|
144
|
-
|
|
145
|
-
export function toBridgeMessages(messages) {
|
|
146
|
-
return (messages || [])
|
|
147
|
-
.filter((m) => m && (m.role === 'user' || m.role === 'assistant' || m.role === 'system'))
|
|
148
|
-
.map((m) => ({ role: m.role, content: flattenContent(m.content) }));
|
|
149
|
-
}
|
|
150
|
-
|
|
151
|
-
// Open a bridge /chat stream WITH tool specs (pageTools), returning the raw fetch
|
|
152
|
-
// Response so the tool-relay can hold the reader open across the OpenAI round-trip.
|
|
153
|
-
export async function openBridgeChat({ bridgeUrl, agent, token, messages, system, specs, options, signal, tokenPath }) {
|
|
154
|
-
const res = await postChat(bridgeUrl, token, JSON.stringify({
|
|
155
|
-
agent,
|
|
156
|
-
messages: toBridgeMessages(messages),
|
|
157
|
-
system: system || '',
|
|
158
|
-
options: options || {},
|
|
159
|
-
...(Array.isArray(specs) && specs.length ? { pageTools: { specs } } : {}),
|
|
160
|
-
}), signal, tokenPath);
|
|
161
|
-
if (!res.ok || !res.body) throw new Error(await bridgeRefusal(res));
|
|
162
|
-
return res;
|
|
163
|
-
}
|
|
164
|
-
|
|
165
|
-
/**
|
|
166
|
-
* What the bridge said when it refused a turn, as a sentence. The bridge answers
|
|
167
|
-
* `{ error: { message } }` — and for the commonest first-run failure that message is the
|
|
168
|
-
* whole story ("Claude Code isn't signed in … run `claude`, type `/login` …"). Wrapping it in
|
|
169
|
-
* `bridge /chat HTTP 503: {"error":{"message":"…` and cutting it at 200 characters turned the
|
|
170
|
-
* one useful sentence into JSON debris.
|
|
171
|
-
*/
|
|
172
|
-
export async function bridgeRefusal(res) {
|
|
173
|
-
const text = await res.text().catch(() => '');
|
|
174
|
-
let message = '';
|
|
175
|
-
try { const j = JSON.parse(text); message = String(j?.error?.message || j?.error || j?.message || '').trim(); } catch { /* not JSON */ }
|
|
176
|
-
if (message) return message.slice(0, 600);
|
|
177
|
-
return `bridge /chat HTTP ${res.status}${text ? `: ${text.slice(0, 200)}` : ''}`;
|
|
178
|
-
}
|
|
179
|
-
|
|
180
|
-
// Stream a turn through the bridge. Calls onText(restorableChunk) for each delta, and
|
|
181
|
-
// onActivity(event) for everything else the agent reports — status lines, the working
|
|
182
|
-
// directory, tool calls, reasoning.
|
|
183
|
-
// of model text and returns the full (un-restored) text. Throws on bridge error.
|
|
184
|
-
export async function streamBridgeChat({ bridgeUrl, agent, token, messages, system, options, signal, tokenPath }, onText, onActivity = null) {
|
|
185
|
-
const res = await postChat(bridgeUrl, token, JSON.stringify({
|
|
186
|
-
agent,
|
|
187
|
-
messages: toBridgeMessages(messages),
|
|
188
|
-
system: system || '',
|
|
189
|
-
options: options || {},
|
|
190
|
-
}), signal, tokenPath);
|
|
191
|
-
|
|
192
|
-
if (!res.ok || !res.body) throw new Error(await bridgeRefusal(res));
|
|
193
|
-
|
|
194
|
-
const reader = res.body.getReader();
|
|
195
|
-
const decoder = new TextDecoder();
|
|
196
|
-
let buf = '';
|
|
197
|
-
let full = '';
|
|
198
|
-
let streamed = false;
|
|
199
|
-
let err = null;
|
|
200
|
-
|
|
201
|
-
const handleEvent = (block) => {
|
|
202
|
-
// SSE: lines of "data: <json>" (the bridge emits one JSON object per event).
|
|
203
|
-
for (const line of block.split('\n')) {
|
|
204
|
-
const s = line.trim();
|
|
205
|
-
if (!s.startsWith('data:')) continue;
|
|
206
|
-
const payload = s.slice(5).trim();
|
|
207
|
-
if (!payload || payload === '[DONE]') continue;
|
|
208
|
-
let evt;
|
|
209
|
-
try { evt = JSON.parse(payload); } catch { continue; }
|
|
210
|
-
if (evt.type === 'delta' && typeof evt.text === 'string') {
|
|
211
|
-
streamed = true;
|
|
212
|
-
full += evt.text;
|
|
213
|
-
onText(evt.text);
|
|
214
|
-
} else if (evt.type === 'done') {
|
|
215
|
-
// Some engines only deliver the full text at the end (not streamed).
|
|
216
|
-
if (!streamed && typeof evt.text === 'string' && evt.text) {
|
|
217
|
-
full += evt.text;
|
|
218
|
-
onText(evt.text);
|
|
219
|
-
}
|
|
220
|
-
} else if (evt.type === 'error') {
|
|
221
|
-
err = new Error(evt.error || 'bridge error');
|
|
222
|
-
} else if (onActivity) {
|
|
223
|
-
// WHAT THE AGENT IS DOING, for a client that wants to show it.
|
|
224
|
-
//
|
|
225
|
-
// These used to be dropped with a comment calling them "the agent's local side
|
|
226
|
-
// effects". They are — and they are also the ONLY thing that happens for the ten
|
|
227
|
-
// seconds an agent spends reading files before it says a word. A client routed
|
|
228
|
-
// through this gateway saw a spinner and nothing else, while one talking to the
|
|
229
|
-
// bridge directly showed the work; that difference was pushing clients toward the
|
|
230
|
-
// direct path, which is the one with no redaction in it.
|
|
231
|
-
//
|
|
232
|
-
// Passed through as-is. Deciding here which of a coding agent's events are worth
|
|
233
|
-
// showing would be this file guessing at someone's UI.
|
|
234
|
-
onActivity(evt);
|
|
235
|
-
}
|
|
236
|
-
}
|
|
237
|
-
};
|
|
238
|
-
|
|
239
|
-
for (;;) {
|
|
240
|
-
const { done, value } = await reader.read();
|
|
241
|
-
if (done) break;
|
|
242
|
-
buf += decoder.decode(value, { stream: true });
|
|
243
|
-
let idx;
|
|
244
|
-
// Events are separated by a blank line.
|
|
245
|
-
while ((idx = buf.indexOf('\n\n')) !== -1) {
|
|
246
|
-
handleEvent(buf.slice(0, idx));
|
|
247
|
-
buf = buf.slice(idx + 2);
|
|
248
|
-
}
|
|
249
|
-
}
|
|
250
|
-
if (buf.trim()) handleEvent(buf);
|
|
251
|
-
if (err) throw err;
|
|
252
|
-
return full;
|
|
253
|
-
}
|
|
5
|
+
`))!==-1;)b(d.slice(0,g)),d=d.slice(g+2)}if(d.trim()&&b(d),w)throw w;return h}export{N as DEFAULT_BRIDGE_URL,$ as bridgeRefusal,J as bridgeTokenRejected,W as openBridgeChat,F as readBridgeToken,z as resetBridgeResolution,M as resetBridgeTokenPreference,k as resolveBridgeUrl,q as streamBridgeChat,_ as toBridgeMessages};
|
package/src/budget.js
CHANGED
|
@@ -1,117 +1 @@
|
|
|
1
|
-
|
|
2
|
-
// A budget — the number a run may not exceed, and the record of what it spent.
|
|
3
|
-
//
|
|
4
|
-
// There was no spend cap anywhere. A live monitor is declared class C and starts model turns
|
|
5
|
-
// for the length of a meeting; a spoken "keep an eye on X" arms that with nothing bounding
|
|
6
|
-
// it; `jobs.js` caps a per-day job COUNT, not spend. The class declarations on every intent
|
|
7
|
-
// and rule were made for exactly this, and nothing read them.
|
|
8
|
-
//
|
|
9
|
-
// A budget is a VALUE: declared on the thing that spends (a team, a schedule, a monitor),
|
|
10
|
-
// charged by whatever runs it, and carried on the run record so the ledger can say what a
|
|
11
|
-
// run cost in the same units it was capped in. Four dimensions, because the expensive thing
|
|
12
|
-
// differs by executor: tokens and calls for a model, wall time for an agent that thinks for
|
|
13
|
-
// minutes, cost when the gateway can report it. Any dimension may be absent; an absent one is
|
|
14
|
-
// not enforced. A budget with NO dimension is not a budget — `validateBudget` refuses it, and
|
|
15
|
-
// a team without one does not run (F8, O1).
|
|
16
|
-
//
|
|
17
|
-
// Pure. `now` is injected so a wall-time cap is testable.
|
|
18
|
-
|
|
19
|
-
export const BUDGET_DIMENSIONS = Object.freeze(['tokens', 'calls', 'ms', 'usd']);
|
|
20
|
-
|
|
21
|
-
export class BudgetError extends Error {
|
|
22
|
-
constructor(code, message) { super(message); this.name = 'BudgetError'; this.code = code; }
|
|
23
|
-
}
|
|
24
|
-
|
|
25
|
-
/** `{ ok, errors }` — a budget must cap at least one thing, and every cap must be a positive number. */
|
|
26
|
-
export function validateBudget(b) {
|
|
27
|
-
const errors = [];
|
|
28
|
-
if (!b || typeof b !== 'object') return { ok: false, errors: ['budget must be an object'] };
|
|
29
|
-
let any = false;
|
|
30
|
-
for (const k of BUDGET_DIMENSIONS) {
|
|
31
|
-
if (b[k] === undefined || b[k] === null) continue;
|
|
32
|
-
const n = Number(b[k]);
|
|
33
|
-
if (!Number.isFinite(n) || n <= 0) errors.push(`${k}: a positive number`);
|
|
34
|
-
else any = true;
|
|
35
|
-
}
|
|
36
|
-
for (const k of Object.keys(b)) if (!BUDGET_DIMENSIONS.includes(k)) errors.push(`${k}: not a budget dimension (${BUDGET_DIMENSIONS.join(', ')})`);
|
|
37
|
-
if (!any) errors.push('a budget must cap at least one of tokens, calls, ms, usd');
|
|
38
|
-
return { ok: errors.length === 0, errors };
|
|
39
|
-
}
|
|
40
|
-
|
|
41
|
-
/** Only the declared dimensions, as numbers. */
|
|
42
|
-
export function normalizeBudget(b) {
|
|
43
|
-
const out = {};
|
|
44
|
-
for (const k of BUDGET_DIMENSIONS) {
|
|
45
|
-
const n = Number(b?.[k]);
|
|
46
|
-
if (Number.isFinite(n) && n > 0) out[k] = n;
|
|
47
|
-
}
|
|
48
|
-
return out;
|
|
49
|
-
}
|
|
50
|
-
|
|
51
|
-
/**
|
|
52
|
-
* The usage a model call reports, in the shapes the providers use, as one record:
|
|
53
|
-
* `{ tokens, calls, usd }`. `ms` is measured by the budget itself.
|
|
54
|
-
*/
|
|
55
|
-
export function usageOf(u = {}) {
|
|
56
|
-
const tokens = Number(u.tokens ?? u.total_tokens ?? ((Number(u.input_tokens ?? u.prompt_tokens) || 0) + (Number(u.output_tokens ?? u.completion_tokens) || 0)));
|
|
57
|
-
return { tokens: Number.isFinite(tokens) ? tokens : 0, calls: Number(u.calls ?? 1) || 0, usd: Number(u.usd ?? u.cost) || 0 };
|
|
58
|
-
}
|
|
59
|
-
|
|
60
|
-
/**
|
|
61
|
-
* A live budget for one run.
|
|
62
|
-
*
|
|
63
|
-
* charge(usage) add a model call's usage; returns what is left
|
|
64
|
-
* canAfford(estimate) false when an estimated call would cross a cap — ask BEFORE calling
|
|
65
|
-
* exhausted() the dimension that ran out, or null
|
|
66
|
-
* snapshot() { cap, spent, remaining, exhausted } for the run record and the meter
|
|
67
|
-
*/
|
|
68
|
-
export function createBudget(declared, { now = () => Date.now() } = {}) {
|
|
69
|
-
const v = validateBudget(declared);
|
|
70
|
-
if (!v.ok) throw new BudgetError('INVALID', v.errors.join('; '));
|
|
71
|
-
const cap = { ...normalizeBudget(declared) };
|
|
72
|
-
const startedAt = now();
|
|
73
|
-
const spent = { tokens: 0, calls: 0, usd: 0 };
|
|
74
|
-
const elapsed = () => now() - startedAt;
|
|
75
|
-
const remaining = () => {
|
|
76
|
-
const out = {};
|
|
77
|
-
for (const k of BUDGET_DIMENSIONS) {
|
|
78
|
-
if (cap[k] === undefined) continue;
|
|
79
|
-
out[k] = Math.max(0, cap[k] - (k === 'ms' ? elapsed() : spent[k]));
|
|
80
|
-
}
|
|
81
|
-
return out;
|
|
82
|
-
};
|
|
83
|
-
const exhausted = () => {
|
|
84
|
-
for (const k of BUDGET_DIMENSIONS) {
|
|
85
|
-
if (cap[k] === undefined) continue;
|
|
86
|
-
if ((k === 'ms' ? elapsed() : spent[k]) >= cap[k]) return k;
|
|
87
|
-
}
|
|
88
|
-
return null;
|
|
89
|
-
};
|
|
90
|
-
return {
|
|
91
|
-
cap,
|
|
92
|
-
charge(usage) {
|
|
93
|
-
const u = usageOf(usage);
|
|
94
|
-
spent.tokens += u.tokens; spent.calls += u.calls; spent.usd += u.usd;
|
|
95
|
-
return remaining();
|
|
96
|
-
},
|
|
97
|
-
canAfford(estimate = {}) {
|
|
98
|
-
if (exhausted()) return false;
|
|
99
|
-
const e = usageOf({ calls: 1, ...estimate });
|
|
100
|
-
for (const k of ['tokens', 'calls', 'usd']) {
|
|
101
|
-
if (cap[k] !== undefined && spent[k] + e[k] > cap[k]) return false;
|
|
102
|
-
}
|
|
103
|
-
return true;
|
|
104
|
-
},
|
|
105
|
-
remaining,
|
|
106
|
-
exhausted,
|
|
107
|
-
/** A person raised the cap mid-run (a budget ask answered "allow"): by a factor, once. */
|
|
108
|
-
raise(factor = 1.5) {
|
|
109
|
-
const f = Math.max(1, Number(factor) || 1);
|
|
110
|
-
for (const k of Object.keys(cap)) if (cap[k] !== undefined) cap[k] = Math.ceil(cap[k] * f);
|
|
111
|
-
return { ...cap };
|
|
112
|
-
},
|
|
113
|
-
snapshot() {
|
|
114
|
-
return { cap, spent: { ...spent, ms: elapsed() }, remaining: remaining(), exhausted: exhausted() };
|
|
115
|
-
},
|
|
116
|
-
};
|
|
117
|
-
}
|
|
1
|
+
const i=Object.freeze(["tokens","calls","ms","usd"]);class k extends Error{constructor(n,r){super(r),this.name="BudgetError",this.code=n}}function p(t){const n=[];if(!t||typeof t!="object")return{ok:!1,errors:["budget must be an object"]};let r=!1;for(const e of i){if(t[e]===void 0||t[e]===null)continue;const f=Number(t[e]);!Number.isFinite(f)||f<=0?n.push(`${e}: a positive number`):r=!0}for(const e of Object.keys(t))i.includes(e)||n.push(`${e}: not a budget dimension (${i.join(", ")})`);return r||n.push("a budget must cap at least one of tokens, calls, ms, usd"),{ok:n.length===0,errors:n}}function b(t){const n={};for(const r of i){const e=Number(t?.[r]);Number.isFinite(e)&&e>0&&(n[r]=e)}return n}function m(t={}){const n=Number(t.tokens??t.total_tokens??(Number(t.input_tokens??t.prompt_tokens)||0)+(Number(t.output_tokens??t.completion_tokens)||0));return{tokens:Number.isFinite(n)?n:0,calls:Number(t.calls??1)||0,usd:Number(t.usd??t.cost)||0}}function h(t,{now:n=()=>Date.now()}={}){const r=p(t);if(!r.ok)throw new k("INVALID",r.errors.join("; "));const e={...b(t)},f=n(),c={tokens:0,calls:0,usd:0},a=()=>n()-f,l=()=>{const s={};for(const o of i)e[o]!==void 0&&(s[o]=Math.max(0,e[o]-(o==="ms"?a():c[o])));return s},d=()=>{for(const s of i)if(e[s]!==void 0&&(s==="ms"?a():c[s])>=e[s])return s;return null};return{cap:e,charge(s){const o=m(s);return c.tokens+=o.tokens,c.calls+=o.calls,c.usd+=o.usd,l()},canAfford(s={}){if(d())return!1;const o=m({calls:1,...s});for(const u of["tokens","calls","usd"])if(e[u]!==void 0&&c[u]+o[u]>e[u])return!1;return!0},remaining:l,exhausted:d,raise(s=1.5){const o=Math.max(1,Number(s)||1);for(const u of Object.keys(e))e[u]!==void 0&&(e[u]=Math.ceil(e[u]*o));return{...e}},snapshot(){return{cap:e,spent:{...c,ms:a()},remaining:l(),exhausted:d()}}}}export{i as BUDGET_DIMENSIONS,k as BudgetError,h as createBudget,b as normalizeBudget,m as usageOf,p as validateBudget};
|
package/src/config.js
CHANGED
|
@@ -1,209 +1 @@
|
|
|
1
|
-
|
|
2
|
-
//
|
|
3
|
-
// Loads, in order of precedence: a JSON file (CHATPANEL_GATEWAY_CONFIG or
|
|
4
|
-
// ./gateway.config.json) < environment variables. The gateway forwards the
|
|
5
|
-
// CLIENT's own auth header upstream (it stores no provider keys), so config here
|
|
6
|
-
// is only routing + the redaction policy.
|
|
7
|
-
|
|
8
|
-
import { readFileSync, existsSync } from 'node:fs';
|
|
9
|
-
import { join } from 'node:path';
|
|
10
|
-
import os from 'node:os';
|
|
11
|
-
import { DEFAULT_MODEL as DEFAULT_NER_MODEL } from './models.js';
|
|
12
|
-
import { DEFAULT_STT_MODEL } from './stt-models.js';
|
|
13
|
-
|
|
14
|
-
// Exported so tests can assert that every section here survives persistConfig's
|
|
15
|
-
// allowlist — a new section that is not persisted reverts on restart, and that
|
|
16
|
-
// reads as a broken feature rather than an unsaved setting.
|
|
17
|
-
export const DEFAULTS = {
|
|
18
|
-
host: '127.0.0.1',
|
|
19
|
-
port: 4320,
|
|
20
|
-
|
|
21
|
-
// 'bridge' = drive the ChatPanel bridge's subscription-authed CLI agents
|
|
22
|
-
// (codex/claude/opencode/pi) — the privacy-bridge-between-agents use
|
|
23
|
-
// case (opencode → gateway → codex). No API keys; uses your login.
|
|
24
|
-
// 'api' = forward redacted traffic to a native provider API (local models,
|
|
25
|
-
// BYO keys, OpenRouter, …). Client passes its own auth through.
|
|
26
|
-
backend: 'bridge',
|
|
27
|
-
|
|
28
|
-
// Model router: the gateway routes each request to a destination by the model
|
|
29
|
-
// name the client asks for. Empty = derive destinations from backend/bridge/
|
|
30
|
-
// upstreams below (back-compat). Each entry:
|
|
31
|
-
// { id, type:'agent'|'api', agent?, baseUrl?, protocol?, models:[..] }
|
|
32
|
-
destinations: [],
|
|
33
|
-
|
|
34
|
-
// Security: legitimate clients (opencode/pi/codex/SDKs) are local processes that
|
|
35
|
-
// send NO Origin header. A browser always attaches one. So we REJECT any request
|
|
36
|
-
// bearing an Origin not in this allowlist — this stops a malicious web page from
|
|
37
|
-
// POSTing to the gateway and driving codex (drive-by / CSRF). Leave empty to
|
|
38
|
-
// block all browser-origin traffic. `maxBodyBytes` caps request size (DoS guard).
|
|
39
|
-
allowedOrigins: [],
|
|
40
|
-
maxBodyBytes: 26214400,
|
|
41
|
-
|
|
42
|
-
// `free.used` is the running lifetime redaction count for the free allowance
|
|
43
|
-
// (freegate.FREE_TOTAL_CAP redactions at full tier), persisted here. A valid
|
|
44
|
-
// ChatPanel entitlement token unlocks unlimited use.
|
|
45
|
-
pro: {
|
|
46
|
-
entitlementToken: '',
|
|
47
|
-
free: {
|
|
48
|
-
used: 0,
|
|
49
|
-
},
|
|
50
|
-
},
|
|
51
|
-
|
|
52
|
-
bridge: {
|
|
53
|
-
url: 'http://127.0.0.1:4319',
|
|
54
|
-
// Default agent the bridge drives. A request's `model` field may also name an
|
|
55
|
-
// agent (codex/claude/opencode/pi) to override per-call.
|
|
56
|
-
agent: 'codex',
|
|
57
|
-
// Bearer token for the bridge's privileged /chat route. Empty = read the
|
|
58
|
-
// per-install token from ~/.chatpanel/bridge-token.
|
|
59
|
-
token: '',
|
|
60
|
-
// What a CLI agent driven THROUGH the gateway may do — the same three modes the
|
|
61
|
-
// extension offers per agent: 'default' (read-only, asks before writing),
|
|
62
|
-
// 'acceptEdits' (edits files in its workspace on its own), 'bypassPermissions' (full
|
|
63
|
-
// access and shell). Absent, the bridge ran every gateway turn read-only and told the
|
|
64
|
-
// model to "set Permissions" in a settings page the desktop did not have.
|
|
65
|
-
permissionMode: 'default',
|
|
66
|
-
// Where the agent works. Empty = the bridge's ChatPanel workspace.
|
|
67
|
-
workingDir: '',
|
|
68
|
-
},
|
|
69
|
-
|
|
70
|
-
upstreams: {
|
|
71
|
-
// Used only when backend === 'api'. Override to point OpenAI-protocol traffic
|
|
72
|
-
// at a local model, Azure, OpenRouter, etc. Auth is passed through from the
|
|
73
|
-
// client, so no key lives here.
|
|
74
|
-
openai: { baseUrl: 'https://api.openai.com' },
|
|
75
|
-
anthropic: { baseUrl: 'https://api.anthropic.com' },
|
|
76
|
-
},
|
|
77
|
-
redaction: {
|
|
78
|
-
// 'basic' = deterministic regex (emails/phones/cards/SSNs/keys/IPs).
|
|
79
|
-
// 'full' = basic + entity detection (names/orgs via the local detector below)
|
|
80
|
-
// + the custom dictionary.
|
|
81
|
-
tier: 'basic',
|
|
82
|
-
// { value|pattern, type, alias? } — see pii-redact.js. `alias` pseudonymizes
|
|
83
|
-
// permanently (upstream + the agent both see the alias).
|
|
84
|
-
dictionary: [],
|
|
85
|
-
// Local entity detector, passed straight to pii-detect.detectEntities.
|
|
86
|
-
// backend: 'off' | 'endpoint' (POST {text}->{entities}) | 'openai' (local LLM)
|
|
87
|
-
// url, model, timeoutMs, maxChars
|
|
88
|
-
// Leave this `off` to use the bundled in-process NER (see `ner` below). Set it
|
|
89
|
-
// only to point at YOUR OWN external detector (a custom NER or local LLM); that
|
|
90
|
-
// takes precedence over the bundled engine.
|
|
91
|
-
detection: { backend: 'off' },
|
|
92
|
-
// Per-request convenience: also redact the system prompt / system blocks.
|
|
93
|
-
redactSystem: true,
|
|
94
|
-
},
|
|
95
|
-
// Bundled IN-PROCESS NER (ONNX via transformers.js). When autostart is on, the
|
|
96
|
-
// gateway loads the entity detector in-process — no Python, no second port — so
|
|
97
|
-
// name/org redaction works out of the box. The model loads from
|
|
98
|
-
// ~/.chatpanel/models and is downloaded once on first run if absent. Larger /
|
|
99
|
-
// alternative models can be installed from the extension's Gateway settings.
|
|
100
|
-
// Fails open: if the model can't load, the gateway runs deterministic-only.
|
|
101
|
-
ner: {
|
|
102
|
-
autostart: true,
|
|
103
|
-
// One definition, in models.js. It lived here, in models.js and in ner-engine.js at
|
|
104
|
-
// once — three constants for one default, which is three chances to move two of them.
|
|
105
|
-
model: DEFAULT_NER_MODEL,
|
|
106
|
-
allowDownload: true,
|
|
107
|
-
// Auto-bump redaction.tier to 'full' once the detector is ready (names/orgs).
|
|
108
|
-
enableFullTier: true,
|
|
109
|
-
},
|
|
110
|
-
|
|
111
|
-
// Local speech-to-text (dictation) — the in-process ONNX engine and model dir shared
|
|
112
|
-
// with NER (stt-engine.js). No autostart on purpose: the model downloads on FIRST
|
|
113
|
-
// dictation, never on gateway boot (first-run load time). The default is Parakeet, which
|
|
114
|
-
// is multilingual and several times faster than Whisper — see stt-models.js for what
|
|
115
|
-
// that costs on a first run.
|
|
116
|
-
stt: {
|
|
117
|
-
enabled: true,
|
|
118
|
-
model: DEFAULT_STT_MODEL,
|
|
119
|
-
allowDownload: true,
|
|
120
|
-
// Speaker diarization ("who said what") is an OPT-IN per-session stage (its
|
|
121
|
-
// model loads only when a session asks). Set false to disable it gateway-wide.
|
|
122
|
-
diarize: true,
|
|
123
|
-
},
|
|
124
|
-
|
|
125
|
-
// Local text-to-speech (read-aloud / voice out) — Kokoro via the same in-process
|
|
126
|
-
// ONNX engine and model dir as NER/STT (tts-engine.js). No autostart, same reason
|
|
127
|
-
// as stt: the model downloads on FIRST synthesis, never on gateway boot.
|
|
128
|
-
tts: {
|
|
129
|
-
enabled: true,
|
|
130
|
-
// 'local' = Kokoro in this process, nothing leaves the machine (the default).
|
|
131
|
-
// 'openai' | 'elevenlabs' = a remote voice. Auth is passed through from the
|
|
132
|
-
// client as everywhere else here; no key is stored. See src/tts-remote.js for
|
|
133
|
-
// why remote synthesis redacts by default and what that costs.
|
|
134
|
-
provider: 'local',
|
|
135
|
-
// Empty = decide at runtime. Pocket TTS is the better default (fastest here,
|
|
136
|
-
// and the only engine that can speak as you) but needs the native onnxruntime,
|
|
137
|
-
// which the standalone binary does not carry — so hardcoding either one is
|
|
138
|
-
// wrong for half the installs. resolveDefaultModel() picks per runtime, and an
|
|
139
|
-
// explicit choice here always wins.
|
|
140
|
-
model: '',
|
|
141
|
-
voice: '',
|
|
142
|
-
allowDownload: true,
|
|
143
|
-
remote: {
|
|
144
|
-
baseUrl: '', // '' = the provider's own default endpoint
|
|
145
|
-
model: '',
|
|
146
|
-
voice: '',
|
|
147
|
-
// Redact before the text leaves this machine. Audio cannot be un-redacted,
|
|
148
|
-
// so this genuinely means the voice says "PERSON_1" — set false only if you
|
|
149
|
-
// accept sending real values to the vendor.
|
|
150
|
-
redact: true,
|
|
151
|
-
},
|
|
152
|
-
},
|
|
153
|
-
|
|
154
|
-
// Log one line per request (method, tokens redacted) without any raw values.
|
|
155
|
-
logRequests: true,
|
|
156
|
-
|
|
157
|
-
// Optional per-request redaction breakdown attached to each log entry (shown
|
|
158
|
-
// expandable in the extension). Memory-only — never persisted to disk with the
|
|
159
|
-
// captured values; only the MODE is saved.
|
|
160
|
-
// 'off' — counts only (default; the privacy-safe baseline)
|
|
161
|
-
// 'types' — entity types + placeholder tokens (e.g. PERSON_1), no real values
|
|
162
|
-
// 'values' — real → placeholder mapping (the actual PII; opt-in, debugging)
|
|
163
|
-
logDetail: 'off',
|
|
164
|
-
};
|
|
165
|
-
|
|
166
|
-
function deepMerge(base, over) {
|
|
167
|
-
if (Array.isArray(over)) return over;
|
|
168
|
-
if (over && typeof over === 'object' && base && typeof base === 'object') {
|
|
169
|
-
const out = { ...base };
|
|
170
|
-
for (const k of Object.keys(over)) out[k] = deepMerge(base[k], over[k]);
|
|
171
|
-
return out;
|
|
172
|
-
}
|
|
173
|
-
return over === undefined ? base : over;
|
|
174
|
-
}
|
|
175
|
-
|
|
176
|
-
export function loadConfig(env = process.env) {
|
|
177
|
-
let cfg = DEFAULTS;
|
|
178
|
-
|
|
179
|
-
// Writable per-user location by default (NOT cwd — a login service runs with
|
|
180
|
-
// cwd "/", which is read-only). Same path persistConfig() writes to.
|
|
181
|
-
const path = env.CHATPANEL_GATEWAY_CONFIG || join(os.homedir(), '.chatpanel', 'gateway.config.json');
|
|
182
|
-
if (existsSync(path)) {
|
|
183
|
-
try {
|
|
184
|
-
cfg = deepMerge(cfg, JSON.parse(readFileSync(path, 'utf8')));
|
|
185
|
-
} catch (e) {
|
|
186
|
-
throw new Error(`bad config file ${path}: ${e.message}`);
|
|
187
|
-
}
|
|
188
|
-
}
|
|
189
|
-
|
|
190
|
-
// Env overrides (handy for Docker/CI where a file is awkward).
|
|
191
|
-
if (env.CHATPANEL_GATEWAY_HOST) cfg = deepMerge(cfg, { host: env.CHATPANEL_GATEWAY_HOST });
|
|
192
|
-
if (env.CHATPANEL_GATEWAY_PORT) cfg = deepMerge(cfg, { port: Number(env.CHATPANEL_GATEWAY_PORT) });
|
|
193
|
-
if (env.OPENAI_BASE_URL) cfg = deepMerge(cfg, { upstreams: { openai: { baseUrl: env.OPENAI_BASE_URL } } });
|
|
194
|
-
if (env.ANTHROPIC_BASE_URL) cfg = deepMerge(cfg, { upstreams: { anthropic: { baseUrl: env.ANTHROPIC_BASE_URL } } });
|
|
195
|
-
if (env.CHATPANEL_REDACTION_TIER) cfg = deepMerge(cfg, { redaction: { tier: env.CHATPANEL_REDACTION_TIER } });
|
|
196
|
-
|
|
197
|
-
// A persisted port of 0 means "let the OS pick a random port" — fatal for a
|
|
198
|
-
// service that clients reach at a FIXED address: the extension, install.sh, and
|
|
199
|
-
// OpenCode/Pi all hardcode 4320. A stale/corrupt config that wrote 0 would bind a
|
|
200
|
-
// random ephemeral port and look "running but unreachable". Coerce 0 / NaN / out-
|
|
201
|
-
// of-range back to the default so the gateway is always where clients expect it.
|
|
202
|
-
const p = Number(cfg.port);
|
|
203
|
-
if (!Number.isInteger(p) || p < 1 || p > 65535) {
|
|
204
|
-
if (cfg.port !== DEFAULTS.port) console.warn(`[gateway] ignoring invalid port ${JSON.stringify(cfg.port)} — using ${DEFAULTS.port}`);
|
|
205
|
-
cfg = deepMerge(cfg, { port: DEFAULTS.port });
|
|
206
|
-
}
|
|
207
|
-
|
|
208
|
-
return cfg;
|
|
209
|
-
}
|
|
1
|
+
import{readFileSync as s,existsSync as p}from"node:fs";import{join as l}from"node:path";import A from"node:os";import{DEFAULT_MODEL as c}from"./models.js";import{DEFAULT_STT_MODEL as d}from"./stt-models.js";const a={host:"127.0.0.1",port:4320,backend:"bridge",destinations:[],allowedOrigins:[],maxBodyBytes:26214400,pro:{entitlementToken:"",free:{used:0}},bridge:{url:"http://127.0.0.1:4319",agent:"codex",token:"",permissionMode:"default",workingDir:""},upstreams:{openai:{baseUrl:"https://api.openai.com"},anthropic:{baseUrl:"https://api.anthropic.com"}},redaction:{tier:"basic",dictionary:[],detection:{backend:"off"},redactSystem:!0},ner:{autostart:!0,model:c,allowDownload:!0,enableFullTier:!0},stt:{enabled:!0,model:d,allowDownload:!0,diarize:!0},tts:{enabled:!0,provider:"local",model:"",voice:"",allowDownload:!0,remote:{baseUrl:"",model:"",voice:"",redact:!0}},logRequests:!0,logDetail:"off"};function o(e,t){if(Array.isArray(t))return t;if(t&&typeof t=="object"&&e&&typeof e=="object"){const i={...e};for(const r of Object.keys(t))i[r]=o(e[r],t[r]);return i}return t===void 0?e:t}function _(e=process.env){let t=a;const i=e.CHATPANEL_GATEWAY_CONFIG||l(A.homedir(),".chatpanel","gateway.config.json");if(p(i))try{t=o(t,JSON.parse(s(i,"utf8")))}catch(n){throw new Error(`bad config file ${i}: ${n.message}`)}e.CHATPANEL_GATEWAY_HOST&&(t=o(t,{host:e.CHATPANEL_GATEWAY_HOST})),e.CHATPANEL_GATEWAY_PORT&&(t=o(t,{port:Number(e.CHATPANEL_GATEWAY_PORT)})),e.OPENAI_BASE_URL&&(t=o(t,{upstreams:{openai:{baseUrl:e.OPENAI_BASE_URL}}})),e.ANTHROPIC_BASE_URL&&(t=o(t,{upstreams:{anthropic:{baseUrl:e.ANTHROPIC_BASE_URL}}})),e.CHATPANEL_REDACTION_TIER&&(t=o(t,{redaction:{tier:e.CHATPANEL_REDACTION_TIER}}));const r=Number(t.port);return(!Number.isInteger(r)||r<1||r>65535)&&(t.port!==a.port&&console.warn(`[gateway] ignoring invalid port ${JSON.stringify(t.port)} — using ${a.port}`),t=o(t,{port:a.port})),t}export{a as DEFAULTS,_ as loadConfig};
|