@commonlyai/cli 0.1.278 → 0.1.280

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@commonlyai/cli",
3
- "version": "0.1.278",
3
+ "version": "0.1.280",
4
4
  "license": "Apache-2.0",
5
5
  "description": "The Commonly CLI — connect agents, manage pods, iterate fast",
6
6
  "type": "module",
@@ -135,7 +135,7 @@ import {
135
135
  refusedItemRef,
136
136
  sanitizeHandoffAgent,
137
137
  } from '../lib/content-refusal.js';
138
- import { CANT_ANSWER_NOTICE_WINDOW_MS, cantAnswerNotice } from '../lib/turn-failure-notice.js';
138
+ import { CANT_ANSWER_NOTICE_WINDOW_MS, CUT_OFF_NOTICE, cantAnswerNotice } from '../lib/turn-failure-notice.js';
139
139
  import {
140
140
  ADDRESSED_EVENT_TYPES,
141
141
  isPersonMention,
@@ -766,6 +766,46 @@ const someoneIsWaiting = (event) => ADDRESSED_EVENT_TYPES.has(event.type)
766
766
  || event.payload?.repliesToYourMessage === true
767
767
  || event.payload?.someoneWaiting === true;
768
768
 
769
+ // The first message in `messages` that this seat posted and `earlierIds` doesn't
770
+ // hold. The server stamps each message with `self` when it knows who is asking.
771
+ // Trust that over any local guess: the wrapper cannot derive its own bot username
772
+ // reliably (the server applies LEGACY_AGENT_MAP and an owner-scoped instanceId),
773
+ // and a wrong guess double-posts.
774
+ const findOwnPost = (messages, earlierIds) => {
775
+ const serverKnowsSelf = messages.some((m) => typeof m.self === 'boolean');
776
+ for (const m of messages) {
777
+ // A new human-authored message must NEVER count: it is either a human
778
+ // typing mid-turn, or the agent misusing an operator CLI profile / human
779
+ // token (the 2026-07-22 as-operator attribution incident) — in both cases
780
+ // the wrapper still delivers the reply under the agent's own identity.
781
+ //
782
+ // With `self`, only THIS agent's own post counts. Without it (an older
783
+ // server), fall back to the legacy any-bot test — which drops this agent's
784
+ // reply whenever another agent answers first (#757).
785
+ if (!earlierIds.has(String(m._id || m.id)) && m.isBot && (serverKnowsSelf ? m.self === true : true)) {
786
+ return {
787
+ id: String(m._id || m.id),
788
+ author: m.username || 'unknown',
789
+ basis: serverKnowsSelf ? 'self' : 'legacy-any-bot',
790
+ threadRootId: m.thread_root_id ?? null,
791
+ };
792
+ }
793
+ }
794
+ return null;
795
+ };
796
+
797
+ // This seat's newest post in `tail` that came after the last row `knownIds` holds,
798
+ // or null when that can't be shown. `knownIds` is a 10-message snapshot, so a row
799
+ // missing from it may only be older, and just "not in the set" would count an old
800
+ // post as new. With no known row in the tail, nothing marks where the turn began.
801
+ // An older server has no `self`, so a peer's post can't be told from this seat's.
802
+ const newestOwnPostSince = (tail, knownIds) => {
803
+ const lastKnown = tail.findLastIndex((m) => knownIds.has(String(m._id || m.id)));
804
+ if (lastKnown === -1) return null;
805
+ const ownPost = findOwnPost(tail.slice(lastKnown + 1).reverse(), knownIds);
806
+ return ownPost?.basis === 'self' ? ownPost : null;
807
+ };
808
+
769
809
  // How long a fresh seat's greeting waits for a person before it runs alone.
770
810
  // One poll lost the race on the 0.1.257 walk (2026-11-05): the mention landed
771
811
  // just after the hold, the greeting took the next turn alone, and the answer
@@ -2480,6 +2520,7 @@ export const performRun = ({
2480
2520
  return await runTurnBody({ ...args, turn });
2481
2521
  } catch (error) {
2482
2522
  turn.finish('reply_lost');
2523
+ failedTurn = args;
2483
2524
  // codex and claude both keep a refused prompt in the thread, and send it
2484
2525
  // again on every resume (measured 2026-11-05 on codex 0.162.1 and claude
2485
2526
  // 2.1.318), so one refusal would refuse every later turn in this pod. The
@@ -2560,6 +2601,60 @@ export const performRun = ({
2560
2601
  }
2561
2602
  };
2562
2603
 
2604
+ // F256: a turn that threw after it posted, whose event the server no longer
2605
+ // holds. The usual way there is a child that checkpointed after part one of an
2606
+ // answer and was then killed, so nothing will retry it and the person holds a
2607
+ // promise of more. Only `lostEvents` reach here, so a turn that ended cleanly
2608
+ // never does, and neither does one whose event is retried or handed back.
2609
+ // No window of its own: an event is lost once, and in a shared pod the server's
2610
+ // duplicate guard already bounds a fixed line to one per 30 minutes.
2611
+ // A turn only agents woke gets no line: "ask me again" isn't for them, and in
2612
+ // an agent-dm the line would wake the peer into a paid turn.
2613
+ const noticeCutOff = async (lostEvents) => {
2614
+ const turnArgs = failedTurn;
2615
+ failedTurn = null;
2616
+ const waiting = lostEvents.filter((event) => event.deliveryMode !== 'digest'
2617
+ && (someoneIsWaiting(event) || PERSON_WAITING_EVENT_TYPES.has(event.type)));
2618
+ if (!turnArgs || turnArgs.trigger === 'agent' || waiting.length === 0) return;
2619
+ const { eventPodId } = turnArgs;
2620
+ const target = commentTargetOf(waiting[0]);
2621
+ try {
2622
+ let delivery;
2623
+ if (target) {
2624
+ // The only comment read is capped and carries no `self` stamp, so it can't
2625
+ // prove this seat replied, and this has no own-post check.
2626
+ // It stands on the prompt instead: a person's direct @ isn't offered
2627
+ // silence, so their item checkpoints only after a reply. That holds only
2628
+ // for a known person, which an 'unknown' comment isn't.
2629
+ if (turnArgs.trigger !== 'human') return;
2630
+ delivery = await deliverCommentReply({
2631
+ client, ...target, text: CUT_OFF_NOTICE, onlyIfUnanswered: false,
2632
+ });
2633
+ } else {
2634
+ const tail = turnArgs.preSpawnIds ? await turnArgs.snapshotMessages(50) : null;
2635
+ // Nothing of this seat's in the pod means no half answer to explain: a
2636
+ // deliberate silence checkpoints too, and a requeue takes a row as well.
2637
+ const ownPost = tail && newestOwnPostSince(tail, turnArgs.preSpawnIds);
2638
+ if (!ownPost) return;
2639
+ delivery = await deliverChatReply({
2640
+ client,
2641
+ podId: eventPodId,
2642
+ text: CUT_OFF_NOTICE,
2643
+ limit: chatCharLimit,
2644
+ maxChunks: maxChatChunks,
2645
+ threadRootId: ownPost.threadRootId === null ? null : String(ownPost.threadRootId),
2646
+ log: (line) => log(`[inbox.batch] ${line}`),
2647
+ });
2648
+ }
2649
+ if (delivery.skipped || delivery.refused) {
2650
+ log(`[inbox.batch] pod ${eventPodId} was not told this agent was cut off: `
2651
+ + `${delivery.reason || 'the notice was not posted'}`);
2652
+ } else log(`[inbox.batch] told pod ${eventPodId} this agent was cut off before it finished`);
2653
+ } catch (noticeError) {
2654
+ log(`[inbox.batch] pod ${eventPodId} was not told this agent was cut off: ${noticeError.message}`);
2655
+ }
2656
+ };
2657
+
2563
2658
  const runTurnBody = async ({
2564
2659
  event, eventPodId, prompt, preSpawnIds, snapshotMessages, claimKeeper, trigger, turn,
2565
2660
  }) => {
@@ -2901,32 +2996,8 @@ export const performRun = ({
2901
2996
  if (preSpawnIds) {
2902
2997
  const postSpawn = await snapshotMessages();
2903
2998
  if (postSpawn) {
2904
- // The server stamps each message with `self` when it knows who is
2905
- // asking. Trust that over any local guess: the wrapper cannot derive
2906
- // its own bot username reliably (the server applies LEGACY_AGENT_MAP
2907
- // and an owner-scoped instanceId), and a wrong guess double-posts.
2908
- const serverKnowsSelf = postSpawn.some((m) => typeof m.self === 'boolean');
2909
- for (const m of postSpawn) {
2910
- if (preSpawnIds.has(String(m._id || m.id))) continue;
2911
- // A new human-authored message must NEVER suppress the echo: it is
2912
- // either a human typing mid-turn, or the agent misusing an operator
2913
- // CLI profile / human token (the 2026-07-22 as-operator attribution
2914
- // incident) — in both cases the wrapper still delivers the reply
2915
- // under the agent's own identity.
2916
- if (!m.isBot) continue;
2917
- // With `self`, only THIS agent's own post suppresses. Without it (an
2918
- // older server), fall back to the legacy any-bot test — which drops
2919
- // this agent's reply whenever another agent answers first (#757).
2920
- if (serverKnowsSelf ? m.self === true : true) {
2921
- agentPostedItself = true;
2922
- suppressedBy = {
2923
- id: String(m._id || m.id),
2924
- author: m.username || 'unknown',
2925
- basis: serverKnowsSelf ? 'self' : 'legacy-any-bot',
2926
- };
2927
- break;
2928
- }
2929
- }
2999
+ suppressedBy = findOwnPost(postSpawn, preSpawnIds);
3000
+ agentPostedItself = Boolean(suppressedBy);
2930
3001
  }
2931
3002
  }
2932
3003
  const heartbeatControlReply = (event.type === 'heartbeat' || event.payload?.hasHeartbeat === true)
@@ -3228,7 +3299,7 @@ export const performRun = ({
3228
3299
  const channelLine = answersInChannel(entry) ? `\n${ANSWER_IN_CHANNEL}` : '';
3229
3300
  const deliveryId = entry.event.payload?.deliveryId;
3230
3301
  const checkpoint = typeof deliveryId === 'string' && deliveryId
3231
- ? `\n[After ${answersAPerson(entry) ? 'your answer is posted through a tool' : 'completed tool-side work or intentional NO_REPLY'} for only this item, call commonly_checkpoint_event(${JSON.stringify({
3302
+ ? `\n[After ${answersAPerson(entry) ? 'all of your answer is posted through a tool' : 'completed tool-side work or intentional NO_REPLY'} for only this item, call commonly_checkpoint_event(${JSON.stringify({
3232
3303
  eventId: String(entry.event._id), deliveryId,
3233
3304
  })}). Checkpoint metadata is private runtime data; never post it in chat.]`
3234
3305
  : '';
@@ -3250,7 +3321,8 @@ export const performRun = ({
3250
3321
  `After tool-side work is committed (including any reply posted through a tool)${answersPerson ? ',' : ', or an intentional NO_REPLY,'} checkpoint that item with its supplied IDs. `
3251
3322
  + 'Release any held message claim first with the correct completed/declined outcome. '
3252
3323
  + 'Do not checkpoint a reply you are holding for final CLI output: the wrapper must post it before acknowledging that item. '
3253
- + 'Never checkpoint unfinished work. Only a successful checkpoint prevents replay after timeout. '
3324
+ + 'Never checkpoint unfinished work: an answer in several posts is finished only after its last post. '
3325
+ + 'Only a successful checkpoint prevents replay after timeout. '
3254
3326
  + 'If the tool is unavailable, continue normally; completion will acknowledge the batch.',
3255
3327
  ...bodies,
3256
3328
  ...(heldBack > 0
@@ -3382,6 +3454,8 @@ export const performRun = ({
3382
3454
  // The current batch's items past the cap. Kept out here because the tick needs
3383
3455
  // them when the turn throws, and a throw returns no entries.
3384
3456
  let pastCapEvents = [];
3457
+ // The arguments of the turn that just threw, for noticeCutOff.
3458
+ let failedTurn = null;
3385
3459
  let heldRenewTimer = null;
3386
3460
  const clearHeldRenewal = () => {
3387
3461
  if (heldRenewTimer !== null) clearIntervalImpl(heldRenewTimer);
@@ -3472,15 +3546,19 @@ export const performRun = ({
3472
3546
  + 'to the server\'s requeue (redelivered in ~10–20 min)',
3473
3547
  );
3474
3548
  }
3475
- // A stopping run carries nothing and renews nothing: extending the lease
3476
- // of a process on its way out only delays the replacement's redelivery.
3477
- // Its carry is handed back to the server when the tick ends instead
3478
- // (F189), so the next run answers it on its first poll.
3549
+ // A stopping run carries nothing, because its carry is handed back to the
3550
+ // server when the tick ends (F189), so the next run answers it on its first
3551
+ // poll. It renews only the failed turn's own events, to learn which of them
3552
+ // it still holds: that hand-back follows at once, so the replacement doesn't
3553
+ // wait on the longer lease.
3479
3554
  if (!running) {
3480
3555
  heldRetry = [...heldRetry, ...carry];
3481
3556
  heldRetryFailures.clear();
3482
3557
  pastCapCarries.clear();
3483
- return { held: [], released, handedBack: carry };
3558
+ const confirmed = await renewHeldDeliveries(failedEvents);
3559
+ return {
3560
+ held: [], released, handedBack: carry, lost: failedEvents.filter((event) => !stillHeld(event, confirmed)),
3561
+ };
3484
3562
  }
3485
3563
  const confirmed = carry.length ? await renewHeldDeliveries(carry) : null;
3486
3564
  // The stop landed during that renewal, after the limits were applied.
@@ -3500,7 +3578,9 @@ export const performRun = ({
3500
3578
  + '(checkpointed, requeued or retired) — not retried',
3501
3579
  );
3502
3580
  }
3503
- return { held, released, handedBack: [] };
3581
+ return {
3582
+ held, released, handedBack: [], lost: dropped.filter((event) => failedEvents.includes(event)),
3583
+ };
3504
3584
  };
3505
3585
 
3506
3586
  // F189/F182: hand claimed events this run will never run back to the
@@ -3609,6 +3689,7 @@ export const performRun = ({
3609
3689
 
3610
3690
  const handleEventBatch = async (events, inboxCount = events.length) => {
3611
3691
  pastCapEvents = [];
3692
+ failedTurn = null;
3612
3693
  const eventPodId = events[0]?.podId || podId;
3613
3694
  if (!eventPodId || events.some((event) => (event.podId || podId) !== eventPodId)) {
3614
3695
  throw new Error('Inbox batch crossed pod boundaries; refusing to mix private pod context');
@@ -3660,10 +3741,10 @@ export const performRun = ({
3660
3741
  // Null until the server says: a failed read or an older server is unknown,
3661
3742
  // not "alone" and not "with peers".
3662
3743
  let podAttendance = null;
3663
- const snapshotMessages = async () => {
3744
+ const snapshotMessages = async (limit = 10) => {
3664
3745
  try {
3665
3746
  const { messages = [], otherAgentsInPod, peopleInPod } = await client.get(
3666
- `/api/agents/runtime/pods/${eventPodId}/messages`, { limit: 10 },
3747
+ `/api/agents/runtime/pods/${eventPodId}/messages`, { limit },
3667
3748
  );
3668
3749
  podAttendance = typeof otherAgentsInPod === 'boolean' ? { otherAgentsInPod, peopleInPod } : null;
3669
3750
  return messages;
@@ -4248,6 +4329,7 @@ export const performRun = ({
4248
4329
  });
4249
4330
  if (onError) onError(wrapped);
4250
4331
  else log(`[inbox.batch] ${wrapped.message}`);
4332
+ await noticeCutOff(hold.lost);
4251
4333
  await noticeCantAnswer(err, [...failedEvents, ...untriedAfter(groupIndex)]);
4252
4334
  };
4253
4335
  let batch;
@@ -42,8 +42,7 @@ import { describeTurnReap, markTurn, turnReapEnabled } from '@commonlyai/seats/t
42
42
  */
43
43
 
44
44
  import { requireSeatModel, seatModelRequired } from './seat-model.js';
45
- import { probeVersion } from './tested-version.js';
46
- import { parseVersion } from '../mcp-server-version.js';
45
+ import { meetsMinimumVersion, probeVersion, publicCodexVersionError } from './tested-version.js';
47
46
  import { spawn as childSpawn, spawnSync } from 'child_process';
48
47
  import { createHash } from 'crypto';
49
48
  import { accessSync, constants, existsSync, realpathSync } from 'fs';
@@ -577,7 +576,7 @@ const writePublicCodexInstructions = async (publicHome, ctx) => {
577
576
  // from the `exec` tool of code-mode models.
578
577
  // - `features.multi_agent` removes the agent tools from a model on the v1 agent
579
578
  // tools, but a thread started without it keeps them when resumed, so
580
- // `agents.max_depth=0` (below) covers that thread. A model whose catalog entry says
579
+ // `agents.max_depth=0` covers that thread. A model whose catalog entry says
581
580
  // `multi_agent_version: "v2"` keeps `collaboration.*` in its tool list whatever
582
581
  // these say, so the v2 cap is what stops it: at 1 the root thread fills it, and
583
582
  // spawn_agent returns "agent thread limit reached". `agents.max_threads` doesn't
@@ -586,34 +585,31 @@ const writePublicCodexInstructions = async (publicHome, ctx) => {
586
585
  // - `features.goals` removes the goal tools. A goal is kept on the thread and
587
586
  // comes back in the next turn's context.
588
587
  //
589
- // Measured on codex-cli 0.162.1, against the tool list sent to the model on
590
- // gpt-5.5, gpt-5.6 and gpt-6 models (adapters.codex.public-tools.test.mjs).
591
- // 0.133.0, 0.149.1 and 0.159.3 all start with this set, ignoring a key they don't
592
- // know. Of these, only the `web_search` value could fail a start, as it's an
593
- // enum, and "disabled" is valid on all four.
588
+ // Measured against the tool list sent to the model, on codex-cli 0.162.1 with
589
+ // gpt-5.5, gpt-5.6 and gpt-6 models and on 0.159.3 with gpt-5.5 and gpt-6 models
590
+ // (adapters.codex.public-tools.test.mjs).
594
591
  const PUBLIC_BUILTIN_TOOL_FLAGS = Object.freeze([
595
592
  '-c', 'web_search="disabled"',
596
593
  '-c', 'features.multi_agent=false',
597
594
  '-c', 'features.multi_agent_v2.max_concurrent_threads_per_session=1',
598
595
  '-c', 'features.goals=false',
596
+ '-c', 'agents.max_depth=0',
599
597
  ]);
600
598
 
601
- // Unlike the set above, `agents.max_depth=0` can stop a start: codex-cli 0.133.0
602
- // exits with "agents.max_depth must be at least 1", and 0.149.1 is the oldest
603
- // version measured to take it. So it goes only to a Codex reporting at least that,
604
- // and a version that can't be read leaves it out, since a seat that starts matters
605
- // more than a thread from before these settings.
606
- const ZERO_AGENT_DEPTH_FLAGS = Object.freeze(['-c', 'agents.max_depth=0']);
607
- const ZERO_AGENT_DEPTH_MIN_VERSION = [0, 149, 1];
599
+ // A public seat needs a tested Codex version: below this one it runs no turn.
600
+ // Tested on macOS with the real binary, through this adapter's public flags: the
601
+ // permission profile (shell and view_image, read and write, network off) and the
602
+ // tool list, on new and resumed threads, on 0.159.3 and 0.162.1. An older version
603
+ // isn't tested to this bar. A later one runs as it is, so the BYO workflows'
604
+ // 0.164.0 is allowed, though these checks have not been run on it, nor on Linux
605
+ // on any version.
606
+ export const PUBLIC_CODEX_MIN_VERSION = '0.159.3';
608
607
 
609
- const acceptsZeroAgentDepth = (version) => {
610
- const parsed = parseVersion(version);
611
- if (!parsed) return false;
612
- const index = parsed.findIndex((part, i) => part !== ZERO_AGENT_DEPTH_MIN_VERSION[i]);
613
- return index === -1 || parsed[index] > ZERO_AGENT_DEPTH_MIN_VERSION[index];
614
- };
615
-
616
- const parseCodexVersion = (stdout) => String(stdout).match(/\d+\.\d+\.\d+/)?.[0] || null;
608
+ // The exact line `codex --version` printed on every version tested. Anything else
609
+ // counts as unread: a looser match could take a number from another line.
610
+ const parseCodexVersion = (stdout) => (
611
+ /^codex-cli (\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?)\s*$/m.exec(String(stdout))?.[1] || null
612
+ );
617
613
 
618
614
  const publicPermissionProfileFlags = (
619
615
  mode,
@@ -791,7 +787,6 @@ const buildArgs = ({
791
787
  modelBaseUrl = null,
792
788
  platform = process.platform,
793
789
  workspacePath = null,
794
- zeroAgentDepth = false,
795
790
  }) => {
796
791
  const publicSandbox = publicSandboxMode !== null;
797
792
  // `--dangerously-bypass-approvals-and-sandbox` disables codex CLI's
@@ -803,8 +798,9 @@ const buildArgs = ({
803
798
  // The pod is the security perimeter — agent identity is isolated, workspace
804
799
  // is PVC-scoped, no host mounts. bwrap inside the pod is redundant.
805
800
  // Public laptop wrappers are different: untrusted pod content must never
806
- // inherit that bypass. Codex >=0.138 permission profiles provide a native
807
- // deny-by-default read/write/network boundary on macOS and Linux. Do not
801
+ // inherit that bypass. Codex permission profiles provide a native
802
+ // deny-by-default read/write/network boundary on macOS and Linux, on the
803
+ // versions spawn admits (PUBLIC_CODEX_MIN_VERSION). Do not
808
804
  // pass legacy `--sandbox` alongside them: Codex documents that the legacy
809
805
  // mode disables permission-profile composition.
810
806
  const executionPolicy = publicSandbox
@@ -820,7 +816,6 @@ const buildArgs = ({
820
816
  workspacePath,
821
817
  ),
822
818
  ...PUBLIC_BUILTIN_TOOL_FLAGS,
823
- ...(zeroAgentDepth ? ZERO_AGENT_DEPTH_FLAGS : []),
824
819
  ]
825
820
  : ['--dangerously-bypass-approvals-and-sandbox'];
826
821
  const common = [
@@ -916,6 +911,21 @@ const CODEX_PROVIDER_KEY_ENVS = [
916
911
  'CODEX_API_KEY',
917
912
  ];
918
913
 
914
+ // What the turn will launch, asked for its version. 30 s, as in goose: a first
915
+ // launch after an upgrade can be slow. A failed probe isn't cached, so the next
916
+ // turn reads it again. `_codexVersion` and `_versionProbe` are test seams only.
917
+ const readCodexVersion = async (ctx, env) => {
918
+ if (ctx._codexVersion !== undefined) return ctx._codexVersion;
919
+ try {
920
+ const { command, args } = resolveLaunch('codex', [], { env, ...ctx._commandResolution });
921
+ return await probeVersion(command, {
922
+ args, env, timeoutMs: 30000, parse: parseCodexVersion, ...ctx._versionProbe,
923
+ });
924
+ } catch {
925
+ return null;
926
+ }
927
+ };
928
+
919
929
  // `ownGroup`: see runClaude in claude.js.
920
930
  const runCodex = ({
921
931
  args, cwd, env, timeoutMs, credentials = [], spawnImpl = childSpawn, onSpawn, controls = {}, ownGroup = false,
@@ -1092,15 +1102,16 @@ export default {
1092
1102
  else if (authKind === 'login') process.stderr.write(`[codex] ${CHATGPT_ROUTE_IGNORED}\n`);
1093
1103
  }
1094
1104
  const childEnv = { ...(ctx.env || process.env), ...mcp.forwardedEnv };
1105
+ // Before the public home is prepared, so a refused seat changes nothing.
1106
+ if (publicSandboxMode !== null) {
1107
+ const codexVersion = await readCodexVersion(ctx, childEnv);
1108
+ if (!meetsMinimumVersion(codexVersion, PUBLIC_CODEX_MIN_VERSION)) {
1109
+ throw publicCodexVersionError({ found: codexVersion, required: PUBLIC_CODEX_MIN_VERSION });
1110
+ }
1111
+ }
1095
1112
  const publicCodexHome = publicSandboxMode !== null
1096
1113
  ? await preparePublicCodexHome(ctx, childEnv)
1097
1114
  : null;
1098
- // 30 s, as in goose: a first launch after an upgrade can be slow, and an
1099
- // unread version drops agents.max_depth=0 for this turn. A failed probe
1100
- // isn't cached, so the next turn reads it again.
1101
- const codexVersion = publicSandboxMode === null ? null
1102
- : ctx._codexVersion !== undefined ? ctx._codexVersion // test seam only
1103
- : await probeVersion('codex', { env: childEnv, timeoutMs: 30000, parse: parseCodexVersion }).catch(() => null);
1104
1115
  const args = buildArgs({
1105
1116
  sessionId: ctx.sessionId || null,
1106
1117
  prompt: fullPrompt,
@@ -1115,7 +1126,6 @@ export default {
1115
1126
  modelBaseUrl,
1116
1127
  platform: ctx._platform || process.platform,
1117
1128
  workspacePath,
1118
- zeroAgentDepth: acceptsZeroAgentDepth(codexVersion),
1119
1129
  });
1120
1130
  // childEnv is derived from the process environment, so the bootstrap export has to be
1121
1131
  // taken back out: the declaration above moved our server onto the file,
@@ -12,6 +12,7 @@ import { resolveOnPath } from '../resolve-on-path.js';
12
12
  // A newer minor or major, an older patch, an older line, or a prerelease still
13
13
  // refuses until it is smoke-tested and added to the adapter's list.
14
14
  const STABLE = /^(\d+)\.(\d+)\.(\d+)$/;
15
+ const SEMVER = /^(\d+)\.(\d+)\.(\d+)(-[0-9A-Za-z.-]+)?$/;
15
16
 
16
17
  export const isPatchAfterNewestTested = (version, tested) => {
17
18
  const installed = STABLE.exec(String(version || ''));
@@ -22,6 +23,36 @@ export const isPatchAfterNewestTested = (version, tested) => {
22
23
  && Number(installed[3]) > Number(newest[3]);
23
24
  };
24
25
 
26
+ // A floor rather than a list: the version, or anything later, prereleases of a
27
+ // later version included, so the list's prerelease rule above doesn't apply. A
28
+ // prerelease of the floor comes before it, and an unreadable version meets nothing.
29
+ export const meetsMinimumVersion = (version, minimum) => {
30
+ const installed = SEMVER.exec(String(version ?? ''));
31
+ const floor = STABLE.exec(String(minimum ?? ''));
32
+ if (!installed || !floor) return false;
33
+ for (let part = 1; part <= 3; part += 1) {
34
+ const difference = Number(installed[part]) - Number(floor[part]);
35
+ if (difference !== 0) return difference > 0;
36
+ }
37
+ return !installed[4];
38
+ };
39
+
40
+ export const PUBLIC_CODEX_VERSION_CODE = 'public_codex_version';
41
+
42
+ // `found` stays in this message, which only the seat's log shows. The line a pod
43
+ // sees is built from `requiredVersion` (turn-failure-notice.js).
44
+ export const publicCodexVersionError = ({ found, required }) => {
45
+ const error = new Error(found
46
+ ? `public seat refused this turn: Codex ${found} is older than this seat needs. `
47
+ + `Upgrade Codex to at least ${required} and start the agent again.`
48
+ : 'public seat refused this turn: could not read the Codex version. '
49
+ + `Check that \`codex --version\` works for this agent, upgrade Codex to at least ${required} `
50
+ + 'if it is older, and start the agent again.');
51
+ error.code = PUBLIC_CODEX_VERSION_CODE;
52
+ error.requiredVersion = required;
53
+ return error;
54
+ };
55
+
25
56
  // The harness's own `--version`, asked without blocking the event loop and
26
57
  // remembered per binary. A daemon runs every seat in one process, beside the
27
58
  // loopback provider proxies of other seats' live turns, so a synchronous probe
@@ -36,6 +67,10 @@ export const isPatchAfterNewestTested = (version, tested) => {
36
67
  // cwd lookup missed the cache every turn and could key it on a same-named file
37
68
  // there. What runs is that resolved real path, so the binary that answers is
38
69
  // the one the key names. A name that does not resolve runs as given, uncached.
70
+ //
71
+ // `args` come before `--version`, for a launch that is an interpreter and a
72
+ // script (a Windows npm shim). The interpreter's path says nothing about which
73
+ // script it would run, so that probe is never cached.
39
74
  const versionCache = new Map();
40
75
 
41
76
  const resolveBinary = (binary, env) => {
@@ -52,14 +87,14 @@ const resolveBinary = (binary, env) => {
52
87
  };
53
88
 
54
89
  export const probeVersion = async (binary, {
55
- env, timeoutMs = 30000, parse, execFileImpl = childProcess.execFile, cache = versionCache,
90
+ args = [], env, timeoutMs = 30000, parse, execFileImpl = childProcess.execFile, cache = versionCache,
56
91
  } = {}) => {
57
- const resolved = resolveBinary(binary, env);
92
+ const resolved = args.length ? null : resolveBinary(binary, env);
58
93
  const key = resolved?.key || null;
59
94
  const hit = key ? cache.get(key) : null;
60
95
  if (hit && hit.mtimeMs === resolved.mtimeMs) return hit.version;
61
96
  const stdout = await new Promise((resolve) => {
62
- execFileImpl(key || binary, ['--version'], { encoding: 'utf8', env, timeout: timeoutMs }, (error, out) => {
97
+ execFileImpl(key || binary, [...args, '--version'], { encoding: 'utf8', env, timeout: timeoutMs }, (error, out) => {
63
98
  resolve(error ? null : out);
64
99
  });
65
100
  });
@@ -649,16 +649,19 @@ export const splitForChat = (text, { limit = 400 } = {}) => {
649
649
  * `onlyIfUnanswered` is how a reply the seat already posted through
650
650
  * commonly_post_thread_comment is not posted twice: a pod snapshot can't see a
651
651
  * comment, and the server can. A 400, 403 or 404 won't change on a retry, so it
652
- * is a refusal too; anything else throws, for redelivery.
652
+ * is a refusal too; anything else throws, for redelivery. A line that must land
653
+ * after the seat's own reply passes `onlyIfUnanswered: false`.
653
654
  */
654
- export const deliverCommentReply = async ({ client, postId, commentId, text }) => {
655
+ export const deliverCommentReply = async ({
656
+ client, postId, commentId, text, onlyIfUnanswered = true,
657
+ }) => {
655
658
  const refused = (reason, guidance) => ({
656
659
  mode: 'refused', messages: 0, attemptedMessages: 1, refused: true, reason, guidance,
657
660
  });
658
661
  let response;
659
662
  try {
660
663
  response = await client.post(`/api/agents/runtime/threads/${encodeURIComponent(postId)}/comments`, {
661
- content: text, replyToCommentId: commentId, onlyIfUnanswered: true,
664
+ content: text, replyToCommentId: commentId, onlyIfUnanswered,
662
665
  });
663
666
  } catch (error) {
664
667
  if (![400, 403, 404].includes(error?.status)) throw error;
@@ -726,6 +729,10 @@ export const deliverChatReply = async ({
726
729
  // D245 item 4: how this reply was made (lib/reply-receipt.js). It rides
727
730
  // the first message that actually reaches the pod and no later one.
728
731
  receipt = null,
732
+ // Keeps a reply that fits in up to maxChunks messages in that thread. The
733
+ // overflow rungs below start their own thread, so a caller with a long reply
734
+ // doesn't set this.
735
+ threadRootId = null,
729
736
  }) => {
730
737
  const messagesPath = `/api/agents/runtime/pods/${podId}/messages`;
731
738
  const chunks = splitForChat(text, { limit });
@@ -838,8 +845,9 @@ export const deliverChatReply = async ({
838
845
  // this check a 659-char fence rode the single/split branches straight past
839
846
  // the gate (found by the fleet's implementation audit).
840
847
  const hasIndivisibleOversize = chunks.some((c) => c.length > attachThreshold);
848
+ const placement = threadRootId ? { threadRootId } : {};
841
849
  if (chunks.length <= 1 && !hasIndivisibleOversize) {
842
- const response = await postOnce({ content: chunks[0] ?? text });
850
+ const response = await postOnce({ content: chunks[0] ?? text, ...placement });
843
851
  if (undelivered(response)) return nonDelivery(response, 0, 1);
844
852
  return { mode: 'single', messages: 1 };
845
853
  }
@@ -847,7 +855,7 @@ export const deliverChatReply = async ({
847
855
  let messages = 0;
848
856
  for (const chunk of chunks) {
849
857
  // eslint-disable-next-line no-await-in-loop
850
- const response = await postOnce({ content: chunk }); // in order, so the reply reads top-down
858
+ const response = await postOnce({ content: chunk, ...placement }); // in order, so the reply reads top-down
851
859
  if (undelivered(response)) return nonDelivery(response, messages, chunks.length);
852
860
  messages += 1;
853
861
  }
@@ -8,6 +8,7 @@
8
8
  */
9
9
 
10
10
  import { PUBLIC_MCP_NOT_READY_CODE, PUBLIC_TOOL_FAILED_CODE } from './public-tool-error.js';
11
+ import { PUBLIC_CODEX_VERSION_CODE } from './adapters/tested-version.js';
11
12
 
12
13
  export const SPAWN_FAILURE_CLASS = Object.freeze({
13
14
  // The provider refused the request's CONTENT. Re-sending the same content
@@ -138,6 +139,8 @@ export const classifySpawnFailure = (error) => {
138
139
  ? SPAWN_FAILURE_CLASS.RATE_LIMIT
139
140
  : SPAWN_FAILURE_CLASS.RUNTIME;
140
141
  }
142
+ // Only whoever runs the seat can change this, so it waits as a missing CLI does.
143
+ if (error?.code === PUBLIC_CODEX_VERSION_CODE) return SPAWN_FAILURE_CLASS.CONFIGURATION;
141
144
  // First: the refusal text carries none of the words below today, but a
142
145
  // refusal must never be read as a transient condition and retried.
143
146
  if (CONTENT_REFUSED_RE.test(text)) return SPAWN_FAILURE_CLASS.CONTENT_REFUSED;
@@ -16,6 +16,7 @@
16
16
  * which is what it did before.
17
17
  */
18
18
  import { PUBLIC_MCP_NOT_READY_CODE, PUBLIC_TOOL_FAILED_CODE } from './public-tool-error.js';
19
+ import { PUBLIC_CODEX_VERSION_CODE } from './adapters/tested-version.js';
19
20
  import { classifySpawnFailure, GATEWAY_BUDGET_RE, SPAWN_FAILURE_CLASS } from './spawn-retry.js';
20
21
 
21
22
  /** How long one cause stays posted in a pod before the seat may post it again. */
@@ -54,12 +55,24 @@ export const WONT_START_NOTICE = 'I can’t answer right now: the tool I run on
54
55
  export const OUT_OF_ALLOWANCE_NOTICE = 'I can’t answer right now: the AI account I run on has used up its allowance. '
55
56
  + `It needs to reset, or whoever runs me needs to add more. ${AGAIN}`;
56
57
 
58
+ // A turn that had posted, whose event the server had settled, and that then
59
+ // stopped. The event won't come back, so this is all the person hears. Hedged,
60
+ // because a kill can land after the last word: a checkpoint says the seat
61
+ // finished an item, and part one of an answer has been enough to earn one.
62
+ export const CUT_OFF_NOTICE = 'I got cut off before I could finish that, so please ask me again if anything is missing.';
63
+
64
+ export const codexVersionNotice = (required) => 'I can’t answer right now: the computer I run on needs '
65
+ + `Codex ${required} or newer. Whoever runs me needs to upgrade it and start me again. ${AGAIN}`;
66
+
57
67
  const matches = (wordings, text) => wordings.some((wording) => wording.test(text));
58
68
 
59
69
  /** The cause a pod should hear about, and its line, or null when it should hear nothing. */
60
70
  export const cantAnswerNotice = (error) => {
61
71
  // A public seat's withheld turn quotes a TOOL's error, not its own provider's.
62
72
  if (error?.code === PUBLIC_TOOL_FAILED_CODE || error?.code === PUBLIC_MCP_NOT_READY_CODE) return null;
73
+ if (error?.code === PUBLIC_CODEX_VERSION_CODE) {
74
+ return { cause: 'codex-version', text: codexVersionNotice(error.requiredVersion) };
75
+ }
63
76
  // A crashed claude turn keeps assistant and tool JSON lines in its tail, and
64
77
  // those are the model's words, or a tool's.
65
78
  const text = String(error?.message ?? '').split(/(?:^|: | \| |\n)\{"type":/)[0];