Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 20 additions & 3 deletions src/adapters/codex-channel.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import { fileURLToPath } from 'node:url';
import { atomicJSON, atomicWrite, BrokerHttp, BrokerSocket, newerVersion, UncertainError, writeStatus } from './core/broker.mjs';
import { expandPath as expand, readUpload, saveDownload, within } from './core/files.mjs';
import { composeInstructions, parseInstructions } from './core/instructions.mjs';
import { serviceTokenFiles, serviceTokenHeader, serviceTokens } from './core/serviceTokens.mjs';

export { atomicJSON, UncertainError, within };

Expand All @@ -24,13 +25,17 @@ const nowISO = () => new Date().toISOString();
const enc = encodeURIComponent;
const json = file => JSON.parse(fs.readFileSync(file, 'utf8').replace(/^\uFEFF/, ''));
const BROKER_TOKEN_ENV = 'AICHAT_CODEX_MCP_TOKEN';
const SERVICE_TOKEN_ENV_PREFIX = 'AICHAT_CODEX_SERVICE_TOKEN_';
const ATTACH_TOKEN_ENV = 'AICHAT_CODEX_APP_SERVER_BEARER';
const ATTACH_LEASE_MS = 10000;
const ATTACH_DIRECTORY = /^appserver-private-[\w-]+$/;

function appEnvironment(cfg) {
const env = { ...process.env, CODEX_HOME: cfg.codexHome };
for (const key of ['CODEX_THREAD_ID', 'CODEX_SESSION_ID', 'CODEX_APP_TOOLS_PIPE_PATH', 'CODEX_TOOL_CALL_ID', 'AICHAT_TOKEN', BROKER_TOKEN_ENV, ATTACH_TOKEN_ENV]) delete env[key];
for (const key of Object.keys(env)) {
if (key.toUpperCase().startsWith(SERVICE_TOKEN_ENV_PREFIX)) delete env[key];
}
return env;
}

Expand Down Expand Up @@ -297,13 +302,25 @@ export class AppRpc extends EventEmitter {
constructor(cfg, { token, brokerMcp, managedMcp } = {}) {
super(); this.pending = new Map(); this.sequence = 1; this.closed = false;
this.remote = cfg.attachPort !== undefined;
const args = [...mcpOverrides(cfg, brokerMcp, managedMcp), 'app-server'];
const args = mcpOverrides(cfg, brokerMcp, managedMcp);
const env = appEnvironment(cfg);
if (token && brokerMcp && managedMcp) {
env[BROKER_TOKEN_ENV] = token;
for (const [id, serviceToken] of serviceTokens(cfg, { dir: cfg.agentDir })) {
const variable = SERVICE_TOKEN_ENV_PREFIX + id.toUpperCase().replaceAll('-', '_');
env[variable] = serviceToken;
// A per-header override preserves other MCP headers. Keep values out of args and shell commands.
args.push('-c', `mcp_servers.aichat.env_http_headers.${serviceTokenHeader(id)}=${quote(variable)}`);
args.push('-c', `shell_environment_policy.set.${variable}=""`);
}
}
args.push('app-server');
if (this.remote) {
this.endpoint = `ws://127.0.0.1:${cfg.attachPort}`;
Object.assign(this, createAttachToken(cfg));
args.push('--listen', this.endpoint, '--ws-auth', 'capability-token', '--ws-token-file', this.tokenFile);
}
this.child = spawn(cfg.codex, args, { env: { ...appEnvironment(cfg), ...(token && brokerMcp && managedMcp ? { [BROKER_TOKEN_ENV]: token } : {}) }, cwd: cfg.agentDir, windowsHide: true,
this.child = spawn(cfg.codex, args, { env, cwd: cfg.agentDir, windowsHide: true,
stdio: [this.remote ? 'ignore' : 'pipe', this.remote ? 'ignore' : 'pipe', 'pipe'] });
this.child.stderr.on('data', data => this.emit('diagnostic', String(data)));
this.child.on('error', error => { this.startError = error; this.fail(error); });
Expand Down Expand Up @@ -421,7 +438,7 @@ export async function callTool(cfg, name, args, http = brokerHttp(cfg)) {
return fs.realpathSync(root) === path.join(parent, path.basename(root));
});
const { bytes, name: filename, mime } = readUpload({ path: args.path, base: cfg.agentDir, roots,
blocked: [cfg.codexHome, cfg.runtime, cfg.tokenFile] });
blocked: [cfg.codexHome, cfg.runtime, cfg.tokenFile, ...serviceTokenFiles(cfg, { dir: cfg.agentDir }).values()] });
const uploaded = await http.request('/api/files', { method: 'POST', body: bytes,
headers: { 'Content-Type': mime, 'X-Filename': enc(filename) } });
if (!uploaded.file?.id) throw new Error('Upload returned no file id');
Expand Down
4 changes: 4 additions & 0 deletions src/adapters/codex-channel.test.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -660,6 +660,10 @@ test('local upload rejects private files, hardlinks and links outside outbox', a
assert.deepEqual(JSON.parse(await upload(normal)), { file_id: 'file-1', name: 'implementation.txt', size: 5 });
const env = path.join(f.cfg.outbox, '.env.production'); fs.writeFileSync(env, 'fake secret'); await assert.rejects(upload(env), /private/);
const auth = path.join(f.cfg.codexHome, 'auth.json'); fs.writeFileSync(auth, '{}'); await assert.rejects(upload(auth), /private/);
const serviceFile = path.join(f.cfg.outbox, 'service-value.txt');
fs.writeFileSync(serviceFile, 'dummy service value');
f.cfg.serviceTokens = { github: path.relative(f.cfg.agentDir, serviceFile) };
await assert.rejects(upload(serviceFile), /private/);
const link = path.join(f.cfg.outbox, 'renamed.txt'); fs.linkSync(f.cfg.tokenFile, link); await assert.rejects(upload(link), /hard links/);
const escape = path.join(f.cfg.outbox, 'escape'); fs.symlinkSync(f.dir, escape, process.platform === 'win32' ? 'junction' : 'dir');
const outside = path.join(f.dir, 'outside.txt'); fs.writeFileSync(outside, 'outside');
Expand Down