orquesta-agent 0.2.295 → 0.2.297

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 (42) hide show
  1. package/dist/cli-auth-detect.d.ts.map +1 -1
  2. package/dist/cli-auth-detect.js +3 -1
  3. package/dist/cli-auth-detect.js.map +1 -1
  4. package/dist/engine-stream.d.ts +8 -0
  5. package/dist/engine-stream.d.ts.map +1 -0
  6. package/dist/engine-stream.js +114 -0
  7. package/dist/engine-stream.js.map +1 -0
  8. package/dist/executor.d.ts +24 -4
  9. package/dist/executor.d.ts.map +1 -1
  10. package/dist/executor.js +246 -52
  11. package/dist/executor.js.map +1 -1
  12. package/dist/index.js +18 -8
  13. package/dist/index.js.map +1 -1
  14. package/dist/sandbox.d.ts.map +1 -1
  15. package/dist/sandbox.js +4 -0
  16. package/dist/sandbox.js.map +1 -1
  17. package/dist/stream-engine.d.ts +4 -4
  18. package/dist/stream-engine.d.ts.map +1 -1
  19. package/dist/stream-engine.js +4 -3
  20. package/dist/stream-engine.js.map +1 -1
  21. package/dist/supabase.d.ts +18 -8
  22. package/dist/supabase.d.ts.map +1 -1
  23. package/dist/supabase.js +31 -1
  24. package/dist/supabase.js.map +1 -1
  25. package/dist/ui/manager.js +1 -1
  26. package/dist/ui/manager.js.map +1 -1
  27. package/dist/ui/onboarding.js +1 -1
  28. package/dist/ui/onboarding.js.map +1 -1
  29. package/dist/ui/public/app.js +4 -0
  30. package/dist/ui/public/index.html +2 -0
  31. package/dist/ui/public/style.css +2 -0
  32. package/dist/ui/public/welcome.html +4 -0
  33. package/dist/ui/server.d.ts +1 -1
  34. package/dist/ui/server.d.ts.map +1 -1
  35. package/dist/ui/server.js +2 -2
  36. package/dist/ui/server.js.map +1 -1
  37. package/dist/ui/types.d.ts +1 -1
  38. package/dist/ui/types.d.ts.map +1 -1
  39. package/dist/ws-client.d.ts +1 -1
  40. package/dist/ws-client.d.ts.map +1 -1
  41. package/package.json +1 -1
  42. package/scripts/build-binaries.sh +5 -9
package/dist/executor.js CHANGED
@@ -137,6 +137,7 @@ import { uploadPromptArtifacts } from './artifacts.js';
137
137
  import { autostashConflicted, buildPullArgs, classifyPullFailure, describePullFailure, PullFailureLedger } from './auto-pull.js';
138
138
  import { usageFromResultEvent } from './claude-usage.js';
139
139
  import { streamEngine, engineFlags } from './stream-engine.js';
140
+ import { jsonlTranslator } from './engine-stream.js';
140
141
  import { startTranscriptTail, readTranscriptHistory, claudeChatSessionMode } from './claude-transcript.js';
141
142
  import { createThinkingLog, createToolCallLog, createToolResultLog, createOutputLog, createErrorLog, createSystemLog, createProgressLog, } from './types/agent-logs.js';
