@chatpanel/bridge 0.11.24 → 0.12.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (69) hide show
  1. package/.env.example +12 -0
  2. package/README.md +7 -7
  3. package/package.json +1 -13
  4. package/scripts/sync-channels.mjs +8 -90
  5. package/scripts/sync-events.mjs +7 -78
  6. package/scripts/sync-pii.mjs +7 -68
  7. package/src/api-compat.js +5 -294
  8. package/src/channels/adapters/telegram.js +3 -298
  9. package/src/channels/bridge.js +1 -59
  10. package/src/channels/eventlog.js +3 -57
  11. package/src/channels/gateway.js +1 -114
  12. package/src/channels/invoke.js +1 -172
  13. package/src/channels/normalize.js +1 -58
  14. package/src/channels/pairing.js +1 -95
  15. package/src/channels/service.js +1 -329
  16. package/src/channels/stream.js +5 -104
  17. package/src/cli-errors.js +3 -136
  18. package/src/connections.js +1 -160
  19. package/src/connectors.js +1 -100
  20. package/src/engines/antigravity.js +5 -235
  21. package/src/engines/args.js +1 -47
  22. package/src/engines/claude-warm.js +3 -0
  23. package/src/engines/claude.js +6 -586
  24. package/src/engines/cli-agents.js +7 -312
  25. package/src/engines/codex-appserver.js +12 -0
  26. package/src/engines/codex.js +6 -481
  27. package/src/engines/custom.js +17 -577
  28. package/src/engines/prompt.js +6 -32
  29. package/src/engines/stream-formats.js +2 -222
  30. package/src/entitlement.js +1 -77
  31. package/src/env.js +3 -628
  32. package/src/events/capability.js +1 -134
  33. package/src/events/event.js +1 -183
  34. package/src/events/reach.js +1 -31
  35. package/src/events/ref.js +1 -63
  36. package/src/events/scm-connection.js +1 -188
  37. package/src/events/scopes.js +1 -20
  38. package/src/events/skill-manifest.js +1 -338
  39. package/src/events/skill-scan.js +3 -217
  40. package/src/events/view.js +1 -96
  41. package/src/mcp-capabilities.js +2 -139
  42. package/src/mcp-local.js +0 -0
  43. package/src/mcp-quarantine.js +1 -110
  44. package/src/mcp-sessions.js +1 -0
  45. package/src/net.js +1 -107
  46. package/src/pii/index.js +1 -29
  47. package/src/pii/net.js +1 -111
  48. package/src/pii/pii-detect.js +2 -296
  49. package/src/pii/pii-redact.js +1 -470
  50. package/src/pii/pipeline.js +1 -137
  51. package/src/pii/sanitize.js +2 -179
  52. package/src/pii/tool-harness.js +1 -184
  53. package/src/pii/tool-rank.js +1 -110
  54. package/src/proc.js +3 -91
  55. package/src/relay-timeout.js +1 -21
  56. package/src/rpc-child.js +3 -0
  57. package/src/runs.js +1 -49
  58. package/src/sanitize.js +1 -7
  59. package/src/scm.js +1 -76
  60. package/src/server.js +10 -1492
  61. package/src/service.js +11 -176
  62. package/src/sign-in.js +1 -91
  63. package/src/skills.js +1 -399
  64. package/src/ssrf.js +1 -70
  65. package/src/update.js +1 -216
  66. package/src/warm-pool.js +1 -0
  67. package/src/warm.js +1 -0
  68. package/src/workdir.js +1 -108
  69. package/src/worktree.js +3 -125
