@chatpanel/bridge 0.11.24 → 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 -481
  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,482 +1,7 @@
1
- // Codex engine — drives the Codex CLI (`codex exec`) using your local Codex login.
2
- //
3
- // Two modes, chosen per-agent in ChatPanel Settings ("Use my local skills & config"):
4
- //
5
- // useLocalConfig: true (DEFAULT) — your real CODEX_HOME loads, so your skills,
6
- // MCP servers and config.toml all work. Best for "it should behave like my
7
- // Codex." Can be slower if your global skills do a lot of work.
8
- //
9
- // useLocalConfig: false — run against an ISOLATED CODEX_HOME (just a symlink to
10
- // your auth so you stay logged in). Skips your global AGENTS.md / skills, so
11
- // it answers fast and never crawls files (~9x faster in practice).
12
- //
13
- // In BOTH modes we run in an EMPTY scratch dir for general chat, so Codex never
14
- // references the bridge's own code or an unrelated project. Set a working dir on
15
- // the agent to point it at a real project.
1
+ import{spawn as T}from"node:child_process";import{killOnAbort as P,spawnGroupOpts as B}from"../proc.js";import{readFile as H,unlink as A,writeFile as F}from"node:fs/promises";import{existsSync as I,mkdirSync as L,symlinkSync as X,readFileSync as C}from"node:fs";import w from"node:os";import g from"node:path";import{findAgentBin as J,selfMcpStdio as R,resolveCommand as q}from"../env.js";import{relayTimeoutMax as z}from"../relay-timeout.js";import{buildCliPrompt as G}from"./prompt.js";import{pushExtraArgs as W,FORBIDDEN as K}from"./args.js";import{resolveWorkdir as U}from"../workdir.js";import{summarizeCliError as Z}from"../cli-errors.js";import{signInStatus as Q,signInMessage as V}from"../sign-in.js";import{disabledMcpServers as Y,planMcpRetry as ee,quarantine as te}from"../mcp-quarantine.js";const M=Number(process.env.CHATPANEL_CODEX_TIMEOUT_MS)||18e4,N=process.env.CHATPANEL_CODEX_EFFORT??"low",oe=["gpt-5-codex","gpt-5","o3","o4-mini"];let E=!1;function ke(){E=!1}async function Ee(){const s=new Set;try{const o=process.env.CODEX_HOME||g.join(w.homedir(),".codex"),t=C(g.join(o,"config.toml"),"utf8");for(const a of t.matchAll(/(?:^|\n)\s*model\s*=\s*["']([^"'\n]+)["']/g))s.add(a[1].trim())}catch{}for(const o of oe)s.add(o);return[...s]}const O=g.join(w.homedir(),".chatpanel","codex-home");let D=!1;function re(){if(!D)try{L(O,{recursive:!0});const s=g.join(w.homedir(),".codex","auth.json"),o=g.join(O,"auth.json");if(I(s)&&!I(o))try{X(s,o)}catch{}D=!0}catch{return null}return O}let b=!1,j=0;async function Oe(){if(Date.now()-j>(b?3e4:4e3)){j=Date.now();try{b=!!J("codex")}catch{b=!1}}return b?await Q("codex",q("codex")).catch(()=>null)===!1?{ok:!1,signedIn:!1,reason:V("Codex","codex")}:{ok:!0}:{ok:!1,reason:"codex not found on PATH. Install it and run `codex login`."}}function se(s){if(!s?.url)return[];const o=s.serverName||"chatpanel_browser",{command:t,args:a}=R(s.url),e=["-c",`mcp_servers.${o}.command=${JSON.stringify(t)}`,"-c",`mcp_servers.${o}.args=${JSON.stringify(a)}`,"-c",`mcp_servers.${o}.default_tools_approval_mode="approve"`,"-c",`mcp_servers.${o}.startup_timeout_sec=30`,"-c",`mcp_servers.${o}.tool_timeout_sec=${Math.ceil(z(s.specs)/1e3)}`],i=[...new Set((s.specs||[]).map(p=>p?.name).filter(Boolean))];return i.length&&e.push("-c",`mcp_servers.${o}.enabled_tools=${JSON.stringify(i)}`),e}function ne(s){try{const o=C(g.join(s,"config.toml"),"utf8"),t=new Set;for(const a of o.matchAll(/^\s*\[mcp_servers\.([A-Za-z0-9_-]+)\s*[.\]]/gm))t.add(a[1]);return t}catch{return new Set}}function ae(s=[]){return s.flatMap(o=>["-c",`mcp_servers.${o}.enabled=false`])}async function ie(s,o){const t=[];for(let a=0;a<(s?.length||0);a++){const e=/^data:([^;]+);base64,(.+)$/s.exec(s[a]?.dataUrl||"");if(!e)continue;const i=(e[1].split("/")[1]||"png").replace(/[^a-z0-9]/gi,"").slice(0,5)||"png",p=g.join(w.tmpdir(),`chatpanel-codex-img-${o}-${a}.${i}`);await F(p,Buffer.from(e[2],"base64")),t.push(p)}return t}function ce({args:s,cwd:o,env:t,prompt:a,outFile:e,emit:i,signal:p}){return new Promise((r,n)=>{let l;try{l=T("codex",s,{cwd:o,stdio:["pipe","pipe","pipe"],env:t,...B})}catch(u){return n(new Error(`Failed to start codex: ${u.message}`))}const f=P(l,p);let m="",$="",v=!1;const S=u=>{u?.type!=="status"&&(v=!0),i(u)},_={started:new Set,reasoned:new Set,n:0};let x;const y=()=>{clearTimeout(x),x=setTimeout(()=>{l.kill("SIGKILL"),n(new Error(`Codex timed out — no output for ${Math.round(M/1e3)}s.`))},M)};y(),l.stdout.on("data",u=>{y(),m+=u.toString();let h;for(;(h=m.indexOf(`
2
+ `))>=0;){const c=m.slice(0,h).trim();if(m=m.slice(h+1),!!c.startsWith("{"))try{le(JSON.parse(c),S,_)}catch{}}}),l.stderr.on("data",u=>{y(),$+=u.toString()}),l.on("error",u=>{clearTimeout(x),f(),n(u)}),l.on("close",async u=>{clearTimeout(x),f();let h="";try{h=(await H(e,"utf8")).trim()}catch{}A(e).catch(()=>{}),r({code:u,stderr:$,text:h,streamed:v,said:!!_.saidAny,policyBlocked:!!_.policyBlocked})}),l.stdin.write(a),l.stdin.end()})}async function Ae({messages:s,system:o,options:t,images:a},e,{signal:i}={}){const p=`${Date.now()}-${Math.random().toString(36).slice(2)}`,r=g.join(w.tmpdir(),`chatpanel-codex-${p}.txt`),n=await ie(a,p),l=()=>n.forEach(c=>A(c).catch(()=>{})),f=U(t.workingDir),m=[];W(m,t.extraArgs,K.codex,e);const $=c=>{const d=["exec","--json","--skip-git-repo-check","-o",r];if(t.permissionMode==="bypassPermissions")d.push("--dangerously-bypass-approvals-and-sandbox");else{const k=t.permissionMode==="acceptEdits"?"workspace-write":"read-only";d.push("-s",k),E||d.push("-c","approval_policy=never")}N&&d.push("-c",`model_reasoning_effort=${N}`),d.push("-c","model_reasoning_summary=auto"),d.push(...se(t.mcp)),d.push(...ae(c)),t.model&&d.push("-m",t.model),d.push(...m);for(const k of n)d.push("-i",k);return d.push("-"),d},v=t.useLocalConfig!==!1,S={...process.env,...t.runEnv||{}};if(!v){const c=re();c&&(S.CODEX_HOME=c)}const _=t.mcp?.serverName||"chatpanel_browser",x=ne(S.CODEX_HOME||process.env.CODEX_HOME||g.join(w.homedir(),".codex"));let y=Y("codex",t,[_]).filter(c=>x.has(c));const u=G(s,o),h=()=>ce({args:$(y),cwd:f,env:S,prompt:u,outFile:r,emit:e,signal:i});try{let c=await h();if(c.policyBlocked&&(E=!0),!i?.aborted&&c.code!==0&&!c.streamed){const d=ee({agent:"codex",text:c.stderr,protect:[_],already:y});d&&x.has(d.server)&&(te("codex",d.server),e({type:"status",text:`MCP server "${d.server}" failed to load — ${d.short}. Skipping it and retrying.`}),y=[...y,d.server],c=await h())}if(i?.aborted)return;if(c.code!==0)throw new Error(Z("Codex",c.code,c.stderr,"",{agentId:"codex"}));c.said||e({type:"delta",text:c.text||"(no output)"}),e({type:"done",text:""})}finally{l()}}function le(s,o,t={started:new Set,reasoned:new Set,n:0}){const a=s.type||"",e=s.item||{},i=e.type||"",p=a==="item.completed"||e.status==="completed"||e.status==="failed";if(i==="agent_message"&&p){const r=e.id||`msg_${t.n++}`,n=String(e.text||"");n&&!t.said?.has(r)&&((t.said||=new Set).add(r),o({type:"delta",text:`${t.saidAny?`
16
3
 
17
- import { spawn, spawnSync } from 'node:child_process';
18
- import { killOnAbort, spawnGroupOpts } from '../proc.js';
19
- import { readFile, unlink, writeFile } from 'node:fs/promises';
20
- import { existsSync, mkdirSync, symlinkSync, readFileSync } from 'node:fs';
21
- import os from 'node:os';
22
- import path from 'node:path';
23
- import { findAgentBin, selfMcpStdio, resolveCommand } from '../env.js';
24
- import { relayTimeoutMax } from '../relay-timeout.js';
25
- import { buildCliPrompt } from './prompt.js';
26
- import { pushExtraArgs, FORBIDDEN } from './args.js';
27
- import { resolveWorkdir } from '../workdir.js';
28
- import { summarizeCliError } from '../cli-errors.js';
29
- import { signInStatus, signInMessage } from '../sign-in.js';
30
- import { disabledMcpServers, planMcpRetry, quarantine } from '../mcp-quarantine.js';
31
-
32
- // Idle timeout: re-armed on every stdout/stderr chunk, so a long run that keeps
33
- // streaming never trips it — only true silence does. Override with
34
- // CHATPANEL_CODEX_TIMEOUT_MS (ms).
35
- const IDLE_MS = Number(process.env.CHATPANEL_CODEX_TIMEOUT_MS) || 180_000;
36
- const REASONING = process.env.CHATPANEL_CODEX_EFFORT ?? 'low'; // '' → respect config
37
-
38
-
39
- // Codex has no "list models" command — its model lives in CODEX_HOME/config.toml
40
- // (e.g. `model = "gpt-5.5"`). Surface the user's REAL configured model(s), read
41
- // straight from that file, plus a few common ids. The picker still accepts any
42
- // free-text value, so an out-of-date curated entry is harmless.
43
- const CODEX_KNOWN = ['gpt-5-codex', 'gpt-5', 'o3', 'o4-mini'];
44
- // Set once Codex has reported that its managed requirements forbid approval_policy=never;
45
- // cleared only by a bridge restart, which is when a policy could plausibly have changed.
46
- let approvalPolicyBlocked = false;
47
- export function resetApprovalPolicy() { approvalPolicyBlocked = false; }
48
-
49
- export async function listModels() {
50
- const set = new Set();
51
- try {
52
- const home = process.env.CODEX_HOME || path.join(os.homedir(), '.codex');
53
- const cfg = readFileSync(path.join(home, 'config.toml'), 'utf8');
54
- for (const m of cfg.matchAll(/(?:^|\n)\s*model\s*=\s*["']([^"'\n]+)["']/g)) set.add(m[1].trim());
55
- } catch { /* no config — fall back to the curated set */ }
56
- for (const m of CODEX_KNOWN) set.add(m);
57
- return [...set];
58
- }
59
- const ISO_HOME = path.join(os.homedir(), '.chatpanel', 'codex-home');
60
-
61
-
62
- // Build (once) an isolated CODEX_HOME that has only a link to your auth, so the
63
- // global skills/config don't load. Returns the path, or null on failure.
64
- let isoReady = false;
65
- function ensureIsolatedHome() {
66
- if (!isoReady) {
67
- try {
68
- mkdirSync(ISO_HOME, { recursive: true });
69
- const realAuth = path.join(os.homedir(), '.codex', 'auth.json');
70
- const linkAuth = path.join(ISO_HOME, 'auth.json');
71
- if (existsSync(realAuth) && !existsSync(linkAuth)) {
72
- try {
73
- symlinkSync(realAuth, linkAuth);
74
- } catch {
75
- /* auth errors surface clearly downstream */
76
- }
77
- }
78
- isoReady = true;
79
- } catch {
80
- return null;
81
- }
82
- }
83
- return ISO_HOME;
84
- }
85
-
86
- let installed = false;
87
- let lastProbe = 0;
88
- export async function available() {
89
- // Availability = "is codex findable on PATH", not "does `codex --version` exit 0" (which
90
- // fails when the CLI just needs login). Re-probed in BOTH directions: caching a positive
91
- // forever kept an uninstalled CLI reporting itself available until the bridge restarted.
92
- if (Date.now() - lastProbe > (installed ? 30_000 : 4000)) {
93
- lastProbe = Date.now();
94
- try {
95
- installed = !!findAgentBin('codex');
96
- } catch {
97
- installed = false;
98
- }
99
- }
100
- if (!installed) return { ok: false, reason: 'codex not found on PATH. Install it and run `codex login`.' };
101
- // Installed is not signed in: `codex login status` says which before a turn is sent (sign-in.js).
102
- const signedIn = await signInStatus('codex', resolveCommand('codex')).catch(() => null);
103
- if (signedIn === false) return { ok: false, signedIn: false, reason: signInMessage('Codex', 'codex') };
104
- return { ok: true };
105
- }
106
-
107
- export function codexMcpConfigArgs(mcp) {
108
- if (!mcp?.url) return [];
109
- const name = mcp.serverName || 'chatpanel_browser';
110
- const { command, args: pargs } = selfMcpStdio(mcp.url);
111
- const args = [
112
- '-c',
113
- `mcp_servers.${name}.command=${JSON.stringify(command)}`,
114
- '-c',
115
- `mcp_servers.${name}.args=${JSON.stringify(pargs)}`,
116
- '-c',
117
- `mcp_servers.${name}.default_tools_approval_mode="approve"`,
118
- '-c',
119
- `mcp_servers.${name}.startup_timeout_sec=30`,
120
- '-c',
121
- // Matches the relay's longest tool (a team run's budget) — see relay-timeout.js.
122
- `mcp_servers.${name}.tool_timeout_sec=${Math.ceil(relayTimeoutMax(mcp.specs) / 1000)}`,
123
- ];
124
- const toolNames = [...new Set((mcp.specs || []).map((s) => s?.name).filter(Boolean))];
125
- if (toolNames.length) {
126
- args.push('-c', `mcp_servers.${name}.enabled_tools=${JSON.stringify(toolNames)}`);
127
- }
128
- return args;
129
- }
130
-
131
- // Which MCP servers this Codex actually has configured.
132
- //
133
- // READ THIS BEFORE TOUCHING codexDisableArgs. `-c mcp_servers.X.enabled=false` for a name
134
- // that is NOT already in config.toml does not disable anything — it DEFINES a new server
135
- // that has no transport, and Codex then refuses to start at all:
136
- // Error: failed to load bootstrap configuration
137
- // Caused by: invalid transport in `mcp_servers.does_not_exist`
138
- // So a stale quarantine entry, or a typo in the user's deny list, would break EVERY run —
139
- // strictly worse than the failure this feature exists to fix. We therefore only ever disable
140
- // a server we can see, and a name we cannot see is left alone (a no-op, never a break).
141
- //
142
- // Read from config.toml — instant, and the same source listModels() already reads — rather
143
- // than shelling out to `codex mcp list --json`, which is authoritative but costs ~0.8s on
144
- // every single turn.
145
- export function configuredMcpServers(home) {
146
- try {
147
- const cfg = readFileSync(path.join(home, 'config.toml'), 'utf8');
148
- const names = new Set();
149
- for (const m of cfg.matchAll(/^\s*\[mcp_servers\.([A-Za-z0-9_-]+)\s*[.\]]/gm)) names.add(m[1]);
150
- return names;
151
- } catch {
152
- return new Set(); // no config (or the isolated home) — there is nothing to disable
153
- }
154
- }
155
-
156
- // Turn off servers from the user's own config.toml for THIS RUN only — never by editing
157
- // their file. Names are validated upstream (mcp-quarantine.js) and filtered against
158
- // configuredMcpServers by the caller, which is what makes it safe to interpolate one into a
159
- // `-c` override key; `-c` is otherwise blocked in extraArgs precisely because it reaches
160
- // config that matters.
161
- export function codexDisableArgs(names = []) {
162
- return names.flatMap((name) => ['-c', `mcp_servers.${name}.enabled=false`]);
163
- }
164
-
165
- // Write base64 data-URL images to temp files so `codex exec -i <file>` can
166
- // attach them to the prompt as vision input. Returns the paths (caller cleans up).
167
- async function writeImages(images, tag) {
168
- const files = [];
169
- for (let i = 0; i < (images?.length || 0); i++) {
170
- const m = /^data:([^;]+);base64,(.+)$/s.exec(images[i]?.dataUrl || '');
171
- if (!m) continue;
172
- const ext = (m[1].split('/')[1] || 'png').replace(/[^a-z0-9]/gi, '').slice(0, 5) || 'png';
173
- const file = path.join(os.tmpdir(), `chatpanel-codex-img-${tag}-${i}.${ext}`);
174
- await writeFile(file, Buffer.from(m[2], 'base64'));
175
- files.push(file);
176
- }
177
- return files;
178
- }
179
-
180
- // A single `codex exec` attempt. Resolves with how it ended rather than emitting the final
181
- // message itself, so the caller can decide whether the run is worth ATTEMPTING AGAIN — the
182
- // terminal delta/done belongs to whichever attempt actually answered.
183
- function runCodex({ args, cwd, env, prompt, outFile, emit, signal }) {
184
- return new Promise((resolve, reject) => {
185
- let child;
186
- try {
187
- child = spawn('codex', args, { cwd, stdio: ['pipe', 'pipe', 'pipe'], env, ...spawnGroupOpts });
188
- } catch (e) {
189
- return reject(new Error(`Failed to start codex: ${e.message}`));
190
- }
191
-
192
- const detach = killOnAbort(child, signal); // Stop → SIGTERM/SIGKILL the codex child
193
-
194
- let stdout = '';
195
- let stderr = '';
196
- // Retrying is only honest while nothing the user can see has been produced. Status lines
197
- // are ours and are replaceable; a delta, a tool call or a reasoning summary is not.
198
- let streamed = false;
199
- const relay = (ev) => {
200
- if (ev?.type !== 'status') streamed = true;
201
- emit(ev);
202
- };
203
- // Per-run event state: correlate a command's started/completed events and emit each
204
- // reasoning summary once (Codex sends the same item id across item.started/updated/completed).
205
- const evState = { started: new Set(), reasoned: new Set(), n: 0 };
206
- let idleTimer;
207
- const armIdle = () => {
208
- clearTimeout(idleTimer);
209
- idleTimer = setTimeout(() => {
210
- child.kill('SIGKILL');
211
- reject(new Error(`Codex timed out — no output for ${Math.round(IDLE_MS / 1000)}s.`));
212
- }, IDLE_MS);
213
- };
214
- armIdle();
215
-
216
- child.stdout.on('data', (d) => {
217
- armIdle();
218
- stdout += d.toString();
219
- let nl;
220
- while ((nl = stdout.indexOf('\n')) >= 0) {
221
- const line = stdout.slice(0, nl).trim();
222
- stdout = stdout.slice(nl + 1);
223
- if (!line.startsWith('{')) continue;
224
- try {
225
- forwardEvent(JSON.parse(line), relay, evState);
226
- } catch {
227
- /* not a JSON event line */
228
- }
229
- }
230
- });
231
- child.stderr.on('data', (d) => { armIdle(); stderr += d.toString(); });
232
- child.on('error', (e) => {
233
- clearTimeout(idleTimer);
234
- detach();
235
- reject(e);
236
- });
237
- child.on('close', async (code) => {
238
- clearTimeout(idleTimer);
239
- detach();
240
- let text = '';
241
- try {
242
- text = (await readFile(outFile, 'utf8')).trim();
243
- } catch {
244
- /* no message file */
245
- }
246
- unlink(outFile).catch(() => {});
247
- resolve({ code, stderr, text, streamed, said: !!evState.saidAny, policyBlocked: !!evState.policyBlocked });
248
- });
249
-
250
- child.stdin.write(prompt);
251
- child.stdin.end();
252
- });
253
- }
254
-
255
- export async function chat({ messages, system, options, images }, emit, { signal } = {}) {
256
- const tag = `${Date.now()}-${Math.random().toString(36).slice(2)}`;
257
- const outFile = path.join(os.tmpdir(), `chatpanel-codex-${tag}.txt`);
258
- const imageFiles = await writeImages(images, tag);
259
- const cleanupImages = () => imageFiles.forEach((f) => unlink(f).catch(() => {}));
260
-
261
- const cwd = resolveWorkdir(options.workingDir);
262
- // Sanitized once, not per attempt — pushExtraArgs emits a status when it drops something,
263
- // and a retry must not say it twice.
264
- const extraArgs = [];
265
- pushExtraArgs(extraArgs, options.extraArgs, FORBIDDEN.codex, emit);
266
-
267
- const buildArgs = (disabled) => {
268
- const args = ['exec', '--json', '--skip-git-repo-check', '-o', outFile];
269
- // Headless exec has no human to approve actions. With MCP/browser tools armed
270
- // Codex would otherwise raise an approval prompt it can't show — and cancel the
271
- // tool call. So in bypassPermissions (full autonomy, what "Act on page" needs)
272
- // use the all-in bypass flag, which also clears MCP-tool approval. Lower modes
273
- // keep the sandbox + never-ask, which auto-runs within bounds.
274
- if (options.permissionMode === 'bypassPermissions') {
275
- args.push('--dangerously-bypass-approvals-and-sandbox');
276
- } else {
277
- const sandbox = options.permissionMode === 'acceptEdits' ? 'workspace-write' : 'read-only';
278
- args.push('-s', sandbox);
279
- // `never` is what a headless run needs — but an organisation can pin approval_policy
280
- // through Codex's managed requirements, and then every turn opened with a paragraph
281
- // of warning and fell back to OnRequest anyway. Once Codex has said so, stop asking.
282
- if (!approvalPolicyBlocked) args.push('-c', 'approval_policy=never');
283
- }
284
- if (REASONING) args.push('-c', `model_reasoning_effort=${REASONING}`);
285
- // Ask Codex to emit reasoning SUMMARIES so the panel can stream the model's thinking.
286
- // Additive + safe: a no-op for models/providers that don't produce summaries (e.g. some
287
- // hosted models expose none), and cheap at the default effort. forwardEvent renders them.
288
- args.push('-c', 'model_reasoning_summary=auto');
289
- // Browser tools: register the bridge's MCP server as a stdio MCP server (the
290
- // bridge binary in --mcp-stdio mode), so Codex can call our page-action tools.
291
- // `-c key=value` parses value as TOML; JSON.stringify yields valid TOML here.
292
- args.push(...codexMcpConfigArgs(options.mcp));
293
- // ...and the other direction: the user's own servers we've been told to leave out.
294
- args.push(...codexDisableArgs(disabled));
295
- if (options.model) args.push('-m', options.model);
296
- // Drop caller extras that would re-open the sandbox/approval boundary (shared sanitizer).
297
- args.push(...extraArgs);
298
- for (const f of imageFiles) args.push('-i', f); // attach images to the initial prompt
299
- args.push('-');
300
- return args;
301
- };
302
-
303
- // Default: use the user's skills/config. Opt-out → isolated home.
304
- const useLocal = options.useLocalConfig !== false;
305
- const env = { ...process.env, ...(options.runEnv || {}) };
306
- if (!useLocal) {
307
- const home = ensureIsolatedHome();
308
- if (home) env.CODEX_HOME = home;
309
- }
310
-
311
- const ownServer = options.mcp?.serverName || 'chatpanel_browser';
312
- // Only servers Codex already knows about can be switched off — see configuredMcpServers.
313
- const known = configuredMcpServers(env.CODEX_HOME || process.env.CODEX_HOME || path.join(os.homedir(), '.codex'));
314
- let disabled = disabledMcpServers('codex', options, [ownServer]).filter((n) => known.has(n));
315
- const prompt = buildCliPrompt(messages, system);
316
- const attempt = () => runCodex({ args: buildArgs(disabled), cwd, env, prompt, outFile, emit, signal });
317
-
318
- try {
319
- let result = await attempt();
320
- if (result.policyBlocked) approvalPolicyBlocked = true;
321
-
322
- // The failure this exists for: one of the user's OWN MCP servers could not authenticate
323
- // or could not be reached, and took a turn with it that never needed that server. Drop it
324
- // and run again — once, out loud, and only while nothing has been streamed.
325
- if (!signal?.aborted && result.code !== 0 && !result.streamed) {
326
- const drop = planMcpRetry({ agent: 'codex', text: result.stderr, protect: [ownServer], already: disabled });
327
- if (drop && known.has(drop.server)) {
328
- quarantine('codex', drop.server);
329
- emit({ type: 'status', text: `MCP server "${drop.server}" failed to load — ${drop.short}. Skipping it and retrying.` });
330
- disabled = [...disabled, drop.server];
331
- result = await attempt();
332
- }
333
- }
334
-
335
- if (signal?.aborted) return; // Stop pressed — end quietly, no error
336
- if (result.code !== 0) throw new Error(summarizeCliError('Codex', result.code, result.stderr, '', { agentId: 'codex' }));
337
- // Said already, message by message (forwardEvent); the file is the fallback, not a repeat.
338
- if (!result.said) emit({ type: 'delta', text: result.text || '(no output)' });
339
- emit({ type: 'done', text: '' });
340
- } finally {
341
- cleanupImages();
342
- }
343
- }
344
-
345
- // Translate Codex `exec --json` events into the bridge's streaming vocabulary the panel
346
- // renders richly. Codex sends item.started (in_progress) then item.completed for each item,
347
- // reusing the item id — so we correlate a tool's start/done by that id and show its command,
348
- // its output, and its exit status, the way Codex's own CLI does. Schema (codex-cli 0.15x):
349
- // command_execution: { id, command, aggregated_output, exit_code, status }
350
- // reasoning: { id, text } (only some models/efforts emit it)
351
- // file_change: { id, changes:[{path}] }
352
- // agent_message: { id, text } (the answer, a delta per message; -o outFile is the fallback)
353
- // web_search: { id, query, action:{ type, query?, url? } } (codex-cli 0.154)
354
- // mcp_tool_call: { id, server, tool, arguments, result?, error?, status }
355
- // todo_list: { id, items:[{ text, completed }] }
356
- export function forwardEvent(ev, emit, state = { started: new Set(), reasoned: new Set(), n: 0 }) {
357
- const t = ev.type || '';
358
- const item = ev.item || {};
359
- const itype = item.type || '';
360
- const completed = t === 'item.completed' || item.status === 'completed' || item.status === 'failed';
361
-
362
- // THE ANSWER, AS IT IS WRITTEN. `codex exec --json` streams no tokens: each agent_message
363
- // arrives whole, and a turn that thinks, runs a command and then concludes writes TWO of
364
- // them. Reading only `-o outFile` at close kept the LAST one and showed it once the process
365
- // had exited — the first sentence was lost and the panel sat blank for the whole run. Each
366
- // message is a delta the moment it completes; the close reads the file only when nothing
367
- // was said this way (an older codex, or a run that ended before its message).
368
- if (itype === 'agent_message' && completed) {
369
- const id = item.id || `msg_${state.n++}`;
370
- const text = String(item.text || '');
371
- if (text && !state.said?.has(id)) {
372
- (state.said ||= new Set()).add(id);
373
- emit({ type: 'delta', text: `${state.saidAny ? '\n\n' : ''}${text}` });
374
- state.saidAny = true;
375
- }
376
- return;
377
- }
378
-
379
- if (itype === 'command_execution' || (!itype && t.includes('command'))) {
380
- const id = item.id || `cmd_${state.n++}`;
381
- if (!state.started.has(id)) {
382
- state.started.add(id);
383
- emit({ type: 'tool', name: 'shell', phase: 'start', callId: id, input: { command: item.command || '' } });
384
- }
385
- if (completed) {
386
- const ok = item.exit_code === 0 || item.exit_code == null;
387
- emit({
388
- type: 'tool', name: 'shell', phase: 'done', callId: id,
389
- status: ok ? 'ok' : `exit ${item.exit_code}`,
390
- result: String(item.aggregated_output || '').slice(0, 4000),
391
- });
392
- }
393
- return;
394
- }
395
-
396
- if (itype === 'file_change' || (!itype && t.includes('patch'))) {
397
- const id = item.id || `edit_${state.n++}`;
398
- const files = Array.isArray(item.changes) ? item.changes.map((c) => c.path || c.file).filter(Boolean) : [];
399
- if (!state.started.has(id)) {
400
- state.started.add(id);
401
- emit({ type: 'tool', name: 'edit', phase: 'start', callId: id, input: { files } });
402
- }
403
- if (completed) emit({ type: 'tool', name: 'edit', phase: 'done', callId: id, status: 'ok' });
404
- return;
405
- }
406
-
407
- // WEB SEARCH — Codex's own, not a command and not an MCP call, so it never reached the
408
- // panel: a weekend-weather turn that searched four times showed no activity at all while
409
- // the CLI printed "Searching the web" four times. Captured from codex-cli 0.154:
410
- // item.started { id, type:'web_search', query:'', action:{ type:'other' } }
411
- // item.completed { id, type:'web_search', query, action:{ type:'search', query } }
412
- // (the query is only known at completion; an `open_page` action carries a url instead).
413
- if (itype === 'web_search') {
414
- const id = item.id || `ws_${state.n++}`;
415
- const action = item.action && typeof item.action === 'object' ? item.action : {};
416
- const query = item.query || action.query || '';
417
- const url = action.url || '';
418
- if (!state.started.has(id)) {
419
- state.started.add(id);
420
- emit({ type: 'tool', name: 'web_search', phase: 'start', callId: id, input: { query, ...(url ? { url } : {}) } });
421
- }
422
- if (completed || t === 'item.completed') {
423
- emit({ type: 'tool', name: 'web_search', phase: 'done', callId: id, status: 'ok', result: url ? `Opened ${url}` : query ? `Searched the web for ${query}` : 'Searched the web' });
424
- }
425
- return;
426
- }
427
-
428
- // MCP TOOL CALLS — the user's own servers, and ChatPanel's page tools relayed through the
429
- // bridge. { id, server, tool, arguments, result?, error?, status }.
430
- if (itype === 'mcp_tool_call') {
431
- const id = item.id || `mcp_${state.n++}`;
432
- const name = item.server ? `${item.server}/${item.tool || 'tool'}` : (item.tool || 'mcp');
433
- if (!state.started.has(id)) {
434
- state.started.add(id);
435
- emit({ type: 'tool', name, phase: 'start', callId: id, input: item.arguments && typeof item.arguments === 'object' ? item.arguments : {} });
436
- }
437
- if (completed) {
438
- const failed = item.status === 'failed' || item.error != null;
439
- const err = item.error && typeof item.error === 'object' ? (item.error.message || JSON.stringify(item.error)) : item.error;
440
- const res = item.result == null ? '' : typeof item.result === 'string' ? item.result : JSON.stringify(item.result);
441
- emit({ type: 'tool', name, phase: 'done', callId: id, status: failed ? `error: ${String(err || 'failed').slice(0, 80)}` : 'ok', result: String(failed ? err || '' : res).slice(0, 4000) });
442
- }
443
- return;
444
- }
445
-
446
- // A plan Codex wrote for itself, shown once when it changes.
447
- if (itype === 'todo_list' && Array.isArray(item.items) && item.items.length) {
448
- const text = item.items.map((x) => `${x.completed ? '☑' : '☐'} ${x.text || ''}`).join('\n');
449
- if (state.lastTodo !== text) { state.lastTodo = text; emit({ type: 'status', text: `Plan:\n${text}` }); }
450
- return;
451
- }
452
-
453
- if (itype === 'error' || t === 'error') {
454
- const msg = String(item.message || ev.message || '');
455
- if (!msg) return;
456
- // The managed-requirements warning: long, per turn, and about a flag WE pass. Say it
457
- // once in a sentence, and remember (see buildArgs) so the next turn does not earn it.
458
- if (/approval_policy.*(disallowed|not in the allowed set)/i.test(msg)) {
459
- state.policyBlocked = true;
460
- if (!state.policyNoted) {
461
- state.policyNoted = true;
462
- emit({ type: 'status', text: 'Codex: your organisation pins approval_policy, so Codex will ask before actions it cannot run on its own. ChatPanel will stop passing its own setting.' });
463
- }
464
- return;
465
- }
466
- emit({ type: 'status', text: `Codex: ${msg.slice(0, 300)}` });
467
- return;
468
- }
469
-
470
- if (itype === 'reasoning' || (!itype && t.includes('reasoning'))) {
471
- // Emit each reasoning summary once (dedup the started/updated/completed repeats).
472
- const id = item.id || `r_${state.n++}`;
473
- const text = item.text || item.summary || '';
474
- if (text && !state.reasoned.has(id)) {
475
- state.reasoned.add(id);
476
- emit({ type: 'reasoning', text: `${text}\n` });
477
- }
478
- return;
479
- }
480
-
481
- if (t === 'turn.started' || t === 'thread.started') emit({ type: 'status', text: 'Codex working' });
482
- }
4
+ `:""}${n}`}),t.saidAny=!0);return}if(i==="command_execution"||!i&&a.includes("command")){const r=e.id||`cmd_${t.n++}`;if(t.started.has(r)||(t.started.add(r),o({type:"tool",name:"shell",phase:"start",callId:r,input:{command:e.command||""}})),p){const n=e.exit_code===0||e.exit_code==null;o({type:"tool",name:"shell",phase:"done",callId:r,status:n?"ok":`exit ${e.exit_code}`,result:String(e.aggregated_output||"").slice(0,4e3)})}return}if(i==="file_change"||!i&&a.includes("patch")){const r=e.id||`edit_${t.n++}`,n=Array.isArray(e.changes)?e.changes.map(l=>l.path||l.file).filter(Boolean):[];t.started.has(r)||(t.started.add(r),o({type:"tool",name:"edit",phase:"start",callId:r,input:{files:n}})),p&&o({type:"tool",name:"edit",phase:"done",callId:r,status:"ok"});return}if(i==="web_search"){const r=e.id||`ws_${t.n++}`,n=e.action&&typeof e.action=="object"?e.action:{},l=e.query||n.query||"",f=n.url||"";t.started.has(r)||(t.started.add(r),o({type:"tool",name:"web_search",phase:"start",callId:r,input:{query:l,...f?{url:f}:{}}})),(p||a==="item.completed")&&o({type:"tool",name:"web_search",phase:"done",callId:r,status:"ok",result:f?`Opened ${f}`:l?`Searched the web for ${l}`:"Searched the web"});return}if(i==="mcp_tool_call"){const r=e.id||`mcp_${t.n++}`,n=e.server?`${e.server}/${e.tool||"tool"}`:e.tool||"mcp";if(t.started.has(r)||(t.started.add(r),o({type:"tool",name:n,phase:"start",callId:r,input:e.arguments&&typeof e.arguments=="object"?e.arguments:{}})),p){const l=e.status==="failed"||e.error!=null,f=e.error&&typeof e.error=="object"?e.error.message||JSON.stringify(e.error):e.error,m=e.result==null?"":typeof e.result=="string"?e.result:JSON.stringify(e.result);o({type:"tool",name:n,phase:"done",callId:r,status:l?`error: ${String(f||"failed").slice(0,80)}`:"ok",result:String(l?f||"":m).slice(0,4e3)})}return}if(i==="todo_list"&&Array.isArray(e.items)&&e.items.length){const r=e.items.map(n=>`${n.completed?"☑":"☐"} ${n.text||""}`).join(`
5
+ `);t.lastTodo!==r&&(t.lastTodo=r,o({type:"status",text:`Plan:
6
+ ${r}`}));return}if(i==="error"||a==="error"){const r=String(e.message||s.message||"");if(!r)return;if(/approval_policy.*(disallowed|not in the allowed set)/i.test(r)){t.policyBlocked=!0,t.policyNoted||(t.policyNoted=!0,o({type:"status",text:"Codex: your organisation pins approval_policy, so Codex will ask before actions it cannot run on its own. ChatPanel will stop passing its own setting."}));return}o({type:"status",text:`Codex: ${r.slice(0,300)}`});return}if(i==="reasoning"||!i&&a.includes("reasoning")){const r=e.id||`r_${t.n++}`,n=e.text||e.summary||"";n&&!t.reasoned.has(r)&&(t.reasoned.add(r),o({type:"reasoning",text:`${n}
7
+ `}));return}(a==="turn.started"||a==="thread.started")&&o({type:"status",text:"Codex working"})}export{Oe as available,Ae as chat,ae as codexDisableArgs,se as codexMcpConfigArgs,ne as configuredMcpServers,le as forwardEvent,Ee as listModels,ke as resetApprovalPolicy};