@just-every/ensemble 0.2.245 → 0.2.246
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cjs/data/model_data.cjs +124 -6
- package/dist/cjs/data/model_data.d.ts.map +1 -1
- package/dist/cjs/data/model_data.js.map +1 -1
- package/dist/cjs/model_providers/claude.cjs +8 -7
- package/dist/cjs/model_providers/claude.d.ts.map +1 -1
- package/dist/cjs/model_providers/claude.js.map +1 -1
- package/dist/cjs/model_providers/codex.cjs +566 -20
- package/dist/cjs/model_providers/codex.d.ts.map +1 -1
- package/dist/cjs/model_providers/codex.js.map +1 -1
- package/dist/cjs/tsconfig.cjs.tsbuildinfo +1 -1
- package/dist/cjs/types/types.d.ts +3 -0
- package/dist/cjs/types/types.d.ts.map +1 -1
- package/dist/data/model_data.d.ts.map +1 -1
- package/dist/data/model_data.js +124 -6
- package/dist/data/model_data.js.map +1 -1
- package/dist/model_providers/claude.d.ts.map +1 -1
- package/dist/model_providers/claude.js +8 -7
- package/dist/model_providers/claude.js.map +1 -1
- package/dist/model_providers/codex.d.ts.map +1 -1
- package/dist/model_providers/codex.js +534 -21
- package/dist/model_providers/codex.js.map +1 -1
- package/dist/tsconfig.tsbuildinfo +1 -1
- package/dist/types/types.d.ts +3 -0
- package/dist/types/types.d.ts.map +1 -1
- package/package.json +1 -1
|
@@ -1,7 +1,9 @@
|
|
|
1
1
|
import { spawn } from 'child_process';
|
|
2
|
-
import {
|
|
2
|
+
import { randomUUID } from 'crypto';
|
|
3
|
+
import { chmod, mkdir, mkdtemp, readdir, readFile, rm, writeFile } from 'fs/promises';
|
|
3
4
|
import { tmpdir, homedir } from 'os';
|
|
4
5
|
import path from 'path';
|
|
6
|
+
import { setTimeout as sleep } from 'timers/promises';
|
|
5
7
|
import { BaseModelProvider } from './base_provider.js';
|
|
6
8
|
import { costTracker } from '../utils/cost_tracker.js';
|
|
7
9
|
import { log_llm_error, log_llm_request, log_llm_response } from '../utils/llm_logger.js';
|
|
@@ -183,7 +185,7 @@ function summarizeCodexExecStream(value) {
|
|
|
183
185
|
truncated: true,
|
|
184
186
|
};
|
|
185
187
|
}
|
|
186
|
-
function codexUsageFromJsonl(stdout, model, requestId) {
|
|
188
|
+
function codexUsageFromJsonl(stdout, model, requestId, metadata) {
|
|
187
189
|
let latestUsage;
|
|
188
190
|
for (const line of stdout.split(/\r?\n/)) {
|
|
189
191
|
const trimmed = line.trim();
|
|
@@ -221,6 +223,7 @@ function codexUsageFromJsonl(stdout, model, requestId) {
|
|
|
221
223
|
cached_tokens: latestUsage.cached_input_tokens,
|
|
222
224
|
request_id: requestId,
|
|
223
225
|
metadata: {
|
|
226
|
+
...metadata,
|
|
224
227
|
source: 'codex_cli_json',
|
|
225
228
|
reasoning_output_tokens: latestUsage.reasoning_output_tokens ?? 0,
|
|
226
229
|
},
|
|
@@ -232,6 +235,418 @@ function finiteNumber(value) {
|
|
|
232
235
|
function isRecord(value) {
|
|
233
236
|
return Boolean(value) && typeof value === 'object' && !Array.isArray(value);
|
|
234
237
|
}
|
|
238
|
+
function getCodexProviderSettings(settings) {
|
|
239
|
+
return settings;
|
|
240
|
+
}
|
|
241
|
+
function compactJson(value) {
|
|
242
|
+
return JSON.stringify(value);
|
|
243
|
+
}
|
|
244
|
+
function getToolNames(tools) {
|
|
245
|
+
return tools.map(tool => tool.definition.function.name);
|
|
246
|
+
}
|
|
247
|
+
function getTerminalToolNameSet(agent) {
|
|
248
|
+
return new Set((agent.terminalToolNames ?? []).filter((name) => typeof name === 'string' && name.trim().length > 0));
|
|
249
|
+
}
|
|
250
|
+
function getAvailableTerminalToolNames(tools, agent) {
|
|
251
|
+
const terminalNames = getTerminalToolNameSet(agent);
|
|
252
|
+
if (terminalNames.size === 0)
|
|
253
|
+
return [];
|
|
254
|
+
return getToolNames(tools).filter(name => terminalNames.has(name));
|
|
255
|
+
}
|
|
256
|
+
function createCodexToolOutputSchema(tools, agent) {
|
|
257
|
+
const requiresTerminalTool = getAvailableTerminalToolNames(tools, agent).length > 0;
|
|
258
|
+
return {
|
|
259
|
+
name: 'codex_tool_action',
|
|
260
|
+
type: 'json_schema',
|
|
261
|
+
description: 'A simulated Ensemble tool action for Codex CLI provider requests.',
|
|
262
|
+
schema: {
|
|
263
|
+
type: 'object',
|
|
264
|
+
additionalProperties: false,
|
|
265
|
+
properties: {
|
|
266
|
+
action: {
|
|
267
|
+
type: 'string',
|
|
268
|
+
enum: requiresTerminalTool ? ['tool_calls'] : ['tool_calls', 'final_response'],
|
|
269
|
+
description: requiresTerminalTool
|
|
270
|
+
? 'Use tool_calls. This request is only complete after calling a terminal tool.'
|
|
271
|
+
: 'Use tool_calls when requesting Ensemble tool execution; use final_response only when no tool is needed.',
|
|
272
|
+
},
|
|
273
|
+
toolCalls: {
|
|
274
|
+
type: 'array',
|
|
275
|
+
description: 'Tool calls to execute in parallel for this turn. Empty when action is final_response.',
|
|
276
|
+
items: {
|
|
277
|
+
type: 'object',
|
|
278
|
+
additionalProperties: false,
|
|
279
|
+
properties: {
|
|
280
|
+
name: {
|
|
281
|
+
type: 'string',
|
|
282
|
+
enum: getToolNames(tools),
|
|
283
|
+
},
|
|
284
|
+
argumentsJson: {
|
|
285
|
+
type: 'string',
|
|
286
|
+
description: 'A compact JSON string containing the complete arguments object for the named tool.',
|
|
287
|
+
},
|
|
288
|
+
},
|
|
289
|
+
required: ['name', 'argumentsJson'],
|
|
290
|
+
},
|
|
291
|
+
},
|
|
292
|
+
finalResponse: {
|
|
293
|
+
type: 'string',
|
|
294
|
+
description: 'Final assistant response. Use an empty string when action is tool_calls.',
|
|
295
|
+
},
|
|
296
|
+
},
|
|
297
|
+
required: ['action', 'toolCalls', 'finalResponse'],
|
|
298
|
+
},
|
|
299
|
+
};
|
|
300
|
+
}
|
|
301
|
+
function describeCodexToolChoice(settings) {
|
|
302
|
+
const toolChoice = settings?.tool_choice;
|
|
303
|
+
if (toolChoice === 'required') {
|
|
304
|
+
return 'This turn requires at least one tool call.';
|
|
305
|
+
}
|
|
306
|
+
if (toolChoice === 'none') {
|
|
307
|
+
return 'This turn forbids tool calls; return final_response.';
|
|
308
|
+
}
|
|
309
|
+
if (typeof toolChoice === 'object' && toolChoice?.type === 'function' && toolChoice.function?.name) {
|
|
310
|
+
return `This turn requires the ${toolChoice.function.name} tool.`;
|
|
311
|
+
}
|
|
312
|
+
return 'Use tool_calls when a tool result is needed; otherwise use final_response.';
|
|
313
|
+
}
|
|
314
|
+
function buildCodexToolInstructions(tools, agent) {
|
|
315
|
+
const settings = agent.modelSettings;
|
|
316
|
+
const terminalToolNames = getAvailableTerminalToolNames(tools, agent);
|
|
317
|
+
const toolDescriptions = tools
|
|
318
|
+
.map(tool => {
|
|
319
|
+
const fn = tool.definition.function;
|
|
320
|
+
return [
|
|
321
|
+
`Tool: ${fn.name}`,
|
|
322
|
+
`Description: ${fn.description}`,
|
|
323
|
+
`Parameters JSON schema: ${compactJson(fn.parameters)}`,
|
|
324
|
+
].join('\n');
|
|
325
|
+
})
|
|
326
|
+
.join('\n\n');
|
|
327
|
+
return [
|
|
328
|
+
'You are using Ensemble simulated tool mode.',
|
|
329
|
+
'You cannot execute these tools yourself. Instead, respond only with JSON matching the provided output schema.',
|
|
330
|
+
describeCodexToolChoice(settings),
|
|
331
|
+
'For action "tool_calls", include one or more entries in toolCalls and set finalResponse to an empty string.',
|
|
332
|
+
terminalToolNames.length > 0
|
|
333
|
+
? `This request is not complete until you call one of these terminal tools: ${terminalToolNames.join(', ')}. Do not use final_response.`
|
|
334
|
+
: 'For action "final_response", set toolCalls to an empty array and put the final answer in finalResponse.',
|
|
335
|
+
'Use exact tool names.',
|
|
336
|
+
'Set argumentsJson to a compact JSON string containing the complete arguments object for the named tool.',
|
|
337
|
+
'For example, the arguments object {"label":"ok"} must be encoded as "{\\"label\\":\\"ok\\"}".',
|
|
338
|
+
'',
|
|
339
|
+
'Available tools:',
|
|
340
|
+
toolDescriptions,
|
|
341
|
+
].join('\n');
|
|
342
|
+
}
|
|
343
|
+
function validateCodexWorkspaceRelativePath(filePath) {
|
|
344
|
+
const normalized = filePath.replace(/\\/g, '/').replace(/^\.\/+/, '');
|
|
345
|
+
if (!normalized ||
|
|
346
|
+
path.isAbsolute(normalized) ||
|
|
347
|
+
normalized.split('/').some(part => part === '..' || part === '')) {
|
|
348
|
+
throw new Error(`Invalid Codex workspace file path: ${filePath}`);
|
|
349
|
+
}
|
|
350
|
+
return normalized;
|
|
351
|
+
}
|
|
352
|
+
async function writeCodexWorkspaceFiles(tempDir, files) {
|
|
353
|
+
const written = [];
|
|
354
|
+
for (const [rawPath, content] of Object.entries(files ?? {})) {
|
|
355
|
+
const relativePath = validateCodexWorkspaceRelativePath(rawPath);
|
|
356
|
+
const targetPath = path.join(tempDir, relativePath);
|
|
357
|
+
await mkdir(path.dirname(targetPath), { recursive: true });
|
|
358
|
+
await writeFile(targetPath, content, 'utf8');
|
|
359
|
+
written.push(relativePath);
|
|
360
|
+
}
|
|
361
|
+
return written.sort();
|
|
362
|
+
}
|
|
363
|
+
function buildCodexWorkspaceFileInstructions(files, extra) {
|
|
364
|
+
if (files.length === 0 && !extra?.trim())
|
|
365
|
+
return '';
|
|
366
|
+
return [
|
|
367
|
+
'A disposable Codex workspace has been prepared for this request.',
|
|
368
|
+
files.length > 0
|
|
369
|
+
? `Workspace files available in the current directory:\n${files.map(file => `- ${file}`).join('\n')}`
|
|
370
|
+
: undefined,
|
|
371
|
+
extra?.trim() || undefined,
|
|
372
|
+
]
|
|
373
|
+
.filter(Boolean)
|
|
374
|
+
.join('\n');
|
|
375
|
+
}
|
|
376
|
+
function shellIdentifier(value) {
|
|
377
|
+
if (!/^[A-Za-z0-9_.:-]+$/.test(value)) {
|
|
378
|
+
throw new Error(`Codex filesystem tool name is not shell-safe: ${value}`);
|
|
379
|
+
}
|
|
380
|
+
return value;
|
|
381
|
+
}
|
|
382
|
+
function buildCodexFilesystemToolInstructions(tools, agent) {
|
|
383
|
+
const terminalToolNames = getAvailableTerminalToolNames(tools, agent);
|
|
384
|
+
const toolDescriptions = tools
|
|
385
|
+
.map(tool => {
|
|
386
|
+
const fn = tool.definition.function;
|
|
387
|
+
return [
|
|
388
|
+
`Command: ./tools/${fn.name} <arguments-json-file>`,
|
|
389
|
+
`Description: ${fn.description}`,
|
|
390
|
+
`Arguments JSON schema: ${compactJson(fn.parameters)}`,
|
|
391
|
+
].join('\n');
|
|
392
|
+
})
|
|
393
|
+
.join('\n\n');
|
|
394
|
+
return [
|
|
395
|
+
'You are using Codex filesystem tool mode.',
|
|
396
|
+
'Work in the current directory. Read the provided JSON files, write candidate JSON files, and run the executable commands in ./tools.',
|
|
397
|
+
'Each ./tools command takes one path to a JSON arguments file. The command prints the real tool result to stdout.',
|
|
398
|
+
'When a layered document argument would otherwise be a large JSON string, you may put candidateLayeredDocumentPath or repairedLayeredDocumentPath in the arguments file; the wrapper will read that file and pass the required JSON string to the real tool.',
|
|
399
|
+
terminalToolNames.length > 0
|
|
400
|
+
? `This request is not complete until you run one of these terminal tool commands: ${terminalToolNames.map(name => `./tools/${name}`).join(', ')}.`
|
|
401
|
+
: undefined,
|
|
402
|
+
'After the terminal tool command succeeds, respond with a brief completion note. Do not invent tool outputs; use the command output.',
|
|
403
|
+
'',
|
|
404
|
+
'Available filesystem tools:',
|
|
405
|
+
toolDescriptions,
|
|
406
|
+
]
|
|
407
|
+
.filter(Boolean)
|
|
408
|
+
.join('\n');
|
|
409
|
+
}
|
|
410
|
+
async function startCodexFilesystemToolBroker(tempDir, tools, agent) {
|
|
411
|
+
const toolsDir = path.join(tempDir, 'tools');
|
|
412
|
+
const requestDir = path.join(tempDir, '.codex-tool-requests');
|
|
413
|
+
const responseDir = path.join(tempDir, '.codex-tool-responses');
|
|
414
|
+
await Promise.all([
|
|
415
|
+
mkdir(toolsDir, { recursive: true }),
|
|
416
|
+
mkdir(requestDir, { recursive: true }),
|
|
417
|
+
mkdir(responseDir, { recursive: true }),
|
|
418
|
+
]);
|
|
419
|
+
for (const tool of tools) {
|
|
420
|
+
const toolName = shellIdentifier(tool.definition.function.name);
|
|
421
|
+
const toolPath = path.join(toolsDir, toolName);
|
|
422
|
+
await writeFile(toolPath, buildCodexFilesystemToolWrapperScript({
|
|
423
|
+
toolName,
|
|
424
|
+
workspaceDir: tempDir,
|
|
425
|
+
requestDir,
|
|
426
|
+
responseDir,
|
|
427
|
+
}), 'utf8');
|
|
428
|
+
await chmod(toolPath, 0o755);
|
|
429
|
+
}
|
|
430
|
+
const toolByName = new Map(tools.map(tool => [tool.definition.function.name, tool]));
|
|
431
|
+
const seen = new Set();
|
|
432
|
+
const inFlight = new Set();
|
|
433
|
+
let stopped = false;
|
|
434
|
+
const serviceRequest = async (fileName) => {
|
|
435
|
+
const requestPath = path.join(requestDir, fileName);
|
|
436
|
+
let request;
|
|
437
|
+
try {
|
|
438
|
+
request = JSON.parse(await readFile(requestPath, 'utf8'));
|
|
439
|
+
}
|
|
440
|
+
catch (error) {
|
|
441
|
+
await writeFile(path.join(responseDir, fileName), JSON.stringify({
|
|
442
|
+
ok: false,
|
|
443
|
+
error: `Could not read Codex filesystem tool request: ${error instanceof Error ? error.message : String(error)}`,
|
|
444
|
+
}), 'utf8');
|
|
445
|
+
return;
|
|
446
|
+
}
|
|
447
|
+
const toolName = typeof request.toolName === 'string' ? request.toolName : '';
|
|
448
|
+
const tool = toolByName.get(toolName);
|
|
449
|
+
if (!tool) {
|
|
450
|
+
await writeFile(path.join(responseDir, fileName), JSON.stringify({ ok: false, error: `Unknown Codex filesystem tool: ${toolName || '<missing>'}` }), 'utf8');
|
|
451
|
+
return;
|
|
452
|
+
}
|
|
453
|
+
try {
|
|
454
|
+
const argumentsJson = typeof request.argumentsJson === 'string' ? request.argumentsJson : '{}';
|
|
455
|
+
const parsedArguments = JSON.parse(argumentsJson);
|
|
456
|
+
const result = await tool.function(parsedArguments);
|
|
457
|
+
const output = typeof result === 'string' ? result : JSON.stringify(result);
|
|
458
|
+
await writeFile(path.join(responseDir, fileName), JSON.stringify({ ok: true, output }), 'utf8');
|
|
459
|
+
}
|
|
460
|
+
catch (error) {
|
|
461
|
+
await writeFile(path.join(responseDir, fileName), JSON.stringify({
|
|
462
|
+
ok: false,
|
|
463
|
+
error: error instanceof Error ? error.message : String(error),
|
|
464
|
+
}), 'utf8');
|
|
465
|
+
}
|
|
466
|
+
};
|
|
467
|
+
const loop = (async () => {
|
|
468
|
+
while (!stopped) {
|
|
469
|
+
const entries = await readdir(requestDir).catch(() => []);
|
|
470
|
+
for (const fileName of entries) {
|
|
471
|
+
if (!fileName.endsWith('.json') || seen.has(fileName))
|
|
472
|
+
continue;
|
|
473
|
+
seen.add(fileName);
|
|
474
|
+
const task = serviceRequest(fileName).finally(() => {
|
|
475
|
+
inFlight.delete(task);
|
|
476
|
+
});
|
|
477
|
+
inFlight.add(task);
|
|
478
|
+
}
|
|
479
|
+
await sleep(50);
|
|
480
|
+
}
|
|
481
|
+
await Promise.allSettled([...inFlight]);
|
|
482
|
+
})();
|
|
483
|
+
return {
|
|
484
|
+
instructions: buildCodexFilesystemToolInstructions(tools, agent),
|
|
485
|
+
stop: async () => {
|
|
486
|
+
stopped = true;
|
|
487
|
+
await loop;
|
|
488
|
+
},
|
|
489
|
+
};
|
|
490
|
+
}
|
|
491
|
+
function buildCodexFilesystemToolWrapperScript(args) {
|
|
492
|
+
return `#!/usr/bin/env node
|
|
493
|
+
const fs = require('fs');
|
|
494
|
+
const path = require('path');
|
|
495
|
+
|
|
496
|
+
const toolName = ${JSON.stringify(args.toolName)};
|
|
497
|
+
const workspaceDir = ${JSON.stringify(args.workspaceDir)};
|
|
498
|
+
const requestDir = ${JSON.stringify(args.requestDir)};
|
|
499
|
+
const responseDir = ${JSON.stringify(args.responseDir)};
|
|
500
|
+
|
|
501
|
+
function sleep(ms) {
|
|
502
|
+
Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms);
|
|
503
|
+
}
|
|
504
|
+
|
|
505
|
+
function readText(filePath) {
|
|
506
|
+
return fs.readFileSync(path.resolve(process.cwd(), filePath), 'utf8');
|
|
507
|
+
}
|
|
508
|
+
|
|
509
|
+
function readArgumentsJson() {
|
|
510
|
+
const argsPath = process.argv[2];
|
|
511
|
+
const raw = argsPath ? readText(argsPath) : fs.readFileSync(0, 'utf8');
|
|
512
|
+
if (!raw.trim()) {
|
|
513
|
+
throw new Error('Expected a JSON arguments file path or JSON on stdin.');
|
|
514
|
+
}
|
|
515
|
+
const parsed = JSON.parse(raw);
|
|
516
|
+
if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) {
|
|
517
|
+
throw new Error('Tool arguments must be a JSON object.');
|
|
518
|
+
}
|
|
519
|
+
if (parsed.candidateLayeredDocumentPath && !parsed.candidateLayeredDocumentJson) {
|
|
520
|
+
parsed.candidateLayeredDocumentJson = readText(parsed.candidateLayeredDocumentPath);
|
|
521
|
+
delete parsed.candidateLayeredDocumentPath;
|
|
522
|
+
}
|
|
523
|
+
if (parsed.repairedLayeredDocumentPath && !parsed.repairedLayeredDocumentJson) {
|
|
524
|
+
parsed.repairedLayeredDocumentJson = readText(parsed.repairedLayeredDocumentPath);
|
|
525
|
+
delete parsed.repairedLayeredDocumentPath;
|
|
526
|
+
}
|
|
527
|
+
return JSON.stringify(parsed);
|
|
528
|
+
}
|
|
529
|
+
|
|
530
|
+
async function main() {
|
|
531
|
+
process.chdir(workspaceDir);
|
|
532
|
+
fs.mkdirSync(requestDir, { recursive: true });
|
|
533
|
+
fs.mkdirSync(responseDir, { recursive: true });
|
|
534
|
+
const id = String(Date.now()) + '-' + String(process.pid) + '-' + Math.random().toString(16).slice(2);
|
|
535
|
+
const fileName = id + '.json';
|
|
536
|
+
fs.writeFileSync(
|
|
537
|
+
path.join(requestDir, fileName),
|
|
538
|
+
JSON.stringify({ id, toolName, argumentsJson: readArgumentsJson() }),
|
|
539
|
+
'utf8'
|
|
540
|
+
);
|
|
541
|
+
|
|
542
|
+
const responsePath = path.join(responseDir, fileName);
|
|
543
|
+
const deadline = Date.now() + 300000;
|
|
544
|
+
while (Date.now() < deadline) {
|
|
545
|
+
if (fs.existsSync(responsePath)) {
|
|
546
|
+
const response = JSON.parse(fs.readFileSync(responsePath, 'utf8'));
|
|
547
|
+
if (!response.ok) {
|
|
548
|
+
console.error(response.error || 'Tool failed.');
|
|
549
|
+
process.exit(1);
|
|
550
|
+
}
|
|
551
|
+
process.stdout.write(String(response.output || ''));
|
|
552
|
+
if (!String(response.output || '').endsWith('\\n')) process.stdout.write('\\n');
|
|
553
|
+
return;
|
|
554
|
+
}
|
|
555
|
+
sleep(50);
|
|
556
|
+
}
|
|
557
|
+
console.error('Timed out waiting for tool result.');
|
|
558
|
+
process.exit(1);
|
|
559
|
+
}
|
|
560
|
+
|
|
561
|
+
main().catch(error => {
|
|
562
|
+
console.error(error && error.message ? error.message : String(error));
|
|
563
|
+
process.exit(1);
|
|
564
|
+
});
|
|
565
|
+
`;
|
|
566
|
+
}
|
|
567
|
+
function normalizeCodexToolArguments(value, toolName) {
|
|
568
|
+
if (typeof value !== 'string') {
|
|
569
|
+
throw new Error(`Codex tool call ${toolName} must provide argumentsJson as a JSON string.`);
|
|
570
|
+
}
|
|
571
|
+
const parsed = JSON.parse(value);
|
|
572
|
+
if (!isRecord(parsed)) {
|
|
573
|
+
throw new Error(`Codex tool call ${toolName} argumentsJson must decode to a JSON object.`);
|
|
574
|
+
}
|
|
575
|
+
return JSON.stringify(parsed);
|
|
576
|
+
}
|
|
577
|
+
function parseCodexToolAction(content, tools, settings, terminalToolNames = []) {
|
|
578
|
+
const parsed = JSON.parse(content);
|
|
579
|
+
if (!isRecord(parsed)) {
|
|
580
|
+
throw new Error('Codex tool response must be a JSON object.');
|
|
581
|
+
}
|
|
582
|
+
const toolChoice = settings?.tool_choice;
|
|
583
|
+
const toolNames = new Set(getToolNames(tools));
|
|
584
|
+
const action = parsed.action;
|
|
585
|
+
if (action === 'final_response') {
|
|
586
|
+
if (terminalToolNames.length > 0) {
|
|
587
|
+
throw new Error(`Codex returned final_response when terminal tool ${terminalToolNames.join(' or ')} was required.`);
|
|
588
|
+
}
|
|
589
|
+
if (toolChoice === 'required') {
|
|
590
|
+
throw new Error('Codex returned final_response when tool_choice required a tool call.');
|
|
591
|
+
}
|
|
592
|
+
if (typeof toolChoice === 'object' && toolChoice?.type === 'function' && toolChoice.function?.name) {
|
|
593
|
+
throw new Error(`Codex returned final_response when ${toolChoice.function.name} was required.`);
|
|
594
|
+
}
|
|
595
|
+
return {
|
|
596
|
+
action: 'final_response',
|
|
597
|
+
content: typeof parsed.finalResponse === 'string' ? parsed.finalResponse : '',
|
|
598
|
+
};
|
|
599
|
+
}
|
|
600
|
+
if (action !== 'tool_calls') {
|
|
601
|
+
throw new Error(`Codex tool response action must be tool_calls or final_response; received ${String(action)}.`);
|
|
602
|
+
}
|
|
603
|
+
if (toolChoice === 'none') {
|
|
604
|
+
throw new Error('Codex returned tool_calls when tool_choice forbids tool use.');
|
|
605
|
+
}
|
|
606
|
+
if (!Array.isArray(parsed.toolCalls) || parsed.toolCalls.length === 0) {
|
|
607
|
+
throw new Error('Codex tool response must include at least one tool call.');
|
|
608
|
+
}
|
|
609
|
+
const requiredToolName = typeof toolChoice === 'object' && toolChoice?.type === 'function' && toolChoice.function?.name
|
|
610
|
+
? toolChoice.function.name
|
|
611
|
+
: undefined;
|
|
612
|
+
const toolCalls = parsed.toolCalls.map((rawCall, index) => {
|
|
613
|
+
if (!isRecord(rawCall)) {
|
|
614
|
+
throw new Error(`Codex tool call at index ${index} must be an object.`);
|
|
615
|
+
}
|
|
616
|
+
const name = rawCall.name;
|
|
617
|
+
if (typeof name !== 'string' || !toolNames.has(name)) {
|
|
618
|
+
throw new Error(`Codex requested unknown tool ${String(name)}.`);
|
|
619
|
+
}
|
|
620
|
+
if (requiredToolName && name !== requiredToolName) {
|
|
621
|
+
throw new Error(`Codex requested ${name}, but ${requiredToolName} was required.`);
|
|
622
|
+
}
|
|
623
|
+
const id = `codex_tool_${randomUUID()}`;
|
|
624
|
+
return {
|
|
625
|
+
id,
|
|
626
|
+
call_id: id,
|
|
627
|
+
type: 'function',
|
|
628
|
+
function: {
|
|
629
|
+
name,
|
|
630
|
+
arguments: normalizeCodexToolArguments(rawCall.argumentsJson, name),
|
|
631
|
+
},
|
|
632
|
+
};
|
|
633
|
+
});
|
|
634
|
+
return {
|
|
635
|
+
action: 'tool_calls',
|
|
636
|
+
toolCalls,
|
|
637
|
+
};
|
|
638
|
+
}
|
|
639
|
+
async function readOptionalUtf8File(filePath) {
|
|
640
|
+
try {
|
|
641
|
+
return await readFile(filePath, 'utf8');
|
|
642
|
+
}
|
|
643
|
+
catch (error) {
|
|
644
|
+
if (error.code === 'ENOENT') {
|
|
645
|
+
return null;
|
|
646
|
+
}
|
|
647
|
+
throw error;
|
|
648
|
+
}
|
|
649
|
+
}
|
|
235
650
|
function serializeCodexExecError(error) {
|
|
236
651
|
if (!(error instanceof Error))
|
|
237
652
|
return error;
|
|
@@ -355,30 +770,60 @@ async function runCodexExec(options) {
|
|
|
355
770
|
});
|
|
356
771
|
return { stdout, stderr, diagnostics };
|
|
357
772
|
}
|
|
358
|
-
function disabledFeatureArgs(
|
|
359
|
-
return CODEX_DISABLED_FEATURES.filter(feature =>
|
|
773
|
+
function disabledFeatureArgs(options = {}) {
|
|
774
|
+
return CODEX_DISABLED_FEATURES.filter(feature => {
|
|
775
|
+
if (options.allowImageGeneration && feature === 'image_generation')
|
|
776
|
+
return false;
|
|
777
|
+
if (options.allowShellTool && feature === 'shell_tool')
|
|
778
|
+
return false;
|
|
779
|
+
return true;
|
|
780
|
+
}).flatMap(feature => ['--disable', feature]);
|
|
360
781
|
}
|
|
361
|
-
async function executeCodexRequest(messages, model, agent, requestId) {
|
|
362
|
-
if (agent.
|
|
363
|
-
throw new Error('Codex provider v1 does not support
|
|
782
|
+
async function executeCodexRequest(messages, model, agent, requestId, options = {}) {
|
|
783
|
+
if (agent.params || agent.processParams) {
|
|
784
|
+
throw new Error('Codex provider v1 does not support params requests.');
|
|
364
785
|
}
|
|
365
786
|
const settings = agent.modelSettings;
|
|
787
|
+
const codexSettings = getCodexProviderSettings(settings);
|
|
788
|
+
const requestJsonSchema = options.jsonSchema ?? settings?.json_schema;
|
|
366
789
|
const { model: codexModel, effort } = resolveCodexModel(model, settings);
|
|
367
790
|
const codexHome = resolveCodexHome(settings);
|
|
368
|
-
const cwd = agent.cwd || process.cwd();
|
|
369
791
|
const tempDir = await mkdtemp(path.join(tmpdir(), 'ensemble-codex-'));
|
|
792
|
+
const cwd = options.useTempCwd ? tempDir : agent.cwd || process.cwd();
|
|
370
793
|
const imageWriter = new CodexImageAttachmentWriter(tempDir, cwd);
|
|
371
|
-
|
|
794
|
+
let filesystemToolBroker = null;
|
|
795
|
+
const workspaceFileNames = await writeCodexWorkspaceFiles(tempDir, codexSettings?.codex_workspace_files);
|
|
796
|
+
if (options.filesystemTools?.length) {
|
|
797
|
+
filesystemToolBroker = await startCodexFilesystemToolBroker(tempDir, options.filesystemTools, agent);
|
|
798
|
+
}
|
|
799
|
+
const extraInstructions = [
|
|
800
|
+
buildCodexWorkspaceFileInstructions(workspaceFileNames, codexSettings?.codex_workspace_instructions),
|
|
801
|
+
filesystemToolBroker?.instructions,
|
|
802
|
+
options.extraInstructions,
|
|
803
|
+
]
|
|
804
|
+
.map(value => value?.trim() ?? '')
|
|
805
|
+
.filter(Boolean)
|
|
806
|
+
.join('\n\n');
|
|
807
|
+
const requestAgent = extraInstructions
|
|
808
|
+
? {
|
|
809
|
+
...agent,
|
|
810
|
+
instructions: [agent.instructions, extraInstructions]
|
|
811
|
+
.map(value => value?.trim() ?? '')
|
|
812
|
+
.filter(Boolean)
|
|
813
|
+
.join('\n\n'),
|
|
814
|
+
}
|
|
815
|
+
: agent;
|
|
816
|
+
const { instructions, prompt, images } = await buildCodexInput(messages, requestAgent, imageWriter);
|
|
372
817
|
const hasInstructions = instructions.trim().length > 0;
|
|
373
818
|
const instructionsPath = path.join(tempDir, 'instructions.md');
|
|
374
819
|
const lastMessagePath = path.join(tempDir, 'last-message.json');
|
|
375
|
-
const schemaPath =
|
|
820
|
+
const schemaPath = requestJsonSchema?.schema ? path.join(tempDir, 'schema.json') : undefined;
|
|
376
821
|
try {
|
|
377
822
|
if (hasInstructions) {
|
|
378
823
|
await writeFile(instructionsPath, instructions, 'utf8');
|
|
379
824
|
}
|
|
380
825
|
if (schemaPath) {
|
|
381
|
-
await writeFile(schemaPath, JSON.stringify(
|
|
826
|
+
await writeFile(schemaPath, JSON.stringify(requestJsonSchema.schema, null, 2), 'utf8');
|
|
382
827
|
}
|
|
383
828
|
const commandArgs = [
|
|
384
829
|
'exec',
|
|
@@ -387,7 +832,7 @@ async function executeCodexRequest(messages, model, agent, requestId) {
|
|
|
387
832
|
'--ignore-user-config',
|
|
388
833
|
'--ignore-rules',
|
|
389
834
|
'--skip-git-repo-check',
|
|
390
|
-
...disabledFeatureArgs(),
|
|
835
|
+
...disabledFeatureArgs({ allowShellTool: options.allowShellTool }),
|
|
391
836
|
'-m',
|
|
392
837
|
codexModel,
|
|
393
838
|
'-c',
|
|
@@ -395,19 +840,21 @@ async function executeCodexRequest(messages, model, agent, requestId) {
|
|
|
395
840
|
...(hasInstructions ? ['-c', `model_instructions_file=${JSON.stringify(instructionsPath)}`] : []),
|
|
396
841
|
...(schemaPath ? ['--output-schema', schemaPath] : []),
|
|
397
842
|
...(images.length > 0 ? ['--image', images.join(',')] : []),
|
|
843
|
+
...(options.allowShellTool ? ['--sandbox', 'workspace-write', '--add-dir', tempDir] : []),
|
|
398
844
|
'--output-last-message',
|
|
399
845
|
lastMessagePath,
|
|
400
846
|
'--cd',
|
|
401
847
|
cwd,
|
|
402
848
|
'-',
|
|
403
849
|
];
|
|
404
|
-
const loggedRequestId = log_llm_request(agent.agent_id || 'default', 'codex',
|
|
850
|
+
const loggedRequestId = log_llm_request(agent.agent_id || 'default', 'codex', model, {
|
|
405
851
|
command: 'codex',
|
|
406
852
|
args: commandArgs,
|
|
407
853
|
cwd,
|
|
408
854
|
prompt,
|
|
409
855
|
images,
|
|
410
|
-
|
|
856
|
+
codex_model: codexModel,
|
|
857
|
+
schema: requestJsonSchema?.schema,
|
|
411
858
|
}, new Date(), requestId, agent.tags);
|
|
412
859
|
let codexExecDiagnostics;
|
|
413
860
|
try {
|
|
@@ -422,7 +869,9 @@ async function executeCodexRequest(messages, model, agent, requestId) {
|
|
|
422
869
|
abortSignal: agent.abortSignal,
|
|
423
870
|
});
|
|
424
871
|
codexExecDiagnostics = codexExecResult.diagnostics;
|
|
425
|
-
const usage = codexUsageFromJsonl(codexExecResult.stdout,
|
|
872
|
+
const usage = codexUsageFromJsonl(codexExecResult.stdout, model, loggedRequestId, {
|
|
873
|
+
codex_cli_model: codexModel,
|
|
874
|
+
});
|
|
426
875
|
if (usage)
|
|
427
876
|
costTracker.addUsage(usage);
|
|
428
877
|
}
|
|
@@ -449,9 +898,58 @@ async function executeCodexRequest(messages, model, agent, requestId) {
|
|
|
449
898
|
throw error;
|
|
450
899
|
}
|
|
451
900
|
finally {
|
|
901
|
+
await filesystemToolBroker?.stop();
|
|
452
902
|
await rm(tempDir, { recursive: true, force: true });
|
|
453
903
|
}
|
|
454
904
|
}
|
|
905
|
+
async function* executeCodexToolRequest(messages, model, agent, tools, requestId) {
|
|
906
|
+
if (agent.modelSettings?.json_schema?.schema) {
|
|
907
|
+
throw new Error('Codex provider cannot combine simulated tool calls with a caller-supplied json_schema.');
|
|
908
|
+
}
|
|
909
|
+
const content = await executeCodexRequest(messages, model, agent, requestId, {
|
|
910
|
+
extraInstructions: buildCodexToolInstructions(tools, agent),
|
|
911
|
+
jsonSchema: createCodexToolOutputSchema(tools, agent),
|
|
912
|
+
});
|
|
913
|
+
const action = parseCodexToolAction(content, tools, agent.modelSettings, getAvailableTerminalToolNames(tools, agent));
|
|
914
|
+
if (action.action === 'final_response') {
|
|
915
|
+
const messageId = `codex-${Date.now()}`;
|
|
916
|
+
yield {
|
|
917
|
+
type: 'message_complete',
|
|
918
|
+
content: action.content,
|
|
919
|
+
message_id: messageId,
|
|
920
|
+
};
|
|
921
|
+
return;
|
|
922
|
+
}
|
|
923
|
+
for (const toolCall of action.toolCalls) {
|
|
924
|
+
yield {
|
|
925
|
+
type: 'tool_start',
|
|
926
|
+
tool_call: toolCall,
|
|
927
|
+
};
|
|
928
|
+
}
|
|
929
|
+
}
|
|
930
|
+
async function* executeCodexFilesystemToolRequest(messages, model, agent, tools, requestId) {
|
|
931
|
+
if (agent.modelSettings?.json_schema?.schema) {
|
|
932
|
+
throw new Error('Codex provider cannot combine filesystem tool mode with a caller-supplied json_schema.');
|
|
933
|
+
}
|
|
934
|
+
const content = await executeCodexRequest(messages, model, agent, requestId, {
|
|
935
|
+
allowShellTool: true,
|
|
936
|
+
filesystemTools: tools,
|
|
937
|
+
useTempCwd: true,
|
|
938
|
+
});
|
|
939
|
+
const messageId = `codex-${Date.now()}`;
|
|
940
|
+
if (content) {
|
|
941
|
+
yield {
|
|
942
|
+
type: 'message_delta',
|
|
943
|
+
content,
|
|
944
|
+
message_id: messageId,
|
|
945
|
+
};
|
|
946
|
+
}
|
|
947
|
+
yield {
|
|
948
|
+
type: 'message_complete',
|
|
949
|
+
content,
|
|
950
|
+
message_id: messageId,
|
|
951
|
+
};
|
|
952
|
+
}
|
|
455
953
|
function buildCodexImagePrompt(prompt, opts = {}) {
|
|
456
954
|
const count = opts.n && opts.n > 0 ? Math.floor(opts.n) : 1;
|
|
457
955
|
const details = [
|
|
@@ -534,7 +1032,7 @@ async function executeCodexImageGeneration(prompt, model, agent, opts = {}) {
|
|
|
534
1032
|
'--skip-git-repo-check',
|
|
535
1033
|
'--enable',
|
|
536
1034
|
'image_generation',
|
|
537
|
-
...disabledFeatureArgs(true),
|
|
1035
|
+
...disabledFeatureArgs({ allowImageGeneration: true }),
|
|
538
1036
|
...(promptModelAttempt
|
|
539
1037
|
? [
|
|
540
1038
|
'-m',
|
|
@@ -583,8 +1081,11 @@ async function executeCodexImageGeneration(prompt, model, agent, opts = {}) {
|
|
|
583
1081
|
});
|
|
584
1082
|
throw error;
|
|
585
1083
|
}
|
|
586
|
-
const rawLastMessage = await
|
|
587
|
-
const
|
|
1084
|
+
const rawLastMessage = await readOptionalUtf8File(lastMessagePath);
|
|
1085
|
+
const lastMessageContent = rawLastMessage ?? '';
|
|
1086
|
+
const responseImagePaths = rawLastMessage
|
|
1087
|
+
? await extractExistingCodexImagePaths(rawLastMessage, outputDir)
|
|
1088
|
+
: [];
|
|
588
1089
|
const outputImagePaths = await newestFirst(await listCodexOutputImages(outputDir));
|
|
589
1090
|
const generatedImagePaths = await newestFirst(await listCodexGeneratedImages(isolatedCodexHome));
|
|
590
1091
|
const selectedImagePaths = [];
|
|
@@ -596,8 +1097,9 @@ async function executeCodexImageGeneration(prompt, model, agent, opts = {}) {
|
|
|
596
1097
|
break;
|
|
597
1098
|
}
|
|
598
1099
|
if (selectedImagePaths.length < expectedImageCount) {
|
|
599
|
-
const lastMessage =
|
|
600
|
-
|
|
1100
|
+
const lastMessage = lastMessageContent.trim();
|
|
1101
|
+
const lastMessageNote = rawLastMessage === null ? ' Codex CLI did not write --output-last-message.' : '';
|
|
1102
|
+
throw new Error(`Codex image generation resolved ${selectedImagePaths.length} image artifact${selectedImagePaths.length === 1 ? '' : 's'}, expected ${expectedImageCount}.${lastMessageNote}${lastMessage ? ` Last message: ${lastMessage}` : ''}`);
|
|
601
1103
|
}
|
|
602
1104
|
const generatedImages = await readCodexImageFiles(selectedImagePaths);
|
|
603
1105
|
log_llm_response(loggedRequestId, {
|
|
@@ -606,7 +1108,8 @@ async function executeCodexImageGeneration(prompt, model, agent, opts = {}) {
|
|
|
606
1108
|
response_image_paths: responseImagePaths,
|
|
607
1109
|
output_image_paths: outputImagePaths,
|
|
608
1110
|
codex_home_image_paths: generatedImagePaths,
|
|
609
|
-
last_message:
|
|
1111
|
+
last_message: lastMessageContent.trim(),
|
|
1112
|
+
last_message_missing: rawLastMessage === null,
|
|
610
1113
|
codex_exec: codexExecDiagnostics,
|
|
611
1114
|
});
|
|
612
1115
|
costTracker.addUsage({
|
|
@@ -646,6 +1149,16 @@ export class CodexProvider extends BaseModelProvider {
|
|
|
646
1149
|
}
|
|
647
1150
|
async *createResponseStream(messages, model, agent, requestId) {
|
|
648
1151
|
try {
|
|
1152
|
+
const { getToolsFromAgent } = await import('../utils/agent.js');
|
|
1153
|
+
const tools = agent ? await getToolsFromAgent(agent) : [];
|
|
1154
|
+
if (tools.length > 0) {
|
|
1155
|
+
if (getCodexProviderSettings(agent.modelSettings)?.codex_tool_transport === 'filesystem') {
|
|
1156
|
+
yield* executeCodexFilesystemToolRequest(messages, model, agent, tools, requestId);
|
|
1157
|
+
return;
|
|
1158
|
+
}
|
|
1159
|
+
yield* executeCodexToolRequest(messages, model, agent, tools, requestId);
|
|
1160
|
+
return;
|
|
1161
|
+
}
|
|
649
1162
|
const content = await executeCodexRequest(messages, model, agent, requestId);
|
|
650
1163
|
const messageId = `codex-${Date.now()}`;
|
|
651
1164
|
if (content) {
|