@@ -1,312 +1,7 @@
1
- // Built-in CLI agents — pi, opencode, kiro — that reuse the shared custom-engine
2
- // runner (runSpec) with a fixed spec each. These are fixed built-in engines and are
3
- // not entitlement-gated; custom BYO CLIs are handled by custom.js.
4
- //
5
- // Specs come from each CLI's actual flags:
6
- // pi — pi -p "<prompt>" · --model · @{path} images · --list-models
7
- // opencode — opencode run "<prompt>" · -m provider/model · -f {path} images · models
8
- // kiro — kiro-cli chat --no-interactive "<prompt>" · --model · --list-models
9
- // hermes — hermes -z "<prompt>" · -m model · config get model (no list command)
10
-
11
- import { runSpec, listSpecModels, runForStdout, CHATPANEL_STABLE_MCP_URL } from './custom.js';
12
- import { findAgentBin, selfMcpStdio } from '../env.js';
13
-
14
- // `listModels` override hook: a CLI whose model listing isn't "one id per line"
15
- // (Copilot prints a quoted list inside `help config`) passes its own parser here
16
- // instead of forcing the generic one to grow special cases.
17
- function makeCliAgent(command, spec, notFoundHint, overrides = {}) {
18
- let installed = false;
19
- let lastProbe = 0;
20
- const resolvedSpec = { ...spec, command };
21
- return {
22
- spec: resolvedSpec,
23
- async available() {
24
- // Re-probe in BOTH directions. Caching a positive result forever meant an UNINSTALLED
25
- // CLI kept reporting itself available until the bridge restarted — the picker showed a
26
- // green dot for an agent that could no longer run, and the turn failed with "couldn't
27
- // find it on your PATH". A found CLI is re-checked on a slow interval (it rarely
28
- // disappears, and `which` is cheap but not free); a missing one keeps the fast interval
29
- // so it still self-heals the moment it is installed.
30
- if (Date.now() - lastProbe > (installed ? 30_000 : 4000)) {
31
- lastProbe = Date.now();
32
- try {
33
- installed = !!findAgentBin(command);
34
- } catch {
35
- installed = false;
36
- }
37
- }
38
- return installed ? { ok: true } : { ok: false, reason: notFoundHint };
39
- },
40
- listModels(options = {}) {
41
- if (overrides.listModels) return overrides.listModels(command, options);
42
- return listSpecModels(command, spec.listModelsArgs, options.workingDir);
43
- },
44
- chat(input, emit, opts) {
45
- return runSpec(resolvedSpec, input, emit, opts);
46
- },
47
- };
48
- }
49
-
50
- export const pi = makeCliAgent(
51
- 'pi',
52
- {
53
- args: '-p',
54
- promptVia: 'arg',
55
- modelArg: '--model {model}',
56
- imageArg: '@{path}',
57
- toolAdapter: 'pi-extension',
58
- listModelsArgs: '--list-models',
59
- label: 'Pi',
60
- },
61
- 'pi not found on PATH. Install Pi, then run `pi` once to sign in.',
62
- );
63
-
64
- export const opencode = makeCliAgent(
65
- 'opencode',
66
- {
67
- // `--format json` → clean NDJSON events (the default emits a TUI that's
68
- // garbage when piped). --dangerously-skip-permissions so headless tool use
69
- // (incl. our relayed browser tools) doesn't block on an approval prompt.
70
- args: 'run --format json --dangerously-skip-permissions',
71
- promptVia: 'arg',
72
- modelArg: '-m {model}',
73
- imageArg: '-f {path}',
74
- format: 'opencode-json',
75
- // Browser tools come via the bridge's STABLE /mcp endpoint, registered once
76
- // with `opencode mcp add chatpanel --url http://127.0.0.1:4319/mcp` (opencode
77
- // only loads MCP from its global config, not a per-run file).
78
- requiresStableMcp: true,
79
- stableMcpConfigCheck: 'opencode',
80
- listModelsArgs: 'models',
81
- label: 'OpenCode',
82
- },
83
- 'opencode not found on PATH. Install opencode, then sign in.',
84
- );
85
-
86
- export const kiro = makeCliAgent(
87
- 'kiro-cli',
88
- {
89
- args: 'chat --no-interactive --require-mcp-startup',
90
- promptVia: 'arg',
91
- modelArg: '--model {model}',
92
- // Kiro can see MCP tools with --trust-tools, but in --no-interactive mode it
93
- // only executes MCP calls when this broader trust flag is present.
94
- trustAllToolsForMcp: true,
95
- trustAllToolsArg: '--trust-all-tools',
96
- requiresStableMcp: true,
97
- autoSetupStableMcp: true,
98
- stableMcpConfigCheck: 'kiro',
99
- stableMcpSetupArgs: ['mcp', 'add', '--scope', 'global', '--name', 'chatpanel_browser', '--url', 'http://127.0.0.1:4319/mcp', '--force'],
100
- stableMcpSetupCommand: 'kiro-cli mcp add --scope global --name chatpanel_browser --url http://127.0.0.1:4319/mcp --force',
101
- listModelsArgs: '--list-models',
102
- label: 'Kiro',
103
- },
104
- 'kiro-cli not found on PATH. Install Kiro CLI, then sign in.',
105
- );
106
-
107
- // GitHub Copilot CLI. Verified against 1.0.80 (`copilot`, not the old
108
- // `gh copilot` extension).
109
- //
110
- // The two things that make or break headless Copilot:
111
- // 1. --allow-all-tools is REQUIRED in -p mode. Without it EVERY tool call dies
112
- // with "Permission denied and could not request permission from user" — the
113
- // CLI has no TTY to ask on — so the agent answers as if it had no tools.
114
- // 2. --output-format json turns the TUI into clean NDJSON we can stream;
115
- // the default text output is not parseable as a live stream.
116
- // Both live in the base spec because neither is optional for this integration.
117
- //
118
- // Permission mode maps onto Copilot's real permission surface (see
119
- // permissionArgs): tools always run unattended, while filesystem reach beyond the
120
- // working dir and arbitrary URL access are what the mode actually escalates.
121
- const COPILOT_BASE_ARGS = [
122
- '-p', '{prompt}',
123
- '--output-format', 'json',
124
- '--no-color',
125
- '--log-level', 'none',
126
- // Headless hygiene: never block asking the user a question, never self-update
127
- // mid-turn, and don't ship the session to GitHub web/mobile from a ChatPanel
128
- // turn (Copilot exports by default; ChatPanel keeps chat local by policy).
129
- '--no-ask-user',
130
- '--no-auto-update',
131
- '--no-remote',
132
- '--no-remote-export',
133
- ];
134
-
135
- export const copilot = makeCliAgent(
136
- 'copilot',
137
- {
138
- args: COPILOT_BASE_ARGS,
139
- promptVia: 'arg',
140
- modelArg: '--model {model}',
141
- // Non-interactive-only flag; one per image.
142
- imageArg: '--attachment {path}',
143
- format: 'copilot-json',
144
- // Copilot takes per-run MCP servers, so browser tools work WITHOUT touching
145
- // the user's ~/.copilot/mcp-config.json (unlike opencode/kiro, which only
146
- // read global config). `@` prefix = "this is a file path, not inline JSON";
147
- // the shape runSpec writes ({mcpServers:{name:{command,args}}}) is the one
148
- // Copilot expects — verified.
149
- mcpArg: '--additional-mcp-config @{file}',
150
- permissionArgs: {
151
- // Tools yes (or nothing works); no path escape, no arbitrary URLs.
152
- default: ['--allow-all-tools'],
153
- // Edits anywhere on disk, still no arbitrary URL fetching.
154
- acceptEdits: ['--allow-all-tools', '--allow-all-paths'],
155
- // == --allow-all-tools --allow-all-paths --allow-all-urls
156
- bypassPermissions: ['--allow-all'],
157
- },
158
- forbidden: 'copilot',
159
- label: 'GitHub Copilot',
160
- },
161
- 'copilot not found on PATH. Install GitHub Copilot CLI, then run `copilot login`.',
162
- { listModels: (command, options) => listCopilotModels(command, options.workingDir) },
163
- );
164
-
165
- // Copilot has no `--list-models`, and an invalid --model reports only that the
166
- // model is unavailable without naming the valid ones. `copilot help config`
167
- // documents the live list under its `model` key, so read it there — the ids stay
168
- // in step with the installed CLI instead of being hardcoded here.
169
- export async function listCopilotModels(command = 'copilot', workingDir) {
170
- const stdout = await runForStdout(command, ['help', 'config'], workingDir);
171
- const out = [];
172
- const seen = new Set();
173
- let inModelBlock = false;
174
- for (const raw of String(stdout || '').split('\n')) {
175
- // Section keys are printed as ` `key`: description`.
176
- const key = /^\s*`([A-Za-z][\w.]*)`\s*:/.exec(raw);
177
- if (key) {
178
- inModelBlock = key[1] === 'model';
179
- continue;
180
- }
181
- if (!inModelBlock) continue;
182
- const m = /^\s*-\s*"([^"]+)"\s*$/.exec(raw);
183
- if (!m) continue;
184
- const id = m[1];
185
- if (seen.has(id)) continue;
186
- seen.add(id);
187
- out.push(id);
188
- if (out.length >= 200) break;
189
- }
190
- // `auto` is a real, documented value (Copilot routes the turn itself) but it is
191
- // not in the enumerated list — offer it first.
192
- return out.length ? ['auto', ...out] : [];
193
- }
194
-
195
- // DeepSeek Harness. The launcher is `dsh`; `--profile headless` is the shipped
196
- // one-shot template ("answer one task, print the final assistant message, exit").
197
- //
198
- // Deliberately sparse compared to the others, because the CLI surface is sparse:
199
- // the headless profile takes ONLY the task text. There is no --model, no JSON
200
- // output and no resume flag — dsh is a Cordis plugin tree, so the model adapter,
201
- // tools and MCP are chosen by the PROFILE, not by argv. Power users retarget it
202
- // with `--patch <file>` through the agent's "Extra arguments" field.
203
- //
204
- // Two consequences worth knowing before wiring UI to this:
205
- // * `modelArg` is absent, so a model picked in Settings is ignored by design
206
- // (runSpec skips model injection without a template) — configure it in the
207
- // profile instead.
208
- // * Output arrives as ONE chunk at the end, not token-by-token, so the turn
209
- // shows progress but no live typing.
210
- export const deepseek = makeCliAgent(
211
- 'dsh',
212
- {
213
- args: ['--profile', 'headless', '{prompt}'],
214
- promptVia: 'arg',
215
- format: 'text',
216
- // No --model flag exists. dsh takes the model as a CONFIG OVERLAY: --patch
217
- // replaces one row of the composed plugin tree by id, and the model lives in
218
- // the `agent-default-model` row. runSpec writes this file per turn.
219
- modelPatch: {
220
- arg: '--patch {file}',
221
- // A patch replaces the row's WHOLE config, so provider must be restated.
222
- build: (model) => `- id: ${DSH_MODEL_ROW}\n config:\n provider: ${DSH_PROVIDER}\n model: ${JSON.stringify(model)}\n`,
223
- },
224
- label: 'DeepSeek Harness',
225
- },
226
- 'dsh not found on PATH. Install DeepSeek Harness, then run `dsh --profile headless "hi"` once to check the profile.',
227
- { listModels: (command, options) => listDshModels(command, options.workingDir) },
228
- );
229
-
230
- const DSH_MODEL_ROW = 'agent-default-model';
231
- const DSH_PROVIDER = 'deepseek-official';
232
- // dsh ships no model catalog command. The provider names its supported ids only
233
- // when you send a bad one ("The supported API model names are ..."), so these are
234
- // those ids, unioned with whatever the profile is actually set to. The field
235
- // still accepts any id — this is a convenience menu, not a whitelist.
236
- const DSH_KNOWN_MODELS = ['deepseek-v4-flash', 'deepseek-v4-pro'];
237
-
238
- // dsh publishes no model catalog — there is no `--list-models`, and the composed
239
- // config tree carries only the model the profile is CURRENTLY set to. So "Load
240
- // models" reports that one truthfully rather than inventing a menu; the field
241
- // still accepts any id the provider serves, applied via the patch above.
242
- export async function listDshModels(command = 'dsh', workingDir) {
243
- const stdout = await runForStdout(command, ['--profile', 'headless', '--dump-config'], workingDir, 60000);
244
- const lines = String(stdout || '').split('\n');
245
- const rowStart = new RegExp(`^-\\s*id:\\s*${DSH_MODEL_ROW}\\s*$`);
246
- for (let i = 0; i < lines.length; i++) {
247
- if (!rowStart.test(lines[i])) continue;
248
- // Scan this row's block for `model: <id>`, stopping at the next top-level row.
249
- for (let j = i + 1; j < lines.length && !/^-\s*id:/.test(lines[j]); j++) {
250
- const m = /^\s*model:\s*['"]?([\w.:-]+)['"]?\s*$/.exec(lines[j]);
251
- if (m) return [...new Set([m[1], ...DSH_KNOWN_MODELS])];
252
- }
253
- }
254
- return [...DSH_KNOWN_MODELS];
255
- }
256
-
257
- // Hermes Agent (Nous Research). `-z/--oneshot` prints ONLY the final response text — no
258
- // banner, no spinner, no tool previews — which is exactly the contract the shared runner
259
- // wants, and it auto-bypasses approvals so a headless turn never blocks on a prompt.
260
- //
261
- // Its own tools and skills (82 of them here) stay ACTIVE: Hermes loads them itself, and the
262
- // bridge's browser tools arrive over the stable /mcp endpoint like opencode and kiro, since
263
- // Hermes only reads MCP servers from its own config rather than a per-run file.
264
- //
265
- // `hermes model` is interactive with no --list flag, so model discovery goes through
266
- // `hermes config get model`, which prints the resolved default + provider as `key: value`
267
- // lines. That yields the one model the user has actually configured — honest, if short.
268
- export const hermes = makeCliAgent(
269
- 'hermes',
270
- {
271
- // `-z {prompt}`, NOT a bare `-z`: Hermes takes the prompt as the VALUE of -z (Python
272
- // argparse), and the runner appends a trailing prompt only when no {prompt} placeholder
273
- // exists — after the model flag. That produced `hermes -z -m <model> "<prompt>"`, where
274
- // argparse saw -z followed by another flag: "expected one argument". The placeholder
275
- // binds the prompt to the flag, so the model flag can sit anywhere after it.
276
- args: '-z {prompt}',
277
- promptVia: 'arg',
278
- modelArg: '-m {model}',
279
- requiresStableMcp: true,
280
- autoSetupStableMcp: true,
281
- stableMcpConfigCheck: 'hermes',
282
- // STDIO, not --url. Hermes's bundled MCP client has no HTTP transport ("requires HTTP
283
- // transport but mcp.client.streamable_http is not available"), so a URL registration
284
- // saves a config that can never connect. The bridge also speaks MCP over stdio — the
285
- // same mode Codex uses — so we register that instead. A function because the executable
286
- // is only known at runtime (a compiled binary runs itself; under node it re-runs its
287
- // entry script). `--args` must come last, per `hermes mcp add`.
288
- stableMcpSetupArgs: () => {
289
- const { command, args } = selfMcpStdio(CHATPANEL_STABLE_MCP_URL);
290
- return ['mcp', 'add', 'chatpanel_browser', '--command', command, '--args', ...args];
291
- },
292
- stableMcpSetupCommand: (() => {
293
- const { command, args } = selfMcpStdio(CHATPANEL_STABLE_MCP_URL);
294
- return `hermes mcp add chatpanel_browser --command ${command} --args ${args.join(' ')}`;
295
- })(),
296
- label: 'Hermes',
297
- },
298
- 'hermes not found on PATH. Install Hermes Agent, then run `hermes setup` to sign in.',
299
- {
300
- // `config get model` prints resolved settings as `key: value`; we want the default model
301
- // id, not the provider or base_url lines around it.
302
- listModels: async (command, options = {}) => {
303
- try {
304
- const out = await runForStdout(command, ['config', 'get', 'model'], options.workingDir);
305
- const m = /^\s*default:\s*(\S+)/m.exec(out || '');
306
- return m ? [m[1]] : [];
307
- } catch {
308
- return []; // not configured yet — the picker still accepts a typed id
309
- }
310
- },
311
- },
312
- );
1
+ import{runSpec as h,listSpecModels as A,runForStdout as d,CHATPANEL_STABLE_MCP_URL as m}from"./custom.js";import{findAgentBin as b,selfMcpStdio as u}from"../env.js";function i(e,o,a,t={}){let r=!1,s=0;const n={...o,command:e};return{spec:n,async available(){if(Date.now()-s>(r?3e4:4e3)){s=Date.now();try{r=!!b(e)}catch{r=!1}}return r?{ok:!0}:{ok:!1,reason:a}},listModels(l={}){return t.listModels?t.listModels(e,l):A(e,o.listModelsArgs,l.workingDir)},chat(l,c,p){return h(n,l,c,p)}}}const H=i("pi",{args:"-p",promptVia:"arg",modelArg:"--model {model}",imageArg:"@{path}",toolAdapter:"pi-extension",listModelsArgs:"--list-models",label:"Pi"},"pi not found on PATH. Install Pi, then run `pi` once to sign in."),D=i("opencode",{args:"run --format json --dangerously-skip-permissions",promptVia:"arg",modelArg:"-m {model}",imageArg:"-f {path}",format:"opencode-json",requiresStableMcp:!0,stableMcpConfigCheck:"opencode",listModelsArgs:"models",label:"OpenCode"},"opencode not found on PATH. Install opencode, then sign in."),P=i("kiro-cli",{args:"chat --no-interactive --require-mcp-startup",promptVia:"arg",modelArg:"--model {model}",trustAllToolsForMcp:!0,trustAllToolsArg:"--trust-all-tools",requiresStableMcp:!0,autoSetupStableMcp:!0,stableMcpConfigCheck:"kiro",stableMcpSetupArgs:["mcp","add","--scope","global","--name","chatpanel_browser","--url","http://127.0.0.1:4319/mcp","--force"],stableMcpSetupCommand:"kiro-cli mcp add --scope global --name chatpanel_browser --url http://127.0.0.1:4319/mcp --force",listModelsArgs:"--list-models",label:"Kiro"},"kiro-cli not found on PATH. Install Kiro CLI, then sign in."),S=["-p","{prompt}","--output-format","json","--no-color","--log-level","none","--no-ask-user","--no-auto-update","--no-remote","--no-remote-export"],_=i("copilot",{args:S,promptVia:"arg",modelArg:"--model {model}",imageArg:"--attachment {path}",format:"copilot-json",mcpArg:"--additional-mcp-config @{file}",permissionArgs:{default:["--allow-all-tools"],acceptEdits:["--allow-all-tools","--allow-all-paths"],bypassPermissions:["--allow-all"]},forbidden:"copilot",label:"GitHub Copilot"},"copilot not found on PATH. Install GitHub Copilot CLI, then run `copilot login`.",{listModels:(e,o)=>M(e,o.workingDir)});async function M(e="copilot",o){const a=await d(e,["help","config"],o),t=[],r=new Set;let s=!1;for(const n of String(a||"").split(`
2
+ `)){const l=/^\s*`([A-Za-z][\w.]*)`\s*:/.exec(n);if(l){s=l[1]==="model";continue}if(!s)continue;const c=/^\s*-\s*"([^"]+)"\s*$/.exec(n);if(!c)continue;const p=c[1];if(!r.has(p)&&(r.add(p),t.push(p),t.length>=200))break}return t.length?["auto",...t]:[]}const T=i("dsh",{args:["--profile","headless","{prompt}"],promptVia:"arg",format:"text",modelPatch:{arg:"--patch {file}",build:e=>`- id: ${g}
3
+ config:
4
+ provider: ${k}
5
+ model: ${JSON.stringify(e)}
6
+ `},label:"DeepSeek Harness"},'dsh not found on PATH. Install DeepSeek Harness, then run `dsh --profile headless "hi"` once to check the profile.',{listModels:(e,o)=>w(e,o.workingDir)}),g="agent-default-model",k="deepseek-official",f=["deepseek-v4-flash","deepseek-v4-pro"];async function w(e="dsh",o){const a=await d(e,["--profile","headless","--dump-config"],o,6e4),t=String(a||"").split(`
7
+ `),r=new RegExp(`^-\\s*id:\\s*${g}\\s*$`);for(let s=0;s<t.length;s++)if(r.test(t[s]))for(let n=s+1;n<t.length&&!/^-\s*id:/.test(t[n]);n++){const l=/^\s*model:\s*['"]?([\w.:-]+)['"]?\s*$/.exec(t[n]);if(l)return[...new Set([l[1],...f])]}return[...f]}const y=i("hermes",{args:"-z {prompt}",promptVia:"arg",modelArg:"-m {model}",requiresStableMcp:!0,autoSetupStableMcp:!0,stableMcpConfigCheck:"hermes",stableMcpSetupArgs:()=>{const{command:e,args:o}=u(m);return["mcp","add","chatpanel_browser","--command",e,"--args",...o]},stableMcpSetupCommand:(()=>{const{command:e,args:o}=u(m);return`hermes mcp add chatpanel_browser --command ${e} --args ${o.join(" ")}`})(),label:"Hermes"},"hermes not found on PATH. Install Hermes Agent, then run `hermes setup` to sign in.",{listModels:async(e,o={})=>{try{const a=await d(e,["config","get","model"],o.workingDir),t=/^\s*default:\s*(\S+)/m.exec(a||"");return t?[t[1]]:[]}catch{return[]}}});export{_ as copilot,T as deepseek,y as hermes,P as kiro,M as listCopilotModels,w as listDshModels,D as opencode,H as pi};
@@ -0,0 +1,12 @@
1
+ import R from"node:os";import _ from"node:path";import{unlink as q}from"node:fs/promises";import{spawnRpcChild as L}from"../rpc-child.js";import{createWarmPool as H}from"../warm-pool.js";import{createSession as W,deleteSession as P,rebindSession as j,releaseSession as z}from"../mcp-sessions.js";import{buildCliPrompt as M}from"./prompt.js";import{codexMcpConfigArgs as U,codexDisableArgs as B,configuredMcpServers as X,ensureIsolatedHome as F,writeImages as J}from"./codex.js";import{disabledMcpServers as G}from"../mcp-quarantine.js";import{resolveWorkdir as V}from"../workdir.js";import{registerWarmPool as K}from"../warm.js";const O=Number(process.env.CHATPANEL_CODEX_TIMEOUT_MS)||18e4,D=process.env.CHATPANEL_CODEX_EFFORT??"low",Q=9e4,N=5e3,v=K("codex",H({log:e=>{process.env.CHATPANEL_WARM_LOG&&console.error(`[codex] ${e}`)}}));let T=0;function ge(){T=0}function Y({agent:e="codex",cwd:p,options:s={},mcpNames:f=[],runEnv:i=null,disabled:u=[]}){return JSON.stringify({agent:e,cwd:p,mode:s.permissionMode||"default",model:s.model||"",local:s.useLocalConfig!==!1,tools:[...f].sort(),env:i?Object.keys(i).sort().map(x=>`${x}=${i[x]}`):[],disabled:[...u].sort()})}function Z(e={}){return!(process.env.CHATPANEL_WARM==="off"||process.env.CHATPANEL_CODEX_APPSERVER==="off"||e.warm===!1||e.extraArgs&&String(e.extraArgs).trim()||Date.now()<T)}function ee(e){return e==="bypassPermissions"?"danger-full-access":e==="acceptEdits"?"workspace-write":"read-only"}function te(e){if(e==null)return"";if(typeof e=="string")return e;if(Array.isArray(e?.content))return e.content.map(p=>typeof p=="string"?p:p?.text||"").filter(Boolean).join(`
2
+ `);try{return JSON.stringify(e)}catch{return String(e)}}function re(e,p,s,f){const i=e?.type||"",u=e?.id||`i_${f.n++}`,x=(l,o)=>{f.started.has(u)||(f.started.add(u),s({type:"tool",name:l,phase:"start",callId:u,input:o}))};if(i==="agentMessage"){p&&e.text&&!f.deltaItems.has(u)&&!f.said.has(u)&&(f.said.add(u),s({type:"delta",text:`${f.saidAny?`
3
+
4
+ `:""}${e.text}`}),f.saidAny=!0);return}if(i==="commandExecution"){if(x("shell",{command:e.command||""}),p){const l=e.exitCode===0||e.exitCode==null;s({type:"tool",name:"shell",phase:"done",callId:u,status:l?"ok":`exit ${e.exitCode}`,result:String(e.aggregatedOutput||"").slice(0,4e3)})}return}if(i==="fileChange"){const l=Array.isArray(e.changes)?e.changes.map(o=>o?.path||o?.file).filter(Boolean):[];x("edit",{files:l}),p&&s({type:"tool",name:"edit",phase:"done",callId:u,status:e.status==="failed"?"error":"ok"});return}if(i==="webSearch"){const l=e.action&&typeof e.action=="object"?e.action:{},o=e.query||l.query||"",t=l.url||"";x("web_search",{query:o,...t?{url:t}:{}}),p&&s({type:"tool",name:"web_search",phase:"done",callId:u,status:"ok",result:t?`Opened ${t}`:o?`Searched the web for ${o}`:"Searched the web"});return}if(i==="mcpToolCall"){const l=e.server?`${e.server}/${e.tool||"tool"}`:e.tool||"mcp";if(x(l,e.arguments&&typeof e.arguments=="object"?e.arguments:{}),p){const o=e.status==="failed"||e.error!=null,t=e.error&&typeof e.error=="object"?e.error.message||JSON.stringify(e.error):e.error;s({type:"tool",name:l,phase:"done",callId:u,status:o?`error: ${String(t||"failed").slice(0,80)}`:"ok",result:String(o?t||"":te(e.result)).slice(0,4e3)})}return}if(i==="plan"&&p&&e.text&&f.lastPlan!==e.text){f.lastPlan=e.text,s({type:"status",text:`Plan:
5
+ ${e.text}`});return}if(i==="reasoning"&&p){if(f.deltaItems.has(u))return;const l=(Array.isArray(e.summary)?e.summary:[]).map(o=>typeof o=="string"?o:o?.text||"").filter(Boolean).join(`
6
+ `);l&&!f.reasoned.has(u)&&(f.reasoned.add(u),s({type:"reasoning",text:`${l}
7
+ `}))}}function se(){return{n:0,started:new Set,said:new Set,reasoned:new Set,deltaItems:new Set,saidAny:!1,lastPlan:null}}async function ae({bin:e="codex",cwd:p,env:s,configArgs:f=[],options:i={},spawnImpl:u,log:x=()=>{}}){const l=i.permissionMode||"default",o=l==="bypassPermissions";let t=null;const E=new Set;let b="";const g=L(e,["app-server",...f],{cwd:p,env:s,spawnImpl:u,onStderr:r=>{b=(b+r).slice(-2e3)},onExit:r=>{x(`app-server exited: ${r.signal||r.code}${b?` — ${b.trim().split(`
8
+ `).pop()}`:""}`),t&&t.finish({status:"died",error:r.error?.message||`Codex exited (${r.signal||r.code})`});for(const a of E)try{a(r)}catch{}},onRequest:async(r,a)=>{if(r==="item/commandExecution/requestApproval"||r==="execCommandApproval")return o||t?.emit({type:"status",text:"Codex asked to run a command outside its sandbox — declined (set Permissions to full access to allow)."}),r==="execCommandApproval"?{decision:o?"approved":"denied"}:{decision:o?"accept":"decline"};if(r==="item/fileChange/requestApproval"||r==="applyPatchApproval")return o||t?.emit({type:"status",text:"Codex asked to change files outside its sandbox — declined (set Permissions to auto-edit or full access to allow)."}),r==="applyPatchApproval"?{decision:o?"approved":"denied"}:{decision:o?"accept":"decline"}},onMessage:r=>{if(!r.method||!t)return;const a=r.params||{};if(a.threadId&&a.threadId!==t.threadId)return;t.touch();const d=r.method;if(d==="item/agentMessage/delta"){if(!a.delta)return;t.state.deltaItems.add(a.itemId),t.state.said.has(a.itemId)||(t.state.said.add(a.itemId),t.state.saidAny&&t.emit({type:"delta",text:`
9
+
10
+ `})),t.state.saidAny=!0,t.streamed=!0,t.emit({type:"delta",text:a.delta})}else if(d==="item/reasoning/summaryTextDelta"||d==="item/reasoning/textDelta"){if(!a.delta)return;t.state.deltaItems.add(a.itemId),t.streamed=!0,t.emit({type:"reasoning",text:a.delta})}else if(d==="item/reasoning/summaryPartAdded")t.state.deltaItems.has(a.itemId)&&t.emit({type:"reasoning",text:`
11
+ `});else if(d==="item/started"||d==="item/completed"){const n=t.state.started.size+t.state.said.size;re(a.item,d==="item/completed",t.emit,t.state),t.state.started.size+t.state.said.size>n&&(t.streamed=!0)}else if(d==="thread/tokenUsage/updated"){const n=a.tokenUsage?.last||a.tokenUsage?.total;n&&(t.usage={type:"usage",provider:"bridge",inputTokens:n.inputTokens||0,outputTokens:n.outputTokens||0,cacheReadTokens:n.cachedInputTokens||0,cacheWriteTokens:n.cacheWriteInputTokens||0,costUsd:null})}else if(d==="error"){const n=a.error?.message||"error";a.willRetry?t.emit({type:"status",text:`Codex: ${n.slice(0,200)} — retrying`}):t.lastError=n}else if(d==="turn/completed"){const n=a.turn||{};if(t.turnId&&n.id&&n.id!==t.turnId)return;t.finish({status:n.status||"completed",error:n.error?.message||t.lastError||null})}}});let w;try{if(await g.request("initialize",{clientInfo:{name:"chatpanel-bridge",version:"1"},capabilities:{experimentalApi:!0}},{timeoutMs:2e4}),g.notify("initialized"),w=(await g.request("thread/start",{cwd:p||void 0,sandbox:ee(l),approvalPolicy:"never",...i.model?{model:i.model}:{}},{timeoutMs:Q}))?.thread?.id,!w)throw new Error("Codex app-server started no thread")}catch(r){g.kill();const a=b.trim().split(`
12
+ `).filter(Boolean).pop()||"";throw new Error(a?`${r.message}: ${a.slice(-300)}`:r.message)}return{threadId:w,get pid(){return g.pid},get alive(){return!g.exited},onExit(r){E.add(r)},close(){g.close()},async turn({prompt:r,imageFiles:a=[],emit:d,signal:n}){if(g.exited)throw new Error("Codex process is gone");if(t)throw new Error("a turn is already running on this thread");const A=se();let S=null,I;const k=new Promise(y=>{I=y}),m={threadId:w,turnId:null,emit:d,state:A,streamed:!1,usage:null,lastError:null,touch(){clearTimeout(S),S=setTimeout(()=>m.finish({status:"timeout",error:`Codex timed out — no output for ${Math.round(O/1e3)}s.`}),O)},finish(y){t===m&&(clearTimeout(S),t=null,I(y))}};t=m,m.touch();const h=async()=>{if(t===m){try{await g.request("turn/interrupt",{threadId:w,turnId:m.turnId},{timeoutMs:N})}catch{}setTimeout(()=>{t===m&&(m.finish({status:"killed",error:null}),g.kill())},N).unref?.()}};if(n?.aborted)return m.finish({status:"killed",error:null}),{streamed:!1,said:!1,status:"killed",usage:null};n?.addEventListener("abort",h,{once:!0}),d({type:"status",text:"Codex working"});try{const y=[{type:"text",text:r},...a.map($=>({type:"localImage",path:$}))],C=await g.request("turn/start",{threadId:w,input:y,summary:"auto",...D?{effort:D}:{}},{timeoutMs:3e4});m.turnId=C?.turn?.id||null}catch(y){m.finish({status:"failed",error:y.message})}const c=await k;return n?.removeEventListener("abort",h),c.status==="timeout"&&g.kill(),m.usage&&d(m.usage),{streamed:m.streamed,said:A.saidAny,status:c.status,error:c.error,usage:m.usage}}}}async function ye({messages:e,system:p,options:s,images:f},i,{signal:u,launch:x=ae}={}){if(!Z(s))return{handled:!1,reason:"not eligible"};const l=V(s.workingDir),o={...process.env,...s.runEnv||{}};if(s.useLocalConfig===!1){const c=F();c&&(o.CODEX_HOME=c)}const t=s.mcp?.serverName||"chatpanel_browser",E=X(o.CODEX_HOME||_.join(R.homedir(),".codex")),b=G("codex",s,[t]).filter(c=>E.has(c)),g=(s.mcp?.specs||[]).map(c=>c?.name).filter(Boolean),w=Y({cwd:l,options:s,mcpNames:g,runEnv:s.runEnv||null,disabled:b});let r=v.acquire({key:w,messages:e}),a=!1,d=null;if(!r){if(r=v.reserve({key:w,label:`codex ${_.basename(l||"")}`}),!r)return{handled:!1,reason:"all warm slots busy"};a=!0;try{const c=[];if(s.mcp?.url&&g.length){d=W(i,s.mcp.specs);const $=s.mcp.url.replace(/\/[^/]*$/,"");c.push(...U({url:`${$}/${d.id}`,serverName:t,specs:s.mcp.specs}))}c.push(...B(b));const y=await x({cwd:l,env:o,configArgs:c,options:s});y.mcpSession=d,y.systemSent="",v.attach(r,y);const C=d;y.onExit(()=>{C&&P(C.id)})}catch(c){return d&&P(d.id),v.drop(r,`launch failed: ${c.message}`),/unknown|unrecognized|unexpected argument|app-server/i.test(c.message)&&(T=Date.now()+10*6e4),{handled:!1,reason:c.message}}}const n=r.session;n.mcpSession&&j(n.mcpSession,i,s.mcp?.specs);const A=e[e.length-1],S=String(p||""),I=a?M(e,S):M([A],S&&S!==n.systemSent?S:""),k=`${Date.now()}-${Math.random().toString(36).slice(2)}`,m=await J(f,k);let h;try{h=await n.turn({prompt:I,imageFiles:m,emit:i,signal:u})}finally{m.forEach(c=>q(c).catch(()=>{})),n.mcpSession&&z(n.mcpSession)}if(n.systemSent=S,u?.aborted||h.status==="interrupted")return h.status==="interrupted"&&n.alive?v.release(r,{user:String(A?.content||""),answered:h.streamed}):v.drop(r,"stopped"),{handled:!0};if(h.status!=="completed"){if(v.drop(r,h.error||h.status),!h.streamed)return{handled:!1,reason:h.error||h.status};throw new Error(h.error||`Codex ${h.status}`)}return h.said||i({type:"delta",text:"(no output)"}),i({type:"done",text:""}),v.release(r,{user:String(A?.content||""),answered:!0}),{handled:!0}}export{ye as chatWarm,re as forwardV2Item,ae as launchCodexSession,se as newTurnState,v as pool,ge as resetSupport,Z as warmEligible,Y as warmKey};