@agentsdock/server 1.0.12-beta.4 → 1.0.12-beta.9

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.
@@ -929,10 +929,8 @@ RUNTIME_CATALOG_DEADLINE: ContextVar[float | None] = ContextVar(
929
929
  )
930
930
  RUNTIME_DIAGNOSTIC_TTL_SECONDS = float(agentsdock_setting("RUNTIME_DIAGNOSTIC_TTL_SECONDS", "60"))
931
931
  # Claude Code only promises the family aliases in ``--help``; account-scoped
932
- # pinned models come from Anthropic's Models API when an API key is available.
933
- # These entries are therefore a last-resort catalog when native SDK metadata
934
- # and the API are unavailable, not the primary source of truth. Keep aliases
935
- # so new models remain selectable even before this fallback is updated.
932
+ # pinned models come from native session metadata or Anthropic's Models API.
933
+ # Aliases are a usable fallback, not evidence of account-specific availability.
936
934
  CLAUDE_CLI_MODEL_ALIASES = (
937
935
  ("fable", "Fable"),
938
936
  ("opus", "Opus"),
@@ -940,19 +938,6 @@ CLAUDE_CLI_MODEL_ALIASES = (
940
938
  ("haiku", "Haiku"),
941
939
  ("opus[1m]", "Opus 1M"),
942
940
  )
943
- CLAUDE_CURRENT_MODEL_FALLBACKS = (
944
- ("claude-fable-5-1", "Fable 5.1", False),
945
- ("claude-mythos-5-1", "Mythos 5.1 (limited access)", True),
946
- ("claude-opus-5", "Opus 5", False),
947
- ("claude-sonnet-5", "Sonnet 5", False),
948
- ("claude-haiku-4-5-20251001", "Haiku 4.5", False),
949
- )
950
- CLAUDE_LEGACY_MODEL_FALLBACKS = (
951
- ("claude-fable-5", "Fable 5", False),
952
- ("claude-mythos-5", "Mythos 5 (limited access)", True),
953
- ("claude-opus-4-8", "Opus 4.8", False),
954
- ("claude-opus-4-8[1m]", "Opus 4.8 1M", False),
955
- )
956
941
  CLAUDE_MODEL_VALUE_RE = re.compile(r"^[A-Za-z0-9][A-Za-z0-9._:/\-\[\]]{0,255}$")
957
942
  CLAUDE_MODELS_API_MAX_BYTES = 2 * 1024 * 1024
958
943
  CLAUDE_PROVIDER_SECRET_ENV_NAMES = (
@@ -11193,8 +11178,11 @@ class SessionStore:
11193
11178
  sess.update(active_runtime)
11194
11179
  if desired != active_runtime:
11195
11180
  sess["_codex_provider_pending"] = desired
11181
+ if "codex_provider" in patch and (sess.get("_codex_provider_context") or {}).get("status") == "failed":
11182
+ sess.pop("_codex_provider_context", None)
11196
11183
  else:
11197
11184
  sess.pop("_codex_provider_pending", None)
11185
+ sess.pop("_codex_provider_context", None)
11198
11186
  # Ordinary/queued turns re-save their backend and may repeat model
11199
11187
  # or provider selections. Only an actual runtime change invalidates
11200
11188
  # the in-flight title; cancelling a no-op consumes its sole attempt.
@@ -22855,6 +22843,7 @@ def public_queued_turn(
22855
22843
  "position": position,
22856
22844
  "promoted": promoted,
22857
22845
  "paused": paused,
22846
+ "send_when_idle": item.get("_send_when_idle") is True and not paused,
22858
22847
  "pause_reason": (
22859
22848
  "delivery_uncertain"
22860
22849
  if delivery_uncertain
@@ -24467,6 +24456,7 @@ async def _run_queued_turn_now_and_release(
24467
24456
  except BaseException:
24468
24457
  with suppress(BaseException):
24469
24458
  await join_task_despite_caller_cancellation(settlement)
24459
+ schedule_requested_claude_followup(session_id)
24470
24460
 
24471
24461
 
24472
24462
  def codex_goal_followup_requires_native(
@@ -24486,24 +24476,53 @@ def codex_goal_followup_requires_native(
24486
24476
  )
24487
24477
 
24488
24478
 
24489
- def codex_goal_steer_selection_is_plain(selected: dict[str, Any]) -> bool:
24490
- """Claude's current native lane accepts text/files, not new route or skill grants."""
24491
- routes = selected.get("provider_cross_chat_route_snapshot")
24492
- return (
24493
- str(selected.get("prompt") or "").strip().split(maxsplit=1)[:1] != ["/mail"]
24494
- and selected.get("skill_selection") is None
24495
- and not any(
24496
- isinstance(route, dict)
24497
- and route.get("route_kind") == PROVIDER_CROSS_CHAT_ROUTE_KIND_REFERENCE
24498
- for route in (routes if isinstance(routes, list) else [])
24499
- )
24500
- and not any(selected.get(field) for field in (
24501
- "purpose", "chat_references", "team_references",
24502
- "secure_peer_route_snapshots", "cross_chat_obligation_ids",
24503
- "cross_chat_exchange_ids", "cross_chat_envelope_id",
24504
- "cross_chat_exchange_id", "cross_chat_exchange_leg_id",
24505
- ))
24506
- )
24479
+ def claude_followup_selection_is_supported(selected: dict[str, Any]) -> bool:
24480
+ """Native user input, including selected local skills and @chat references."""
24481
+ return codex_goal_steer_selection_is_supported(selected)
24482
+
24483
+
24484
+ def schedule_requested_claude_followup(session_id: str) -> None:
24485
+ """Deliver an explicit Send now after readiness, without a retry timer."""
24486
+ active = ACTIVE.get(session_id)
24487
+ if (not active or active.get("transport") != CLAUDE_TRANSPORT_AGENT_SDK
24488
+ or not active.get("provider_turn_ready") or active.get("stop_requested")
24489
+ or active.get("claude_followup_queue") is None):
24490
+ return
24491
+ previous = active.get("claude_send_now_task")
24492
+ if isinstance(previous, asyncio.Task) and not previous.done():
24493
+ return
24494
+ head = next(iter(QUEUED_TURNS.get(session_id) or ()), None)
24495
+ if (not head or not head.get("_claude_send_on_ready") or head.get("_paused_after_stop")
24496
+ or head.get("_native_delivery_fenced")
24497
+ or not claude_followup_selection_is_supported(head)):
24498
+ return
24499
+ queued_id = str(head["queued_id"])
24500
+ run_id = active.get("run_id")
24501
+ provider_queue = active.get("claude_followup_queue")
24502
+
24503
+ async def deliver() -> None:
24504
+ pending = RUN_NOW_REQUESTS.get(session_id)
24505
+ if pending is not None:
24506
+ with suppress(Exception):
24507
+ await asyncio.shield(pending[1])
24508
+ # Stop, replacement or removal after the click wins. This callback
24509
+ # never grants permission to a different run or retries uncertain input.
24510
+ if (ACTIVE.get(session_id) is not active or active.get("stop_requested")
24511
+ or active.get("run_id") != run_id
24512
+ or active.get("claude_followup_queue") is not provider_queue
24513
+ or not active.get("provider_turn_ready")
24514
+ or head.get("_paused_after_stop") or head.get("_native_delivery_fenced")
24515
+ or next(iter(QUEUED_TURNS.get(session_id) or ()), None) is not head):
24516
+ return
24517
+ head.pop("_claude_send_on_ready", None)
24518
+ try:
24519
+ await run_queued_turn_now(session_id, queued_id)
24520
+ except Exception:
24521
+ # The delivery coordinator retains the durable row/error. A native
24522
+ # terminal event can drain a definitely-unsent row normally.
24523
+ logger.info("Deferred Claude Send now settled without acceptance session=%s", session_id)
24524
+
24525
+ active["claude_send_now_task"] = asyncio.create_task(deliver())
24507
24526
 
24508
24527
 
24509
24528
  def codex_goal_steer_selection_is_supported(selected: dict[str, Any]) -> bool:
@@ -24541,12 +24560,6 @@ async def _run_queued_turn_now_once(
24541
24560
  ) -> dict[str, Any]:
24542
24561
  if session_id not in STORE.sessions:
24543
24562
  raise HTTPException(status_code=404, detail="session not found")
24544
- if stop_cleanup_in_progress(session_id):
24545
- raise HTTPException(
24546
- status_code=409,
24547
- detail="Stop is still finishing for this chat; retry Force Send shortly",
24548
- )
24549
-
24550
24563
  async with ACTIVE_LOCK:
24551
24564
  active_turn = dict(ACTIVE.get(session_id) or {})
24552
24565
  interrupted_turn = dict(CURRENT_TURNS.get(session_id) or {})
@@ -24680,6 +24693,31 @@ async def _run_queued_turn_now_once(
24680
24693
  or STORE.sessions[session_id].get("backend")
24681
24694
  or DEFAULT_BACKEND
24682
24695
  )
24696
+ if stop_cleanup_in_progress(session_id):
24697
+ # Accept the click while exact-owner teardown settles.
24698
+ # Its completion callback drains this durable queue; a
24699
+ # second click or another interrupt is not necessary.
24700
+ reordered = [selected, *(item for item in items if item is not selected)]
24701
+ message = "Waiting for the current turn to stop. This message will send automatically."
24702
+ await append_durable_event(session_id, "turn_deferred", {
24703
+ "queued_id": queued_id, "remaining": len(items),
24704
+ "message": message, "send_when_idle": True,
24705
+ "positions": queue_positions(deque(reordered)),
24706
+ })
24707
+ selected["_send_when_idle"] = True
24708
+ selected["_paused_after_stop"] = False
24709
+ QUEUED_TURNS[session_id] = deque(reordered)
24710
+ # Cover cleanup completing during the durable write. If
24711
+ # still stopping, queue admission leaves delivery to the
24712
+ # existing Stop completion callback.
24713
+ schedule_next_queued_turn(session_id)
24714
+ return {
24715
+ "ok": False, "queued_id": queued_id, "interrupted": False,
24716
+ "deferred": True, "send_when_idle": True,
24717
+ "replays_interrupted_message": False,
24718
+ "remaining": len(items), "superseded_queued_ids": [],
24719
+ "message": message,
24720
+ }
24683
24721
  # QUEUE_LOCK admission and async message lookup can yield while
24684
24722
  # the live provider creates a goal or replaces its turn. Read
24685
24723
  # the latest owner here without an inverse ACTIVE/QUEUE lock
@@ -24785,33 +24823,30 @@ async def _run_queued_turn_now_once(
24785
24823
  and active_turn.get("provider_turn_ready")
24786
24824
  and not active_turn.get("stop_requested")
24787
24825
  and native_steer_queue is not None
24788
- and codex_goal_steer_selection_is_plain(selected)
24826
+ and claude_followup_selection_is_supported(selected)
24789
24827
  )
24790
- if not native_steer and codex_goal_steer_selection_is_plain(selected):
24791
- if not selected.get("_turn_deferred_notified"):
24792
- selected["_turn_deferred_notified"] = True
24793
- await append_event(session_id, "turn_deferred", {
24794
- "queued_id": queued_id, "remaining": len(items),
24795
- "message": "Claude is starting or finishing. Your message remains queued; running subagents have been kept alive.",
24796
- })
24828
+ if not native_steer:
24829
+ # A click is a durable request to send this exact row,
24830
+ # even while Claude is starting/finishing. Never leave
24831
+ # a previous Stop hold in place or stop its children.
24832
+ reordered = [selected, *(item for item in items if item is not selected)]
24833
+ message = "Will send automatically when Claude is ready."
24834
+ await append_durable_event(session_id, "turn_deferred", {
24835
+ "queued_id": queued_id, "remaining": len(items),
24836
+ "message": message, "send_when_idle": True,
24837
+ "positions": queue_positions(deque(reordered)),
24838
+ })
24839
+ selected["_send_when_idle"] = True
24840
+ selected["_claude_send_on_ready"] = claude_followup_selection_is_supported(selected)
24841
+ selected["_paused_after_stop"] = False
24842
+ QUEUED_TURNS[session_id] = deque(reordered)
24797
24843
  return {
24798
24844
  "ok": False, "queued_id": queued_id, "interrupted": False,
24799
- "deferred": True, "replays_interrupted_message": False,
24845
+ "deferred": True, "send_when_idle": True,
24846
+ "replays_interrupted_message": False,
24800
24847
  "remaining": len(items), "superseded_queued_ids": [],
24801
- "message": "Claude is starting or finishing. Your message remains queued; running subagents have been kept alive.",
24848
+ "message": message,
24802
24849
  }
24803
- if not native_steer:
24804
- raise HTTPException(status_code=409, detail=force_send_conflict_detail(
24805
- session_id, queued_id, guard="claude_followup_not_ready",
24806
- message=(
24807
- "This action needs a new Claude turn and remains queued. Running subagents have been kept alive."
24808
- if not codex_goal_steer_selection_is_plain(selected) else
24809
- "Claude is finishing or starting its turn. Your message remains queued."
24810
- ),
24811
- action="Send text or files now, or let this action run next.",
24812
- retryable=codex_goal_steer_selection_is_plain(selected),
24813
- owner_queued_id=queued_id,
24814
- ))
24815
24850
  if goal_followup and not native_steer:
24816
24851
  unsupported_input = not codex_goal_steer_selection_is_supported(selected)
24817
24852
  raise HTTPException(
@@ -25036,6 +25071,37 @@ async def _run_queued_turn_now_once(
25036
25071
  )
25037
25072
  interrupted = bool(stop_result.get("stopped")) and not deferred
25038
25073
  if deferred:
25074
+ if stop_result.get("pending"):
25075
+ # The interrupt is still owned by the current turn. Preserve
25076
+ # this explicit Send now as the next queue row, without
25077
+ # claiming provider acceptance or creating another stop loop.
25078
+ message = "Waiting for the current turn to stop. This message will send automatically."
25079
+ async with QUEUE_LOCK:
25080
+ queue_items = list(QUEUED_TURNS.get(session_id) or [])
25081
+ queue_items.insert(0, selected)
25082
+ if not selected.get("_send_when_idle") or selected_index != 0 or selected_was_paused:
25083
+ await append_durable_event(session_id, "turn_deferred", {
25084
+ "queued_id": queued_id,
25085
+ "message": message,
25086
+ "send_when_idle": True,
25087
+ "positions": queue_positions(deque(queue_items)),
25088
+ "remaining": len(queue_items),
25089
+ })
25090
+ selected["_send_when_idle"] = True
25091
+ selected.pop("_update_transitioning", None)
25092
+ QUEUED_TURNS[session_id] = deque(queue_items)
25093
+ RUN_NOW_TURNS.pop(session_id, None)
25094
+ STEERING_SESSIONS.discard(session_id)
25095
+ # The normal exact-owner terminal path schedules this queue.
25096
+ # Also reconcile once in case release raced the interrupt.
25097
+ if session_id not in BUSY_SESSIONS:
25098
+ schedule_next_queued_turn(session_id)
25099
+ return {
25100
+ "ok": False, "queued_id": queued_id, "interrupted": False,
25101
+ "deferred": True, "send_when_idle": True,
25102
+ "replays_interrupted_message": False, "message": message,
25103
+ "remaining": len(queue_items), "superseded_queued_ids": [],
25104
+ }
25039
25105
  already_notified = bool(selected.get("_turn_deferred_notified"))
25040
25106
  selected["_turn_deferred_notified"] = True
25041
25107
  selected.pop("_update_transitioning", None)
@@ -25047,12 +25113,7 @@ async def _run_queued_turn_now_once(
25047
25113
  queue_items.insert(insert_at, selected)
25048
25114
  QUEUED_TURNS[session_id] = deque(queue_items)
25049
25115
  remaining = len(queue_items)
25050
- if stop_result.get("pending"):
25051
- message = (
25052
- "Stop is still finishing. This message remains queued; "
25053
- "try Force Send again shortly."
25054
- )
25055
- elif stop_result.get("superseded"):
25116
+ if stop_result.get("superseded"):
25056
25117
  message = (
25057
25118
  "The active turn changed before it could be stopped. "
25058
25119
  "This message remains queued; try Force Send again shortly."
@@ -26403,6 +26464,16 @@ def scan_queued_turns_from_events(
26403
26464
  if paused_id in pending:
26404
26465
  pending[paused_id]["_paused_after_stop"] = True
26405
26466
  continue
26467
+ if (event_type == "turn_deferred" and event.get("send_when_idle") is True
26468
+ and queued_id in pending):
26469
+ # Explicit Force Send resumes only this row. A later Stop or
26470
+ # uncertain delivery still wins through its own durable event.
26471
+ pending[queued_id]["_paused_after_stop"] = False
26472
+ pending[queued_id]["_send_when_idle"] = True
26473
+ if queued_id in order:
26474
+ order.remove(queued_id)
26475
+ order.insert(0, queued_id)
26476
+ continue
26406
26477
  if event_type == "turn_queue_delivery_fenced" and queued_id:
26407
26478
  if queued_id not in pending:
26408
26479
  pending[queued_id] = queued_turn_from_event(
@@ -28448,6 +28519,10 @@ def run_tmux(args: list[str], *, check: bool = True, timeout: float = TMUX_COMMA
28448
28519
  capture_output=True,
28449
28520
  timeout=timeout,
28450
28521
  check=False,
28522
+ # A long-lived tmux daemon must not inherit a removable checkout
28523
+ # as its cwd. Affected tmux versions ignore even absolute -c paths
28524
+ # after that directory disappears (tmux/tmux#5473).
28525
+ cwd="/",
28451
28526
  # Any tmux command can be the one that implicitly starts the
28452
28527
  # shared daemon. Never let that first command seed server secrets
28453
28528
  # into tmux's long-lived global environment.
@@ -28821,6 +28896,7 @@ def bootstrap_isolated_tmux_server() -> bool:
28821
28896
  check=False,
28822
28897
  timeout=10,
28823
28898
  env=environment,
28899
+ cwd="/",
28824
28900
  )
28825
28901
  except (OSError, subprocess.SubprocessError) as exc:
28826
28902
  run_tmux(["kill-session", "-t", sentinel], check=False)
@@ -29000,14 +29076,17 @@ def terminal_session_path() -> str:
29000
29076
  return os.pathsep.join(entries)
29001
29077
 
29002
29078
 
29003
- def terminal_login_command(shell: str, path: str | None = None) -> str:
29079
+ def terminal_login_command(shell: str, path: str | None = None, *, cwd: str | None = None) -> str:
29004
29080
  """Return a tmux shell-command that starts a login shell with known env."""
29005
- if path is None:
29006
- return f"exec {shlex.quote(shell)} -l"
29007
- return (
29008
- f"SHELL={shlex.quote(shell)} PATH={shlex.quote(path)} "
29009
- f"exec {shlex.quote(shell)} -l"
29010
- )
29081
+ command = f"exec {shlex.quote(shell)} -l"
29082
+ if path is not None:
29083
+ command = f"SHELL={shlex.quote(shell)} PATH={shlex.quote(path)} {command}"
29084
+ # Also recover new panes on an already-running affected daemon. Do this
29085
+ # before login startup files (brew/pip/etc. may call getcwd). Never send cd
29086
+ # into an existing pane: it may be running a user's foreground command.
29087
+ if cwd is not None:
29088
+ command = f"cd -- {shlex.quote(cwd)} && {command}"
29089
+ return command
29011
29090
 
29012
29091
 
29013
29092
  def configure_terminal_session_shell(name: str, shell: str, path: str) -> None:
@@ -29061,7 +29140,7 @@ def _ensure_terminal_session_locked(
29061
29140
  # first tmux use on a Linux systemd-user installation.
29062
29141
  bootstrap_isolated_tmux_server()
29063
29142
  scrub_tmux_global_secret_environment()
29064
- workdir = existing_cwd(cwd or sess.get("cwd") or DEFAULT_CWD)
29143
+ workdir = str(Path(existing_cwd(cwd or sess.get("cwd") or DEFAULT_CWD)).absolute())
29065
29144
  cols, lines = terminal_dimensions(columns, rows)
29066
29145
  try:
29067
29146
  run_tmux([
@@ -29075,7 +29154,7 @@ def _ensure_terminal_session_locked(
29075
29154
  str(lines),
29076
29155
  "-c",
29077
29156
  workdir,
29078
- terminal_login_command(shell, path),
29157
+ terminal_login_command(shell, path, cwd=workdir),
29079
29158
  ])
29080
29159
  created = True
29081
29160
  except HTTPException:
@@ -29825,13 +29904,16 @@ def _terminal_action_locked(session_id: str, action: str, target: str | None = N
29825
29904
  ["display-message", "-p", "-t", name, "#{pane_current_path}"],
29826
29905
  check=False,
29827
29906
  ).stdout.strip()
29828
- workdir = existing_cwd(active_cwd or STORE.sessions[session_id].get("cwd") or DEFAULT_CWD)
29907
+ workdir = str(Path(existing_cwd(active_cwd or STORE.sessions[session_id].get("cwd") or DEFAULT_CWD)).absolute())
29829
29908
  if clean_action == "new-window":
29830
- run_tmux(["new-window", "-t", name, "-c", workdir])
29909
+ run_tmux(["new-window", "-t", name, "-c", workdir,
29910
+ terminal_login_command(resolve_terminal_login_shell(), terminal_session_path(), cwd=workdir)])
29831
29911
  elif clean_action == "split-right":
29832
- run_tmux(["split-window", "-h", "-t", name, "-c", workdir])
29912
+ run_tmux(["split-window", "-h", "-t", name, "-c", workdir,
29913
+ terminal_login_command(resolve_terminal_login_shell(), terminal_session_path(), cwd=workdir)])
29833
29914
  elif clean_action == "split-down":
29834
- run_tmux(["split-window", "-v", "-t", name, "-c", workdir])
29915
+ run_tmux(["split-window", "-v", "-t", name, "-c", workdir,
29916
+ terminal_login_command(resolve_terminal_login_shell(), terminal_session_path(), cwd=workdir)])
29835
29917
  elif clean_action == "next-window":
29836
29918
  run_tmux(["next-window", "-t", name])
29837
29919
  elif clean_action == "previous-window":
@@ -31258,7 +31340,8 @@ async def mark_claude_sdk_turn_ready_after_ack(
31258
31340
  tools_ready = active.get("provider_tools_ready")
31259
31341
  if isinstance(tools_ready, asyncio.Event):
31260
31342
  tools_ready.set()
31261
- return True
31343
+ schedule_requested_claude_followup(session_id)
31344
+ return True
31262
31345
 
31263
31346
 
31264
31347
  def active_snapshot_input(active: dict[str, Any]) -> dict[str, Any]:
@@ -31271,6 +31354,7 @@ def active_snapshot_input(active: dict[str, Any]) -> dict[str, Any]:
31271
31354
  "native_steer_queue",
31272
31355
  "codex_goal_steer_queue",
31273
31356
  "codex_child_continuation_stop",
31357
+ "claude_send_now_task",
31274
31358
  "owner_task",
31275
31359
  }
31276
31360
  }
@@ -56148,6 +56232,10 @@ async def prepare_codex_login_turn(session: dict[str, Any]) -> None:
56148
56232
  if current is not None:
56149
56233
  session.update(codex_provider.runtime_selection(current))
56150
56234
  session.pop("_codex_provider_pending", None)
56235
+ current = STORE.sessions.get(str(session.get("id") or "")) or session
56236
+ if (isinstance(current.get("_codex_provider_pending"), dict)
56237
+ and (current.get("_codex_provider_context") or {}).get("status") == "failed"):
56238
+ raise HTTPException(409, "Codex could not prepare this chat's context on the current endpoint. Select the requested connection again to retry; the chat and draft are retained.")
56151
56239
  if codex_provider.session_choice(session.get("codex_provider")) == "custom":
56152
56240
  return
56153
56241
  await refresh_codex_app_server_login(source="turn_admission")
@@ -56973,6 +57061,7 @@ async def acquire_codex_control_thread(
56973
57061
  reserve_session: bool = False,
56974
57062
  allow_active_goal_mutation: bool = False,
56975
57063
  allow_active_control: bool = False,
57064
+ prepare_provider: bool = True,
56976
57065
  ) -> tuple[CodexAppServerManager, str, dict[str, Any]]:
56977
57066
  """Load and pin a Codex thread for an explicit desktop control."""
56978
57067
  reservation_task = asyncio.current_task() if reserve_session else None
@@ -56994,7 +57083,7 @@ async def acquire_codex_control_thread(
56994
57083
  detail="Codex controls require the app-server transport",
56995
57084
  )
56996
57085
 
56997
- if reserve_session:
57086
+ if reserve_session and prepare_provider:
56998
57087
  await prepare_codex_login_turn(session)
56999
57088
 
57000
57089
  reserved = False
@@ -57560,7 +57649,7 @@ async def prepare_codex_goal_route_steer(
57560
57649
  or reference.grant_intent is not True or reference.route_action is not None
57561
57650
  for reference in references
57562
57651
  ):
57563
- raise ValueError("Only explicit local @Chat access can be added to a running goal")
57652
+ raise ValueError("Only explicit local @Chat access can be added to a running chat")
57564
57653
  references = validate_chat_references(
57565
57654
  session_id, prompt, references, selected.get("client_capabilities") or [],
57566
57655
  )
@@ -57604,7 +57693,7 @@ async def prepare_codex_goal_route_steer(
57604
57693
  or float(matches[0][1].get("expires_at") or 0) <= time.time()
57605
57694
  )):
57606
57695
  raise NativeSteerHandoffError(
57607
- "This running goal has no compatible chat-access authority; the follow-up remains queued",
57696
+ "This chat’s current connection cannot accept the selected chat access yet; the message will send in its next turn",
57608
57697
  safe_to_requeue=True,
57609
57698
  )
57610
57699
  token_hash, capability = matches[0] if matches else (None, None)
@@ -58043,6 +58132,7 @@ async def consume_codex_native_turn(
58043
58132
  finalize_operation: bool = True,
58044
58133
  initial_sequence: int = 0,
58045
58134
  initial_pending_steer: dict[str, Any] | None = None,
58135
+ provider_handoff_context: dict[str, Any] | None = None,
58046
58136
  ) -> dict[str, Any]:
58047
58137
  """Consume native work; an inline ordinary runner retains its own cleanup."""
58048
58138
  assistant_deltas: dict[str, list[str]] = {}
@@ -58051,6 +58141,7 @@ async def consume_codex_native_turn(
58051
58141
  completed_reasoning_items: set[str | tuple[str, str]] = set()
58052
58142
  terminal_status = "completed"
58053
58143
  terminal_error: str | None = None
58144
+ compaction_checkpoint_completed = False
58054
58145
  schedule_queue = True
58055
58146
  goal_resume = operation == "goal_resume"
58056
58147
  shell_resume = operation == "shell_resume"
@@ -58507,6 +58598,7 @@ async def consume_codex_native_turn(
58507
58598
  completed_reasoning_items.add(item_id)
58508
58599
  await clear_reasoning_summary_stream(session_id, operation_id, item_id)
58509
58600
  elif item_type == "contextCompaction" and operation == "compaction":
58601
+ compaction_checkpoint_completed = True
58510
58602
  native_turn_id = str(params.get("turnId") or turn_id or "") or None
58511
58603
  native_item_id = str(
58512
58604
  params.get("itemId") or item.get("id") or ""
@@ -58625,6 +58717,21 @@ async def consume_codex_native_turn(
58625
58717
  terminal_status = "failed"
58626
58718
  terminal_error = concise_error_message(exc)
58627
58719
  finally:
58720
+ if provider_handoff_context is not None:
58721
+ checkpoint_task = asyncio.create_task(settle_codex_provider_context(
58722
+ session_id, provider_handoff_context,
58723
+ completed=(compaction_checkpoint_completed
58724
+ and terminal_status == "completed" and not terminal_error),
58725
+ ))
58726
+ try:
58727
+ try:
58728
+ await asyncio.shield(checkpoint_task)
58729
+ except asyncio.CancelledError:
58730
+ await join_task_despite_caller_cancellation(checkpoint_task)
58731
+ except Exception:
58732
+ # Never strand the native control slot when persistence fails.
58733
+ # The unacknowledged checkpoint cannot authorize a handoff.
58734
+ logger.exception("could not retain Codex provider context checkpoint session=%s", session_id)
58628
58735
  if (shell_owner is not None and ACTIVE.get(session_id) is shell_owner
58629
58736
  and shell_owner.get("codex_shell_subscription") is subscription):
58630
58737
  shell_owner.pop("codex_shell_subscription", None)
@@ -60407,21 +60514,11 @@ def discover_codex_catalog() -> dict[str, Any]:
60407
60514
  service_tier = str(model.get("default_service_tier") or "").strip()
60408
60515
  model_options.append(runtime_option(slug, label, efforts=model_efforts.get(slug, []), service_tier=service_tier or None))
60409
60516
 
60410
- if not model_options:
60411
- for slug, label in CODEX_FALLBACK_MODELS:
60412
- if slug in replacements:
60413
- continue
60414
- fallback_efforts = [
60415
- runtime_option(effort, title_effort_label(effort))
60416
- for effort in CODEX_FALLBACK_MODEL_EFFORTS.get(slug, CODEX_FALLBACK_EFFORTS)
60417
- ]
60418
- model_efforts[slug] = fallback_efforts
60419
- service_tier = codex_default_service_tier(slug)
60420
- model_options.append(runtime_option(slug, label, efforts=fallback_efforts, service_tier=service_tier or None))
60517
+ # A failed/empty account inventory is not permission to advertise our old
60518
+ # pinned versions. Keep the configured default for existing turn settings,
60519
+ # but do not manufacture selectable model rows from it.
60421
60520
  if not effort_options:
60422
60521
  effort_options.extend(runtime_option(effort, title_effort_label(effort)) for effort in CODEX_FALLBACK_EFFORTS)
60423
- if configured_model and configured_model not in replacements and not any(option.get("value") == configured_model for option in model_options):
60424
- model_options.insert(0, runtime_option(configured_model, title_model_label(configured_model)))
60425
60522
  if configured_effort and not any(option.get("value") == configured_effort for option in effort_options):
60426
60523
  effort_options.append(runtime_option(configured_effort, title_effort_label(configured_effort)))
60427
60524
  if default_model not in model_efforts:
@@ -60439,6 +60536,7 @@ def discover_codex_catalog() -> dict[str, Any]:
60439
60536
  "efforts": unique_runtime_options(effort_options, f"Server default ({default_effort_label})" if default_effort_label else None),
60440
60537
  "model_efforts": model_efforts,
60441
60538
  "model_source": model_source,
60539
+ "discovery_status": "unavailable" if model_source.endswith("failed") else "ready" if model_options else "empty",
60442
60540
  "effort_source": effort_source,
60443
60541
  "default_model": default_model or None,
60444
60542
  "default_effort": default_effort or None,
@@ -60647,20 +60745,6 @@ def discover_claude_provider_models(
60647
60745
  return [], "failed"
60648
60746
 
60649
60747
 
60650
- def claude_fallback_model_options() -> list[dict[str, Any]]:
60651
- return [
60652
- runtime_option(
60653
- value,
60654
- label,
60655
- **({"availability": "limited"} if limited else {}),
60656
- )
60657
- for value, label, limited in (
60658
- *CLAUDE_CURRENT_MODEL_FALLBACKS,
60659
- *CLAUDE_LEGACY_MODEL_FALLBACKS,
60660
- )
60661
- ]
60662
-
60663
-
60664
60748
  def discover_claude_native_models() -> tuple[list[dict[str, Any]], str]:
60665
60749
  from claude_model_catalog import cached_native_models
60666
60750
 
@@ -60677,12 +60761,12 @@ def discover_claude_native_models() -> tuple[list[dict[str, Any]], str]:
60677
60761
  def parse_claude_help_catalog() -> dict[str, Any]:
60678
60762
  model_options: list[dict[str, Any]] = []
60679
60763
  effort_options: list[dict[str, Any]] = []
60680
- default_model = (
60764
+ configured_default_model = (
60681
60765
  os.environ.get("CLAUDE_MODEL")
60682
60766
  or os.environ.get("ANTHROPIC_MODEL")
60683
60767
  or agentsdock_setting("CLAUDE_MODEL", "")
60684
- or "sonnet"
60685
60768
  )
60769
+ default_model = configured_default_model or "sonnet"
60686
60770
  default_effort = os.environ.get("CLAUDE_EFFORT") or agentsdock_setting("CLAUDE_EFFORT", "")
60687
60771
  supports_ultracode = claude_supports_effort("ultracode")
60688
60772
  # Optional candidate discovery must leave time for the native picker,
@@ -60709,20 +60793,20 @@ def parse_claude_help_catalog() -> dict[str, Any]:
60709
60793
  # after the native picker applies account/organization restrictions.
60710
60794
  # Never append unfiltered static pins to a successful native result.
60711
60795
  model_options.extend(native_options)
60796
+ if not configured_default_model and any(option["value"] == "default" for option in native_options):
60797
+ # The account's native default can change independently of the
60798
+ # Sonnet alias. Preserve the native selector instead of labeling
60799
+ # or pinning the server default to our historical assumption.
60800
+ default_model = "default"
60712
60801
  else:
60713
60802
  model_options.extend(discovered_help_aliases)
60714
60803
  model_options.extend(runtime_option(value, label) for value, label in CLAUDE_CLI_MODEL_ALIASES)
60715
60804
  if provider_status == "success":
60716
60805
  # The API is account-scoped; don't add static pins absent from it.
60717
60806
  model_options.extend(provider_options)
60718
- else:
60719
- model_options.extend(claude_fallback_model_options())
60720
- model_options.extend(discovered_help_full_names)
60721
- if native_status != "success" and provider_status != "success" and default_model and not any(
60722
- str(option.get("value") or "") == default_model
60723
- for option in model_options
60724
- ):
60725
- model_options.insert(0, runtime_option(default_model, title_model_label(default_model)))
60807
+ # Help examples and our historical version pins are not evidence of
60808
+ # account access. Retain native aliases on a cache miss, not guessed
60809
+ # versions. Real SDK connections populate the passive native catalog.
60726
60810
 
60727
60811
  effort_match = re.search(r"--effort\s+<level>.*?\(([^)]+)\)", help_text, re.IGNORECASE | re.DOTALL)
60728
60812
  if effort_match:
@@ -60748,7 +60832,7 @@ def parse_claude_help_catalog() -> dict[str, Any]:
60748
60832
  if native_status != "success" and provider_status != "success":
60749
60833
  if provider_status == "failed":
60750
60834
  model_sources.append("Anthropic Models API failed")
60751
- model_sources.append("current fallback")
60835
+ model_sources.append("native aliases; availability unverified")
60752
60836
  effort_source = "claude --help" if help_available else "claude --help failed"
60753
60837
  default_model_label = next(
60754
60838
  (option["label"] for option in model_options if option["value"] == default_model),
@@ -60758,30 +60842,41 @@ def parse_claude_help_catalog() -> dict[str, Any]:
60758
60842
  "models": unique_runtime_options(model_options, default_model_label),
60759
60843
  "efforts": unique_runtime_options(effort_options, title_effort_label(default_effort) if default_effort else ""),
60760
60844
  "model_source": " + ".join(model_sources),
60845
+ "discovery_status": "ready" if native_status == "success" or provider_status == "success" else "unavailable",
60761
60846
  "effort_source": effort_source,
60762
60847
  "default_model": default_model,
60763
60848
  "default_effort": default_effort or None,
60764
60849
  }
60765
60850
 
60766
60851
 
60767
- def discover_opencode_catalog(*, executable: str | None = None) -> dict[str, Any]:
60852
+ def discover_opencode_catalog(*, executable: str | None = None, refresh: bool = False) -> dict[str, Any]:
60768
60853
  """Discover models from the OpenCode CLI.
60769
60854
 
60770
- `opencode models` prints one `provider/model` id per line and returns in
60771
- well under a second. The list is account-shaped: with no credentials only
60772
- the `opencode/*` models (mostly free ones) appear, and configuring a
60773
- provider adds its models. Nothing is marked locked, because unlike Cursor
60774
- the listed models were the runnable ones in every capture.
60855
+ `opencode models` prints connected providers' inventory as `provider/model`
60856
+ IDs. Explicit refresh also refreshes the CLI registry. Listing is not proof
60857
+ of inference entitlement: the provider may still reject a particular model.
60775
60858
  """
60776
60859
  from opencode_agent_client import parse_opencode_models_list
60777
60860
 
60778
60861
  model_source = "opencode models"
60862
+ discovery_status = "ready"
60779
60863
  try:
60780
60864
  executable = executable or resolve_opencode_executable()
60781
60865
  if executable is None:
60782
60866
  raise RuntimeError("no compatible OpenCode executable is available")
60783
60867
  model_source = f"{Path(executable).name} models"
60784
- output = run_catalog_command([executable, "models"])
60868
+ try:
60869
+ output = run_catalog_command([executable, "models", *(["--refresh"] if refresh else [])])
60870
+ except Exception:
60871
+ if not refresh or runtime_catalog_budget_expired():
60872
+ raise
60873
+ # Registry refresh can need the network. Ask the same native CLI
60874
+ # for its current inventory within the remaining shared budget;
60875
+ # do not resurrect another account's server/client cached rows or
60876
+ # claim that this fallback confirms a successful online refresh.
60877
+ output = run_catalog_command([executable, "models"])
60878
+ discovery_status = "unavailable"
60879
+ model_source += " (registry refresh unavailable; native cached registry)"
60785
60880
  parsed = parse_opencode_models_list(output)
60786
60881
  except Exception as exc:
60787
60882
  logger.warning(
@@ -60789,6 +60884,7 @@ def discover_opencode_catalog(*, executable: str | None = None) -> dict[str, Any
60789
60884
  type(exc).__name__,
60790
60885
  )
60791
60886
  parsed = []
60887
+ discovery_status = "unavailable"
60792
60888
  model_source = f"{model_source} failed"
60793
60889
 
60794
60890
  if not parsed:
@@ -60806,6 +60902,7 @@ def discover_opencode_catalog(*, executable: str | None = None) -> dict[str, Any
60806
60902
  "effort_source": "none",
60807
60903
  "default_model": "",
60808
60904
  "default_effort": None,
60905
+ "discovery_status": "empty" if discovery_status == "ready" else discovery_status,
60809
60906
  }
60810
60907
  default_entry = next(
60811
60908
  (model for model in parsed if model.get("is_free")), parsed[0]
@@ -60820,6 +60917,7 @@ def discover_opencode_catalog(*, executable: str | None = None) -> dict[str, Any
60820
60917
  "effort_source": "none",
60821
60918
  "default_model": str(default_entry.get("id") or ""),
60822
60919
  "default_effort": None,
60920
+ "discovery_status": discovery_status,
60823
60921
  }
60824
60922
 
60825
60923
 
@@ -60950,6 +61048,11 @@ def discover_runtime_backend_catalog(backend: str, *, force_runtime_probe: bool
60950
61048
  catalog = parse_claude_help_catalog()
60951
61049
  elif backend == BACKEND_CODEX:
60952
61050
  catalog = discover_codex_catalog()
61051
+ if not runtime_catalog_budget_expired():
61052
+ try:
61053
+ CODEX_PROVIDER_STORE.refresh_catalog(force=force_runtime_probe)
61054
+ except (HTTPException, OSError):
61055
+ logger.debug("Custom Codex model refresh unavailable")
60953
61056
  catalog["custom_provider"] = CODEX_PROVIDER_STORE.catalog(
60954
61057
  available=CODEX_TRANSPORT != CODEX_TRANSPORT_EXEC
60955
61058
  and diagnostic.get("installed") is True,
@@ -60968,7 +61071,7 @@ def discover_runtime_backend_catalog(backend: str, *, force_runtime_probe: bool
60968
61071
  "default_permission_mode": CURSOR_DEFAULT_PERMISSION_MODE,
60969
61072
  })
60970
61073
  else:
60971
- catalog = discover_opencode_catalog(executable=executable) if ready and not runtime_catalog_budget_expired() else {
61074
+ catalog = discover_opencode_catalog(executable=executable, refresh=force_runtime_probe) if ready and not runtime_catalog_budget_expired() else {
60972
61075
  "models": [],
60973
61076
  "efforts": [],
60974
61077
  "model_source": "Runtime refresh deadline" if ready else "OpenCode runtime unavailable",
@@ -65844,7 +65947,7 @@ async def send_claude_followup(
65844
65947
  and session_id not in STOP_REQUESTS
65845
65948
  and session_id not in DELETING_SESSIONS
65846
65949
  and run_id not in STOPPED_RUNS
65847
- and codex_goal_steer_selection_is_plain(selected)
65950
+ and claude_followup_selection_is_supported(selected)
65848
65951
  )
65849
65952
  if not valid:
65850
65953
  raise NativeSteerHandoffError(
@@ -65854,6 +65957,16 @@ async def send_claude_followup(
65854
65957
 
65855
65958
  try:
65856
65959
  await before_send(ownership_token)
65960
+ command_selection = selected.get("skill_selection")
65961
+ if command_selection is not None:
65962
+ await resolve_provider_command_selection(
65963
+ session_id, STORE.sessions[session_id],
65964
+ SkillSelection.model_validate(command_selection),
65965
+ prompt=str(selected.get("prompt") or ""), purpose=None,
65966
+ provider_context_mode="chat",
65967
+ client_capabilities=list(selected.get("client_capabilities") or []),
65968
+ )
65969
+ route_steer = await prepare_codex_goal_route_steer(session_id, run_id, selected)
65857
65970
  prompt = build_user_provider_prompt(
65858
65971
  session_id, str(selected.get("prompt") or ""), list(selected.get("file_ids") or []),
65859
65972
  )
@@ -65865,6 +65978,7 @@ async def send_claude_followup(
65865
65978
  query_session_id=provider_id or None, on_before_send=before_send,
65866
65979
  )
65867
65980
  acknowledged = True
65981
+ chat_access_applied = await commit_codex_goal_route_steer(session_id, run_id, route_steer)
65868
65982
  display_prompt = str(selected.get("display_prompt") if selected.get("display_prompt") is not None else selected.get("prompt") or "")
65869
65983
  display_files = list(selected.get("display_file_ids") if selected.get("display_file_ids") is not None else selected.get("file_ids") or [])
65870
65984
  # One accepted user message, one retained logical run. In particular,
@@ -65899,6 +66013,9 @@ async def send_claude_followup(
65899
66013
  "ok": True, "queued_id": selected.get("queued_id"), "run_id": run_id,
65900
66014
  "interrupted": False, "native_steer": True, "native_followup": True,
65901
66015
  "replays_interrupted_message": False, "superseded_queued_ids": [],
66016
+ **({"chat_access_applied": chat_access_applied,
66017
+ "message": "Message sent; selected chat access changed during delivery."}
66018
+ if route_steer is not None and not chat_access_applied else {}),
65902
66019
  }
65903
66020
  except NativeSteerHandoffError:
65904
66021
  raise
@@ -66588,6 +66705,7 @@ async def run_claude_sdk(
66588
66705
  sdk_ownership_token = str(
66589
66706
  startup_active.get("claude_sdk_owner_token") or ""
66590
66707
  )
66708
+ schedule_requested_claude_followup(session_id)
66591
66709
  if native_continuation_ready is not None and not native_continuation_ready.done():
66592
66710
  native_continuation_ready.set_result(True)
66593
66711
  current_run_id = run_id
@@ -85764,6 +85882,100 @@ async def release_codex_provider_writers(manager: CodexAppServerManager, session
85764
85882
  raise
85765
85883
 
85766
85884
 
85885
+ async def settle_codex_provider_context(
85886
+ session_id: str, context: dict[str, Any], *, completed: bool,
85887
+ ) -> None:
85888
+ """A native checkpoint, never an RPC acknowledgement, authorizes handoff."""
85889
+ if completed:
85890
+ # Verify the actual native checkpoint instead of inferring portability
85891
+ # from provider labels: remote compaction can retain encrypted content.
85892
+ completed = await asyncio.to_thread(lambda: codex_provider.context_has_encrypted_items(
85893
+ codex_rollout_path(str(context.get("thread_id") or "")))) is False
85894
+ async with STORE._lock:
85895
+ session = STORE.sessions.get(session_id)
85896
+ if not session or session.get("_codex_provider_context") != context:
85897
+ return
85898
+ previous_context = session["_codex_provider_context"]
85899
+ previous_reason = session.get("_codex_provider_pending_reason")
85900
+ session["_codex_provider_context"] = {**context, "status": "ready" if completed else "failed"}
85901
+ session["_codex_provider_pending_reason"] = "preparing_context" if completed else "context_preparation_failed"
85902
+ try:
85903
+ await STORE.save(durable=True)
85904
+ except BaseException:
85905
+ session["_codex_provider_context"] = previous_context
85906
+ session["_codex_provider_pending_reason"] = previous_reason
85907
+ raise
85908
+ await broadcast_codex_provider_changed(session_id)
85909
+
85910
+
85911
+ async def prepare_codex_provider_context(session_id: str) -> bool:
85912
+ """Use the old custom provider's native plaintext compaction checkpoint.
85913
+
85914
+ Responses reasoning is encrypted by its originating provider. Resuming the
85915
+ same rollout with another provider does not translate those opaque items.
85916
+ Native local compaction retains the original timeline and native identity,
85917
+ and replaces only model-visible context with Codex's own summary. Normal
85918
+ OpenAI remote compaction is encrypted too and is not used as a migration.
85919
+ """
85920
+ session = STORE.sessions.get(session_id) or {}
85921
+ pending = session.get("_codex_provider_pending")
85922
+ thread_id = session_codex_thread_id(session)
85923
+ if (not isinstance(pending, dict) or not thread_id
85924
+ or session.get("codex_provider") != "custom"
85925
+ or pending.get("_codex_provider_removed")
85926
+ or (pending.get("codex_provider") == "custom"
85927
+ and ((session.get("codex_provider_revision") and pending.get("codex_provider_revision") == session.get("codex_provider_revision"))
85928
+ or (session.get("codex_provider_binding") and pending.get("codex_provider_binding") == session.get("codex_provider_binding"))))):
85929
+ return True
85930
+ source = {"thread_id": thread_id, "revision": session.get("codex_provider_revision")}
85931
+ context = session.get("_codex_provider_context")
85932
+ if isinstance(context, dict) and all(context.get(key) == value for key, value in source.items()):
85933
+ # A stopped/failed preparation needs an explicit endpoint selection to
85934
+ # retry; lifecycle callbacks must not create a provider retry loop.
85935
+ if context.get("status") == "failed":
85936
+ return False
85937
+ task = CODEX_NATIVE_ACTION_TASKS.get((session_id, str(context.get("operation_id") or "")))
85938
+ if task is not None and not task.done():
85939
+ return False
85940
+ # Plaintext threads need no extra model request. Only native rollout
85941
+ # metadata/context is inspected; no transcript is reconstructed or edited.
85942
+ encrypted = await asyncio.to_thread(lambda: codex_provider.context_has_encrypted_items(codex_rollout_path(thread_id)))
85943
+ if encrypted is False:
85944
+ return True
85945
+ if isinstance(context, dict) and context.get("status") == "ready" and encrypted is None:
85946
+ # A saved acknowledgement cannot authorize context we can no longer
85947
+ # verify after restart, rollback or an external native writer.
85948
+ await settle_codex_provider_context(session_id, context, completed=False)
85949
+ return False
85950
+ context = {**source, "id": uuid.uuid4().hex, "status": "running"}
85951
+ async with STORE._lock:
85952
+ session["_codex_provider_context"] = context
85953
+ session["_codex_provider_pending_reason"] = "preparing_context"
85954
+ await STORE.save(durable=True)
85955
+ await broadcast_codex_provider_changed(session_id)
85956
+ starter = asyncio.create_task(_post_codex_compact_locked(session_id, provider_handoff_context=context))
85957
+ cancelled = False
85958
+ try:
85959
+ try:
85960
+ result = await asyncio.shield(starter)
85961
+ except asyncio.CancelledError:
85962
+ # The native RPC may already have accepted compaction. Finish
85963
+ # registering its consumer before releasing the lifecycle lock.
85964
+ cancelled = True
85965
+ result = await join_task_despite_caller_cancellation(starter)
85966
+ # The consumer cannot finish until this caller releases the lifecycle
85967
+ # lock. Its exact checkpoint token is retained across this update.
85968
+ context["operation_id"] = result["operation_id"]
85969
+ async with STORE._lock:
85970
+ await STORE.save(durable=True)
85971
+ except BaseException:
85972
+ await settle_codex_provider_context(session_id, context, completed=False)
85973
+ raise
85974
+ if cancelled:
85975
+ raise asyncio.CancelledError
85976
+ return False
85977
+
85978
+
85767
85979
  async def apply_codex_provider_when_idle(session_id: str, *, ignore_task=None) -> bool:
85768
85980
  """Hand off exactly one idle chat, retaining its native history and goal.
85769
85981
 
@@ -85805,11 +86017,15 @@ async def apply_codex_provider_when_idle(session_id: str, *, ignore_task=None) -
85805
86017
  else None
85806
86018
  )
85807
86019
  if reason is not None:
86020
+ if (session.get("_codex_provider_context") or {}).get("status") == "running":
86021
+ reason = "preparing_context"
85808
86022
  if session.get("_codex_provider_pending_reason") != reason:
85809
86023
  session["_codex_provider_pending_reason"] = reason
85810
86024
  await broadcast_codex_provider_changed(session_id)
85811
86025
  logger.info("Codex provider selection deferred session=%s reason=%s", session_id, reason)
85812
86026
  return False
86027
+ if not await prepare_codex_provider_context(session_id):
86028
+ return False
85813
86029
  manager = existing_codex_app_server_manager(session)
85814
86030
  if manager is not None:
85815
86031
  if not await release_idle_codex_manager_session(manager, session_id, ignore_task=ignore_task):
@@ -85832,6 +86048,7 @@ async def apply_codex_provider_when_idle(session_id: str, *, ignore_task=None) -
85832
86048
  session.update(pending)
85833
86049
  session.pop("_codex_provider_pending", None)
85834
86050
  session.pop("_codex_provider_pending_reason", None)
86051
+ session.pop("_codex_provider_context", None)
85835
86052
  session["_codex_provider_switched"] = True
85836
86053
  session.pop("_codex_subagent_limit_applied", None)
85837
86054
  session["updated_at"] = now_iso()
@@ -92744,10 +92961,13 @@ async def post_codex_compact(session_id: str) -> dict[str, Any]:
92744
92961
  return await _post_codex_compact_locked(session_id)
92745
92962
 
92746
92963
 
92747
- async def _post_codex_compact_locked(session_id: str) -> dict[str, Any]:
92964
+ async def _post_codex_compact_locked(
92965
+ session_id: str, *, provider_handoff_context: dict[str, Any] | None = None,
92966
+ ) -> dict[str, Any]:
92748
92967
  manager, thread_id, control_session = await acquire_codex_control_thread(
92749
92968
  session_id,
92750
92969
  reserve_session=True,
92970
+ **({"prepare_provider": False} if provider_handoff_context is not None else {}),
92751
92971
  )
92752
92972
  reservation_id = str(
92753
92973
  control_session.get("_codex_control_reservation_id") or ""
@@ -92780,6 +93000,7 @@ async def _post_codex_compact_locked(session_id: str) -> dict[str, Any]:
92780
93000
  thread_id,
92781
93001
  reservation_id,
92782
93002
  subscription,
93003
+ provider_handoff_context=provider_handoff_context,
92783
93004
  )
92784
93005
  )
92785
93006
  register_codex_native_action(session_id, operation_id, task)
@@ -101328,6 +101549,11 @@ def configure_server_logging(
101328
101549
 
101329
101550
  def main() -> int:
101330
101551
  global SERVER_BIND_ADDRESS, SERVER_PORT
101552
+ # Legacy managed services still start here after an update, not through
101553
+ # execution_service.main(). Give their provider children the same safe
101554
+ # descriptor headroom as the split worker/gateway entrypoints.
101555
+ from execution_service import ensure_file_descriptor_headroom
101556
+ ensure_file_descriptor_headroom()
101331
101557
  configure_server_logging(STATE_DIR)
101332
101558
  parser = argparse.ArgumentParser(description="AgentsServer")
101333
101559
  parser.add_argument("cmd", nargs="?", default="serve", choices=["serve"])