@chatpanel/bridge 0.11.23 → 0.11.25

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (62) hide show
  1. package/README.md +7 -7
  2. package/package.json +1 -13
  3. package/scripts/sync-channels.mjs +8 -90
  4. package/scripts/sync-events.mjs +7 -78
  5. package/scripts/sync-pii.mjs +7 -68
  6. package/src/api-compat.js +5 -294
  7. package/src/channels/adapters/telegram.js +3 -298
  8. package/src/channels/bridge.js +1 -59
  9. package/src/channels/eventlog.js +3 -57
  10. package/src/channels/gateway.js +1 -114
  11. package/src/channels/invoke.js +1 -172
  12. package/src/channels/normalize.js +1 -58
  13. package/src/channels/pairing.js +1 -95
  14. package/src/channels/service.js +1 -329
  15. package/src/channels/stream.js +5 -104
  16. package/src/cli-errors.js +3 -136
  17. package/src/connections.js +1 -160
  18. package/src/connectors.js +1 -100
  19. package/src/engines/antigravity.js +5 -235
  20. package/src/engines/args.js +1 -47
  21. package/src/engines/claude.js +6 -586
  22. package/src/engines/cli-agents.js +7 -312
  23. package/src/engines/codex.js +6 -463
  24. package/src/engines/custom.js +17 -577
  25. package/src/engines/prompt.js +6 -32
  26. package/src/engines/stream-formats.js +2 -222
  27. package/src/entitlement.js +1 -77
  28. package/src/env.js +3 -628
  29. package/src/events/capability.js +1 -134
  30. package/src/events/event.js +1 -183
  31. package/src/events/reach.js +1 -31
  32. package/src/events/ref.js +1 -63
  33. package/src/events/scm-connection.js +1 -188
  34. package/src/events/scopes.js +1 -20
  35. package/src/events/skill-manifest.js +1 -338
  36. package/src/events/skill-scan.js +3 -217
  37. package/src/events/view.js +1 -96
  38. package/src/mcp-capabilities.js +2 -139
  39. package/src/mcp-local.js +0 -0
  40. package/src/mcp-quarantine.js +1 -110
  41. package/src/net.js +1 -107
  42. package/src/pii/index.js +1 -29
  43. package/src/pii/net.js +1 -111
  44. package/src/pii/pii-detect.js +2 -296
  45. package/src/pii/pii-redact.js +1 -470
  46. package/src/pii/pipeline.js +1 -137
  47. package/src/pii/sanitize.js +2 -179
  48. package/src/pii/tool-harness.js +1 -184
  49. package/src/pii/tool-rank.js +1 -110
  50. package/src/proc.js +2 -91
  51. package/src/relay-timeout.js +1 -21
  52. package/src/runs.js +1 -49
  53. package/src/sanitize.js +1 -7
  54. package/src/scm.js +1 -76
  55. package/src/server.js +10 -1492
  56. package/src/service.js +11 -176
  57. package/src/sign-in.js +1 -91
  58. package/src/skills.js +1 -399
  59. package/src/ssrf.js +1 -70
  60. package/src/update.js +1 -216
  61. package/src/workdir.js +1 -108
  62. package/src/worktree.js +3 -125