142
143
  /**
@@ -1293,6 +1294,109 @@ export function checkKiroAuth() {
1293
1294
  return cache({ available: true, authenticated: true, method: null });
1294
1295
  }
1295
1296
  }
1297
+ // Codex (`@openai/codex`) and Gemini CLI (`@google/gemini-cli`) are npm globals,
1298
+ // so the usual miss is a daemon whose PATH lacks the nvm bin dir. Node's own bin
1299
+ // dir covers that case. Order: <ENV>_PATH → on PATH → node's bin dir →
1300
+ // ~/.npm-global/bin → ~/.local/bin.
1301
+ const npmCliCache = new Map();
1302
+ function resolveNpmCli(name, envVar) {
1303
+ const now = Date.now();
1304
+ const cached = npmCliCache.get(name);
1305
+ if (cached && cacheFresh(cached, cached.path !== null, now))
1306
+ return cached.path;
1307
+ let resolved = null;
1308
+ const envPath = process.env[envVar];
1309
+ if (envPath) {
1310
+ try {
1311
+ fs.accessSync(envPath, fs.constants.X_OK);
1312
+ resolved = envPath;
1313
+ }
1314
+ catch { /* bad override */ }
1315
+ }
1316
+ if (!resolved) {
1317
+ try {
1318
+ execSync(`${name} --version`, { stdio: 'pipe', timeout: 15000 });
1319
+ resolved = name;
1320
+ }
1321
+ catch { /* not on PATH */ }
1322
+ }
1323
+ if (!resolved && process.platform !== 'win32') {
1324
+ const dirs = [path.dirname(process.execPath), path.join(os.homedir(), '.npm-global', 'bin'), path.join(os.homedir(), '.local', 'bin')];
1325
+ for (const dir of dirs) {
1326
+ const candidate = path.join(dir, name);
1327
+ try {
1328
+ fs.accessSync(candidate, fs.constants.X_OK);
1329
+ resolved = candidate;
1330
+ break;
1331
+ }
1332
+ catch { /* not installed there */ }
1333
+ }
1334
+ }
1335
+ npmCliCache.set(name, { path: resolved, at: now });
1336
+ return resolved;
1337
+ }
1338
+ export function resolveCodexBinary() {
1339
+ return resolveNpmCli('codex', 'CODEX_CLI_PATH');
1340
+ }
1341
+ export function isCodexCliAvailable() {
1342
+ return resolveCodexBinary() !== null;
1343
+ }
1344
+ export function resolveGeminiBinary() {
1345
+ return resolveNpmCli('gemini', 'GEMINI_CLI_PATH');
1346
+ }
1347
+ export function isGeminiCliAvailable() {
1348
+ return resolveGeminiBinary() !== null;
1349
+ }
1350
+ // Is codex LOGGED IN? `codex login status` says so for ChatGPT and API-key
1351
+ // logins alike. Same contract as checkKiroAuth: only the logged-out wording
1352
+ // flips the flag. An expired ChatGPT session still reads as logged in here; the
1353
+ // run itself then fails with "sign in again".
1354
+ let codexAuthCache = null;
1355
+ export function checkCodexAuth() {
1356
+ const now = Date.now();
1357
+ if (codexAuthCache && now - codexAuthCache.at < CLI_DETECTION_TTL_MS)
1358
+ return codexAuthCache.result;
1359
+ const cache = (result) => {
1360
+ codexAuthCache = { result, at: now };
1361
+ return result;
1362
+ };
1363
+ const binary = resolveCodexBinary();
1364
+ if (!binary)
1365
+ return cache({ available: false, authenticated: false, method: null });
1366
+ try {
1367
+ const out = execSync(`"${binary}" login status 2>&1`, { stdio: ['ignore', 'pipe', 'pipe'], timeout: 15000, encoding: 'utf-8' });
1368
+ if (isLoggedOutMessage(out))
1369
+ return cache({ available: true, authenticated: false, method: null });
1370
+ return cache({ available: true, authenticated: true, method: /api key/i.test(out) ? 'api_key' : 'subscription' });
1371
+ }
1372
+ catch (error) {
1373
+ const err = error;
1374
+ const combined = `${err.stdout ?? ''}${err.stderr ?? ''}`;
1375
+ if (isLoggedOutMessage(combined))
1376
+ return cache({ available: true, authenticated: false, method: null });
1377
+ return cache({ available: true, authenticated: true, method: null });
1378
+ }
1379
+ }
1380
+ // Gemini CLI has no status command, so login is read from where it can come
1381
+ // from: a key in the environment, a cached Google login, or an auth type chosen
1382
+ // in settings (Vertex AI, for one, keeps no file of its own). Files are only
1383
+ // tested for existence; nothing reads a credential.
1384
+ export function checkGeminiAuth() {
1385
+ if (!isGeminiCliAvailable())
1386
+ return { available: false, authenticated: false, method: null };
1387
+ if (process.env.GEMINI_API_KEY || process.env.GOOGLE_API_KEY)
1388
+ return { available: true, authenticated: true, method: 'api_key' };
1389
+ const dir = path.join(os.homedir(), '.gemini');
1390
+ if (fs.existsSync(path.join(dir, 'oauth_creds.json')))
1391
+ return { available: true, authenticated: true, method: 'subscription' };
1392
+ try {
1393
+ const settings = fs.readFileSync(path.join(dir, 'settings.json'), 'utf-8');
1394
+ if (/"selectedType"\s*:\s*"[^"]+"/.test(settings))
1395
+ return { available: true, authenticated: true, method: null };
1396
+ }
1397
+ catch { /* no settings yet */ }
1398
+ return { available: true, authenticated: false, method: null };
1399
+ }
1296
1400
  // Dedupe the fallback warning: selectCli() runs on every heartbeat (the agent
1297
1401
  // reports activeCli), so logging unconditionally spammed thousands of identical
1298
1402
  // WARN lines. Only log when the message actually changes.
@@ -1303,22 +1407,40 @@ function warnCliOnce(msg) {
1303
1407
  lastCliWarn = msg;
1304
1408
  logger.warn(msg);
1305
1409
  }
1410
+ // These CLIs have no system-prompt flag, so the capabilities block stays inline.
1411
+ const NO_SYSTEM_PROMPT_FLAG = ['kimi', 'cursor', 'kiro', 'codex', 'gemini'];
1412
+ // Env each engine needs through strict sandbox's allowlist. Per engine, so a
1413
+ // run of another CLI does not get to read these keys.
1414
+ const ENGINE_ENV = {
1415
+ codex: ['OPENAI_API_KEY', 'CODEX_API_KEY', 'CODEX_HOME'],
1416
+ gemini: ['GEMINI_API_KEY', 'GOOGLE_API_KEY', 'GOOGLE_CLOUD_PROJECT', 'GOOGLE_CLOUD_LOCATION', 'GOOGLE_GENAI_USE_VERTEXAI', 'GEMINI_CLI_TRUST_WORKSPACE'],
1417
+ };
1418
+ // Gemini CLI exits 55 in a folder it has not been told to trust, and the agent
1419
+ // runs unattended in a folder the project owner already chose. The env var
1420
+ // exists on every version; --skip-trust does not.
1421
+ function applyEngineEnv(env, cli) {
1422
+ if (cli === 'gemini')
1423
+ env.GEMINI_CLI_TRUST_WORKSPACE = 'true';
1424
+ }
1306
1425
  // Preference order when nothing is pinned, and the order a fallback walks when
1307
1426
  // the pinned CLI turns out not to be installed. Table-driven rather than a nest
1308
1427
  // of pairwise ifs: every CLI added here otherwise costs another N branches, and
1309
1428
  // the pair that got missed is exactly how a preference silently no-ops.
1310
- const CLI_AUTO_ORDER = ['orquesta', 'claude', 'kimi', 'cursor', 'kiro'];
1429
+ const CLI_AUTO_ORDER = ['orquesta', 'claude', 'kimi', 'cursor', 'kiro', 'codex', 'gemini'];
1311
1430
  const CLI_AUTO_REASON = {
1312
1431
  orquesta: 'Auto: orquesta available (local LLM)',
1313
1432
  claude: 'Auto: claude available (Anthropic API)',
1314
1433
  kimi: 'Auto: kimi available',
1315
1434
  cursor: 'Auto: cursor-agent available',
1316
1435
  kiro: 'Auto: kiro-cli available',
1436
+ codex: 'Auto: codex available',
1437
+ gemini: 'Auto: gemini available',
1317
1438
  };
1318
1439
  /** Forget every cached detection, hit or miss. */
1319
1440
  export function resetCliDetectionCache() {
1320
1441
  orquestaCliCache = claudeCliCache = kimiCliCache = null;
1321
1442
  claudeBinaryCache = kimiBinaryCache = cursorBinaryCache = kiroBinaryCache = null;
1443
+ npmCliCache.clear();
1322
1444
  }
1323
1445
  // Select which CLI to use based on availability and preference