@@ -1,329 +1 @@
1
- // GENERATED — do not edit.
2
- // Source of truth: chatpanel-channels/src/service.js (npm @chatpanel/channels).
3
- // Edit there, then run: npm run sync:channels
4
- //
5
- // Vendored rather than depended on: the bridge ships zero runtime dependencies so a
6
- // curl one-liner install cannot fail on someone's registry, and so the compiled
7
- // single-file binary has nothing to resolve. Package imports are rewritten to the
8
- // vendored engines (src/pii, src/events) by the sync script.
9
-
10
- // The channel SERVICE — connect · pair · status · disconnect, as one contract a UI can drive.
11
- //
12
- // The adapter is a loop. A *service* is what a person can actually operate: is it connected,
13
- // to which bot, who is paired, give me a code, stop it. That contract lives here rather than
14
- // inside whichever process happens to host the loop, because there is more than one host — the
15
- // bridge (always on, and what a non-technical user already has), the CLI (headless boxes), and
16
- // a desktop app later. Three hosts implementing "connect a bot" is three different security
17
- // postures for the same secret.
18
- //
19
- // It owns exactly the state a channel has:
20
- // • the bot token — a 0600 file, read at start, NEVER returned by status();
21
- // • the pairing store — who may drive an agent, and their reach ceiling;
22
- // • the per-channel settings — which agent answers, and the privacy mode.
23
- //
24
- // It owns none of the transport around it: no HTTP, no auth, no UI. The host does that, which
25
- // is why this module needs no server and is testable with a stub fetch.
26
-
27
- import path from 'node:path';
28
- import { readFile, writeFile, mkdir, rm, stat } from 'node:fs/promises';
29
- import { createPairingStore } from './pairing.js';
30
- import * as bridgeTransport from './bridge.js';
31
- import * as gateway from './gateway.js';
32
-
33
- // The gateway's fixed local port (see chatpanel-gateway: 4319 bridge / 4320 gateway).
34
- const DEFAULT_GATEWAY_URL = 'http://127.0.0.1:4320';
35
- import { createEventLog } from './eventlog.js';
36
- import { startTelegram } from './adapters/telegram.js';
37
-
38
- const TELEGRAM_API = 'https://api.telegram.org';
39
- // `agent` routes through the bridge (a CLI on this machine). `model` routes through the
40
- // gateway, which reaches every destination the user configured there — API providers AND, via
41
- // its own bridge backend, the same agents. They are mutually exclusive: update() clears one
42
- // when the other is set, because "which thing answers" is one choice, not two.
43
- export const DEFAULT_SETTINGS = Object.freeze({
44
- agent: 'claude', model: '', provider: '', gatewayUrl: DEFAULT_GATEWAY_URL,
45
- privacy: 'standard', tier: 'basic',
46
- });
47
-
48
- // Restart backoff. A long-poll that dies (network drop, laptop asleep, Telegram hiccup) must
49
- // come back on its own — a channel nobody is watching is exactly the one that must self-heal —
50
- // but a token that has been REVOKED would otherwise spin forever, so the wait grows.
51
- const RETRY_MS = [2_000, 5_000, 15_000, 60_000];
52
-
53
- const readJson = async (file, fallback) => {
54
- try { return JSON.parse(await readFile(file, 'utf8')); } catch { return fallback; }
55
- };
56
- const writeJson = (file, value) => writeFile(file, JSON.stringify(value, null, 2), { mode: 0o600 });
57
-
58
- /**
59
- * Ask Telegram who this token belongs to. This is the ONLY validation that matters at connect
60
- * time: a typo'd token must fail in the settings screen, with a reason, rather than becoming a
61
- * silent poll loop nobody sees the logs of.
62
- */
63
- export async function verifyBot(botToken, { fetchImpl = fetch, signal } = {}) {
64
- const res = await fetchImpl(`${TELEGRAM_API}/bot${String(botToken || '').trim()}/getMe`, { signal });
65
- const body = await res.json().catch(() => null);
66
- if (!body?.ok) {
67
- const why = body?.description || `HTTP ${res.status}`;
68
- throw new Error(/unauthorized/i.test(why) ? 'Telegram rejected that token — copy it again from @BotFather' : why);
69
- }
70
- return { id: body.result.id, username: body.result.username, name: body.result.first_name || '' };
71
- }
72
-
73
- /** The t.me link that pairs in one tap: Telegram turns it into "/start <code>" in the chat. */
74
- export const pairLink = (username, code) => `https://t.me/${username}?start=${code}`;
75
-
76
- export function createChannelService({
77
- home, // ~/.chatpanel — where the token file lives
78
- dataDir, // ~/.chatpanel/channels — pairing, config, event log
79
- bridge, // { baseUrl, token } — how the adapter reaches the agent
80
- logger = console,
81
- fetchImpl = undefined, // injected in tests
82
- now = () => Date.now(),
83
- // The adapter is injectable for the same reason fetchImpl is: the thing worth asserting
84
- // about the loop is WHAT it is handed, and a real Telegram long-poll cannot be asked.
85
- startAdapter = startTelegram,
86
- } = {}) {
87
- const tokenFile = path.join(home, 'telegram-token');
88
- const configFile = path.join(dataDir, 'config.json');
89
- const pairingFile = path.join(dataDir, 'pairing.json');
90
-
91
- let pairing = null; // created by load(), then kept — see the note there
92
- let settings = { ...DEFAULT_SETTINGS };
93
- let appender = null;
94
- let bot = null; // { id, username, name } once verified
95
- let controller = null; // aborts the running loop
96
- let running = false;
97
- let lastError = '';
98
- let attempt = 0;
99
- let stopped = true; // deliberate stop — suppresses the restart
100
-
101
- const savePairing = () => writeJson(pairingFile, pairing ? pairing.toJSON() : {});
102
- const saveSettings = () => writeJson(configFile, settings);
103
-
104
- async function readToken() {
105
- try {
106
- const t = (await readFile(tokenFile, 'utf8')).trim();
107
- if (!t) return '';
108
- try {
109
- const { mode } = await stat(tokenFile);
110
- if (mode & 0o077) logger.warn?.(`[channels] ${tokenFile} is group/world-readable — chmod 600 it (it holds your bot token).`);
111
- } catch { /* best effort */ }
112
- return t;
113
- } catch { return ''; }
114
- }
115
-
116
- async function load() {
117
- await mkdir(dataDir, { recursive: true });
118
- // Built ONCE and never replaced. spawnLoop() hands this exact object to the adapter, which
119
- // holds it for the life of a polling loop — so rebuilding it here (as every service call
120
- // used to) broke pairing in both directions at once: `pair()` minted the code into a fresh
121
- // store the adapter could not see, so every redeem answered "unknown or expired code" no
122
- // matter how many codes you generated; and `savePairing()` serialises whichever store this
123
- // variable currently points at, so a redeem that DID land would have been persisted from
124
- // the wrong object. Two aliases of one thing is the bug — there is only ever one store.
125
- if (!pairing) pairing = createPairingStore(await readJson(pairingFile, {}), { now });
126
- settings = { ...DEFAULT_SETTINGS, ...(await readJson(configFile, {})) };
127
- if (!appender) appender = await createEventLog({ file: path.join(dataDir, 'events.jsonl'), host: 'channel' });
128
- }
129
-
130
- // One supervised run of the loop. Resolves when the loop ends; schedules its own restart
131
- // unless the stop was deliberate.
132
- function spawnLoop(botToken) {
133
- controller = new AbortController();
134
- running = true;
135
- // Resolved PER MESSAGE, not once at start. The loop owns every conversation's history and
136
- // privacy vault, so restarting it to pick up a settings change threw away the thing the
137
- // user came for. Now nothing needs a restart: the next message simply reads this.
138
- const route = () => {
139
- const viaGateway = !!settings.model;
140
- return {
141
- transport: viaGateway ? gateway : bridgeTransport,
142
- agent: viaGateway ? '' : settings.agent,
143
- model: viaGateway ? settings.model : '',
144
- provider: viaGateway ? (settings.provider || '') : '',
145
- baseUrl: viaGateway ? (settings.gatewayUrl || DEFAULT_GATEWAY_URL) : bridge.baseUrl,
146
- system: settings.system || '',
147
- privacy: settings.privacy,
148
- };
149
- };
150
- const done = startAdapter({
151
- botToken,
152
- route,
153
- transport: route().transport,
154
- model: route().model,
155
- provider: route().provider,
156
- baseUrl: route().baseUrl,
157
- token: bridge.token,
158
- pairing,
159
- savePairing,
160
- appender,
161
- agent: settings.agent,
162
- system: settings.system || '',
163
- redact: { tier: settings.tier },
164
- privacy: settings.privacy,
165
- logger,
166
- signal: controller.signal,
167
- });
168
- Promise.resolve(done)
169
- .catch((e) => { lastError = e?.message || String(e); logger.warn?.(`[channels] telegram loop failed: ${lastError}`); })
170
- .finally(() => {
171
- running = false;
172
- if (stopped) return;
173
- const wait = RETRY_MS[Math.min(attempt++, RETRY_MS.length - 1)];
174
- logger.warn?.(`[channels] telegram stopped unexpectedly — retrying in ${Math.round(wait / 1000)}s`);
175
- setTimeout(() => { if (!stopped) spawnLoop(botToken); }, wait).unref?.();
176
- });
177
- }
178
-
179
- async function start() {
180
- if (running) return { ok: true, already: true };
181
- await load();
182
- const botToken = await readToken();
183
- if (!botToken) return { ok: false, error: 'no bot token configured' };
184
- if (settings.enabled === false) return { ok: false, error: 'channel is turned off' };
185
- try {
186
- bot = await verifyBot(botToken, { fetchImpl });
187
- } catch (e) {
188
- // A revoked or mistyped token must SAY so and stay stopped — a poll loop against a dead
189
- // token is the failure that looks like "nobody has messaged me yet".
190
- lastError = e?.message || String(e);
191
- return { ok: false, error: lastError };
192
- }
193
- lastError = '';
194
- attempt = 0;
195
- stopped = false;
196
- spawnLoop(botToken);
197
- return { ok: true, bot };
198
- }
199
-
200
- return {
201
- /** Start on host boot, but only if the user already connected one. Never throws. */
202
- async startIfConfigured() {
203
- await load();
204
- if (!(await readToken()) || settings.enabled === false) return { ok: false, skipped: true };
205
- return start().catch((e) => ({ ok: false, error: e?.message || String(e) }));
206
- },
207
-
208
- start,
209
-
210
- /**
211
- * Connect a bot: verify the token FIRST, then persist it 0600 and start. Verifying before
212
- * writing means a typo never leaves a dead secret on disk.
213
- */
214
- async connect({ token: botToken, agent, privacy, tier } = {}) {
215
- await load();
216
- const verified = await verifyBot(botToken, { fetchImpl }); // throws with a readable reason
217
- await writeFile(tokenFile, String(botToken).trim(), { mode: 0o600 });
218
- settings = {
219
- ...settings,
220
- ...(agent ? { agent } : {}),
221
- ...(privacy ? { privacy } : {}),
222
- ...(tier ? { tier } : {}),
223
- enabled: true,
224
- };
225
- await saveSettings();
226
- await this.stop();
227
- const r = await start();
228
- if (!r.ok) throw new Error(r.error);
229
- return { bot: verified, settings: { ...settings } };
230
- },
231
-
232
- /**
233
- * Mint a one-time enrollment code and the link that redeems it in one tap. The code is the
234
- * fallback for someone reading it off a screen; the link is the path most people take.
235
- */
236
- async pair({ ttlMs = 10 * 60_000 } = {}) {
237
- await load();
238
- if (!bot) throw new Error('connect a bot first');
239
- const code = pairing.requestCode({ ttlMs });
240
- await savePairing();
241
- return { code, link: pairLink(bot.username, code), expiresAt: now() + ttlMs, bot: { ...bot } };
242
- },
243
-
244
- /**
245
- * Pre-pair without a code — an operator allow-list for scripted setups. Explicit by
246
- * design: there is no path here that enrolls a chat because it messaged you.
247
- */
248
- async allow(actorId, { reach = 'trusted' } = {}) {
249
- await load();
250
- pairing.allow(actorId, { reach });
251
- await savePairing();
252
- return { actorId, reach };
253
- },
254
-
255
- /** Revoke one phone. Takes effect on its NEXT message — nothing is cached per chat. */
256
- async unpair(actorId) {
257
- await load();
258
- const removed = pairing.revoke(actorId);
259
- await savePairing();
260
- return { removed };
261
- },
262
-
263
- async update(patch = {}) {
264
- await load();
265
- const next = { ...settings };
266
- for (const k of ['agent', 'model', 'provider', 'gatewayUrl', 'privacy', 'tier', 'system']) {
267
- if (patch[k] != null) next[k] = patch[k];
268
- }
269
- // Picking one target unpicks the other. Without this a stale `model` would silently win
270
- // over the agent the user just chose, and the screen would disagree with the machine.
271
- if (patch.agent != null && patch.model == null) { next.model = ''; next.provider = ''; }
272
- if (patch.model) next.agent = '';
273
- settings = next;
274
- await saveSettings();
275
- // NO RESTART. The loop reads settings per message through `route`, and restarting it
276
- // would discard every conversation's history and vault — which is exactly what made
277
- // changing the model answer the next question with "this looks like a fresh session".
278
- // The only change that still needs a restart is a new bot token, and connect() does that.
279
- return { settings: { ...settings } };
280
- },
281
-
282
- /** Stop the loop. `forget` also deletes the token and every pairing — a real disconnect. */
283
- async stop({ forget = false } = {}) {
284
- stopped = true;
285
- controller?.abort();
286
- controller = null;
287
- running = false;
288
- if (forget) {
289
- await load();
290
- settings = { ...settings, enabled: false };
291
- await saveSettings();
292
- await rm(tokenFile, { force: true });
293
- for (const p of pairing.list()) pairing.revoke(p.actorId);
294
- await savePairing();
295
- bot = null;
296
- }
297
- return { ok: true };
298
- },
299
-
300
- /**
301
- * Everything a settings screen needs and nothing it must not have: no bot token, ever.
302
- * `configured` says a token exists; `running` says the loop is actually polling.
303
- */
304
- async status() {
305
- await load();
306
- const configured = !!(await readToken());
307
- return {
308
- channel: 'telegram',
309
- configured,
310
- enabled: settings.enabled !== false,
311
- running,
312
- bot: bot ? { ...bot } : null,
313
- error: lastError,
314
- paired: pairing.list(),
315
- settings: {
316
- agent: settings.agent,
317
- model: settings.model || '',
318
- provider: settings.provider || '',
319
- gatewayUrl: settings.gatewayUrl || DEFAULT_GATEWAY_URL,
320
- privacy: settings.privacy,
321
- tier: settings.tier,
322
- },
323
- // Which transport a message will actually take, so a screen can say so rather than
324
- // inferring it from two fields and getting it wrong.
325
- via: settings.model ? 'gateway' : 'bridge',
326
- };
327
- },
328
- };
329
- }
1
+ import k from"node:path";import{readFile as x,writeFile as L,mkdir as R,rm as z,stat as B}from"node:fs/promises";import{createPairingStore as I}from"./pairing.js";import*as Y from"./bridge.js";import*as q from"./gateway.js";const U="http://127.0.0.1:4320";import{createEventLog as H}from"./eventlog.js";import{startTelegram as W}from"./adapters/telegram.js";const D="https://api.telegram.org",J=Object.freeze({agent:"claude",model:"",provider:"",gatewayUrl:U,privacy:"standard",tier:"basic"}),P=[2e3,5e3,15e3,6e4],C=async(i,n)=>{try{return JSON.parse(await x(i,"utf8"))}catch{return n}},G=(i,n)=>L(i,JSON.stringify(n,null,2),{mode:384});async function M(i,{fetchImpl:n=fetch,signal:y}={}){const f=await n(`${D}/bot${String(i||"").trim()}/getMe`,{signal:y}),l=await f.json().catch(()=>null);if(!l?.ok){const m=l?.description||`HTTP ${f.status}`;throw new Error(/unauthorized/i.test(m)?"Telegram rejected that token — copy it again from @BotFather":m)}return{id:l.result.id,username:l.result.username,name:l.result.first_name||""}}const K=(i,n)=>`https://t.me/${i}?start=${n}`;function et({home:i,dataDir:n,bridge:y,logger:f=console,fetchImpl:l=void 0,now:m=()=>Date.now(),startAdapter:N=W}={}){const p=k.join(i,"telegram-token"),_=k.join(n,"config.json"),j=k.join(n,"pairing.json");let o=null,e={...J},b=null,c=null,v=null,w=!1,d="",A=0,h=!0;const g=()=>G(j,o?o.toJSON():{}),S=()=>G(_,e);async function T(){try{const t=(await x(p,"utf8")).trim();if(!t)return"";try{const{mode:r}=await B(p);r&63&&f.warn?.(`[channels] ${p} is group/world-readable — chmod 600 it (it holds your bot token).`)}catch{}return t}catch{return""}}async function s(){await R(n,{recursive:!0}),o||(o=I(await C(j,{}),{now:m})),e={...J,...await C(_,{})},b||(b=await H({file:k.join(n,"events.jsonl"),host:"channel"}))}function F(t){v=new AbortController,w=!0;const r=()=>{const a=!!e.model;return{transport:a?q:Y,agent:a?"":e.agent,model:a?e.model:"",provider:a&&e.provider||"",baseUrl:a?e.gatewayUrl||U:y.baseUrl,system:e.system||"",privacy:e.privacy}},u=N({botToken:t,route:r,transport:r().transport,model:r().model,provider:r().provider,baseUrl:r().baseUrl,token:y.token,pairing:o,savePairing:g,appender:b,agent:e.agent,system:e.system||"",redact:{tier:e.tier},privacy:e.privacy,logger:f,signal:v.signal});Promise.resolve(u).catch(a=>{d=a?.message||String(a),f.warn?.(`[channels] telegram loop failed: ${d}`)}).finally(()=>{if(w=!1,h)return;const a=P[Math.min(A++,P.length-1)];f.warn?.(`[channels] telegram stopped unexpectedly — retrying in ${Math.round(a/1e3)}s`),setTimeout(()=>{h||F(t)},a).unref?.()})}async function E(){if(w)return{ok:!0,already:!0};await s();const t=await T();if(!t)return{ok:!1,error:"no bot token configured"};if(e.enabled===!1)return{ok:!1,error:"channel is turned off"};try{c=await M(t,{fetchImpl:l})}catch(r){return d=r?.message||String(r),{ok:!1,error:d}}return d="",A=0,h=!1,F(t),{ok:!0,bot:c}}return{async startIfConfigured(){return await s(),!await T()||e.enabled===!1?{ok:!1,skipped:!0}:E().catch(t=>({ok:!1,error:t?.message||String(t)}))},start:E,async connect({token:t,agent:r,privacy:u,tier:a}={}){await s();const O=await M(t,{fetchImpl:l});await L(p,String(t).trim(),{mode:384}),e={...e,...r?{agent:r}:{},...u?{privacy:u}:{},...a?{tier:a}:{},enabled:!0},await S(),await this.stop();const $=await E();if(!$.ok)throw new Error($.error);return{bot:O,settings:{...e}}},async pair({ttlMs:t=10*6e4}={}){if(await s(),!c)throw new Error("connect a bot first");const r=o.requestCode({ttlMs:t});return await g(),{code:r,link:K(c.username,r),expiresAt:m()+t,bot:{...c}}},async allow(t,{reach:r="trusted"}={}){return await s(),o.allow(t,{reach:r}),await g(),{actorId:t,reach:r}},async unpair(t){await s();const r=o.revoke(t);return await g(),{removed:r}},async update(t={}){await s();const r={...e};for(const u of["agent","model","provider","gatewayUrl","privacy","tier","system"])t[u]!=null&&(r[u]=t[u]);return t.agent!=null&&t.model==null&&(r.model="",r.provider=""),t.model&&(r.agent=""),e=r,await S(),{settings:{...e}}},async stop({forget:t=!1}={}){if(h=!0,v?.abort(),v=null,w=!1,t){await s(),e={...e,enabled:!1},await S(),await z(p,{force:!0});for(const r of o.list())o.revoke(r.actorId);await g(),c=null}return{ok:!0}},async status(){return await s(),{channel:"telegram",configured:!!await T(),enabled:e.enabled!==!1,running:w,bot:c?{...c}:null,error:d,paired:o.list(),settings:{agent:e.agent,model:e.model||"",provider:e.provider||"",gatewayUrl:e.gatewayUrl||U,privacy:e.privacy,tier:e.tier},via:e.model?"gateway":"bridge"}}}}export{J as DEFAULT_SETTINGS,et as createChannelService,K as pairLink,M as verifyBot};
@@ -1,106 +1,7 @@
1
- // GENERATED — do not edit.
2
- // Source of truth: chatpanel-channels/src/stream.js (npm @chatpanel/channels).
3
- // Edit there, then run: npm run sync:channels
4
- //
5
- // Vendored rather than depended on: the bridge ships zero runtime dependencies so a
6
- // curl one-liner install cannot fail on someone's registry, and so the compiled
7
- // single-file binary has nothing to resolve. Package imports are rewritten to the
8
- // vendored engines (src/pii, src/events) by the sync script.
1
+ function s(){return{runId:null,text:"",status:"",error:null,done:!1}}function c(e,t){switch(t?.type){case"run":return{...e,runId:t.id||e.runId};case"delta":return{...e,text:e.text+(t.text||"")};case"status":return{...e,status:t.text||e.status};case"done":return{...e,done:!0,text:!e.text&&t.text?t.text:e.text};case"error":return{...e,done:!0,error:t.error||"unknown error"};default:return e}}function l(e,t){if(t?.type==="run")return{...e,runId:t.id||e.runId};if(t?.error)return{...e,done:!0,error:t.error.message||String(t.error)};const r=t?.choices?.[0];let n=e;const o=r?.delta?.content;typeof o=="string"&&o&&(n={...n,text:n.text+o});const i=r?.message?.content;return!n.text&&typeof i=="string"&&i&&(n={...n,text:i}),r?.finish_reason&&(n={...n,done:!0}),n}function f(e){const t=[];let r=String(e),n;for(;(n=r.indexOf(`
9
2
 
10
- // The model's reply, assembled from the bridge's SSE stream — PURE so accumulation and the
11
- // token-restore boundary are testable without a socket. Per chatpanel-bridge /chat, the bridge
12
- // emits `data: <json>\n\n` frames of:
13
- // {type:'run', id} a cancel-by-name handle, emitted first
14
- // {type:'workdir'|'status'|'reasoning'|'tool', ...} progress a caller MAY show
15
- // {type:'delta', text} incremental assistant text
16
- // {type:'done', text?} text only when it wasn't streamed
17
- // {type:'error', error}
18
- // We only need run/delta/done/error to build a reply.
3
+ `))>=0;){const o=r.slice(0,n);r=r.slice(n+2);for(const i of o.split(`
4
+ `)){if(!i.startsWith("data:"))continue;const u=i.slice(5).trim();if(u)try{t.push(JSON.parse(u))}catch{}}}return{events:t,rest:r}}function d(e,t=4096){let r=String(e??"");const n=[];for(;r.length>t;){let o=r.lastIndexOf(`
19
5
 
20
- export function initialState() {
21
- return { runId: null, text: '', status: '', error: null, done: false };
22
- }
23
-
24
- /** Fold one bridge event into the running reply. Returns a NEW state (never mutates). */
25
- export function foldEvent(state, ev) {
26
- switch (ev?.type) {
27
- case 'run': return { ...state, runId: ev.id || state.runId };
28
- case 'delta': return { ...state, text: state.text + (ev.text || '') };
29
- case 'status': return { ...state, status: ev.text || state.status };
30
- // A `done` may carry the whole text (engines that don't stream). Only take it when we
31
- // streamed nothing, or the reply doubles.
32
- case 'done': return { ...state, done: true, text: (!state.text && ev.text) ? ev.text : state.text };
33
- case 'error': return { ...state, done: true, error: ev.error || 'unknown error' };
34
- default: return state;
35
- }
36
- }
37
-
38
- /**
39
- * Fold one OpenAI-style chunk (what the gateway streams) into the same reply state, so a
40
- * caller cannot tell which transport it has. Shares parseSse: `data: [DONE]` is not JSON and
41
- * is dropped there, which is why the transport marks `done` itself when the stream ends.
42
- */
43
- export function foldOpenAiEvent(state, ev) {
44
- if (ev?.type === 'run') return { ...state, runId: ev.id || state.runId };
45
- // An error can arrive as a streamed frame rather than an HTTP status.
46
- if (ev?.error) return { ...state, done: true, error: ev.error.message || String(ev.error) };
47
- const choice = ev?.choices?.[0];
48
- let next = state;
49
- const delta = choice?.delta?.content;
50
- if (typeof delta === 'string' && delta) next = { ...next, text: next.text + delta };
51
- // Non-streaming replies (a gateway destination that cannot stream) carry the whole message.
52
- const whole = choice?.message?.content;
53
- if (!next.text && typeof whole === 'string' && whole) next = { ...next, text: whole };
54
- if (choice?.finish_reason) next = { ...next, done: true };
55
- return next;
56
- }
57
-
58
- /**
59
- * Pull complete SSE events out of a growing buffer. Returns the parsed events and the
60
- * UNCONSUMED tail (a partial frame still arriving), which the caller prepends next read.
61
- */
62
- export function parseSse(buffer) {
63
- const events = [];
64
- let rest = String(buffer);
65
- let idx;
66
- while ((idx = rest.indexOf('\n\n')) >= 0) {
67
- const raw = rest.slice(0, idx);
68
- rest = rest.slice(idx + 2);
69
- for (const line of raw.split('\n')) {
70
- if (!line.startsWith('data:')) continue;
71
- const json = line.slice(5).trim();
72
- if (!json) continue;
73
- try { events.push(JSON.parse(json)); } catch { /* skip a malformed frame */ }
74
- }
75
- }
76
- return { events, rest };
77
- }
78
-
79
- // Telegram rejects a message body over 4096 chars. Split on paragraph, then line, then a hard
80
- // cut, so a long answer arrives as several messages instead of one API error.
81
- export function splitForTelegram(text, max = 4096) {
82
- let s = String(text ?? '');
83
- const out = [];
84
- while (s.length > max) {
85
- let cut = s.lastIndexOf('\n\n', max);
86
- if (cut < max * 0.5) cut = s.lastIndexOf('\n', max);
87
- if (cut < max * 0.5) cut = max;
88
- out.push(s.slice(0, cut));
89
- s = s.slice(cut).replace(/^\n+/, '');
90
- }
91
- if (s) out.push(s);
92
- return out.length ? out : [''];
93
- }
94
-
95
- // A minimal time gate for throttling live edits — Telegram allows ~1 edit/sec to a chat.
96
- // `now` injected for tests. ready() returns true and advances only when `ms` has elapsed.
97
- export function createGate(ms, { now = () => Date.now() } = {}) {
98
- // -Infinity, not 0, so the FIRST call always fires (replace the "…" placeholder promptly)
99
- // regardless of the clock's magnitude — then throttle. With last=0 this only worked because
100
- // the real Date.now() dwarfs `ms`; an injected test clock at t=0 exposed the latent bug.
101
- let last = -Infinity;
102
- return {
103
- ready() { const t = now(); if (t - last >= ms) { last = t; return true; } return false; },
104
- reset() { last = -Infinity; },
105
- };
106
- }
6
+ `,t);o<t*.5&&(o=r.lastIndexOf(`
7
+ `,t)),o<t*.5&&(o=t),n.push(r.slice(0,o)),r=r.slice(o).replace(/^\n+/,"")}return r&&n.push(r),n.length?n:[""]}function x(e,{now:t=()=>Date.now()}={}){let r=-1/0;return{ready(){const n=t();return n-r>=e?(r=n,!0):!1},reset(){r=-1/0}}}export{x as createGate,c as foldEvent,l as foldOpenAiEvent,s as initialState,f as parseSse,d as splitForTelegram};
package/src/cli-errors.js CHANGED
@@ -1,136 +1,3 @@
1
- // Turning a CLI agent's dying breath into something a person can act on.
2
- //
3
- // When an agent exits non-zero we used to surface its raw stderr. For a crash that is fine;
4
- // for the common real failure — one of the AGENT'S OWN MCP servers refusing to authenticate —
5
- // it is not: those servers answer with an HTML error page, so the user got kilobytes of
6
- // markup, inline CSS and an SVG logo in the chat, with the one useful sentence buried inside.
7
- //
8
- // The failure is also usually not ChatPanel's to fix. Saying whose it is, and naming the
9
- // server, is the difference between "something broke" and "re-auth that server".
10
- //
11
- // `mcpFailure` is the machine-readable half of the same knowledge: mcp-quarantine.js reads
12
- // it to DROP the offending server and run again, so the common cases never reach a human at
13
- // all. One set of patterns serves both — a second copy would drift.
14
-
15
- import { loginRequired, signInMessage } from './sign-in.js';
16
-
17
- const NOISE = [
18
- /^\s*$/,
19
- /^\s*at\s+/, // stack frames
20
- /^\s*[.#]?[\w-]+\s*\{/, // CSS rules
21
- /^\s*[\w-]+:\s*[^;]+;$/,// CSS declarations
22
- /^\s*<\//, // closing tags
23
- ];
24
-
25
- // Strip HTML/CSS/SVG so an error page collapses to whatever prose it contained.
26
- export function stripMarkup(text) {
27
- return String(text || '')
28
- .replace(/<script[\s\S]*?<\/script>/gi, ' ')
29
- .replace(/<style[\s\S]*?<\/style>/gi, ' ')
30
- .replace(/<svg[\s\S]*?<\/svg>/gi, ' ')
31
- .replace(/<[^>]+>/g, ' ')
32
- .replace(/&nbsp;/g, ' ')
33
- .replace(/[ \t]+/g, ' ');
34
- }
35
-
36
- // Which server the output blames, if it names one. Codex and Claude Code phrase this several
37
- // ways, so try each; a name we cannot read means there is nothing to disable, which is why
38
- // every caller must tolerate `null`.
39
- const SERVER_PATTERNS = [
40
- /(?:refresh OAuth tokens|refresh tools) for (?:MCP )?server ['"`]?([\w.-]+)['"`]?/i,
41
- /MCP server ['"`]([\w.-]+)['"`]/i,
42
- /server ['"]?([\w.-]+)['"]? (?:requires|failed) auth/i,
43
- ];
44
- export function mcpServerName(text) {
45
- for (const re of SERVER_PATTERNS) {
46
- const name = re.exec(String(text || ''))?.[1];
47
- if (name) return name;
48
- }
49
- return null;
50
- }
51
-
52
- // The named MCP causes worth translating. `say` is the sentence for a human; `short` is the
53
- // clause used when we skip the server and carry on. Order matters — specific before generic.
54
- const MCP_CAUSES = [
55
- {
56
- kind: 'expired',
57
- test: /refresh token (?:does not exist|was rejected)|invalid_grant/i,
58
- short: 'its saved login has expired',
59
- say: (who) => `${who} needs re-authentication — its saved OAuth token has expired or been revoked. Re-login to that server in the agent's own config; ChatPanel can't refresh it.`,
60
- },
61
- {
62
- kind: 'unauthorized',
63
- test: /invalid_token|AuthRequired|www-authenticate|\b401\b/i,
64
- short: 'it rejected the agent\'s token',
65
- say: (who) => `${who} rejected the agent's token (401/invalid_token). Re-authenticate that server in the agent, then retry.`,
66
- },
67
- {
68
- kind: 'refused',
69
- test: /HTTP 403|\b403\b/,
70
- short: 'it is refusing requests',
71
- say: (who) => `${who} returned 403 and an error page — that server is refusing requests or is temporarily down. This is outside ChatPanel; retry when it recovers.`,
72
- },
73
- {
74
- // The off-network case: a VPN-only server seen from a cafe. Only counted when the text
75
- // is talking about MCP at all, so an ordinary provider timeout is not misread as this.
76
- kind: 'unreachable',
77
- requiresMcpContext: true,
78
- test: /handshaking with MCP server failed|ECONNREFUSED|ENOTFOUND|EAI_AGAIN|dns error|connection (?:refused|reset)|failed to start and is unavailable|network is unreachable/i,
79
- short: 'it could not be reached',
80
- say: (who) => `${who} could not be reached — it is offline, or needs a network (VPN) this machine is not on. ChatPanel can't reach it either; retry when it is available.`,
81
- },
82
- ];
83
-
84
- /**
85
- * Classify an MCP-server failure in an agent's output.
86
- * @returns {{server: string|null, kind: string, short: string, say: string}|null}
87
- */
88
- export function mcpFailure(text) {
89
- const raw = String(text || '');
90
- const server = mcpServerName(raw);
91
- const hasMcpContext = /\bmcp\b/i.test(raw) || !!server;
92
- for (const cause of MCP_CAUSES) {
93
- if (cause.requiresMcpContext && !hasMcpContext) continue;
94
- if (!cause.test.test(raw)) continue;
95
- return {
96
- server,
97
- kind: cause.kind,
98
- short: cause.short,
99
- say: cause.say(server ? `its MCP server "${server}"` : 'one of its MCP servers'),
100
- };
101
- }
102
- return null;
103
- }
104
-
105
- // The named causes worth translating. Each returns a sentence that says what to DO.
106
- function knownCause(text) {
107
- const mcp = mcpFailure(text);
108
- if (mcp) return mcp.say;
109
- if (/ENOENT|command not found/i.test(text)) return 'the command could not be found on PATH.';
110
- return null;
111
- }
112
-
113
- const AGENT_IDS = { 'claude code': 'claude', claude: 'claude', codex: 'codex', 'github copilot': 'copilot', copilot: 'copilot', opencode: 'opencode', kiro: 'kiro', hermes: 'hermes', antigravity: 'antigravity', pi: 'pi' };
114
-
115
- /**
116
- * A short, actionable summary of why a CLI agent exited. Never returns markup, and never more
117
- * than a couple of lines — the full output stays in the bridge log for anyone debugging.
118
- *
119
- * "Not signed in" comes FIRST and drops the exit code: "Claude Code exited 1" read as a
120
- * ChatPanel bug, when the whole story was that the user had never run `/login`.
121
- */
122
- export function summarizeCliError(label, code, stderr, stdout = '', { agentId = null } = {}) {
123
- const raw = `${stderr || ''}\n${stdout || ''}`;
124
- if (loginRequired(raw)) return signInMessage(label, agentId || AGENT_IDS[String(label).toLowerCase()] || null);
125
- const cause = knownCause(raw);
126
- if (cause) return `${label} exited ${code}: ${cause}`;
127
-
128
- const lines = stripMarkup(raw)
129
- .split('\n')
130
- .map((l) => l.trim())
131
- .filter((l) => l && !NOISE.some((re) => re.test(l)));
132
- // Prefer the last line that reads like an error, else the last line at all.
133
- const errish = lines.filter((l) => /error|fail|fatal|panic|refused|denied|timeout/i.test(l));
134
- const pick = (errish.length ? errish : lines).pop() || 'failed';
135
- return `${label} exited ${code}: ${pick.length > 300 ? `${pick.slice(0, 300)}…` : pick}`;
136
- }
1
+ import{loginRequired as h,signInMessage as p}from"./sign-in.js";const f=[/^\s*$/,/^\s*at\s+/,/^\s*[.#]?[\w-]+\s*\{/,/^\s*[\w-]+:\s*[^;]+;$/,/^\s*<\//];function g(e){return String(e||"").replace(/<script[\s\S]*?<\/script>/gi," ").replace(/<style[\s\S]*?<\/style>/gi," ").replace(/<svg[\s\S]*?<\/svg>/gi," ").replace(/<[^>]+>/g," ").replace(/&nbsp;/g," ").replace(/[ \t]+/g," ")}const v=[/(?:refresh OAuth tokens|refresh tools) for (?:MCP )?server ['"`]?([\w.-]+)['"`]?/i,/MCP server ['"`]([\w.-]+)['"`]/i,/server ['"]?([\w.-]+)['"]? (?:requires|failed) auth/i];function k(e){for(const t of v){const r=t.exec(String(e||""))?.[1];if(r)return r}return null}const m=[{kind:"expired",test:/refresh token (?:does not exist|was rejected)|invalid_grant/i,short:"its saved login has expired",say:e=>`${e} needs re-authentication — its saved OAuth token has expired or been revoked. Re-login to that server in the agent's own config; ChatPanel can't refresh it.`},{kind:"unauthorized",test:/invalid_token|AuthRequired|www-authenticate|\b401\b/i,short:"it rejected the agent's token",say:e=>`${e} rejected the agent's token (401/invalid_token). Re-authenticate that server in the agent, then retry.`},{kind:"refused",test:/HTTP 403|\b403\b/,short:"it is refusing requests",say:e=>`${e} returned 403 and an error page — that server is refusing requests or is temporarily down. This is outside ChatPanel; retry when it recovers.`},{kind:"unreachable",requiresMcpContext:!0,test:/handshaking with MCP server failed|ECONNREFUSED|ENOTFOUND|EAI_AGAIN|dns error|connection (?:refused|reset)|failed to start and is unavailable|network is unreachable/i,short:"it could not be reached",say:e=>`${e} could not be reached — it is offline, or needs a network (VPN) this machine is not on. ChatPanel can't reach it either; retry when it is available.`}];function w(e){const t=String(e||""),r=k(t),s=/\bmcp\b/i.test(t)||!!r;for(const n of m)if(!(n.requiresMcpContext&&!s)&&n.test.test(t))return{server:r,kind:n.kind,short:n.short,say:n.say(r?`its MCP server "${r}"`:"one of its MCP servers")};return null}function C(e){const t=w(e);return t?t.say:/ENOENT|command not found/i.test(e)?"the command could not be found on PATH.":null}const $={"claude code":"claude",claude:"claude",codex:"codex","github copilot":"copilot",copilot:"copilot",opencode:"opencode",kiro:"kiro",hermes:"hermes",antigravity:"antigravity",pi:"pi"};function y(e,t,r,s="",{agentId:n=null}={}){const o=`${r||""}
2
+ ${s||""}`;if(h(o))return p(e,n||$[String(e).toLowerCase()]||null);const c=C(o);if(c)return`${e} exited ${t}: ${c}`;const u=g(o).split(`
3
+ `).map(i=>i.trim()).filter(i=>i&&!f.some(l=>l.test(i))),d=u.filter(i=>/error|fail|fatal|panic|refused|denied|timeout/i.test(i)),a=(d.length?d:u).pop()||"failed";return`${e} exited ${t}: ${a.length>300?`${a.slice(0,300)}…`:a}`}export{w as mcpFailure,k as mcpServerName,g as stripMarkup,y as summarizeCliError};