1324
1446
  export function selectCli() {
@@ -1328,6 +1450,8 @@ export function selectCli() {
1328
1450
  kimi: isKimiCliAvailable(),
1329
1451
  cursor: isCursorCliAvailable(),
1330
1452
  kiro: isKiroCliAvailable(),
1453
+ codex: isCodexCliAvailable(),
1454
+ gemini: isGeminiCliAvailable(),
1331
1455
  };
1332
1456
  if (!CLI_AUTO_ORDER.some(cli => available[cli])) {
1333
1457
  return { cli: null, reason: `No CLI found (${CLI_AUTO_ORDER.join(', ')})` };
@@ -1708,6 +1832,9 @@ const ARTIFACT_EXTS = new Set([
1708
1832
  '.zip', '.tar', '.gz', '.tgz',
1709
1833
  '.mp4', '.mov', '.webm', '.mp3', '.wav',
1710
1834
  ]);
1835
+ // A page can be a deliverable (a deck, a report) or just the project's source,
1836
+ // so these publish only when the run CREATED the file, never when it edited one.
1837
+ const NEW_ONLY_ARTIFACT_EXTS = new Set(['.html', '.htm']);
1711
1838
  // Directories never worth scanning (deps, build output, VCS internals).
1712
1839
  const ARTIFACT_SKIP_DIRS = new Set([
1713
1840
  'node_modules', '.git', '.next', 'dist', 'build', 'out', 'coverage',
@@ -1715,6 +1842,16 @@ const ARTIFACT_SKIP_DIRS = new Set([
1715
1842
  ]);
1716
1843
  const MAX_ARTIFACT_UPLOADS = 8;
1717
1844
  const MAX_ARTIFACT_SIZE = 20 * 1024 * 1024;
1845
+ /** Whether a file found in the working directory counts as this run's output. */
1846
+ export function isRunOutput(name, stat, sinceMs) {
1847
+ if (stat.mtimeMs < sinceMs || stat.size <= 0 || stat.size > MAX_ARTIFACT_SIZE)
1848
+ return false;
1849
+ const ext = path.extname(name).toLowerCase();
1850
+ if (ARTIFACT_EXTS.has(ext))
1851
+ return true;
1852
+ // birthtimeMs is 0 where the filesystem does not record it; publish rather than lose a deliverable.
1853
+ return NEW_ONLY_ARTIFACT_EXTS.has(ext) && (stat.birthtimeMs === 0 || stat.birthtimeMs >= sinceMs);
1854
+ }
1718
1855
  /**
1719
1856
  * After a successful run, find asset/document files that were created or
1720
1857
  * modified in the working directory DURING this run and publish each to the
@@ -1749,14 +1886,10 @@ async function autoPublishGeneratedArtifacts(cwd, promptId, sinceMs, report) {
1749
1886
  walk(full, depth + 1);
1750
1887
  }
1751
1888
  else if (entry.isFile()) {
1752
- const ext = path.extname(entry.name).toLowerCase();
1753
- if (!ARTIFACT_EXTS.has(ext))
1754
- continue;
1755
1889
  try {
1756
1890
  const stat = fs.statSync(full);
1757
- if (stat.mtimeMs >= sinceMs && stat.size > 0 && stat.size <= MAX_ARTIFACT_SIZE) {
1891
+ if (isRunOutput(entry.name, stat, sinceMs))
1758
1892
  found.push({ path: full, size: stat.size });
1759
- }
1760
1893
  }
1761
1894
  catch { /* unreadable — skip */ }
1762
1895
  }
@@ -2282,10 +2415,10 @@ Wake up a peer agent that isn't currently listening on a channel (sends a "rejoi
2282
2415
  curl -sS -X POST "$ORQUESTA_API_URL/api/agent/coordination/ping" -H "Authorization: Bearer $ORQUESTA_TOKEN" -H "Content-Type: application/json" -d '{"channel_id":"<uuid>"}'
2283
2416
  Use this when the user asks to "ping" / "wake up" / "ask" another agent. The peer's Claude session will spin up, re-join the channel, and start listening — then you can send messages with the channel's send curl.
2284
2417
 
2285
- Publish a generated file (doc, image, chart, log) to the project's Files panel so the human can see and download it:
2418
+ Publish a generated file (doc, page, image, chart, log) to the project's Files panel so the human can see and open it:
2286
2419
  curl -sS -X POST "$ORQUESTA_API_URL/api/agent/files" -H "Authorization: Bearer $ORQUESTA_TOKEN" -F "file=@/abs/path/to/output.png" -F "prompt_id=$ORQUESTA_PROMPT_ID"
2287
- Returns { attachment: { id, file_url, ... } }. Max 20 MB. \`prompt_id\` is optional but recommended (links the file back to the prompt that produced it). For one-shot prompts \$ORQUESTA_PROMPT_ID is in your env.
2288
- NOTE: document/asset files you WRITE into the working directory (images, pdf, office docs, csv, archives, media) are auto-published to the Files panel when the run finishes — you do NOT need to curl those. Use this endpoint only for files OUTSIDE the working directory, or non-asset outputs (e.g. a generated Markdown report) you still want the operator to download.
2420
+ Returns { attachment: { id, file_url, ... } }. Your final reply must include that file_url as a link: it is how the person opens the file. Max 20 MB. \`prompt_id\` is optional but recommended (links the file back to the prompt that produced it). For one-shot prompts \$ORQUESTA_PROMPT_ID is in your env.
2421
+ NOTE: document/asset files you WRITE into the working directory (images, pdf, office docs, csv, archives, media) and HTML pages you CREATE are auto-published to the Files panel when the run finishes — you do NOT need to curl those. A committed file is not delivered: to hand over an EDITED HTML page, curl it and give the link. Use this endpoint only for files OUTSIDE the working directory, or non-asset outputs (e.g. a generated Markdown report) you still want the operator to download.
2289
2422
 
2290
2423
  Ask another project's agent in your organization (only when the CURRENT request needs something another project owns):
2291
2424
  curl -s "$ORQUESTA_API_URL/api/agent/directory" -H "Authorization: Bearer $ORQUESTA_TOKEN"
@@ -2638,6 +2771,7 @@ ${userRequestBody}`;
2638
2771
  const installed = {
2639
2772
  orquesta: isOrquestaCliAvailable, claude: isClaudeCliAvailable, kimi: isKimiCliAvailable,
2640
2773
  cursor: isCursorCliAvailable, kiro: isKiroCliAvailable,
2774
+ codex: isCodexCliAvailable, gemini: isGeminiCliAvailable,
2641
2775
  };
2642
2776
  if (installed[engine.cli]()) {
2643
2777
  selectedCli = engine.cli;
@@ -2693,9 +2827,13 @@ ${userRequestBody}`;
2693
2827
  ? (resolveCursorBinary() || 'cursor-agent')
2694
2828
  : cliCommand === 'kiro'
2695
2829
  ? (resolveKiroBinary() || 'kiro-cli')
2696
- : cliCommand === 'claude'
2697
- ? (resolveClaudeBinary() || 'claude')
2698
- : (cliCommand || 'claude');
2830
+ : cliCommand === 'codex'
2831
+ ? (resolveCodexBinary() || 'codex')
2832
+ : cliCommand === 'gemini'
2833
+ ? (resolveGeminiBinary() || 'gemini')
2834
+ : cliCommand === 'claude'
2835
+ ? (resolveClaudeBinary() || 'claude')
2836
+ : (cliCommand || 'claude');
2699
2837
  const cwd = workingDirectory || process.cwd();
2700
2838
  // Which branch this prompt runs on — captured up front so it's persisted even
2701
2839
  // if the run fails, and broadcast live below once sendSpecialEvent exists.
@@ -2707,7 +2845,11 @@ ${userRequestBody}`;
2707
2845
  let detectedCommitSha = null;
2708
2846
  let detectedCommitUrl = null;
2709
2847
  logger.info(`CLI Selection: ${cliCommand} (${reason})`);
2710
- logger.info(`Spawning: ${cliBinary} ${cliCommand === 'kiro' ? 'chat' : '-p'} "${fullContent.slice(0, 50)}..." in ${cwd}${currentBranch ? ` on branch ${currentBranch}` : ''}`);
2848
+ applyEngineEnv(env, cliCommand);
2849
+ // kiro-cli and codex take the prompt as a subcommand's positional arg; the
2850
+ // others as the value of -p.
2851
+ const promptVerb = cliCommand === 'kiro' ? 'chat' : cliCommand === 'codex' ? 'exec' : '-p';
2852
+ logger.info(`Spawning: ${cliBinary} ${promptVerb} "${fullContent.slice(0, 50)}..." in ${cwd}${currentBranch ? ` on branch ${currentBranch}` : ''}`);
2711
2853
  // Hoist the static block into the CLI system prompt (claude/orquesta support
2712
2854
  // --append-system-prompt-file; kimi has no such flag and stays inline). On any
2713
2855
  // write failure we fall back to the inline fullContent, so a dispatched prompt
@@ -2723,9 +2865,9 @@ ${userRequestBody}`;
2723
2865
  const inlineContent = session.useMessage ? `${staticSystemBlock}\n\n[User Request]\n${requestBody}` : fullContent;
2724
2866
  let promptContent = inlineContent;
2725
2867
  let sysPromptFilePath = null;
2726
- // kimi, cursor-agent and kiro-cli have no --append-system-prompt-file, so
2727
- // their static context stays inline in the prompt.
2728
- if (cliCommand !== 'kimi' && cliCommand !== 'cursor' && cliCommand !== 'kiro') {
2868
+ // kimi, cursor-agent, kiro-cli, codex and gemini have no
2869
+ // --append-system-prompt-file, so their static context stays inline.
2870
+ if (!NO_SYSTEM_PROMPT_FLAG.includes(cliCommand)) {
2729
2871
  try {
2730
2872
  const promptDir = process.platform === 'win32'
2731
2873
  ? os.tmpdir()
@@ -2763,13 +2905,18 @@ ${userRequestBody}`;
2763
2905
  // --no-interactive answers once and exits, --wrap
2764
2906
  // never stops it re-flowing the answer to the
2765
2907
  // (absent) terminal width.
2766
- : cliCommand === 'kimi'
2767
- ? '--output-format text' // Kimi: plain text. NOTE: -p (one-shot) CANNOT be
2768
- // combined with -y ("Cannot combine --prompt with
2769
- // --yolo"), so dispatched kimi prompts respond as
2770
- // chat (no autonomous tool use). Interactive kimi
2771
- // sessions DO get -y (see ptyArgs below).
2772
- : '--verbose --output-format stream-json'; // Claude: stream-json format
2908
+ : cliCommand === 'codex'
2909
+ ? '--json --skip-git-repo-check' // Codex: JSONL, see engine-stream.ts. A
2910
+ // project folder need not be a git repo.
2911
+ : cliCommand === 'gemini'
2912
+ ? '--output-format stream-json' // Gemini: JSONL, see engine-stream.ts.
2913
+ : cliCommand === 'kimi'
2914
+ ? '--output-format text' // Kimi: plain text. NOTE: -p (one-shot) CANNOT be
2915
+ // combined with -y ("Cannot combine --prompt with
2916
+ // --yolo"), so dispatched kimi prompts respond as
2917
+ // chat (no autonomous tool use). Interactive kimi
2918
+ // sessions DO get -y (see ptyArgs below).
2919
+ : '--verbose --output-format stream-json'; // Claude: stream-json format
2773
2920
  // Kimi has no --dangerously-skip-permissions, and -p forbids -y. Cursor spells
2774
2921
  // the same thing --force (alias --yolo); kiro spells it --trust-all-tools.
2775
2922
  let readOnlySettingsPath = null;
@@ -2790,14 +2937,18 @@ ${userRequestBody}`;
2790
2937
  ? '--force'
2791
2938
  : cliCommand === 'kiro'
2792
2939
  ? '--trust-all-tools'
2793
- : '--dangerously-skip-permissions';
2940
+ : cliCommand === 'codex'
2941
+ ? '--dangerously-bypass-approvals-and-sandbox'
2942
+ : cliCommand === 'gemini'
2943
+ ? '--yolo'
2944
+ : '--dangerously-skip-permissions';
2794
2945
  // Per-project endpoint override (orquesta CLI only). Single-quoted for the
2795
2946
  // shell-wrapped (Linux) path; pushed as a separate arg on Win/macOS below.
2796
- const { claudeModel, endpoint: effectiveEndpoint } = engineFlags(cliCommand, engine, globalCliEndpoint);
2947
+ const { cliModel, endpoint: effectiveEndpoint } = engineFlags(cliCommand, engine, globalCliEndpoint);
2797
2948
  const useEndpoint = !!effectiveEndpoint;
2798
2949
  const endpointFlag = useEndpoint ? `--endpoint '${effectiveEndpoint.replace(/'/g, "'\\''")}'` : '';
2799
- // Workstream model pin for claude (stream-engine.ts validated the charset).
2800
- const modelFlag = claudeModel ? `--model '${claudeModel}'` : '';
2950
+ // Workstream model pin (stream-engine.ts validated the charset).
2951
+ const modelFlag = cliModel ? `--model '${cliModel}'` : '';
2801
2952
  // Static context hoisted to the CLI system prompt (Linux shell-string form).
2802
2953
  const sysPromptFlag = sysPromptFilePath
2803
2954
  ? `--append-system-prompt-file '${sysPromptFilePath.replace(/'/g, "'\\''")}'`
@@ -2807,7 +2958,6 @@ ${userRequestBody}`;
2807
2958
  // paths so Claude's Read tool can pick them up.
2808
2959
  // kiro-cli has no `-p`: the one-shot form is `kiro-cli chat "<prompt>"` with
2809
2960
  // --no-interactive (baseFlags), the prompt as the verb's positional arg.
2810
- const promptVerb = cliCommand === 'kiro' ? 'chat' : '-p';
2811
2961
  const sessionFlag = session.args.join(' ');
2812
2962
  command = `${cliBinary} ${promptVerb} '${escapedContent}' ${permFlags} ${baseFlags} ${endpointFlag} ${modelFlag} ${sysPromptFlag} ${sessionFlag}`;
2813
2963
  if (imageReferences.length > 0) {
@@ -2822,7 +2972,8 @@ ${userRequestBody}`;
2822
2972
  const isDarwin = process.platform === 'darwin';
2823
2973
  let claude;
2824
2974
  if (isWindows || isDarwin) {
2825
- const args = [promptVerb];
2975
+ // Gemini takes piped input only without -p: a bare -p is a usage error.
2976
+ const args = isWindows && cliCommand === 'gemini' ? [] : [promptVerb];
2826
2977
  // Windows cmd.exe caps the whole command line at ~8191 chars. The prompt is
2827
2978
  // prefixed with large context blocks (capabilities, project CLAUDE.md,
2828
2979
  // coordination…), so passing it as an argv overflows that limit and the CLI
@@ -2841,8 +2992,8 @@ ${userRequestBody}`;
2841
2992
  args.push(...baseFlags.split(/\s+/).filter(Boolean));
2842
2993
  if (useEndpoint)
2843
2994
  args.push('--endpoint', effectiveEndpoint);
2844
- if (claudeModel)
2845
- args.push('--model', claudeModel);
2995
+ if (cliModel)
2996
+ args.push('--model', cliModel);
2846
2997
  if (sysPromptArgs.length)
2847
2998
  args.push(...sysPromptArgs);
2848
2999
  if (session.args.length)
@@ -2860,6 +3011,12 @@ ${userRequestBody}`;
2860
3011
  }
2861
3012
  catch { /* stdin closed early — failure surfaces via exit code */ }
2862
3013
  }
3014
+ else if (cliCommand === 'codex' || cliCommand === 'gemini') {
3015
+ // Both append piped stdin to the prompt, so an open pipe never finishes:
3016
+ // `codex exec` sits on "Reading additional input from stdin..." for good.
3017
+ // Under Linux `script` stdin is a tty and neither waits.
3018
+ claude.stdin?.end();
3019
+ }
2863
3020
  }
2864
3021
  else {
2865
3022
  // Sandbox wraps the `script` invocation in bwrap when active (Linux only);
@@ -2870,7 +3027,7 @@ ${userRequestBody}`;
2870
3027
  }
2871
3028
  claude = spawn(spawnFile, spawnArgs, {
2872
3029
  cwd,
2873
- env: sandboxEnv(env),
3030
+ env: sandboxEnv(env, ENGINE_ENV[cliCommand ?? ''] ?? []),
2874
3031
  stdio: ['pipe', 'pipe', 'pipe'],
2875
3032
  });
2876
3033
  }
@@ -3260,13 +3417,18 @@ ${userRequestBody}`;
3260
3417
  }, 5000).unref?.();
3261
3418
  },
3262
3419
  });
3420
+ const translateJsonl = cliCommand === 'codex' || cliCommand === 'gemini' ? jsonlTranslator(cliCommand) : null;
3421
+ // Where stderr has its own pipe (macOS, Windows) the same chatter arrives here.
3422
+ const filterStderr = cliCommand === 'codex' || cliCommand === 'gemini' ? jsonlTranslator(cliCommand) : null;
3263
3423
  if (claude.stdout) {
3264
3424
  claude.stdout.on('data', (data) => {
3265
- const text = cliCommand === 'kimi'
3266
- ? cleanKimiText(data.toString())
3267
- : cliCommand === 'kiro'
3268
- ? cleanKiroText(data.toString())
3269
- : data.toString();
3425
+ const text = translateJsonl
3426
+ ? translateJsonl(data.toString())
3427
+ : cliCommand === 'kimi'
3428
+ ? cleanKimiText(data.toString())
3429
+ : cliCommand === 'kiro'
3430
+ ? cleanKiroText(data.toString())
3431
+ : data.toString();
3270
3432
  stallDetector.feed(data.toString());
3271
3433
  // Skip logging if it looks like base64/binary data (long strings without spaces)
3272
3434
  const preview = text.slice(0, 150);
@@ -3278,7 +3440,11 @@ ${userRequestBody}`;
3278
3440
  logger.debug(`[STDOUT] ${text.slice(0, 100)}`);
3279
3441
  }
3280
3442
  // Parse stream-json and send formatted output
3281
- const { output: parsed, hadValidJson, logs: structuredLogs, pendingLine } = parseStreamJson(text);
3443
+ // Translated output is already plain text. A line of it can be valid JSON
3444
+ // (a tool printing a config), which parseStreamJson would swallow.
3445
+ const { output: parsed, hadValidJson, logs: structuredLogs, pendingLine } = translateJsonl
3446
+ ? { output: text, hadValidJson: false, logs: [], pendingLine: '' }
3447
+ : parseStreamJson(text);
3282
3448
  // Only fallback to raw text if it wasn't valid JSON
3283
3449
  // If it was valid JSON but produced no output (e.g., system init), don't send anything
3284
3450
  const outputToSend = hadValidJson ? parsed : rawChunkOutput(text, parsed, pendingLine);
@@ -3396,7 +3562,7 @@ ${userRequestBody}`;
3396
3562
  claude.stderr.on('data', (data) => {
3397
3563
  const raw = data.toString();
3398
3564
  stallDetector.feed(raw);
3399
- const text = stripAnsiCodes(raw);
3565
+ const text = filterStderr ? filterStderr(raw) : stripAnsiCodes(raw);
3400
3566
  if (!text.trim())
3401
3567
  return;
3402
3568
  noteRawOutput(text);
@@ -3566,7 +3732,11 @@ ${userRequestBody}`;
3566
3732
  ? 'cursor-cli'
3567
3733
  : cliCommand === 'kiro'
3568
3734
  ? 'kiro-cli'
3569
- : 'claude-cli';
3735
+ : cliCommand === 'codex'
3736
+ ? 'codex-cli'
3737
+ : cliCommand === 'gemini'
3738
+ ? 'gemini-cli'
3739
+ : 'claude-cli';
3570
3740
  let modelForDb;
3571
3741
  if (cliCommand === 'kimi')
3572
3742
  modelForDb = 'kimi-for-coding';
@@ -3578,7 +3748,9 @@ ${userRequestBody}`;
3578
3748
  else if (cliCommand === 'orquesta')
3579
3749
  modelForDb = (effectiveEndpoint === 'batuta' || !effectiveEndpoint) ? 'batuta-auto' : effectiveEndpoint;
3580
3750
  else if (cliCommand === 'claude')
3581
- modelForDb = claudeModel || process.env.ANTHROPIC_MODEL || undefined;
3751
+ modelForDb = cliModel || process.env.ANTHROPIC_MODEL || undefined;
3752
+ else if (cliCommand === 'codex' || cliCommand === 'gemini')
3753
+ modelForDb = cliModel || undefined;
3582
3754
  updatePromptStatus(promptId, status, summary || undefined, Object.keys(usage).length > 0 ? usage : undefined, finalResult, { cliType: cliTypeForDb, model: modelForDb, gitBranch: currentBranch || undefined, gitCommitSha: detectedCommitSha || undefined, gitCommitUrl: detectedCommitUrl || undefined }).catch(err => {
3583
3755
  logger.error(`Failed to update prompt status: ${err}`);
3584
3756
  });
@@ -4470,10 +4642,14 @@ export async function startSession(options) {
4470
4642
  ? (resolveCursorBinary() || 'cursor-agent')
4471
4643
  : cliCommand === 'kiro'
4472
4644
  ? (resolveKiroBinary() || 'kiro-cli')
4473
- : cliCommand === 'claude'
4474
- ? (resolveClaudeBinary() || 'claude')
4475
- : cliCommand;
4476
- const resolvedByPath = cliCommand === 'kimi' || cliCommand === 'cursor' || cliCommand === 'kiro';
4645
+ : cliCommand === 'codex'
4646
+ ? (resolveCodexBinary() || 'codex')
4647
+ : cliCommand === 'gemini'
4648
+ ? (resolveGeminiBinary() || 'gemini')
4649
+ : cliCommand === 'claude'
4650
+ ? (resolveClaudeBinary() || 'claude')
4651
+ : cliCommand;
4652
+ const resolvedByPath = cliCommand !== 'claude' && cliCommand !== 'orquesta';
4477
4653
  logger.info(`Interactive session CLI: ${cliCommand}${resolvedByPath ? ` (${cliBinary})` : ''}`);
4478
4654
  // Best-effort model + cli label reported in session:started so the dashboard
4479
4655
  // can tag the interactive prompt (same mapping dispatched prompts use on
@@ -4481,8 +4657,8 @@ export async function startSession(options) {
4481
4657
  // back to ANTHROPIC_MODEL when set, else undefined.
4482
4658
  const sessionModel = cliCommand === 'kimi'
4483
4659
  ? 'kimi-for-coding'
4484
- : cliCommand === 'cursor' || cliCommand === 'kiro'
4485
- // cursor-agent / kiro-cli use whatever model the user selected in their own
4660
+ : cliCommand === 'cursor' || cliCommand === 'kiro' || cliCommand === 'codex' || cliCommand === 'gemini'
4661
+ // These use whatever model the user selected in their own
4486
4662
  // account; it isn't knowable from the PTY, so report nothing rather than lie.
4487
4663
  ? undefined
4488
4664
  : cliCommand === 'orquesta'
@@ -4492,12 +4668,15 @@ export async function startSession(options) {
4492
4668
  : cliCommand === 'kimi' ? 'kimi'
4493
4669
  : cliCommand === 'cursor' ? 'cursor'
4494
4670
  : cliCommand === 'kiro' ? 'kiro'
4495
- : 'claude';
4671
+ : cliCommand === 'codex' ? 'codex'
4672
+ : cliCommand === 'gemini' ? 'gemini'
4673
+ : 'claude';
4496
4674
  // Filter undefined env values — node-pty requires Record<string, string>.
4497
4675
  // In strict sandbox mode, sandboxEnv() first reduces to the allowlist so the
4498
4676
  // interactive CLI can't read unrelated host secrets from its own env.
4499
4677
  const ptyEnv = {};
4500
- for (const [key, val] of Object.entries(sandboxEnv(env))) {
4678
+ applyEngineEnv(env, cliCommand);
4679
+ for (const [key, val] of Object.entries(sandboxEnv(env, ENGINE_ENV[cliCommand ?? ''] ?? []))) {
4501
4680
  if (val !== undefined)
4502
4681
  ptyEnv[key] = val;
4503
4682
  }
@@ -4586,7 +4765,7 @@ export async function startSession(options) {
4586
4765
  // `ps aux`. Default-off because a file unreadable inside bwrap would silently
4587
4766
  // strip the system prompt (degraded session, not a crash) — flip the default
4588
4767
  // only after E2E confirms the sandbox reads it. Rollback = unset the var.
4589
- const wantSysPromptFile = cliCommand !== 'kimi' && cliCommand !== 'cursor' && cliCommand !== 'kiro' && ((process.platform === 'win32' && cliCommand === 'orquesta') ||
4768
+ const wantSysPromptFile = !NO_SYSTEM_PROMPT_FLAG.includes(cliCommand) && ((process.platform === 'win32' && cliCommand === 'orquesta') ||
4590
4769
  /^(1|true|yes|on)$/i.test(process.env.ORQUESTA_SYSPROMPT_FILE || ''));
4591
4770
  if (wantSysPromptFile) {
4592
4771
  try {
@@ -4620,6 +4799,21 @@ export async function startSession(options) {
4620
4799
  logger.info('[Session] Resuming most recent conversation in this directory (--resume) for kiro');
4621
4800
  }
4622
4801
  }
4802
+ else if (cliCommand === 'codex') {
4803
+ // Codex reads AGENTS.md, and `resume` is a subcommand, so resume flags go
4804
+ // here too: the generic unshift below would put them before nothing valid.
4805
+ const bypass = '--dangerously-bypass-approvals-and-sandbox';
4806
+ ptyArgs = resumeSessionId ? ['resume', resumeSessionId, bypass] : resume ? ['resume', '--last', bypass] : [bypass];
4807
+ logger.info(`[Session] Codex session${resumeSessionId || resume ? ' (resume)' : ''}`);
4808
+ }
4809
+ else if (cliCommand === 'gemini') {
4810
+ // Gemini reads GEMINI.md. --resume takes an id or "latest".
4811
+ ptyArgs = ['--yolo'];
4812
+ if (resumeSessionId)
4813
+ ptyArgs.push('--resume', resumeSessionId);
4814
+ else if (resume)
4815
+ ptyArgs.push('--resume', 'latest');
4816
+ }
4623
4817
  else if (cliCommand === 'cursor') {
4624
4818
  // cursor-agent has no --append-system-prompt; it reads AGENTS.md / CLAUDE.md
4625
4819
  // from the working dir (which the agent already syncs), so the capabilities
@@ -4643,7 +4837,7 @@ export async function startSession(options) {
4643
4837
  // cli.ts) both reattach the latest session non-interactively; kimi has no
4644
4838
  // resume flag, so the option is silently ignored there. Prepended so it's an
4645
4839
  // unambiguous standalone flag, separate from --append-system-prompt's value.
4646
- if ((resume || resumeSessionId) && cliCommand !== 'kimi' && cliCommand !== 'kiro') {
4840
+ if ((resume || resumeSessionId) && !['kimi', 'kiro', 'codex', 'gemini'].includes(cliCommand)) {
4647
4841
  // cursor-agent spells these the same way claude does (--continue / --resume <id>).
4648
4842
  // claude can target a SPECIFIC past conversation by id (--resume <id>);
4649
4843
  // orquesta-cli only reattaches the latest (--continue). So when a specific
@@ -4795,7 +4989,7 @@ export async function startSession(options) {
4795
4989
  rogerthatWatcher: null,
4796
4990
  transcriptTail: null,
4797
4991
  conversationId: claudeTranscriptId
4798
- ?? (resumeSessionId && (cliCommand === 'cursor' || cliCommand === 'kiro') ? resumeSessionId : null),
4992
+ ?? (resumeSessionId && ['cursor', 'kiro', 'codex', 'gemini'].includes(cliCommand) ? resumeSessionId : null),
4799
4993
  assisted,
4800
4994
  };
4801
4995
  sessions.set(sessionId, session);