@agentsdock/server 1.0.12-beta.1 → 1.0.12-beta.2

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.
@@ -52,7 +52,7 @@ import unicodedata
52
52
  import uuid
53
53
  import weakref
54
54
  from collections import Counter, OrderedDict, defaultdict, deque
55
- from concurrent.futures import ThreadPoolExecutor
55
+ from concurrent.futures import Future, ThreadPoolExecutor
56
56
  from contextlib import asynccontextmanager, contextmanager, suppress
57
57
  from contextvars import ContextVar, copy_context
58
58
  from dataclasses import dataclass
@@ -76,6 +76,7 @@ import websockets
76
76
  import team_mail_grants
77
77
  import chat_mailbox
78
78
  import workspace_git
79
+ import workspace_intelligence
79
80
  import codex_auth
80
81
  import codex_provider
81
82
  from codex_response_stream import CustomCodexAppServerManager
@@ -97,6 +98,7 @@ from codex_app_server import (
97
98
  CodexAppServerTimeout,
98
99
  decline_server_request,
99
100
  )
101
+ from claude_chat_routing import print_routing_settings
100
102
  from claude_sdk_client import (
101
103
  CLAUDE_PROVIDER_MCP_SERVER_NAME,
102
104
  CLAUDE_PROVIDER_MCP_TOOL_NAME,
@@ -106,6 +108,8 @@ from claude_sdk_client import (
106
108
  ClaudeSDKGenerationChanged,
107
109
  ClaudeSDKGoalReceipt,
108
110
  ClaudeSDKMCPServerNotFound,
111
+ ClaudeSDKNativeContinuation,
112
+ ClaudeSDKNativeWakeDeferred,
109
113
  ClaudeSDKQueryError,
110
114
  ClaudeSDKRunActive,
111
115
  ClaudeSDKSupervisorClosed,
@@ -1815,6 +1819,9 @@ You are operating through AgentsDock, backed by AgentsServer.
1815
1819
  - Link editor-readable files with Markdown paths relative to the chat working directory, optionally with `#L42`; do not use `file://`.
1816
1820
  - Publish user-facing files to this chat with the AgentsDock provider tool described below. Say “attached” only after a successful JSON receipt. Older-server fallback: write `{{"files":["/absolute/path.ext"]}}` to resolved `$AGENTSDOCK_MANIFEST_PATH` and say only “submitted for attachment.” Use absolute paths and playable `.mp4`/`.mov` videos.
1817
1821
  - Use the run-bound AgentsDock provider tool described below for cross-chat messages.
1822
+ - An AgentsDock @Chat is not a native Claude session, teammate, or child agent. Never use ListAgents/ListPeers or native SendMessage to resolve or contact it, even when a name or working directory matches. A native success receipt is not AgentsDock delivery; report delivery only from the AgentsDock helper's accepted message/exchange receipt.
1823
+ - Discover the selected AgentsDock @Chat with Chats list. For an async_route_v1 route, send or ask with its exact route_id and --route. Do not assume a selected mention is a one-use --target-index handle; use that only when a one-use handle is actually available.
1824
+ - Native SendMessage remains available for children created in this Claude session: address the exact agent ID returned by Agent/Task, not a display name; children may reply to main. If an AgentsDock route is unavailable, report that blocker rather than substituting another recipient or transport.
1818
1825
  - `$AGENTSDOCK_TMUX_SESSION` identifies this chat's persistent terminal when available.
1819
1826
  - Check skills and project playbooks before claiming an environment or remote path is unavailable.
1820
1827
  - If optional cleanup makes a compound command fail, immediately retry the still-safe requested operation without it.
@@ -1836,7 +1843,7 @@ Attaching files to this AgentsDock chat from Cursor:
1836
1843
  - On older runtimes without the internal tool, the authorized file-writing fallback needs no shell: write `{{"files":["/absolute/path.ext"]}}` to `{manifest_path}` and say only "submitted for attachment". Do not use this fallback to bypass an explicit denial.
1837
1844
  - For attachments to this chat, including generated images: write the image to a real file first, then list that absolute path in the manifest.
1838
1845
  """
1839
- CLAUDE_SDK_CONFIGURATION_VERSION = 12
1846
+ CLAUDE_SDK_CONFIGURATION_VERSION = 13
1840
1847
  CODEX_PROMPT_PRELUDE = """\
1841
1848
  You are operating through AgentsDock, backed by AgentsServer.
1842
1849
  - Keep the final answer concise; the UI renders tool calls, command output, reasoning, and artifacts separately.
@@ -14340,6 +14347,9 @@ CODEX_APP_SERVER_MANAGER_EPOCH = 0
14340
14347
  CODEX_APP_SERVER_MANAGER_CLEANUP_EPOCH: int | None = None
14341
14348
  CLAUDE_SDK_MANAGER: ClaudeSDKSupervisorManager | None = None
14342
14349
  CLAUDE_SDK_MANAGER_LOCK = asyncio.Lock()
14350
+ CLAUDE_TURN_ADMISSIONS: dict[str, asyncio.Event] = {}
14351
+ CLAUDE_NATIVE_PAUSED_STARTS: dict[str, dict[str, Any]] = {}
14352
+ CLAUDE_START_TASKS: dict[tuple[str, str], asyncio.Task[Any]] = {}
14343
14353
  CODEX_GOALS_CONFIG_LOCK = asyncio.Lock()
14344
14354
  CODEX_GOALS_RECONFIGURING = False
14345
14355
  CODEX_AUTH_LOCK = asyncio.Lock()
@@ -16727,6 +16737,10 @@ HANDOFF_DIGEST_FINALIZING: set[str] = set()
16727
16737
  RUNTIME_DIAGNOSTICS: dict[str, dict[str, Any]] = {}
16728
16738
  RUNTIME_DIAGNOSTICS_LOCK = threading.RLock()
16729
16739
  RUNTIME_DIAGNOSTIC_GENERATIONS: dict[str, int] = {}
16740
+ # Only overlapping work is shared; completed catalogs are never cached here.
16741
+ RUNTIME_DIAGNOSTIC_PROBES: dict[tuple[str, int], Future[dict[str, Any]]] = {}
16742
+ RUNTIME_DIAGNOSTIC_REVISION = 0
16743
+ RUNTIME_CATALOG_TASKS: dict[bool, tuple[tuple[Any, ...] | None, asyncio.Task[dict[str, Any]]]] = {}
16730
16744
  CODEX_MODEL_MIGRATION_TARGET = "gpt-6-luna"
16731
16745
  ABANDONED_FORK_PROVIDER_THREADS: set[str] = set()
16732
16746
  ABANDONED_FORK_PROVIDER_THREADS_LOCK = asyncio.Lock()
@@ -17069,6 +17083,9 @@ def inherit_internal_status_run_metadata(
17069
17083
  stored = dict(payload or {})
17070
17084
  run_id = str(stored.get("run_id") or "").strip()
17071
17085
  metadata = run_event_metadata(run_id) if run_id else {}
17086
+ predecessor = metadata.get("provider_admission_after_run_id")
17087
+ if isinstance(predecessor, str) and predecessor:
17088
+ stored.setdefault("provider_admission_after_run_id", predecessor)
17072
17089
  if metadata.get("cross_chat_exchange_status") is not True:
17073
17090
  return stored
17074
17091
  for key in (
@@ -24100,6 +24117,7 @@ def native_steer_requeue_event_payload(
24100
24117
  ),
24101
24118
  "model": selected.get("model"),
24102
24119
  "effort": selected.get("effort"),
24120
+ "skill_selection": selected.get("skill_selection"),
24103
24121
  "prompt": display_prompt,
24104
24122
  "request_prompt": str(selected.get("prompt") or ""),
24105
24123
  "display_prompt": selected.get("display_prompt"),
@@ -24402,21 +24420,45 @@ def codex_goal_followup_requires_native(
24402
24420
 
24403
24421
 
24404
24422
  def codex_goal_steer_selection_is_plain(selected: dict[str, Any]) -> bool:
24405
- """User text/attachments may steer without changing runtime authority."""
24423
+ """Claude's current native lane accepts text/files, not new route or skill grants."""
24406
24424
  routes = selected.get("provider_cross_chat_route_snapshot")
24407
24425
  return (
24408
24426
  str(selected.get("prompt") or "").strip().split(maxsplit=1)[:1] != ["/mail"]
24409
24427
  and selected.get("skill_selection") is None
24410
- # Saved/ambient snapshots are automatic queue metadata and are never
24411
- # applied by the owner-preserving goal lane. Explicit new @ grants
24412
- # still require separate work, even without their structured refs.
24413
24428
  and not any(
24414
24429
  isinstance(route, dict)
24415
24430
  and route.get("route_kind") == PROVIDER_CROSS_CHAT_ROUTE_KIND_REFERENCE
24416
24431
  for route in (routes if isinstance(routes, list) else [])
24417
24432
  )
24418
24433
  and not any(selected.get(field) for field in (
24419
- "purpose", "chat_references", "team_references",
24434
+ "purpose", "chat_references", "team_references",
24435
+ "secure_peer_route_snapshots", "cross_chat_obligation_ids",
24436
+ "cross_chat_exchange_ids", "cross_chat_envelope_id",
24437
+ "cross_chat_exchange_id", "cross_chat_exchange_leg_id",
24438
+ ))
24439
+ )
24440
+
24441
+
24442
+ def codex_goal_steer_selection_is_supported(selected: dict[str, Any]) -> bool:
24443
+ """User follow-ups keep the current run owner and explicitly selected input."""
24444
+ routes = selected.get("provider_cross_chat_route_snapshot")
24445
+ references = selected.get("chat_references") or []
24446
+ return (
24447
+ str(selected.get("prompt") or "").strip().split(maxsplit=1)[:1] != ["/mail"]
24448
+ and isinstance(references, list)
24449
+ and all(isinstance(reference, dict) and reference.get("target_kind") is None
24450
+ and reference.get("action") == "route"
24451
+ and reference.get("grant_intent") is True
24452
+ and reference.get("route_action") is None for reference in references)
24453
+ # Only exact current user selections extend chat access. Historical
24454
+ # unattended-job route snapshots are not user-selected references.
24455
+ and not any(
24456
+ isinstance(route, dict)
24457
+ and route.get("route_kind") == PROVIDER_CROSS_CHAT_ROUTE_KIND_REFERENCE
24458
+ for route in (routes if isinstance(routes, list) else [])
24459
+ )
24460
+ and not any(selected.get(field) for field in (
24461
+ "purpose", "team_references",
24420
24462
  "secure_peer_route_snapshots", "cross_chat_obligation_ids",
24421
24463
  "cross_chat_exchange_ids", "cross_chat_envelope_id",
24422
24464
  "cross_chat_exchange_id", "cross_chat_exchange_leg_id",
@@ -24609,14 +24651,14 @@ async def _run_queued_turn_now_once(
24609
24651
  isinstance(STORE.sessions[session_id].get("codex_goal"), dict)
24610
24652
  and STORE.sessions[session_id]["codex_goal"].get("status") == "active"
24611
24653
  and not STORE.sessions[session_id].get("codex_goal_time_budget_exhausted")
24612
- and codex_goal_steer_selection_is_plain(selected)
24654
+ and codex_goal_steer_selection_is_supported(selected)
24613
24655
  )
24614
24656
  )
24615
- and not selected.get("chat_references")
24657
+ and (goal_followup or not selected.get("chat_references"))
24616
24658
  and not selected.get("team_references")
24617
24659
  and not selected.get("cross_chat_obligation_ids")
24618
24660
  and not selected.get("cross_chat_exchange_ids")
24619
- and selected.get("skill_selection") is None
24661
+ and (goal_followup or selected.get("skill_selection") is None)
24620
24662
  # Only ordinary logical-run replacement issues fresh
24621
24663
  # authority. A goal steer keeps its exact owner and does
24622
24664
  # not replace the original turn's references or command.
@@ -24704,19 +24746,19 @@ async def _run_queued_turn_now_once(
24704
24746
  owner_queued_id=queued_id,
24705
24747
  ))
24706
24748
  if goal_followup and not native_steer:
24707
- unsupported_input = not codex_goal_steer_selection_is_plain(selected)
24749
+ unsupported_input = not codex_goal_steer_selection_is_supported(selected)
24708
24750
  raise HTTPException(
24709
24751
  status_code=409,
24710
24752
  detail=force_send_conflict_detail(
24711
24753
  session_id, queued_id,
24712
24754
  guard="active_goal_requires_native_steer",
24713
24755
  message=(
24714
- "This queued action adds chat access or invokes a provider command, which cannot be applied inside the running Codex turn."
24756
+ "This queued action contains a Team, remote-chat or legacy delivery that needs a separate turn."
24715
24757
  if unsupported_input else
24716
24758
  "Codex does not have a running goal turn ready to receive this message."
24717
24759
  ),
24718
24760
  action=(
24719
- "It remains queued for a new turn. Text and file follow-ups can be sent now."
24761
+ "It remains queued. Text, files, local skills and local @chat mentions can be sent now."
24720
24762
  if unsupported_input else
24721
24763
  "Your message remains queued. Retry Send now when Codex is running."
24722
24764
  ),
@@ -30278,6 +30320,7 @@ async def release_turn_slot(
30278
30320
  *,
30279
30321
  expected_run_id: str | None = None,
30280
30322
  expected_admission_id: str | None = None,
30323
+ resume_paused_claude_start: bool = False,
30281
30324
  ) -> bool:
30282
30325
  """Release a chat turn reservation without clearing a newer owner.
30283
30326
 
@@ -30322,12 +30365,38 @@ async def release_turn_slot(
30322
30365
  conflicting_owner = bool(active_run_id)
30323
30366
  if not owns_slot or conflicting_owner:
30324
30367
  return False
30368
+ paused = CLAUDE_NATIVE_PAUSED_STARTS.get(session_id)
30369
+ if paused is not None and paused["native_run_id"] == expected_run_id:
30370
+ restored = bool(
30371
+ resume_paused_claude_start
30372
+ and session_id not in STOP_REQUESTS
30373
+ and expected_run_id not in STOPPED_RUNS
30374
+ and not stop_cleanup_in_progress(session_id)
30375
+ and not SERVER_SHUTTING_DOWN
30376
+ and session_id not in DELETING_SESSIONS
30377
+ and session_id not in DELETED_SESSION_TOMBSTONES
30378
+ and session_id in STORE.sessions
30379
+ and not paused.get("cancelled")
30380
+ )
30381
+ paused.update(released=True, restored=restored)
30382
+ if restored:
30383
+ RUN_METADATA.setdefault(paused["run_id"], {})["provider_admission_after_run_id"] = expected_run_id
30384
+ CURRENT_TURNS[session_id] = paused["turn"]
30385
+ if paused["active"] is not None:
30386
+ ACTIVE[session_id] = paused["active"]
30387
+ else:
30388
+ ACTIVE.pop(session_id, None)
30389
+ # Keep the original admission reserved until its first query.
30390
+ # Its runner is released only after native terminal persistence.
30391
+ return True
30325
30392
  ACTIVE.pop(session_id, None)
30326
30393
  BUSY_SESSIONS.discard(session_id)
30327
30394
  CURRENT_TURNS.pop(session_id, None)
30328
30395
  STOP_REQUESTS.discard(session_id)
30329
30396
  schedule_codex_subagent_limit_application(session_id)
30330
- return True
30397
+ if paused is not None and paused["native_run_id"] == expected_run_id:
30398
+ await finish_claude_paused_start(session_id, expected_run_id)
30399
+ return True
30331
30400
 
30332
30401
 
30333
30402
  async def bind_active_turn(
@@ -30452,6 +30521,10 @@ async def reconcile_provider_task_exit(
30452
30521
  prevents delayed cleanup from touching a replacement turn.
30453
30522
  """
30454
30523
 
30524
+ if backend == BACKEND_CLAUDE and await cancel_claude_paused_start(session_id, run_id):
30525
+ # The paused admission owns its terminal and metadata, even while
30526
+ # the native wake still owns the live chat reservation.
30527
+ return False
30455
30528
  if backend == BACKEND_GEMINI:
30456
30529
  async with ACTIVE_LOCK:
30457
30530
  active = ACTIVE.get(session_id) or {}
@@ -31639,7 +31712,7 @@ def build_subagent_snapshot(session_id: str, limit: int = 64) -> dict[str, Any]:
31639
31712
  SUBAGENT_SNAPSHOT_STATE_LIMIT,
31640
31713
  )
31641
31714
  for state in claude.get("subagents") or []:
31642
- key = f"{str(state.get('backend') or BACKEND_CLAUDE)}:{state.get('subagent_id')}"
31715
+ key = f"{str(state.get('backend') or BACKEND_CLAUDE)}:{state.get('run_id')}:{state.get('subagent_id')}"
31643
31716
  merged[key] = dict(state)
31644
31717
  with CODEX_SUBAGENT_INDEX_LOCK:
31645
31718
  codex_states = [dict(state) for state in CODEX_SUBAGENT_STATE.values()]
@@ -31706,6 +31779,69 @@ def codex_child_status_from_turn(turn: Any) -> str | None:
31706
31779
  return None
31707
31780
 
31708
31781
 
31782
+ def reconcile_claude_subagent_snapshot(
31783
+ session_id: str, snapshot: dict[str, Any], limit: int,
31784
+ ) -> dict[str, Any]:
31785
+ """Reconcile display state with existing ownership on the event loop.
31786
+
31787
+ History alone cannot establish present liveness after a restart, eviction,
31788
+ or replacement run. This read neither contacts Claude nor writes history;
31789
+ operational Stop/update guards continue to inspect the durable ledger.
31790
+ """
31791
+ try:
31792
+ owner = (CLAUDE_SDK_MANAGER.subagent_tracking_snapshot(session_id)
31793
+ if CLAUDE_SDK_MANAGER is not None else {"run_id": "", "tasks": ()})
31794
+ owned_runs = {str(owner.get("run_id") or "")} - {""}
31795
+ active = ACTIVE.get(session_id) or {}
31796
+ process = active.get("proc")
31797
+ if (active.get("backend") == BACKEND_CLAUDE
31798
+ and active.get("transport") == CLAUDE_TRANSPORT_PRINT
31799
+ and process is not None and process.returncode is None
31800
+ and active.get("run_id")):
31801
+ owned_runs.add(str(active.get("run_id") or ""))
31802
+ receipts = tuple(owner.get("tasks") or ())
31803
+ except Exception:
31804
+ # An inspection failure is not evidence that a known owner has gone.
31805
+ logger.warning("Claude subagent ownership inspection failed session=%s", session_id, exc_info=True)
31806
+ return {**snapshot, "subagents": list(snapshot.get("subagents") or [])[:limit]}
31807
+
31808
+ states = []
31809
+ for original in snapshot.get("subagents") or []:
31810
+ state = dict(original)
31811
+ if (state.get("backend") == BACKEND_CLAUDE
31812
+ and state.get("subagent_status") in {"starting", "running"}):
31813
+ run_id = str(state.get("run_id") or "")
31814
+ status = None
31815
+ for receipt in receipts:
31816
+ if (receipt.get("owner_run_id") == run_id and run_id in owned_runs
31817
+ and (receipt.get("task_id") == state.get("subagent_id")
31818
+ or (receipt.get("tool_use_id")
31819
+ and receipt.get("tool_use_id") == state.get("subagent_tool_id")))):
31820
+ status = normalize_subagent_status(receipt.get("status"))
31821
+ break
31822
+ if status not in {None, "starting", "running"}:
31823
+ state["subagent_status"] = status
31824
+ state["subagent_activity"] = f"Subagent {status.replace('_', ' ')}"
31825
+ elif run_id not in owned_runs:
31826
+ state["subagent_status"] = "tracking_lost"
31827
+ state["subagent_activity"] = "Background task tracking lost; completion is not confirmed"
31828
+ if state["subagent_status"] != original.get("subagent_status"):
31829
+ state["subagent_log"] = [
31830
+ *(state.get("subagent_log") or []),
31831
+ {"ts": state.get("ts"), "text": state["subagent_activity"]},
31832
+ ][-SUBAGENT_SNAPSHOT_LOG_LIMIT:]
31833
+ states.append(state)
31834
+ states.sort(key=lambda state: (
31835
+ 0 if state.get("subagent_status") in {"starting", "running"} else 1,
31836
+ -(durable_event_seq(state) or 0),
31837
+ ))
31838
+ return {
31839
+ **snapshot,
31840
+ "subagents": states[:limit],
31841
+ "active_count": sum(state.get("subagent_status") in {"starting", "running"} for state in states),
31842
+ }
31843
+
31844
+
31709
31845
  async def reconcile_codex_subagents(
31710
31846
  session_id: str,
31711
31847
  manager: CodexAppServerManager | None = None,
@@ -32260,11 +32396,18 @@ def build_claude_subagent_snapshot(session_id: str, limit: int = 64) -> dict[str
32260
32396
  started = [value for value in (primary["started_at"], secondary["started_at"]) if value]
32261
32397
  if started:
32262
32398
  primary["started_at"] = min(started)
32263
- if int(secondary["seq"]) > int(primary["seq"]):
32399
+ def status_priority(state: dict[str, Any]) -> int:
32400
+ if not state["terminal_confirmed"]:
32401
+ return 0
32402
+ return 1 if state["status"] == "tracking_lost" else 2
32403
+ primary_priority, secondary_priority = status_priority(primary), status_priority(secondary)
32404
+ if ((secondary_priority > primary_priority)
32405
+ or (primary_priority == secondary_priority and int(secondary["seq"]) > int(primary["seq"]))):
32264
32406
  primary["updated_at"] = secondary["updated_at"]
32265
32407
  primary["activity"] = secondary["activity"] or primary["activity"]
32266
32408
  primary["summary"] = secondary["summary"] or primary["summary"]
32267
32409
  primary["status"] = secondary["status"]
32410
+ primary["terminal_confirmed"] = secondary["terminal_confirmed"]
32268
32411
  primary["seq"] = max(int(primary["seq"]), int(secondary["seq"]))
32269
32412
  primary["background"] = bool(primary["background"] or secondary["background"])
32270
32413
  primary["saw_task_started"] = bool(primary["saw_task_started"] or secondary["saw_task_started"])
@@ -32291,13 +32434,23 @@ def build_claude_subagent_snapshot(session_id: str, limit: int = 64) -> dict[str
32291
32434
  kind: Any = "",
32292
32435
  status: str = "running",
32293
32436
  background: bool | None = None,
32294
- ) -> dict[str, Any]:
32437
+ terminal_confirmed: bool = True,
32438
+ ) -> dict[str, Any] | None:
32295
32439
  run_id = str(event.get("run_id") or "")
32296
32440
  task_state_key = task_keys.get(scoped(run_id, task_id)) if task_id else None
32297
32441
  tool_state_key = tool_keys.get(scoped(run_id, tool_id)) if tool_id else None
32298
32442
  if task_state_key and tool_state_key and task_state_key != tool_state_key:
32299
32443
  merge_states(task_state_key, tool_state_key)
32300
32444
  state_key, state = find(run_id, task_id, tool_id)
32445
+ ignore_update = False
32446
+ if state is not None and state["terminal_confirmed"]:
32447
+ incoming_status = normalize_subagent_status(status)
32448
+ # Provider snapshots/progress can arrive after terminal receipts.
32449
+ # Never reopen that task or replace its final activity with stale
32450
+ # progress. A lost task may still acquire an explicit final receipt.
32451
+ if (incoming_status in {"starting", "running"}
32452
+ or (state["status"] != "tracking_lost" and incoming_status != state["status"])):
32453
+ ignore_update = True
32301
32454
  if state is None:
32302
32455
  provider_id = task_id or tool_id
32303
32456
  state_key = f"{run_id}\x00{provider_id}\x00{event.get('seq', 0)}"
@@ -32308,6 +32461,7 @@ def build_claude_subagent_snapshot(session_id: str, limit: int = 64) -> dict[str
32308
32461
  "name": compact_subagent_text(name) or "Claude subagent",
32309
32462
  "kind": compact_subagent_text(kind) or "agent",
32310
32463
  "status": normalize_subagent_status(status),
32464
+ "terminal_confirmed": terminal_confirmed and normalize_subagent_status(status) not in {"starting", "running"},
32311
32465
  "started_at": str(event.get("ts") or ""),
32312
32466
  "updated_at": str(event.get("ts") or ""),
32313
32467
  "seq": int(event.get("seq") or 0),
@@ -32324,6 +32478,8 @@ def build_claude_subagent_snapshot(session_id: str, limit: int = 64) -> dict[str
32324
32478
  if tool_id:
32325
32479
  state["tool_id"] = tool_id
32326
32480
  tool_keys[scoped(run_id, tool_id)] = state_key
32481
+ if ignore_update:
32482
+ return None
32327
32483
  clean_name = compact_subagent_text(name)
32328
32484
  clean_kind = compact_subagent_text(kind)
32329
32485
  if clean_name:
@@ -32333,6 +32489,7 @@ def build_claude_subagent_snapshot(session_id: str, limit: int = 64) -> dict[str
32333
32489
  if background is not None:
32334
32490
  state["background"] = bool(background)
32335
32491
  state["status"] = normalize_subagent_status(status)
32492
+ state["terminal_confirmed"] = terminal_confirmed and state["status"] not in {"starting", "running"}
32336
32493
  state["updated_at"] = str(event.get("ts") or state["updated_at"])
32337
32494
  state["seq"] = max(int(state["seq"]), int(event.get("seq") or 0))
32338
32495
  states.move_to_end(state_key)
@@ -32378,6 +32535,8 @@ def build_claude_subagent_snapshot(session_id: str, limit: int = 64) -> dict[str
32378
32535
  kind="" if previous is not None else receipt["task_type"],
32379
32536
  status=receipt["status"], background=True,
32380
32537
  )
32538
+ if state is None:
32539
+ continue
32381
32540
  note(state, event, (
32382
32541
  "Background task tracking lost; completion is not confirmed"
32383
32542
  if receipt["status"] == "tracking_lost"
@@ -32399,6 +32558,8 @@ def build_claude_subagent_snapshot(session_id: str, limit: int = 64) -> dict[str
32399
32558
  status="starting",
32400
32559
  background=tool_input.get("run_in_background") is True,
32401
32560
  )
32561
+ if state is None:
32562
+ continue
32402
32563
  note(state, event, f"Starting {state['name']}")
32403
32564
  continue
32404
32565
 
@@ -32406,10 +32567,11 @@ def build_claude_subagent_snapshot(session_id: str, limit: int = 64) -> dict[str
32406
32567
  tool = event.get("tool") if isinstance(event.get("tool"), dict) else {}
32407
32568
  tool_id = str(event.get("tool_id") or tool.get("id") or "")
32408
32569
  _, state = find(run_id, tool_id=tool_id)
32409
- if state is None:
32570
+ if state is None or state["status"] not in {"starting", "running"}:
32410
32571
  continue
32411
32572
  if event.get("is_error") is True:
32412
32573
  state["status"] = "failed"
32574
+ state["terminal_confirmed"] = True
32413
32575
  note(state, event, "Subagent failed")
32414
32576
  elif state["background"] or state["saw_task_started"]:
32415
32577
  if state["status"] == "starting":
@@ -32417,6 +32579,9 @@ def build_claude_subagent_snapshot(session_id: str, limit: int = 64) -> dict[str
32417
32579
  note(state, event, state["activity"])
32418
32580
  elif state["status"] in {"starting", "running"}:
32419
32581
  state["status"] = "completed"
32582
+ # A foreground tool result is only a fallback: Claude
32583
+ # may report its native async launch/task identity later.
32584
+ state["terminal_confirmed"] = False
32420
32585
  note(state, event, "Subagent completed")
32421
32586
  continue
32422
32587
 
@@ -32453,6 +32618,8 @@ def build_claude_subagent_snapshot(session_id: str, limit: int = 64) -> dict[str
32453
32618
  status="running",
32454
32619
  background=True,
32455
32620
  )
32621
+ if state is None:
32622
+ continue
32456
32623
  note(state, event, "Subagent running")
32457
32624
  continue
32458
32625
 
@@ -32471,6 +32638,8 @@ def build_claude_subagent_snapshot(session_id: str, limit: int = 64) -> dict[str
32471
32638
  status=normalize_subagent_status(task.get("status")),
32472
32639
  background=True,
32473
32640
  )
32641
+ if state is None:
32642
+ continue
32474
32643
  note(state, event, task.get("description") or f"Subagent {state['status']}")
32475
32644
  continue
32476
32645
 
@@ -32483,6 +32652,8 @@ def build_claude_subagent_snapshot(session_id: str, limit: int = 64) -> dict[str
32483
32652
  kind=raw.get("subagent_type"),
32484
32653
  status="running",
32485
32654
  )
32655
+ if state is None:
32656
+ continue
32486
32657
  state["saw_task_started"] = True
32487
32658
  note(state, event, raw.get("description") or "Subagent started")
32488
32659
  continue
@@ -32499,6 +32670,8 @@ def build_claude_subagent_snapshot(session_id: str, limit: int = 64) -> dict[str
32499
32670
  kind=raw.get("subagent_type"),
32500
32671
  status="running",
32501
32672
  )
32673
+ if state is None:
32674
+ continue
32502
32675
  state["status"] = "running"
32503
32676
  note(state, event, claude_subagent_progress_activity(raw) or "Working")
32504
32677
  continue
@@ -32506,6 +32679,9 @@ def build_claude_subagent_snapshot(session_id: str, limit: int = 64) -> dict[str
32506
32679
  if raw.get("type") == "system" and subtype == "task_updated" and task_id:
32507
32680
  patch = raw.get("patch") if isinstance(raw.get("patch"), dict) else {}
32508
32681
  _, state = find(run_id, task_id, tool_id)
32682
+ if (state is not None and state["terminal_confirmed"]
32683
+ and not (patch.get("status") or raw.get("status"))):
32684
+ continue
32509
32685
  is_agent = state is not None or raw.get("task_type") == "local_agent" or bool(raw.get("subagent_type"))
32510
32686
  if not is_agent:
32511
32687
  continue
@@ -32517,7 +32693,10 @@ def build_claude_subagent_snapshot(session_id: str, limit: int = 64) -> dict[str
32517
32693
  kind=raw.get("subagent_type"),
32518
32694
  status=normalize_subagent_status(status_value),
32519
32695
  background=True if patch.get("is_backgrounded") is True else None,
32696
+ terminal_confirmed=bool(patch.get("status") or raw.get("status")),
32520
32697
  )
32698
+ if state is None:
32699
+ continue
32521
32700
  state["status"] = normalize_subagent_status(status_value)
32522
32701
  summary = compact_subagent_text(patch.get("summary") or raw.get("summary"))
32523
32702
  if summary:
@@ -32538,6 +32717,8 @@ def build_claude_subagent_snapshot(session_id: str, limit: int = 64) -> dict[str
32538
32717
  kind=raw.get("subagent_type"),
32539
32718
  status=normalize_subagent_status(raw.get("status")),
32540
32719
  )
32720
+ if state is None:
32721
+ continue
32541
32722
  state["status"] = normalize_subagent_status(raw.get("status"))
32542
32723
  state["summary"] = compact_subagent_text(raw.get("summary"))
32543
32724
  note(state, event, state["summary"] or f"Subagent {state['status']}")
@@ -32547,7 +32728,7 @@ def build_claude_subagent_snapshot(session_id: str, limit: int = 64) -> dict[str
32547
32728
  if parent_tool_id:
32548
32729
  _, state = find(run_id, tool_id=parent_tool_id)
32549
32730
  activity = claude_subagent_child_activity(raw)
32550
- if state is not None and activity:
32731
+ if state is not None and state["status"] in {"starting", "running"} and activity:
32551
32732
  note(state, event, activity)
32552
32733
  continue
32553
32734
 
@@ -32566,6 +32747,7 @@ def build_claude_subagent_snapshot(session_id: str, limit: int = 64) -> dict[str
32566
32747
  if event_type == "turn_finished" and state["background"]:
32567
32748
  continue
32568
32749
  state["status"] = terminal_status
32750
+ state["terminal_confirmed"] = terminal_status != "completed"
32569
32751
  note(state, event, activity)
32570
32752
  continue
32571
32753
 
@@ -32590,6 +32772,7 @@ def build_claude_subagent_snapshot(session_id: str, limit: int = 64) -> dict[str
32590
32772
  ):
32591
32773
  continue
32592
32774
  state["status"] = "stopped"
32775
+ state["terminal_confirmed"] = True
32593
32776
  note(state, event, "Stopped with parent chat")
32594
32777
 
32595
32778
  active_statuses = {"starting", "running"}
@@ -35518,6 +35701,25 @@ def semantic_timeline_event_is_completed_commentary(
35518
35701
  )
35519
35702
 
35520
35703
 
35704
+ def semantic_timeline_event_is_claude_output(event: dict[str, Any]) -> bool:
35705
+ """Keep public Claude output ahead of optional compact-history traces."""
35706
+ if event.get("backend") != BACKEND_CLAUDE:
35707
+ return False
35708
+ text = str(event.get("text") or "").strip()
35709
+ if not text:
35710
+ return False
35711
+ if event.get("type") == "assistant_text":
35712
+ return True
35713
+ # Older servers stored native text as commentary. Match the desktop's
35714
+ # existing legacy-report projection without reclassifying genuine thinking
35715
+ # or changing stored events; the client still owns final-answer deduplication.
35716
+ return semantic_timeline_event_is_completed_commentary(event) and (
35717
+ len(text) >= 1200
35718
+ or re.search(r"^#{1,6}\s+\S", text, re.MULTILINE) is not None
35719
+ or re.search(r"\n\s*\|[^|\n]+\|[^|\n]+\|", text) is not None
35720
+ )
35721
+
35722
+
35521
35723
  def semantic_timeline_event_is_trace_anchor(event: dict[str, Any]) -> bool:
35522
35724
  """Keep one lightweight handle so completed trace detail stays discoverable."""
35523
35725
  event_type = str(event.get("type") or "")
@@ -35582,13 +35784,14 @@ def semantic_timeline_ordinary_candidates(
35582
35784
  for event in remaining
35583
35785
  if str(event.get("type") or "") in SEMANTIC_TIMELINE_ESSENTIAL_DETAIL_TYPES
35584
35786
  ]
35585
- commentary_essential = [
35787
+ output_essential = [
35586
35788
  event
35587
35789
  for event in remaining
35588
- if preserve_completed_commentary
35589
- and semantic_timeline_event_is_completed_commentary(event)
35790
+ if semantic_timeline_event_is_claude_output(event)
35791
+ or (preserve_completed_commentary
35792
+ and semantic_timeline_event_is_completed_commentary(event))
35590
35793
  ]
35591
- essential = [*detail_essential, *commentary_essential]
35794
+ essential = [*detail_essential, *output_essential]
35592
35795
  essential_ids = {
35593
35796
  semantic_timeline_event_identity(event)
35594
35797
  for event in essential
@@ -44233,9 +44436,10 @@ async def reserve_async_provider_route_message(
44233
44436
  if (str(capability.get("source_run_id") or "") != source_run_id
44234
44437
  or live_provider_cross_chat_route(source_session_id, issued) != live):
44235
44438
  raise HTTPException(status_code=403, detail="permanent chat pair or source turn changed")
44236
- delegation_action = next((action for action in ("instruction", "request_reply", "route")
44439
+ route_instruction = (capability.get("provider_route_source_instructions") or {}).get(route_id)
44440
+ delegation_action = "route" if route_instruction is not None else next((action for action in ("instruction", "request_reply", "route")
44237
44441
  if (target_session_id, action) in (capability.get("user_delegation_grants") or set())), "")
44238
- recorded_instruction = str(capability.get("source_user_instruction") or "")
44442
+ recorded_instruction = str(route_instruction if route_instruction is not None else capability.get("source_user_instruction") or "")
44239
44443
  fallback_delegation = (not delegation_action and capability.get("source_is_user_turn") is True
44240
44444
  and recorded_instruction.strip()
44241
44445
  and len(recorded_instruction) <= CROSS_CHAT_SOURCE_USER_INSTRUCTION_MAX_CHARS)
@@ -45663,7 +45867,8 @@ def bounded_jsonl_paths(
45663
45867
 
45664
45868
 
45665
45869
 
45666
- def bounded_jsonl_events(path: Path, *, preserve_invalid: bool = False) -> Iterator[dict[str, Any] | None]:
45870
+ def bounded_jsonl_events(path: Path, *, preserve_invalid: bool = False,
45871
+ allow_nul_padding: bool = False) -> Iterator[dict[str, Any] | None]:
45667
45872
  """Project native records with bounded memory, not a source-byte cap."""
45668
45873
  initial = path.stat()
45669
45874
  expected = {field: int(getattr(initial, field)) for field in ("st_dev", "st_ino", "st_size", "st_mtime_ns")}
@@ -45673,7 +45878,8 @@ def bounded_jsonl_events(path: Path, *, preserve_invalid: bool = False) -> Itera
45673
45878
  raise ValueError("transcript changed before parsing")
45674
45879
  for event, _end, raw in jsonl_records(stream, end=initial.st_size,
45675
45880
  require_newline=False, max_records=MAX_LOCAL_TRANSCRIPT_SCAN_LINES,
45676
- max_retained_bytes=MAX_LOCAL_TRANSCRIPT_LINE_BYTES):
45881
+ max_retained_bytes=MAX_LOCAL_TRANSCRIPT_LINE_BYTES,
45882
+ allow_nul_padding=allow_nul_padding):
45677
45883
  if not raw.blank and (event is not None or preserve_invalid):
45678
45884
  yield event
45679
45885
  finished = os.fstat(stream.fileno())
@@ -45683,7 +45889,7 @@ def bounded_jsonl_events(path: Path, *, preserve_invalid: bool = False) -> Itera
45683
45889
 
45684
45890
  def bounded_jsonl_records_range(
45685
45891
  path: Path, start: int, end: int, *, expected_stat: dict[str, int],
45686
- require_newline: bool = True, allow_partial: bool = False,
45892
+ require_newline: bool = True, allow_partial: bool = False, allow_nul_padding: bool = False,
45687
45893
  ) -> Iterator[tuple[dict[str, Any] | None, int]]:
45688
45894
  """Read every record and ending offset in one immutable JSONL range."""
45689
45895
  if start < 0 or end < start or end > expected_stat["st_size"]:
@@ -45695,7 +45901,8 @@ def bounded_jsonl_records_range(
45695
45901
  stream.seek(start)
45696
45902
  for count, (event, offset, _raw) in enumerate(jsonl_records(stream, end=end,
45697
45903
  require_newline=require_newline, max_records=MAX_LOCAL_TRANSCRIPT_SCAN_LINES,
45698
- max_retained_bytes=MAX_LOCAL_TRANSCRIPT_LINE_BYTES), 1):
45904
+ max_retained_bytes=MAX_LOCAL_TRANSCRIPT_LINE_BYTES,
45905
+ allow_nul_padding=allow_nul_padding), 1):
45699
45906
  yield event, offset
45700
45907
  if allow_partial and count >= MAX_LOCAL_TRANSCRIPT_SCAN_LINES:
45701
45908
  break
@@ -46504,7 +46711,7 @@ def parse_claude_history(
46504
46711
  expected_session_id: str | None = None,
46505
46712
  ) -> list[dict[str, str]]:
46506
46713
  return parse_claude_history_events(
46507
- bounded_jsonl_events(path, preserve_invalid=True),
46714
+ bounded_jsonl_events(path, preserve_invalid=True, allow_nul_padding=True),
46508
46715
  limit,
46509
46716
  expected_session_id=expected_session_id,
46510
46717
  )
@@ -48624,6 +48831,7 @@ def parse_provider_history_delta(
48624
48831
  end,
48625
48832
  expected_stat=expected_stat,
48626
48833
  allow_partial=True,
48834
+ allow_nul_padding=(backend == BACKEND_CLAUDE),
48627
48835
  ):
48628
48836
  if blocked_on_unseen_message:
48629
48837
  # Exhaust the fixed range so its final fstat validation still
@@ -49027,6 +49235,36 @@ def history_timeline_message_keys(
49027
49235
  if len(provider_runs) > maximum:
49028
49236
  provider_runs.pop(next(iter(provider_runs)))
49029
49237
  before_window = raw_seq <= after_seq
49238
+ if (event_type == "turn_started" and event.get("backend") == BACKEND_CLAUDE
49239
+ and event.get("purpose") == "provider_background_wake"
49240
+ and event.get("metadata_only") is True
49241
+ and event.get("provider_generated") is True
49242
+ and event.get("imported") is not True and event.get("prompt") in (None, "")
49243
+ and not event.get("file_ids")
49244
+ and event.get("provider_user_authored") is not True):
49245
+ # Native task/schedule completion opens a lifecycle-only run.
49246
+ # Claude's notification is intentionally absent from imported
49247
+ # user messages. An empty credit here would block matching its
49248
+ # reply and every subsequent real user/assistant occurrence.
49249
+ continue
49250
+ if (event_type == "turn_started" and event.get("backend") == BACKEND_CODEX
49251
+ and event.get("purpose") == "codex_goal_resume"
49252
+ and event.get("imported") is not True and event.get("prompt") in (None, "")
49253
+ and not event.get("file_ids")
49254
+ and event.get("provider_user_authored") is not True):
49255
+ # Resuming a native goal records a lifecycle boundary, not a
49256
+ # provider user message. An empty ownership credit would block
49257
+ # every subsequent assistant match in this cursor window.
49258
+ continue
49259
+ if (event.get("purpose") == "codex_goal_resume" and event.get("imported") is not True
49260
+ and event.get("backend") in (None, "", BACKEND_CODEX)
49261
+ and (event_type in {"assistant_text", "turn_finished", "job_summary"} or (
49262
+ event_type == "reasoning_summary" and event.get("phase") == "commentary"))):
49263
+ # Goal continuations can repeat words in distinct native items.
49264
+ # Their exact item/turn/thread ownership is reconciled by the
49265
+ # native import filter; a text credit could consume a genuine
49266
+ # external repeat before reaching the owned source item.
49267
+ continue
49030
49268
  if event_type == "turn_started" or is_native_goal_steer_event(event):
49031
49269
  key = history_dedup_key("user", event.get("prompt"), source_text_sha256=event.get("source_text_sha256"))
49032
49270
  elif event_type == "assistant_text":
@@ -55760,9 +55998,13 @@ async def stop_idle_claude_background_subagents(
55760
55998
  return result
55761
55999
  manager = CLAUDE_SDK_MANAGER
55762
56000
  loaded = False
56001
+ pending_native = False
55763
56002
  if manager is not None:
55764
56003
  try:
55765
56004
  loaded = manager.is_loaded(session_id)
56005
+ pending_check = getattr(manager, "has_pending_native_continuations", None)
56006
+ pending_native = bool(loaded and callable(pending_check)
56007
+ and pending_check(session_id) is True)
55766
56008
  except Exception as exc:
55767
56009
  # Do not claim success or hide historical work when ownership of
55768
56010
  # a potentially live process cannot be determined.
@@ -55790,8 +56032,11 @@ async def stop_idle_claude_background_subagents(
55790
56032
  active = []
55791
56033
  active_count = 1
55792
56034
  result["errors"].append(concise_error_message(exc))
55793
- if not active_count:
56035
+ if not active_count and not pending_native:
55794
56036
  return result
56037
+ # Native background Bash tasks do not appear in the Agent-only durable
56038
+ # subagent snapshot. Their exact SDK wake provenance still belongs to Stop.
56039
+ active_count = max(active_count, int(pending_native))
55795
56040
 
55796
56041
  result["fence_committed"] = False
55797
56042
 
@@ -55825,7 +56070,7 @@ async def stop_idle_claude_background_subagents(
55825
56070
  "run_ids": run_ids,
55826
56071
  "subagent_ids": subagent_ids,
55827
56072
  "all": True,
55828
- "message": "Stopped background Claude agents with the parent chat.",
56073
+ "message": "Stopped background Claude work with the parent chat.",
55829
56074
  })
55830
56075
  result["fence_committed"] = True
55831
56076
  except Exception as exc:
@@ -56369,6 +56614,7 @@ async def acquire_codex_control_thread(
56369
56614
  "provider_turn_id": None,
56370
56615
  "provider_turn_ready": False,
56371
56616
  "interactive_app_server": True,
56617
+ "cwd": cwd,
56372
56618
  "codex_approval_policy": effective_codex_approval_policy(session),
56373
56619
  "codex_native_operation": True,
56374
56620
  "codex_native_operation_kind": None,
@@ -56732,6 +56978,7 @@ def suspend_codex_goal_steer_user_delegation(
56732
56978
  continue
56733
56979
  previous = {key: capability[key] for key in (
56734
56980
  "source_user_instruction", "source_is_user_turn", "user_delegation_grants",
56981
+ "provider_route_source_instructions",
56735
56982
  ) if key in capability}
56736
56983
  records.append((token_hash, capability, previous))
56737
56984
  # No await occurs here or between before_send and the transport write.
@@ -56739,6 +56986,9 @@ def suspend_codex_goal_steer_user_delegation(
56739
56986
  # route grants, capability token and logical run identity do not change.
56740
56987
  capability["source_is_user_turn"] = False
56741
56988
  capability["user_delegation_grants"] = set()
56989
+ # Route-specific provenance is also task authority. Do not let a prior
56990
+ # @ selection bypass the uncertain-write fence or attest a later task.
56991
+ capability.pop("provider_route_source_instructions", None)
56742
56992
  capability["_goal_steer_user_delegation_marker"] = marker
56743
56993
  request["_goal_steer_user_delegation"] = (marker, records, instruction)
56744
56994
 
@@ -56768,7 +57018,7 @@ def settle_codex_goal_steer_user_delegation(
56768
57018
  # A plain goal follow-up supplies no new explicit reference grants.
56769
57019
  capability["user_delegation_grants"] = set()
56770
57020
  elif restore:
56771
- for key in ("source_user_instruction", "source_is_user_turn", "user_delegation_grants"):
57021
+ for key in ("source_user_instruction", "source_is_user_turn", "user_delegation_grants", "provider_route_source_instructions"):
56772
57022
  if key in previous:
56773
57023
  capability[key] = previous[key]
56774
57024
  else:
@@ -56776,6 +57026,175 @@ def settle_codex_goal_steer_user_delegation(
56776
57026
  # Uncertain acceptance leaves attestation disabled without blocking mail.
56777
57027
 
56778
57028
 
57029
+ async def prepare_codex_goal_route_steer(
57030
+ session_id: str, run_id: str, selected: dict[str, Any],
57031
+ ) -> dict[str, Any] | None:
57032
+ """Validate an exact local @ selection without changing live authority."""
57033
+ raw_references = selected.get("chat_references")
57034
+ if not raw_references:
57035
+ return None
57036
+ prompt = str(selected.get("prompt") or "")
57037
+ try:
57038
+ references = [ChatReference.model_validate(value) for value in raw_references]
57039
+ if selected.get("purpose") is not None or any(
57040
+ reference.target_kind is not None or reference.action != "route"
57041
+ or reference.grant_intent is not True or reference.route_action is not None
57042
+ for reference in references
57043
+ ):
57044
+ raise ValueError("Only explicit local @Chat access can be added to a running goal")
57045
+ references = validate_chat_references(
57046
+ session_id, prompt, references, selected.get("client_capabilities") or [],
57047
+ )
57048
+ except (HTTPException, ValueError, TypeError) as exc:
57049
+ raise NativeSteerHandoffError(
57050
+ str(exc.detail) if isinstance(exc, HTTPException) else str(exc),
57051
+ safe_to_requeue=True,
57052
+ ) from exc
57053
+ targets = {reference.session_id for reference in references}
57054
+ # Queued snapshots may also contain unmentioned permanent pairs. Only
57055
+ # the exact visible selection can extend this already-running owner.
57056
+ routes = [route for route in provider_cross_chat_route_snapshot_for_authority(
57057
+ selected.get("provider_cross_chat_route_snapshot"), references,
57058
+ source_session_id=session_id,
57059
+ ) if route.get("target_session_id") in targets and route.get("pair_id")
57060
+ and live_provider_cross_chat_route(session_id, route) is not None]
57061
+ if {route.get("target_session_id") for route in routes} != targets:
57062
+ raise NativeSteerHandoffError(
57063
+ "Selected chat access was revoked or changed; the follow-up remains queued",
57064
+ safe_to_requeue=True,
57065
+ )
57066
+ async with CROSS_CHAT_CAPABILITY_LOCK:
57067
+ matches = [(key, value) for key, value in CROSS_CHAT_CAPABILITIES.items()
57068
+ if value.get("source_session_id") == session_id
57069
+ and value.get("source_run_id") == run_id
57070
+ and not value.get("native_transition_nonce")]
57071
+ active = ACTIVE.get(session_id) or {}
57072
+ current = CURRENT_TURNS.get(session_id) or {}
57073
+ resumed_owner_without_authority = bool(
57074
+ not matches and re.fullmatch(r"run_[A-Za-z0-9_-]+", run_id)
57075
+ and active.get("run_id") == current.get("run_id") == run_id
57076
+ and active.get("codex_native_operation_kind") == "goal_resume"
57077
+ and active.get("codex_control_reservation_id")
57078
+ == current.get("codex_control_reservation_id")
57079
+ and active.get("codex_control_reservation_id")
57080
+ )
57081
+ if (not provider_capability_is_attached_to_live_run(session_id, run_id)
57082
+ or not resumed_owner_without_authority and (
57083
+ len(matches) != 1 or matches[0][1].get("server_identity") != server_identity()
57084
+ or matches[0][1].get("async_route_v1") is not True
57085
+ or float(matches[0][1].get("expires_at") or 0) <= time.time()
57086
+ )):
57087
+ raise NativeSteerHandoffError(
57088
+ "This running goal has no compatible chat-access authority; the follow-up remains queued",
57089
+ safe_to_requeue=True,
57090
+ )
57091
+ token_hash, capability = matches[0] if matches else (None, None)
57092
+ # Capture the registry object as well as its key: a replacement run or
57093
+ # capability cannot inherit this admission after native acknowledgement.
57094
+ return {
57095
+ "token_hash": token_hash, "capability": capability,
57096
+ "routes": tuple(copy.deepcopy(route) for route in routes),
57097
+ "source_user_instruction": prompt,
57098
+ }
57099
+
57100
+
57101
+ async def commit_codex_goal_route_steer(
57102
+ session_id: str, run_id: str, prepared: dict[str, Any] | None,
57103
+ ) -> bool:
57104
+ """Extend only the accepted owner's live routes; never revive revoked access."""
57105
+ if prepared is None:
57106
+ return True
57107
+ async with CROSS_CHAT_CAPABILITY_LOCK:
57108
+ capability = CROSS_CHAT_CAPABILITIES.get(prepared["token_hash"])
57109
+ if (capability is None or capability is not prepared["capability"]
57110
+ or capability.get("source_session_id") != session_id
57111
+ or capability.get("source_run_id") != run_id
57112
+ or capability.get("server_identity") != server_identity()
57113
+ or capability.get("native_transition_nonce")
57114
+ or float(capability.get("expires_at") or 0) <= time.time()
57115
+ or not provider_capability_is_attached_to_live_run(session_id, run_id)):
57116
+ return False
57117
+ routes = [live_provider_cross_chat_route(session_id, route) for route in prepared["routes"]]
57118
+ if any(route is None for route in routes):
57119
+ return False
57120
+ # Keep handles, reply bindings, action ceilings and consumed effects
57121
+ # from the original run. The static tool reads this environment afresh.
57122
+ actions = set(capability.get("actions") or set()) | {"agent_cross_chat_routes"}
57123
+ runtime_env = validate_provider_runtime_env({
57124
+ **(capability.get("provider_runtime_env") or {}),
57125
+ "AGENTSDOCK_PROVIDER_AUTHORITY_ACTIONS": ",".join(sorted(actions)),
57126
+ "AGENTSDOCK_CROSS_CHAT_MODE": "async_route_v1",
57127
+ })
57128
+ grants = dict(capability.get("provider_route_grants") or {})
57129
+ instructions = dict(capability.get("provider_route_source_instructions") or {})
57130
+ for route in routes:
57131
+ assert route is not None
57132
+ previous = grants.get(route["route_id"])
57133
+ if previous is None or any(previous.get(key) != route.get(key) for key in (
57134
+ "revision", "alias", "target_session_id", "pair_id", "paired_route_id",
57135
+ )):
57136
+ grants[route["route_id"]] = copy.deepcopy(route)
57137
+ instructions[route["route_id"]] = prepared["source_user_instruction"]
57138
+ capability.update({
57139
+ "provider_route_grants": grants,
57140
+ "provider_route_source_instructions": instructions,
57141
+ "actions": actions, "provider_runtime_env": runtime_env,
57142
+ })
57143
+ return True
57144
+
57145
+
57146
+ async def issue_codex_goal_route_steer_authority(
57147
+ session_id: str, run_id: str, prepared: dict[str, Any],
57148
+ ) -> bool:
57149
+ """Bind accepted user references to a resumed goal without replacing it."""
57150
+ active = ACTIVE.get(session_id) or {}
57151
+ if (active.get("codex_native_operation_kind") != "goal_resume"
57152
+ or not provider_capability_is_attached_to_live_run(session_id, run_id)
57153
+ or any(live_provider_cross_chat_route(session_id, route) is None
57154
+ for route in prepared["routes"])):
57155
+ return False
57156
+ async with CROSS_CHAT_CAPABILITY_LOCK:
57157
+ if any(value.get("source_run_id") == run_id
57158
+ for value in CROSS_CHAT_CAPABILITIES.values()):
57159
+ return False
57160
+ authority_path = None
57161
+ try:
57162
+ authority_path = await issue_cross_chat_capability(
57163
+ session_id, run_id, [],
57164
+ source_user_instruction=prepared["source_user_instruction"],
57165
+ actions={"agent_cross_chat_routes"},
57166
+ provider_route_snapshot=list(prepared["routes"]),
57167
+ async_route_v1=True,
57168
+ )
57169
+ if authority_path is None:
57170
+ return False
57171
+ await provider_authority_runtime_env(run_id, authority_path, session_id, [])
57172
+ async with CROSS_CHAT_CAPABILITY_LOCK:
57173
+ matches = [(key, value) for key, value in CROSS_CHAT_CAPABILITIES.items()
57174
+ if value.get("source_run_id") == run_id
57175
+ and value.get("authority_path") == str(authority_path)]
57176
+ if (len(matches) == 1
57177
+ and provider_capability_is_attached_to_live_run(session_id, run_id)):
57178
+ prepared["token_hash"], prepared["capability"] = matches[0]
57179
+ return True
57180
+ except Exception as exc:
57181
+ # Input is already accepted. Never return it to the queue after a
57182
+ # local authority failure, or deliver it twice on the next goal turn.
57183
+ logger.warning("could not bind accepted goal chat access session=%s: %s",
57184
+ session_id, concise_error_message(exc))
57185
+ finally:
57186
+ if authority_path is not None and prepared["capability"] is None:
57187
+ # Remove exactly our new record; never revoke the original owner
57188
+ # or a capability installed by later work in the same chat.
57189
+ async with CROSS_CHAT_CAPABILITY_LOCK:
57190
+ for key, value in list(CROSS_CHAT_CAPABILITIES.items()):
57191
+ if value.get("source_run_id") == run_id and value.get("authority_path") == str(authority_path):
57192
+ CROSS_CHAT_CAPABILITIES.pop(key, None)
57193
+ with suppress(OSError):
57194
+ authority_path.unlink()
57195
+ return False
57196
+
57197
+
56779
57198
  async def send_codex_goal_steer(
56780
57199
  session_id: str, operation_id: str, manager: CodexAppServerManager,
56781
57200
  thread_id: str, reservation_id: str, subscription: Any,
@@ -56783,6 +57202,11 @@ async def send_codex_goal_steer(
56783
57202
  ) -> dict[str, Any]:
56784
57203
  """Steer one exact native goal turn without replacing its authority/owner."""
56785
57204
  selected = request["selected"]
57205
+ selected_command = selected.get("skill_selection")
57206
+ command_selection = dict(selected_command) if isinstance(selected_command, dict) else selected_command
57207
+ user_prompt = str(selected.get("prompt") or "")
57208
+ reference_selection = copy.deepcopy(selected.get("chat_references"))
57209
+ route_steer = None
56786
57210
  expected_turn_id = str(request.get("expected_provider_turn_id") or "")
56787
57211
  generation = manager.generation
56788
57212
 
@@ -56838,10 +57262,20 @@ async def send_codex_goal_steer(
56838
57262
  and str(current.get("run_id") or "") == operation_id
56839
57263
  and str(active.get("codex_control_reservation_id") or "") == reservation_id
56840
57264
  and str(current.get("codex_control_reservation_id") or "") == reservation_id
56841
- and codex_goal_steer_selection_is_plain(selected)
56842
- # Only text/files are sent. The current turn's command, references,
56843
- # runtime and authority stay intact, regardless of picker changes
56844
- # or capability metadata on an older queued message.
57265
+ and codex_goal_steer_selection_is_supported(selected)
57266
+ and selected.get("skill_selection") == command_selection
57267
+ and str(selected.get("prompt") or "") == user_prompt
57268
+ and selected.get("chat_references") == reference_selection
57269
+ and (route_steer is None or route_steer["capability"] is None or (
57270
+ CROSS_CHAT_CAPABILITIES.get(route_steer["token_hash"]) is route_steer["capability"]
57271
+ and float(route_steer["capability"].get("expires_at") or 0) > time.time()
57272
+ ))
57273
+ and (route_steer is None or all(
57274
+ live_provider_cross_chat_route(session_id, route) is not None
57275
+ for route in route_steer["routes"]
57276
+ ))
57277
+ # Runtime and the original command remain pinned. Only accepted,
57278
+ # explicitly selected references add to the same owner's routes.
56845
57279
  )
56846
57280
 
56847
57281
  async def validate_delivery_owner() -> None:
@@ -56857,16 +57291,28 @@ async def send_codex_goal_steer(
56857
57291
  if not delivery_owner_valid():
56858
57292
  return False
56859
57293
  suspend_codex_goal_steer_user_delegation(
56860
- session_id, operation_id, request, user_instruction,
57294
+ session_id, operation_id, request, user_prompt,
56861
57295
  )
56862
57296
  return True
56863
57297
 
56864
57298
  try:
56865
57299
  await validate_delivery_owner()
56866
- user_instruction = str(selected.get("prompt") or "")
57300
+ command = None
57301
+ if command_selection is not None:
57302
+ owner_session = {**(STORE.sessions.get(session_id) or {}),
57303
+ "cwd": (ACTIVE.get(session_id) or {}).get("cwd")
57304
+ or (STORE.sessions.get(session_id) or {}).get("cwd")}
57305
+ command = await resolve_provider_command_selection(
57306
+ session_id, owner_session, SkillSelection.model_validate(command_selection),
57307
+ prompt=user_prompt, purpose=None, provider_context_mode="chat",
57308
+ client_capabilities=list(selected.get("client_capabilities") or []),
57309
+ refresh_native=True, codex_manager=manager,
57310
+ )
56867
57311
  prompt = build_user_provider_prompt(
56868
- session_id, user_instruction, list(selected.get("file_ids") or []),
57312
+ session_id, user_prompt, list(selected.get("file_ids") or []),
56869
57313
  )
57314
+ input_items = codex_provider_command_turn_input(prompt, command)
57315
+ route_steer = await prepare_codex_goal_route_steer(session_id, operation_id, selected)
56870
57316
  await fence_native_steer_delivery(session_id, selected, backend=BACKEND_CODEX)
56871
57317
  # Stop/Pause, budget/goal changes, and native turn rollover can win
56872
57318
  # during the durable fence. Check again at the RPC boundary.
@@ -56874,7 +57320,7 @@ async def send_codex_goal_steer(
56874
57320
  request["_goal_steer_rpc_started"] = True
56875
57321
  acknowledged_turn_id, watermark = await manager.steer_turn_with_notification_watermark(
56876
57322
  thread_id, expected_turn_id,
56877
- [{"type": "text", "text": prompt, "text_elements": []}],
57323
+ input_items,
56878
57324
  client_user_message_id=str(selected.get("queued_id") or ""),
56879
57325
  notification_subscription=subscription,
56880
57326
  before_send=before_send,
@@ -56885,7 +57331,11 @@ async def send_codex_goal_steer(
56885
57331
  request_sent=True, safe_to_retry=False,
56886
57332
  )
56887
57333
  settle_codex_goal_steer_user_delegation(request, accepted=True)
56888
- return {"request": request, "watermark": watermark, "provider_turn_id": expected_turn_id}
57334
+ return {"request": request, "watermark": watermark, "provider_turn_id": expected_turn_id,
57335
+ "route_steer": route_steer,
57336
+ **({"skill_selection": command_selection,
57337
+ "source_text_sha256": history_dedup_key("user", codex_provider_command_turn_input(user_prompt, command)[0]["text"])[1]}
57338
+ if command is not None else {})}
56889
57339
  except NativeSteerHandoffError as exc:
56890
57340
  settle_codex_goal_steer_user_delegation(
56891
57341
  request, accepted=False, restore=exc.safe_to_requeue,
@@ -56935,11 +57385,14 @@ async def commit_codex_goal_steer(
56935
57385
  if selected.get("display_file_ids") is not None
56936
57386
  else selected.get("file_ids") or []
56937
57387
  )
57388
+ reference_fields = ({"chat_references": selected["chat_references"]}
57389
+ if selected.get("chat_references") else {})
56938
57390
  await append_durable_event_batch(session_id, [
56939
57391
  ("turn_queue_run_now", {
56940
57392
  "queued_id": selected.get("queued_id"), "run_id": operation_id,
56941
57393
  "backend": BACKEND_CODEX, "prompt": display_prompt,
56942
57394
  "file_ids": display_file_ids,
57395
+ **reference_fields,
56943
57396
  "native_steer": True, "native_goal_steer": True,
56944
57397
  "interrupted": False, "replays_interrupted_message": False,
56945
57398
  "remaining": request.get("remaining", 0), "superseded_queued_ids": [],
@@ -56951,12 +57404,26 @@ async def commit_codex_goal_steer(
56951
57404
  "queued_id": selected.get("queued_id"), "prompt": display_prompt,
56952
57405
  "file_ids": display_file_ids, "native_steer": True, "native_goal_steer": True,
56953
57406
  "provider_user_authored": True,
57407
+ **reference_fields,
57408
+ **({"skill_selection": pending["skill_selection"],
57409
+ "source_text_sha256": pending["source_text_sha256"]}
57410
+ if pending.get("skill_selection") is not None else {}),
56954
57411
  }),
56955
57412
  ])
57413
+ route_steer = pending.get("route_steer")
57414
+ access_applied = True
57415
+ if route_steer is not None:
57416
+ if route_steer["capability"] is None:
57417
+ access_applied = await issue_codex_goal_route_steer_authority(session_id, operation_id, route_steer)
57418
+ if access_applied:
57419
+ access_applied = await commit_codex_goal_route_steer(session_id, operation_id, route_steer)
56956
57420
  return {
56957
57421
  "ok": True, "queued_id": selected.get("queued_id"), "run_id": operation_id,
56958
57422
  "interrupted": False, "native_steer": True, "native_goal_steer": True,
56959
57423
  "replays_interrupted_message": False, "superseded_queued_ids": [],
57424
+ **({"chat_access_applied": access_applied} if route_steer is not None else {}),
57425
+ **({"message": "Message sent, but the selected chat access was revoked or became unavailable. The message will not be resent."}
57426
+ if not access_applied else {}),
56960
57427
  }
56961
57428
 
56962
57429
 
@@ -57474,6 +57941,8 @@ async def consume_codex_native_turn(
57474
57941
  **({"phase": phase} if phase in {"commentary", "final_answer"} else {}),
57475
57942
  "text": text,
57476
57943
  "purpose": f"codex_{operation}",
57944
+ **({"backend": BACKEND_CODEX, "provider_thread_id": thread_id}
57945
+ if goal_resume else {}),
57477
57946
  },
57478
57947
  )
57479
57948
  elif item_type in {"reasoning", "plan"}:
@@ -57779,6 +58248,13 @@ async def consume_codex_native_turn(
57779
58248
  },
57780
58249
  )
57781
58250
  finally:
58251
+ if goal_resume:
58252
+ authority_cleanup = asyncio.create_task(revoke_cross_chat_capability(operation_id))
58253
+ try:
58254
+ await asyncio.shield(authority_cleanup)
58255
+ except BaseException:
58256
+ with suppress(BaseException):
58257
+ await join_task_despite_caller_cancellation(authority_cleanup)
57782
58258
  STOPPED_RUNS.discard(operation_id)
57783
58259
  if terminal_claimed:
57784
58260
  # The slot is already exactly released. Remove the admission
@@ -58876,7 +59352,8 @@ def probe_runtime(backend: str) -> dict[str, Any]:
58876
59352
  return runtime_diagnostic_payload(backend, "error", installed=True, authenticated=None, version=version)
58877
59353
 
58878
59354
 
58879
- def store_runtime_diagnostic(diagnostic: dict[str, Any], *, preserve_last_error: bool = True) -> dict[str, Any]:
59355
+ def store_runtime_diagnostic(diagnostic: dict[str, Any], *, preserve_last_error: bool = True, from_probe: bool = False) -> dict[str, Any]:
59356
+ global RUNTIME_DIAGNOSTIC_REVISION
58880
59357
  backend = str(diagnostic.get("backend") or "")
58881
59358
  with RUNTIME_DIAGNOSTICS_LOCK:
58882
59359
  previous = RUNTIME_DIAGNOSTICS.get(backend) or {}
@@ -58885,6 +59362,8 @@ def store_runtime_diagnostic(diagnostic: dict[str, Any], *, preserve_last_error:
58885
59362
  current["last_error"] = previous.get("last_error")
58886
59363
  current["last_error_at"] = previous.get("last_error_at")
58887
59364
  RUNTIME_DIAGNOSTICS[backend] = current
59365
+ if not from_probe:
59366
+ RUNTIME_DIAGNOSTIC_REVISION += 1
58888
59367
  RUNTIME_DIAGNOSTIC_GENERATIONS[backend] = (
58889
59368
  RUNTIME_DIAGNOSTIC_GENERATIONS.get(backend, 0) + 1
58890
59369
  )
@@ -58904,34 +59383,70 @@ def expire_codex_login_diagnostic() -> None:
58904
59383
  store_runtime_diagnostic(current)
58905
59384
 
58906
59385
 
59386
+ def runtime_diagnostic_budget_fallback(backend: str) -> dict[str, Any]:
59387
+ # Do not cache an incomplete check or make old evidence look fresh.
59388
+ # In particular, budget starvation must not mark another provider
59389
+ # missing, incompatible, or signed out for the diagnostic cache TTL.
59390
+ with RUNTIME_DIAGNOSTICS_LOCK:
59391
+ current = dict(RUNTIME_DIAGNOSTICS.get(backend) or {})
59392
+ if current:
59393
+ return current
59394
+ return runtime_diagnostic_payload(
59395
+ backend, "unknown", installed=None, authenticated=None,
59396
+ message=(
59397
+ f"{runtime_display_name(backend)} check did not finish before the "
59398
+ "runtime refresh deadline. Try Re-check again."
59399
+ ),
59400
+ )
59401
+
59402
+
58907
59403
  def runtime_diagnostic(backend: str, *, force: bool = False) -> dict[str, Any]:
58908
59404
  with RUNTIME_DIAGNOSTICS_LOCK:
58909
59405
  cached = dict(RUNTIME_DIAGNOSTICS.get(backend) or {})
58910
59406
  generation = RUNTIME_DIAGNOSTIC_GENERATIONS.get(backend, 0)
58911
- checked_at = cached.get("_installation_checked_at_epoch", cached.get("checked_at_epoch"))
58912
- if backend == BACKEND_CODEX and cached.get("_codex_auth_mode_checked_at_epoch") is not None:
58913
- checked_at = min(checked_at or 0, cached["_codex_auth_mode_checked_at_epoch"])
58914
- if not force and isinstance(checked_at, (int, float)) and time.time() - checked_at < RUNTIME_DIAGNOSTIC_TTL_SECONDS:
58915
- return cached
59407
+ checked_at = cached.get("_installation_checked_at_epoch", cached.get("checked_at_epoch"))
59408
+ if backend == BACKEND_CODEX and cached.get("_codex_auth_mode_checked_at_epoch") is not None:
59409
+ checked_at = min(checked_at or 0, cached["_codex_auth_mode_checked_at_epoch"])
59410
+ if not force and isinstance(checked_at, (int, float)) and time.time() - checked_at < RUNTIME_DIAGNOSTIC_TTL_SECONDS:
59411
+ return cached
59412
+ if runtime_catalog_budget_expired():
59413
+ return runtime_diagnostic_budget_fallback(backend)
59414
+ # A changed login/runtime generation must not join a pre-change probe.
59415
+ key = (backend, generation)
59416
+ pending = RUNTIME_DIAGNOSTIC_PROBES.get(key)
59417
+ owner = pending is None
59418
+ if pending is None:
59419
+ pending = Future()
59420
+ RUNTIME_DIAGNOSTIC_PROBES[key] = pending
59421
+ if not owner:
59422
+ deadline = RUNTIME_CATALOG_DEADLINE.get()
59423
+ try:
59424
+ return dict(pending.result(timeout=None if deadline is None else max(0.0, deadline - time.monotonic())))
59425
+ except TimeoutError:
59426
+ if pending.done():
59427
+ return dict(pending.result()) # Preserve an owner's own exception.
59428
+ return runtime_diagnostic_budget_fallback(backend)
59429
+ try:
59430
+ result = probe_runtime_diagnostic(backend, cached, generation)
59431
+ except BaseException as exc:
59432
+ with RUNTIME_DIAGNOSTICS_LOCK:
59433
+ RUNTIME_DIAGNOSTIC_PROBES.pop(key, None)
59434
+ pending.set_exception(exc)
59435
+ raise
59436
+ else:
59437
+ with RUNTIME_DIAGNOSTICS_LOCK:
59438
+ RUNTIME_DIAGNOSTIC_PROBES.pop(key, None)
59439
+ pending.set_result(result)
59440
+ return dict(result)
59441
+
59442
+
59443
+ def probe_runtime_diagnostic(backend: str, cached: dict[str, Any], generation: int) -> dict[str, Any]:
58916
59444
  try:
58917
59445
  if runtime_catalog_budget_expired():
58918
59446
  raise RuntimeCatalogBudgetExpired()
58919
59447
  probed = probe_runtime(backend)
58920
59448
  except RuntimeCatalogBudgetExpired:
58921
- # Do not cache an incomplete check or make old evidence look fresh.
58922
- # In particular, budget starvation must not mark another provider
58923
- # missing, incompatible, or signed out for the diagnostic cache TTL.
58924
- with RUNTIME_DIAGNOSTICS_LOCK:
58925
- current = dict(RUNTIME_DIAGNOSTICS.get(backend) or {})
58926
- if current:
58927
- return current
58928
- return runtime_diagnostic_payload(
58929
- backend, "unknown", installed=None, authenticated=None,
58930
- message=(
58931
- f"{runtime_display_name(backend)} check did not finish before the "
58932
- "runtime refresh deadline. Try Re-check again."
58933
- ),
58934
- )
59449
+ return runtime_diagnostic_budget_fallback(backend)
58935
59450
  with RUNTIME_DIAGNOSTICS_LOCK:
58936
59451
  if RUNTIME_DIAGNOSTIC_GENERATIONS.get(backend, 0) != generation:
58937
59452
  current = dict(RUNTIME_DIAGNOSTICS.get(backend) or {})
@@ -58952,7 +59467,7 @@ def runtime_diagnostic(backend: str, *, force: bool = False) -> dict[str, Any]:
58952
59467
  "version": probed.get("version"),
58953
59468
  "_installation_checked_at_epoch": probed.get("checked_at_epoch"),
58954
59469
  }
58955
- return store_runtime_diagnostic(probed)
59470
+ return store_runtime_diagnostic(probed, from_probe=True)
58956
59471
 
58957
59472
 
58958
59473
  def refresh_runtime_diagnostics(*, force: bool = False) -> dict[str, dict[str, Any]]:
@@ -60994,19 +61509,21 @@ def build_claude_cmd(
60994
61509
  cmd.extend(["--model", str(sess["model"])])
60995
61510
  if sess.get("effort"):
60996
61511
  cmd.extend(["--effort", str(sess["effort"])])
61512
+ runtime_settings = print_routing_settings(manifest_path)
60997
61513
  subagent_limit = sess.get("subagent_limit")
60998
61514
  if type(subagent_limit) is int and subagent_limit > 0:
60999
61515
  # Flag settings override inherited user/project env without writing
61000
61516
  # shared Claude settings or changing another chat's process.
61001
- cmd.extend(["--settings", json.dumps({"env": {
61517
+ runtime_settings["env"] = {
61002
61518
  "CLAUDE_CODE_MAX_CONCURRENT_SUBAGENTS": str(subagent_limit),
61003
- }}, separators=(",", ":"))])
61519
+ }
61004
61520
  if sess.get("provider_connection") == "custom":
61005
- _, settings_path = PROVIDER_CONNECTION_STORE.claude_overrides(sess)
61006
- if "--settings" in cmd:
61007
- index = cmd.index("--settings")
61008
- del cmd[index:index + 2]
61521
+ _, settings_path = PROVIDER_CONNECTION_STORE.claude_overrides(
61522
+ sess, runtime_settings=runtime_settings,
61523
+ )
61009
61524
  cmd.extend(["--settings", settings_path])
61525
+ else:
61526
+ cmd.extend(["--settings", json.dumps(runtime_settings, separators=(",", ":"))])
61010
61527
  if no_session_persistence and not provider_id:
61011
61528
  cmd.append("--no-session-persistence")
61012
61529
  if provider_id:
@@ -61120,12 +61637,15 @@ def build_claude_sdk_options(
61120
61637
  raise ValueError("The completed Claude fork snapshot is unavailable; refusing an empty resume.")
61121
61638
  permission_owner = {"token": ""}
61122
61639
  provider_tool_owner = {"ownership_token": "", "run_id": ""}
61640
+ native_admission_gate: asyncio.Event | None = None
61123
61641
 
61124
61642
  async def can_use_tool(
61125
61643
  tool_name: str,
61126
61644
  input_data: dict[str, Any],
61127
61645
  context: Any,
61128
61646
  ) -> Any:
61647
+ if native_admission_gate is not None:
61648
+ await native_admission_gate.wait()
61129
61649
  return await handle_claude_tool_permission(
61130
61650
  session_id,
61131
61651
  tool_name,
@@ -61140,6 +61660,8 @@ def build_claude_sdk_options(
61140
61660
  setattr(can_use_tool, "_agentsdock_bind_owner", bind_permission_owner)
61141
61661
 
61142
61662
  async def run_agentsdock_tool(input_data: dict[str, Any]) -> dict[str, Any]:
61663
+ if native_admission_gate is not None:
61664
+ await native_admission_gate.wait()
61143
61665
  ownership_token = str(provider_tool_owner["ownership_token"] or "")
61144
61666
  owner_run_id = str(provider_tool_owner["run_id"] or "")
61145
61667
  try:
@@ -61210,7 +61732,7 @@ def build_claude_sdk_options(
61210
61732
  },
61211
61733
  permission_mode=effective_claude_permission_mode(sess),
61212
61734
  can_use_tool=can_use_tool,
61213
- hooks=claude_background_tracking_hooks(),
61735
+ hooks=claude_background_tracking_hooks(manifest_path.with_name("claude-child-routing")),
61214
61736
  # This internal tool performs its own exact live-run authorization.
61215
61737
  # Do not make the desktop ask the user to approve the transport
61216
61738
  # wrapper in normal Claude permission modes.
@@ -61243,11 +61765,17 @@ def build_claude_sdk_options(
61243
61765
  provider_tool_owner["ownership_token"] = str(ownership_token)
61244
61766
  provider_tool_owner["run_id"] = str(run_id)
61245
61767
 
61768
+ def bind_native_admission_gate(gate: asyncio.Event | None) -> None:
61769
+ nonlocal native_admission_gate
61770
+ native_admission_gate = gate
61771
+
61246
61772
  if isinstance(options, dict):
61773
+ options["_agentsdock_bind_native_admission_gate"] = bind_native_admission_gate
61247
61774
  options["_agentsdock_bind_provider_tool_owner"] = (
61248
61775
  bind_provider_tool_owner
61249
61776
  )
61250
61777
  else:
61778
+ setattr(options, "_agentsdock_bind_native_admission_gate", bind_native_admission_gate)
61251
61779
  setattr(
61252
61780
  options,
61253
61781
  "_agentsdock_bind_provider_tool_owner",
@@ -61291,6 +61819,7 @@ async def discover_session_provider_commands(
61291
61819
  session: dict[str, Any],
61292
61820
  *,
61293
61821
  refresh: bool = False,
61822
+ codex_manager: CodexAppServerManager | None = None,
61294
61823
  ) -> tuple[dict[str, Any], ProviderCommandInventory]:
61295
61824
  """Read one backend's native inventory without exposing provider metadata."""
61296
61825
 
@@ -61378,7 +61907,7 @@ async def discover_session_provider_commands(
61378
61907
 
61379
61908
  if backend == BACKEND_CODEX:
61380
61909
  try:
61381
- manager = await codex_app_server_manager(session)
61910
+ manager = codex_manager if codex_manager is not None else await codex_app_server_manager(session)
61382
61911
  raw = await manager.request(
61383
61912
  "skills/list",
61384
61913
  {"cwds": [cwd], "forceReload": bool(refresh)},
@@ -61417,11 +61946,24 @@ async def discover_session_provider_commands(
61417
61946
  cwd,
61418
61947
  codex_manifest_path(session_id),
61419
61948
  )
61420
- raw, generation = await manager.get_server_info(
61421
- session_id,
61422
- options=options,
61423
- configuration_key=configuration_key,
61424
- )
61949
+ cached_getter = getattr(manager, "get_cached_server_info", None)
61950
+ cached = (cached_getter(session_id, configuration_key=configuration_key)
61951
+ if session_id in CLAUDE_TURN_ADMISSIONS and callable(cached_getter)
61952
+ else None)
61953
+ if cached is not None:
61954
+ # Native wake admission may be waiting for this human's
61955
+ # local persistence. Its exact initialization snapshot needs
61956
+ # no actor request, including before that collision occurs.
61957
+ raw, generation = cached
61958
+ else:
61959
+ if (session_id in CLAUDE_TURN_ADMISSIONS and callable(cached_getter)
61960
+ and manager.is_loaded(session_id)):
61961
+ raise ClaudeSDKUnavailable("Claude initialization metadata is unavailable for this admission")
61962
+ raw, generation = await manager.get_server_info(
61963
+ session_id,
61964
+ options=options,
61965
+ configuration_key=configuration_key,
61966
+ )
61425
61967
  inventory = claude_provider_command_inventory(
61426
61968
  raw,
61427
61969
  cwd=cwd,
@@ -61523,6 +62065,7 @@ async def resolve_provider_command_selection(
61523
62065
  provider_context_mode: str,
61524
62066
  client_capabilities: list[str],
61525
62067
  refresh_native: bool = False,
62068
+ codex_manager: CodexAppServerManager | None = None,
61526
62069
  ) -> ProviderCommandRecord | None:
61527
62070
  """Revalidate an opaque provider command at every actual admission."""
61528
62071
 
@@ -61561,6 +62104,7 @@ async def resolve_provider_command_selection(
61561
62104
  # Revalidate against the exact current provider generation. Do not
61562
62105
  # evict it here: Claude command inventories can vary across connects.
61563
62106
  refresh=bool(refresh_native and backend == BACKEND_CODEX),
62107
+ **({"codex_manager": codex_manager} if codex_manager is not None else {}),
61564
62108
  )
61565
62109
  if snapshot["support"].get("available") is not True:
61566
62110
  deterministic_transport_mismatch = (
@@ -64780,6 +65324,316 @@ async def send_claude_followup(
64780
65324
  ) from exc
64781
65325
 
64782
65326
 
65327
+ async def bind_claude_native_continuation_authority(
65328
+ session_id: str, run_id: str, authority: dict[str, Any],
65329
+ ) -> None:
65330
+ """Rebind retained parent authority without minting new user intent.
65331
+
65332
+ The exact record survives only in its SDK generation's native callback. Its
65333
+ expiry, original instruction, revocation generations, consumed grants and
65334
+ counters survive the rollover; the retired run's token is never revived.
65335
+ """
65336
+ async with CROSS_CHAT_CAPABILITY_LOCK:
65337
+ if (
65338
+ authority.get("source_session_id") != session_id
65339
+ or authority.get("server_identity") != server_identity()
65340
+ or any(record is authority for record in CROSS_CHAT_CAPABILITIES.values())
65341
+ ):
65342
+ raise ProviderToolError("native continuation authority is unavailable")
65343
+ token = secrets.token_urlsafe(32)
65344
+ token_hash = hashlib.sha256(token.encode("utf-8")).hexdigest()
65345
+ path = cross_chat_authority_path(run_id, secrets.token_hex(16))
65346
+ payload = json.dumps({
65347
+ "version": 1, "server_identity": authority["server_identity"],
65348
+ "provider_server_origin": provider_helper_server_origin(),
65349
+ "source_session_id": session_id, "source_run_id": run_id,
65350
+ "provider_capability": token, "capability": token,
65351
+ "provider_jobs_access": authority.get("provider_jobs_access", "blocked"),
65352
+ "expires_at": authority["expires_at"],
65353
+ }, separators=(",", ":")).encode("utf-8")
65354
+ descriptor = -1
65355
+ try:
65356
+ descriptor = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_EXCL
65357
+ | getattr(os, "O_NOFOLLOW", 0), 0o600)
65358
+ write_all(descriptor, payload)
65359
+ os.fsync(descriptor)
65360
+ os.close(descriptor)
65361
+ descriptor = -1
65362
+ if os.name != "nt":
65363
+ directory_fd = os.open(CROSS_CHAT_AUTHORITY_ROOT,
65364
+ os.O_RDONLY | getattr(os, "O_DIRECTORY", 0))
65365
+ try:
65366
+ os.fsync(directory_fd)
65367
+ finally:
65368
+ os.close(directory_fd)
65369
+ runtime_env = dict(authority.get("provider_runtime_env") or {})
65370
+ runtime_env["AGENTSDOCK_PROVIDER_AUTHORITY_FILE"] = str(path)
65371
+ authority.update({
65372
+ "source_run_id": run_id, "authority_path": str(path),
65373
+ "native_transition_nonce": "",
65374
+ "provider_runtime_env": validate_provider_runtime_env(runtime_env),
65375
+ })
65376
+ CROSS_CHAT_CAPABILITIES[token_hash] = authority
65377
+ except BaseException:
65378
+ with suppress(OSError):
65379
+ path.unlink()
65380
+ raise
65381
+ finally:
65382
+ if descriptor >= 0:
65383
+ os.close(descriptor)
65384
+
65385
+
65386
+ async def claude_native_continuation_context(
65387
+ session_id: str, run_id: str, prompt: str, turn: dict[str, Any],
65388
+ manager: Any, options: tuple[Any, str, str], manifest_path: Path,
65389
+ ) -> dict[str, Any] | None:
65390
+ async with CROSS_CHAT_CAPABILITY_LOCK:
65391
+ authorities = [record for record in CROSS_CHAT_CAPABILITIES.values()
65392
+ if record.get("source_session_id") == session_id
65393
+ and record.get("source_run_id") == run_id]
65394
+ if len(authorities) != 1:
65395
+ return None
65396
+ return {
65397
+ "authority": authorities[0], "manager": manager, "options": options,
65398
+ "manifest_path": manifest_path, "prompt": prompt, "turn": dict(turn),
65399
+ "completed": {run_id: asyncio.Event()},
65400
+ }
65401
+
65402
+
65403
+ async def wait_for_claude_paused_start(session_id: str, run_id: str) -> bool:
65404
+ """Wait for the original, never-submitted admission; do not create intent."""
65405
+ while True:
65406
+ paused = CLAUDE_NATIVE_PAUSED_STARTS.get(session_id)
65407
+ if paused is None or paused["run_id"] != run_id:
65408
+ return True
65409
+ await paused["ready"].wait()
65410
+ if CLAUDE_NATIVE_PAUSED_STARTS.get(session_id) is not paused:
65411
+ continue
65412
+ if paused["ready"].is_set():
65413
+ CLAUDE_NATIVE_PAUSED_STARTS.pop(session_id, None)
65414
+ return paused.get("restored") is True
65415
+
65416
+
65417
+ async def cancel_claude_paused_start(session_id: str, run_id: str) -> bool:
65418
+ paused = CLAUDE_NATIVE_PAUSED_STARTS.get(session_id)
65419
+ if paused is None or paused["run_id"] != run_id:
65420
+ return False
65421
+ paused["cancelled"] = True
65422
+ await finish_claude_paused_start(session_id, paused["native_run_id"])
65423
+ return True
65424
+
65425
+
65426
+ async def finish_claude_paused_start(session_id: str, native_run_id: str | None) -> None:
65427
+ paused = CLAUDE_NATIVE_PAUSED_STARTS.get(session_id)
65428
+ if paused is None or paused["native_run_id"] != native_run_id:
65429
+ return
65430
+ async with paused.setdefault("finish_lock", asyncio.Lock()):
65431
+ if (CLAUDE_NATIVE_PAUSED_STARTS.get(session_id) is not paused
65432
+ or not paused.get("released")
65433
+ or (paused["ready"].is_set()
65434
+ and not (paused.get("cancelled") and paused.get("restored")))):
65435
+ return
65436
+ try:
65437
+ if paused.get("restored") and (
65438
+ paused.get("cancelled")
65439
+ or session_id in STOP_REQUESTS or paused["run_id"] in STOPPED_RUNS
65440
+ or stop_cleanup_in_progress(session_id) or SERVER_SHUTTING_DOWN
65441
+ or session_id in DELETING_SESSIONS or session_id in DELETED_SESSION_TOMBSTONES
65442
+ or session_id not in STORE.sessions
65443
+ ):
65444
+ paused["restored"] = False
65445
+ await release_turn_slot(session_id, expected_run_id=paused["run_id"])
65446
+ if not paused.get("restored"):
65447
+ run_id = paused["run_id"]
65448
+ await revoke_cross_chat_capability(run_id)
65449
+ await append_event(session_id, "turn_stopped", {
65450
+ "run_id": run_id, "backend": BACKEND_CLAUDE,
65451
+ "transport": CLAUDE_TRANSPORT_AGENT_SDK,
65452
+ "stopped": True, "provider_query_submitted": False,
65453
+ "message": "Stopped before the pending message was sent to Claude.",
65454
+ **run_event_metadata(run_id),
65455
+ })
65456
+ RUN_METADATA.pop(run_id, None)
65457
+ finally:
65458
+ paused["ready"].set()
65459
+ if paused.get("cancelled") and CLAUDE_NATIVE_PAUSED_STARTS.get(session_id) is paused:
65460
+ CLAUDE_NATIVE_PAUSED_STARTS.pop(session_id, None)
65461
+
65462
+
65463
+ async def admit_claude_native_continuation(
65464
+ receipt: ClaudeSDKNativeContinuation, context: dict[str, Any],
65465
+ ) -> bool:
65466
+ """Own an already-running native wake; never submit another provider query."""
65467
+ session_id, run_id = receipt.chat_id, receipt.run_id
65468
+ scheduled_wake = getattr(receipt, "wake_kind", "task") == "schedule"
65469
+ parent_done = context["completed"].get(receipt.parent_run_id)
65470
+ if parent_done is None:
65471
+ return False
65472
+ # A fast child may wake while the parent's terminal persistence is still
65473
+ # releasing authority. Wait for that exact finalizer, never another turn.
65474
+ try:
65475
+ await asyncio.wait_for(parent_done.wait(), timeout=10.0)
65476
+ except asyncio.TimeoutError:
65477
+ return False
65478
+ admission = CLAUDE_TURN_ADMISSIONS.get(session_id)
65479
+ if admission is not None:
65480
+ # The accepted human request finishes local persistence independently
65481
+ # of the SDK actor. Preserve those effects rather than re-enqueueing it.
65482
+ await admission.wait()
65483
+ lock = session_lifecycle_lock(session_id)
65484
+ # A human admission may hold this lock while waiting on the SDK actor
65485
+ # that invoked us. Refuse instead of waiting and deadlocking that actor.
65486
+ if lock.locked():
65487
+ return False
65488
+ async with lock:
65489
+ sess = STORE.sessions.get(session_id)
65490
+ manager = context["manager"]
65491
+ if (
65492
+ sess is None or SERVER_SHUTTING_DOWN
65493
+ or session_id in DELETING_SESSIONS
65494
+ or session_id in DELETED_SESSION_TOMBSTONES
65495
+ or session_id in SERVER_MAINTENANCE_SESSIONS
65496
+ or stop_cleanup_in_progress(session_id)
65497
+ or session_id in STOP_REQUESTS
65498
+ # A clean native interrupt stops that turn, while successful
65499
+ # cron registrations remain live in the same SDK generation.
65500
+ or (receipt.parent_run_id in STOPPED_RUNS and not scheduled_wake)
65501
+ or str(sess.get("backend") or DEFAULT_BACKEND) != BACKEND_CLAUDE
65502
+ or claude_provider_id_for_session(sess) != receipt.provider_session_id
65503
+ or not manager.owns_active_run(session_id, receipt.ownership_token, run_id)
65504
+ or claude_sdk_configuration_key(
65505
+ sess, existing_cwd(str(sess.get("cwd") or DEFAULT_CWD)),
65506
+ context["options"][2],
65507
+ session_system_prompt(session_id, sess, context["manifest_path"]),
65508
+ ) != context["options"][1]
65509
+ ):
65510
+ return False
65511
+ async with ACTIVE_LOCK:
65512
+ current = CURRENT_TURNS.get(session_id)
65513
+ active = ACTIVE.get(session_id)
65514
+ if session_id in BUSY_SESSIONS or active is not None or current is not None:
65515
+ pending_human = bool(
65516
+ current is not None and current.get("run_id")
65517
+ and current.get("run_id") != run_id
65518
+ and current.get("backend") == BACKEND_CLAUDE
65519
+ and current.get("purpose") is None
65520
+ and current.get("provider_context_mode", "chat") == "chat"
65521
+ and current.get("_claude_native_pause_allowed") is True
65522
+ and (active is None or (
65523
+ active.get("provider_starting") is True
65524
+ and active.get("claude_sdk_run") is None
65525
+ and not active.get("claude_sdk_owner_token")
65526
+ and not active.get("stop_requested")
65527
+ ))
65528
+ )
65529
+ if not pending_human:
65530
+ return False
65531
+ paused = CLAUDE_NATIVE_PAUSED_STARTS.get(session_id)
65532
+ if paused is None:
65533
+ paused = {"run_id": current["run_id"], "turn": current,
65534
+ "active": active, "ready": asyncio.Event()}
65535
+ owner = CLAUDE_START_TASKS.get((session_id, current["run_id"]))
65536
+ paused["cancelled"] = owner is not None and owner.done()
65537
+ CLAUDE_NATIVE_PAUSED_STARTS[session_id] = paused
65538
+ elif paused["run_id"] != current["run_id"]:
65539
+ return False
65540
+ paused.update(native_run_id=run_id, released=False, restored=False)
65541
+ paused["ready"].clear()
65542
+ ACTIVE.pop(session_id, None)
65543
+ BUSY_SESSIONS.add(session_id)
65544
+ CURRENT_TURNS[session_id] = {
65545
+ **context["turn"], "run_id": run_id,
65546
+ "purpose": "provider_background_wake",
65547
+ "parent_run_id": receipt.parent_run_id,
65548
+ "provider_context_mode": "chat",
65549
+ "queued_id": None, "skill_selection": None,
65550
+ }
65551
+ metadata = {
65552
+ "purpose": "provider_background_wake",
65553
+ "provider_generated": True, "provider_context_mode": "chat",
65554
+ "parent_run_id": receipt.parent_run_id,
65555
+ "parent_run_ids": list(getattr(receipt, "parent_run_ids", ()) or (receipt.parent_run_id,)),
65556
+ "provider_tool_use_id": receipt.tool_use_id,
65557
+ }
65558
+ if scheduled_wake:
65559
+ metadata.update({
65560
+ "provider_wake_kind": "schedule",
65561
+ "provider_schedule_ids": list(receipt.schedule_ids),
65562
+ "provider_native_wake_id": receipt.native_wake_id,
65563
+ })
65564
+ if receipt.schedule_id:
65565
+ metadata["provider_schedule_id"] = receipt.schedule_id
65566
+ if getattr(receipt, "concurrent_task_ids", ()):
65567
+ metadata["provider_concurrent_task_ids"] = list(receipt.concurrent_task_ids)
65568
+ else:
65569
+ metadata.update({
65570
+ "provider_task_id": receipt.task_id,
65571
+ "provider_task_ids": list(receipt.task_ids),
65572
+ "provider_task_type": receipt.task_type,
65573
+ })
65574
+ RUN_METADATA[run_id] = metadata
65575
+ ready = asyncio.get_running_loop().create_future()
65576
+ runner: asyncio.Task[Any] | None = None
65577
+ started = False
65578
+ context["completed"][run_id] = asyncio.Event()
65579
+ try:
65580
+ await bind_claude_native_continuation_authority(
65581
+ session_id, run_id, context["authority"],
65582
+ )
65583
+ event = await append_durable_event(session_id, "turn_started", {
65584
+ "run_id": run_id, "backend": BACKEND_CLAUDE,
65585
+ "transport": CLAUDE_TRANSPORT_AGENT_SDK,
65586
+ "provider_session_id": receipt.provider_session_id,
65587
+ "prompt": "", "file_ids": [], "metadata_only": True,
65588
+ **metadata,
65589
+ })
65590
+ if event.get("discarded"):
65591
+ return False
65592
+ started = True
65593
+
65594
+ async def consume() -> None:
65595
+ try:
65596
+ await supervise_provider_turn_task(
65597
+ session_id, run_id, BACKEND_CLAUDE,
65598
+ run_claude_sdk(
65599
+ session_id, run_id, context["prompt"], dict(sess),
65600
+ context["manifest_path"],
65601
+ preaccepted_native_continuation=receipt,
65602
+ native_continuation_context=context,
65603
+ native_continuation_ready=ready,
65604
+ ),
65605
+ )
65606
+ except Exception as exc:
65607
+ logger.warning("Claude native continuation runner failed session=%s run=%s error_type=%s",
65608
+ session_id, run_id, type(exc).__name__)
65609
+ finally:
65610
+ if not ready.done():
65611
+ ready.set_result(False)
65612
+ context["completed"][run_id].set()
65613
+
65614
+ runner = asyncio.create_task(consume())
65615
+ register_session_task(SESSION_TURN_TASKS, session_id, runner)
65616
+ done, _ = await asyncio.wait({ready, runner}, timeout=10.0,
65617
+ return_when=asyncio.FIRST_COMPLETED)
65618
+ if ready in done and ready.result() is True:
65619
+ return True
65620
+ return False
65621
+ finally:
65622
+ if not (ready.done() and not ready.cancelled() and ready.result() is True):
65623
+ if runner is not None and not runner.done():
65624
+ runner.cancel()
65625
+ # Actor retirement follows callback refusal. Do not join a
65626
+ # runner that may be trying to interrupt that same actor.
65627
+ await revoke_cross_chat_capability(run_id)
65628
+ if started:
65629
+ await finalize_owned_turn_finished(session_id, run_id, stopped=True,
65630
+ payload={"run_id": run_id, "backend": BACKEND_CLAUDE,
65631
+ "stopped": True, **metadata})
65632
+ else:
65633
+ await release_turn_slot(session_id, expected_run_id=run_id)
65634
+ RUN_METADATA.pop(run_id, None)
65635
+
65636
+
64783
65637
  async def run_claude_sdk(
64784
65638
  session_id: str,
64785
65639
  run_id: str,
@@ -64789,9 +65643,37 @@ async def run_claude_sdk(
64789
65643
  *,
64790
65644
  provider_command: ProviderCommandRecord | None = None,
64791
65645
  provider_runtime_env: dict[str, str] | None = None,
65646
+ preaccepted_native_continuation: ClaudeSDKNativeContinuation | None = None,
65647
+ native_continuation_context: dict[str, Any] | None = None,
65648
+ native_continuation_ready: asyncio.Future[bool] | None = None,
64792
65649
  ) -> None:
64793
65650
  """Run Claude on one persistent, chat-owned Agent SDK process."""
64794
65651
 
65652
+ start_task = asyncio.current_task()
65653
+ if preaccepted_native_continuation is None and start_task is not None:
65654
+ key = (session_id, run_id)
65655
+ CLAUDE_START_TASKS[key] = start_task
65656
+
65657
+ def start_finished(completed: asyncio.Task[Any]) -> None:
65658
+ if CLAUDE_START_TASKS.get(key) is completed:
65659
+ CLAUDE_START_TASKS.pop(key, None)
65660
+ pending = CLAUDE_NATIVE_PAUSED_STARTS.get(session_id)
65661
+ if pending is not None and pending["run_id"] == run_id:
65662
+ pending["cancelled"] = True
65663
+ if pending.get("released"):
65664
+ if pending["ready"].is_set() and not pending.get("restored"):
65665
+ CLAUDE_NATIVE_PAUSED_STARTS.pop(session_id, None)
65666
+ else:
65667
+ pending["cleanup_task"] = asyncio.create_task(
65668
+ finish_claude_paused_start(session_id, pending["native_run_id"]),
65669
+ )
65670
+
65671
+ start_task.add_done_callback(start_finished)
65672
+ paused = CLAUDE_NATIVE_PAUSED_STARTS.get(session_id)
65673
+ admitted_turn = dict(paused["turn"] if paused is not None and paused["run_id"] == run_id
65674
+ else CURRENT_TURNS.get(session_id) or {})
65675
+ if not await wait_for_claude_paused_start(session_id, run_id):
65676
+ return
64795
65677
  requested_cwd = str(sess.get("cwd") or DEFAULT_CWD)
64796
65678
  cwd = existing_cwd(requested_cwd)
64797
65679
  resume_provider_id, resume_skip_message = resolve_claude_resume_provider(
@@ -64800,14 +65682,15 @@ async def run_claude_sdk(
64800
65682
  )
64801
65683
  diff_baseline = await capture_git_baseline(session_id, run_id, cwd)
64802
65684
  try:
64803
- options, configuration_key, cli_path = build_claude_sdk_options(
64804
- session_id,
64805
- sess,
64806
- cwd,
64807
- manifest_path,
64808
- provider_runtime_env,
64809
- )
64810
- manager = await claude_sdk_manager()
65685
+ if preaccepted_native_continuation is not None:
65686
+ assert native_continuation_context is not None
65687
+ options, configuration_key, cli_path = native_continuation_context["options"]
65688
+ manager = native_continuation_context["manager"]
65689
+ else:
65690
+ options, configuration_key, cli_path = build_claude_sdk_options(
65691
+ session_id, sess, cwd, manifest_path, provider_runtime_env,
65692
+ )
65693
+ manager = await claude_sdk_manager()
64811
65694
  except ClaudeSDKUnavailable:
64812
65695
  raise
64813
65696
  except Exception as exc:
@@ -64885,14 +65768,18 @@ async def run_claude_sdk(
64885
65768
  "stdout_total_lines": 0,
64886
65769
  "stdout_updated_at": None,
64887
65770
  }
64888
- bound, stop_requested = await bind_active_turn(
64889
- session_id,
64890
- run_id,
64891
- startup_active,
64892
- )
64893
- if not bound:
64894
- return
65771
+ while True:
65772
+ if not await wait_for_claude_paused_start(session_id, run_id):
65773
+ return
65774
+ bound, stop_requested = await bind_active_turn(session_id, run_id, startup_active)
65775
+ if bound:
65776
+ break
65777
+ paused = CLAUDE_NATIVE_PAUSED_STARTS.get(session_id)
65778
+ if paused is None or paused["run_id"] != run_id:
65779
+ return
64895
65780
  if stop_requested:
65781
+ if preaccepted_native_continuation is not None:
65782
+ return
64896
65783
  # Stop won before provider delivery. Do not submit the prompt merely
64897
65784
  # to acquire a handle that would immediately be interrupted.
64898
65785
  await finish_cancelled_claude_sdk_start(
@@ -64908,6 +65795,13 @@ async def run_claude_sdk(
64908
65795
 
64909
65796
  async def activate_initial_supervisor(ownership_token: str) -> None:
64910
65797
  async with ACTIVE_LOCK:
65798
+ paused = CLAUDE_NATIVE_PAUSED_STARTS.get(session_id)
65799
+ if (paused is not None and paused["run_id"] == run_id
65800
+ and (not paused["ready"].is_set() or not paused.get("restored"))):
65801
+ raise ClaudeSDKNativeWakeDeferred(
65802
+ blocking_run_id=paused["native_run_id"], native_wake_id=None,
65803
+ settled=paused["ready"],
65804
+ )
64911
65805
  active = ACTIVE.get(session_id)
64912
65806
  if (
64913
65807
  active is not startup_active
@@ -64926,6 +65820,18 @@ async def run_claude_sdk(
64926
65820
  (STORE.sessions.get(session_id) or {}).get(CLAUDE_BACKGROUND_SESSION_FIELD),
64927
65821
  provider_session_id=str(resume_provider_id or ""),
64928
65822
  )
65823
+ if native_continuation_context is None:
65824
+ native_continuation_context = await claude_native_continuation_context(
65825
+ session_id, run_id, prompt, admitted_turn,
65826
+ manager, (options, configuration_key, cli_path), manifest_path,
65827
+ )
65828
+
65829
+ async def accept_native_continuation(
65830
+ receipt: ClaudeSDKNativeContinuation, context: dict[str, Any] | None = native_continuation_context,
65831
+ ) -> bool:
65832
+ assert context is not None
65833
+ return await admit_claude_native_continuation(receipt, context)
65834
+
64929
65835
  try:
64930
65836
  provider_command_start_options = (
64931
65837
  {
@@ -64939,21 +65845,39 @@ async def run_claude_sdk(
64939
65845
  if provider_command is not None
64940
65846
  else {}
64941
65847
  )
64942
- handle = await manager.start_run(
64943
- session_id,
64944
- prompt,
64945
- run_id=run_id,
64946
- options=options,
64947
- configuration_key=configuration_key,
64948
- on_supervisor_ready=activate_initial_supervisor,
64949
- pending_mail_hint=lambda: take_chat_mailbox_hint(session_id, run_id),
64950
- **provider_command_start_options,
64951
- **({"background_task_reconciliation": reconciliation_envelope(initial_reconciliation_batches)}
64952
- if initial_reconciliation_batches else {}),
64953
- )
65848
+ if preaccepted_native_continuation is not None:
65849
+ handle = preaccepted_native_continuation.handle
65850
+ handle.set_pending_mail_hint(lambda: take_chat_mailbox_hint(session_id, run_id))
65851
+ await activate_initial_supervisor(preaccepted_native_continuation.ownership_token)
65852
+ else:
65853
+ while True:
65854
+ if not await wait_for_claude_paused_start(session_id, run_id):
65855
+ return
65856
+ try:
65857
+ handle = await manager.start_run(
65858
+ session_id, prompt, run_id=run_id, options=options,
65859
+ configuration_key=configuration_key,
65860
+ on_supervisor_ready=activate_initial_supervisor,
65861
+ pending_mail_hint=lambda: take_chat_mailbox_hint(session_id, run_id),
65862
+ **({"native_continuation_callback": accept_native_continuation}
65863
+ if native_continuation_context is not None else {}),
65864
+ **provider_command_start_options,
65865
+ **({"background_task_reconciliation": reconciliation_envelope(initial_reconciliation_batches)}
65866
+ if initial_reconciliation_batches else {}),
65867
+ )
65868
+ break
65869
+ except ClaudeSDKNativeWakeDeferred as deferred:
65870
+ # The actor proves zero query delivery. Keep this exact
65871
+ # admission and its effects while the native run owns it.
65872
+ await deferred.settled.wait()
64954
65873
  except asyncio.CancelledError:
64955
- cleanup_task = asyncio.create_task(
64956
- finish_cancelled_claude_sdk_start(
65874
+ if preaccepted_native_continuation is not None:
65875
+ raise
65876
+
65877
+ async def finish_cancelled_start() -> None:
65878
+ if await cancel_claude_paused_start(session_id, run_id):
65879
+ return
65880
+ await finish_cancelled_claude_sdk_start(
64957
65881
  session_id,
64958
65882
  run_id,
64959
65883
  manager,
@@ -64962,7 +65886,8 @@ async def run_claude_sdk(
64962
65886
  or None
64963
65887
  ),
64964
65888
  )
64965
- )
65889
+
65890
+ cleanup_task = asyncio.create_task(finish_cancelled_start())
64966
65891
  await join_task_despite_caller_cancellation(cleanup_task)
64967
65892
  raise
64968
65893
  except ClaudeSDKUnavailable:
@@ -65045,6 +65970,8 @@ async def run_claude_sdk(
65045
65970
  else:
65046
65971
  stop_requested = True
65047
65972
  if not attached:
65973
+ if preaccepted_native_continuation is not None:
65974
+ return
65048
65975
  # Stop/delete may have hard-terminalized and released the placeholder
65049
65976
  # while a cancellation-hostile SDK query was returning. Interrupt only
65050
65977
  # this old handle; chat-ID eviction could target a newer replacement.
@@ -65052,6 +65979,8 @@ async def run_claude_sdk(
65052
65979
  await interrupt_claude_sdk_run_bounded(handle)
65053
65980
  return
65054
65981
  if stop_requested:
65982
+ if preaccepted_native_continuation is not None:
65983
+ return
65055
65984
  try:
65056
65985
  await interrupt_claude_sdk_run_bounded(handle)
65057
65986
  except Exception:
@@ -65069,6 +65998,8 @@ async def run_claude_sdk(
65069
65998
  sdk_ownership_token = str(
65070
65999
  startup_active.get("claude_sdk_owner_token") or ""
65071
66000
  )
66001
+ if native_continuation_ready is not None and not native_continuation_ready.done():
66002
+ native_continuation_ready.set_result(True)
65072
66003
  current_run_id = run_id
65073
66004
  current_handle = handle
65074
66005
  current_reconciliation_batches = initial_reconciliation_batches
@@ -65672,7 +66603,8 @@ async def run_claude_sdk(
65672
66603
  cwd=cwd,
65673
66604
  )
65674
66605
  provider_persisted_id = provider_id
65675
- if result_details is not None and provider_id:
66606
+ if (result_details is not None and provider_id
66607
+ and not getattr(current_handle, "native_continuation_pending", False)):
65676
66608
  # The SDK's authoritative usage RPC is only sampled after its
65677
66609
  # terminal ResultMessage and remains serialized through the
65678
66610
  # chat-owned actor. Failure is telemetry-only and cannot hold
@@ -65985,6 +66917,12 @@ async def run_claude_sdk(
65985
66917
  manifest_path,
65986
66918
  steer_state["candidate_runtime_env"],
65987
66919
  )
66920
+ candidate_native_context = await claude_native_continuation_context(
66921
+ session_id, candidate_run_id, str(steer_state["request_prompt"]),
66922
+ selected, manager,
66923
+ (candidate_options, candidate_configuration_key, _candidate_cli_path),
66924
+ manifest_path,
66925
+ )
65988
66926
  # Once manager.start_run is entered, cancellation cannot
65989
66927
  # prove whether client.query accepted the prompt: the SDK
65990
66928
  # actor deliberately shields its command response. Preserve
@@ -65998,6 +66936,10 @@ async def run_claude_sdk(
65998
66936
  configuration_key=candidate_configuration_key,
65999
66937
  on_supervisor_ready=activate_candidate_supervisor,
66000
66938
  pending_mail_hint=lambda: take_chat_mailbox_hint(session_id, candidate_run_id),
66939
+ **({"native_continuation_callback": (
66940
+ lambda receipt, context=candidate_native_context:
66941
+ admit_claude_native_continuation(receipt, context)
66942
+ )} if candidate_native_context is not None else {}),
66001
66943
  **({"background_task_reconciliation": reconciliation_envelope(candidate_reconciliation_batches)}
66002
66944
  if candidate_reconciliation_batches else {}),
66003
66945
  )
@@ -66208,6 +67150,11 @@ async def run_claude_sdk(
66208
67150
  **previous_metadata,
66209
67151
  })
66210
67152
  await revoke_cross_chat_capability(previous_run_id)
67153
+ if native_continuation_context is not None:
67154
+ native_continuation_context["completed"][previous_run_id].set()
67155
+ native_continuation_context = candidate_native_context
67156
+ if native_continuation_context is not None:
67157
+ native_continuation_context["turn"] = dict(CURRENT_TURNS.get(session_id) or {})
66211
67158
  await append_durable_event_batch(session_id, [
66212
67159
  ("turn_queue_run_now", {
66213
67160
  "queued_id": selected.get("queued_id"),
@@ -66558,6 +67505,10 @@ async def run_claude_sdk(
66558
67505
  released = await release_turn_slot(
66559
67506
  session_id,
66560
67507
  expected_run_id=current_run_id,
67508
+ **({"resume_paused_claude_start": True}
67509
+ if not stopped and not retire_supervisor
67510
+ and (CLAUDE_NATIVE_PAUSED_STARTS.get(session_id) or {}).get("native_run_id") == current_run_id
67511
+ else {}),
66561
67512
  )
66562
67513
  if released:
66563
67514
  try:
@@ -66600,6 +67551,10 @@ async def run_claude_sdk(
66600
67551
  retire_supervisor = True
66601
67552
  STOPPED_RUNS.add(current_run_id)
66602
67553
  await join_task_despite_caller_cancellation(finalize_task)
67554
+ finally:
67555
+ await finish_claude_paused_start(session_id, current_run_id)
67556
+ if native_continuation_context is not None:
67557
+ native_continuation_context["completed"][current_run_id].set()
66603
67558
  if cancelled_error is not None:
66604
67559
  raise cancelled_error
66605
67560
 
@@ -73468,7 +74423,23 @@ async def start_turn(
73468
74423
  SESSION_TURN_TASKS.pop(session_id, None)
73469
74424
 
73470
74425
 
73471
- async def _start_turn_locked(
74426
+ async def _start_turn_locked(session_id: str, req: TurnRequest, **kwargs: Any) -> dict[str, Any]:
74427
+ session = STORE.sessions.get(session_id) or {}
74428
+ track = (str(req.backend or session.get("backend") or DEFAULT_BACKEND) == BACKEND_CLAUDE
74429
+ and req.purpose is None and kwargs.get("provider_context_mode", "chat") == "chat")
74430
+ ready = asyncio.Event() if track else None
74431
+ if ready is not None:
74432
+ CLAUDE_TURN_ADMISSIONS[session_id] = ready
74433
+ try:
74434
+ return await _start_turn_admission_locked(session_id, req, **kwargs)
74435
+ finally:
74436
+ if ready is not None:
74437
+ if CLAUDE_TURN_ADMISSIONS.get(session_id) is ready:
74438
+ CLAUDE_TURN_ADMISSIONS.pop(session_id, None)
74439
+ ready.set()
74440
+
74441
+
74442
+ async def _start_turn_admission_locked(
73472
74443
  session_id: str,
73473
74444
  req: TurnRequest,
73474
74445
  *,
@@ -73979,6 +74950,10 @@ async def _start_turn_locked(
73979
74950
  # checks, so the blocker revision needs its own token to
73980
74951
  # distinguish a replacement reservation in that interval.
73981
74952
  "_server_restart_admission_id": reservation_admission_id,
74953
+ "_claude_native_pause_allowed": bool(
74954
+ interactive_agent_sdk and req.purpose is None
74955
+ and provider_context_mode == "chat"
74956
+ ),
73982
74957
  "prompt": req.prompt,
73983
74958
  "display_prompt": req.display_prompt,
73984
74959
  "file_ids": list(req.file_ids),
@@ -79218,7 +80193,10 @@ async def lifespan(app: FastAPI):
79218
80193
  "terminal-attachments",
79219
80194
  TERMINAL_ATTACHMENTS.close_admission_and_all(permanent=True),
79220
80195
  )
79221
- await bounded_shutdown_phase("port-tunnels", PORT_TUNNELS.close_all())
80196
+ await bounded_shutdown_phase(
80197
+ "workspace-transports",
80198
+ asyncio.gather(PORT_TUNNELS.close_all(), WORKSPACE_INTELLIGENCE.shutdown()),
80199
+ )
79222
80200
  secure_peer_task.cancel()
79223
80201
  secure_peer_connector_task.cancel()
79224
80202
  secure_peer_response_outbox_task.cancel()
@@ -82403,21 +83381,23 @@ async def codex_provider_mcp(request: Request) -> Response:
82403
83381
  client_meta = turn_meta
82404
83382
  run_id = str(client_meta.get("agentsdock_run_id") or "")
82405
83383
  proof = str(client_meta.get("agentsdock_run_proof") or "")
82406
- # Codex's own goal turns need not inherit turn/start client metadata.
82407
- # Their authenticated native thread/turn identity still has an exact
82408
- # server-owned supervisor. Resolve that owner, never a caller's chat ID
82409
- # or a previously completed run. Partially supplied proofs stay invalid.
82410
- native_goal_metadata = not run_id and not proof
83384
+ native_goal_metadata = (
83385
+ all(key not in metadata for metadata in (
83386
+ turn_meta, turn_meta.get("responsesapi_client_metadata"),
83387
+ turn_meta.get("responsesapiClientMetadata"),
83388
+ ) if isinstance(metadata, dict)
83389
+ for key in ("agentsdock_run_id", "agentsdock_run_proof"))
83390
+ )
82411
83391
  core_call_id = str(meta.get("callId") or "")
82412
83392
  if (
82413
83393
  not thread_id
82414
83394
  or len(thread_id) > 256
82415
83395
  or not turn_id
82416
83396
  or len(turn_id) > 256
82417
- or (not native_goal_metadata and (
83397
+ or not native_goal_metadata and (
82418
83398
  re.fullmatch(r"run_[A-Za-z0-9_-]{1,128}", run_id) is None
82419
83399
  or re.fullmatch(r"[0-9a-f]{64}", proof) is None
82420
- ))
83400
+ )
82421
83401
  or not core_call_id
82422
83402
  ):
82423
83403
  return codex_provider_mcp_jsonrpc_error(request_id, -32602, "Incomplete turn metadata")
@@ -82425,6 +83405,26 @@ async def codex_provider_mcp(request: Request) -> Response:
82425
83405
  return codex_provider_mcp_jsonrpc_error(request_id, -32602, "Invalid call identity")
82426
83406
  standalone_active_owner = False
82427
83407
  async with ACTIVE_LOCK:
83408
+ if native_goal_metadata:
83409
+ # thread/goal/set cannot carry responsesapiClientMetadata. The
83410
+ # authenticated static MCP still supplies provider-owned thread
83411
+ # and turn IDs; bind those only to one exact live goal reservation.
83412
+ # Supplied partial, invalid or stale proofs never use this lane.
83413
+ native_owners = []
83414
+ for candidate, active in ACTIVE.items():
83415
+ candidate_run = str(active.get("run_id") or "")
83416
+ manager = existing_codex_app_server_manager(STORE.sessions.get(candidate))
83417
+ matches, _ready = provider_tool_active_matches(
83418
+ candidate, candidate_run, backend=BACKEND_CODEX,
83419
+ provider_thread_id=thread_id, provider_turn_id=turn_id,
83420
+ )
83421
+ if (re.fullmatch(r"run_[A-Za-z0-9_-]{1,128}", candidate_run)
83422
+ and manager is not None and manager.ready and matches
83423
+ and codex_native_mailbox_owner_matches(candidate, candidate_run, thread_id, turn_id)):
83424
+ native_owners.append(candidate_run)
83425
+ if len(native_owners) != 1:
83426
+ return codex_provider_mcp_jsonrpc_error(request_id, -32602, "Incomplete turn metadata")
83427
+ run_id = native_owners[0]
82428
83428
  owners = [
82429
83429
  session_id
82430
83430
  for session_id, active in ACTIVE.items()
@@ -82857,6 +83857,14 @@ async def health() -> dict[str, Any]:
82857
83857
  "max_preview_file_bytes": MAX_WORKSPACE_PREVIEW_BYTES,
82858
83858
  "preview_media_types": sorted(set(WORKSPACE_PREVIEW_MEDIA_TYPES.values())),
82859
83859
  },
83860
+ "workspace_intelligence": {
83861
+ "available": bool(AGENT_TOKEN) and WORKSPACE_SECURE_OPEN_AVAILABLE,
83862
+ "required": False,
83863
+ "version": 1,
83864
+ "languages": list(workspace_intelligence.LANGUAGES),
83865
+ "websocket_protocol": workspace_intelligence.WEBSOCKET_PROTOCOL,
83866
+ "message": "Project language servers are discovered on demand for each editor connection.",
83867
+ },
82860
83868
  "working_directory_completion": {
82861
83869
  "available": True,
82862
83870
  "required": False,
@@ -87509,12 +88517,55 @@ async def host_diagnostics(limit: int = 40) -> dict[str, Any]:
87509
88517
  }
87510
88518
 
87511
88519
 
88520
+ def runtime_catalog_scope() -> tuple[Any, ...]:
88521
+ # External auth/runtime evidence and saved endpoint changes invalidate only
88522
+ # in-flight sharing. A probe publishing its own result does not fork work.
88523
+ with RUNTIME_DIAGNOSTICS_LOCK:
88524
+ revision = RUNTIME_DIAGNOSTIC_REVISION
88525
+ paths = [CODEX_PROVIDER_STORE.root / "settings.json", *(
88526
+ PROVIDER_CONNECTION_STORE.root / f"{backend}.json"
88527
+ for backend in sorted(VALID_BACKENDS) if backend != BACKEND_CODEX
88528
+ )]
88529
+ login_revision = codex_auth.native_login_revision(
88530
+ codex_app_server_env(), cwd=existing_cwd(DEFAULT_CWD),
88531
+ )
88532
+ return revision, login_revision, *(file_signature(str(path)) for path in paths)
88533
+
88534
+
88535
+ async def refresh_runtime_catalog(refresh: bool) -> dict[str, Any]:
88536
+ task = asyncio.current_task()
88537
+ try:
88538
+ if refresh:
88539
+ await refresh_codex_app_server_binary(force=True)
88540
+ await refresh_codex_app_server_login(source="catalog_refresh")
88541
+ # Preflight can itself observe a new login. Joiners during preflight
88542
+ # share it; subsequent joiners compare against its resulting scope.
88543
+ scope = await asyncio.to_thread(runtime_catalog_scope)
88544
+ pending = RUNTIME_CATALOG_TASKS.get(refresh)
88545
+ if pending is not None and pending[1] is task:
88546
+ RUNTIME_CATALOG_TASKS[refresh] = (scope, task)
88547
+ return await asyncio.to_thread(discover_runtime_catalog, force_runtime_probe=refresh)
88548
+ finally:
88549
+ pending = RUNTIME_CATALOG_TASKS.get(refresh)
88550
+ if pending is not None and pending[1] is task:
88551
+ RUNTIME_CATALOG_TASKS.pop(refresh, None)
88552
+
88553
+
87512
88554
  @app.get("/api/runtime/catalog")
87513
88555
  async def runtime_catalog(refresh: bool = False) -> dict[str, Any]:
87514
- if refresh:
87515
- await refresh_codex_app_server_binary(force=True)
87516
- await refresh_codex_app_server_login(source="catalog_refresh")
87517
- return await asyncio.to_thread(discover_runtime_catalog, force_runtime_probe=refresh)
88556
+ # Passive reads may share a manual recheck. A manual recheck must not be
88557
+ # satisfied by a passive read's cached diagnostics, or wait out its budget.
88558
+ scope = await asyncio.to_thread(runtime_catalog_scope)
88559
+ task = next((pending[1] for mode in (True, refresh)
88560
+ if (pending := RUNTIME_CATALOG_TASKS.get(mode)) is not None
88561
+ and pending[0] in (None, scope)), None)
88562
+ if task is None:
88563
+ task = asyncio.create_task(refresh_runtime_catalog(refresh))
88564
+ RUNTIME_CATALOG_TASKS[refresh] = (None, task)
88565
+ # A disconnected client must neither cancel shared work nor leave an
88566
+ # unobserved failure when all its waiters have gone away.
88567
+ task.add_done_callback(lambda done: None if done.cancelled() else done.exception())
88568
+ return copy.deepcopy(await asyncio.shield(task))
87518
88569
 
87519
88570
 
87520
88571
  @app.get("/api/runtime/usage")
@@ -87961,6 +89012,13 @@ async def get_session_subagents(
87961
89012
  session_id,
87962
89013
  concise_error_message(exc),
87963
89014
  )
89015
+ if str(session.get("backend") or "") == BACKEND_CLAUDE:
89016
+ # Fold all bounded states first: reconciling only the response page
89017
+ # would leave active_count wrong and let stale rows hide live children.
89018
+ snapshot = await asyncio.to_thread(
89019
+ build_subagent_snapshot, session_id, SUBAGENT_SNAPSHOT_STATE_LIMIT,
89020
+ )
89021
+ return reconcile_claude_subagent_snapshot(session_id, snapshot, limit)
87964
89022
  return await asyncio.to_thread(build_subagent_snapshot, session_id, limit)
87965
89023
 
87966
89024
 
@@ -90002,6 +91060,7 @@ CLAUDE_GOAL_PATHS: dict[str, Path] = {}
90002
91060
  CLAUDE_GOAL_LOCKS: dict[str, asyncio.Lock] = {}
90003
91061
  CLAUDE_GOAL_PENDING: dict[str, dict[str, Any]] = {}
90004
91062
  CLAUDE_GOAL_ERRORS: dict[str, str] = {}
91063
+ CLAUDE_GOAL_CLEAR_ARGUMENTS = frozenset({"clear", "stop", "off", "reset", "none", "cancel"})
90005
91064
 
90006
91065
 
90007
91066
  async def settle_claude_goal_command(
@@ -90073,7 +91132,41 @@ def require_claude_goal_session(session_id: str) -> dict[str, Any]:
90073
91132
  return session
90074
91133
 
90075
91134
 
90076
- async def start_claude_goal_command(session_id: str, argument: str) -> dict[str, Any]:
91135
+ async def queued_claude_goal(session_id: str) -> dict[str, Any] | None:
91136
+ """Project the next durable goal request, separately from native goal state."""
91137
+ await wait_for_queue_recovery_admission(session_id)
91138
+ session = STORE.sessions.get(session_id) or {}
91139
+ async with QUEUE_LOCK:
91140
+ promoted = RUN_NOW_TURNS.get(session_id)
91141
+ rows = ([promoted] if promoted is not None else []) + list(QUEUED_TURNS.get(session_id) or [])
91142
+ goals = []
91143
+ for position, item in enumerate(rows, 1):
91144
+ selection = item.get("skill_selection")
91145
+ prompt = str(item.get("prompt") or "")
91146
+ # Selection admission (including queue edits) validates the exact
91147
+ # native invocation. Plain slash-looking user text is not a goal.
91148
+ if (item.get("_durable") is False or not item.get("queued_id")
91149
+ or item.get("purpose") is not None
91150
+ or str(item.get("backend") or session.get("backend") or DEFAULT_BACKEND) != BACKEND_CLAUDE
91151
+ or not isinstance(selection, dict) or not selection.get("id") or not selection.get("revision")
91152
+ or not provider_command_prompt_matches(prompt, "/goal")):
91153
+ continue
91154
+ condition = prompt[len("/goal"):].strip()
91155
+ if not condition or len(condition) > 4000 or condition.lower() in CLAUDE_GOAL_CLEAR_ARGUMENTS:
91156
+ continue
91157
+ uncertain = item.get("_native_delivery_fenced") is True
91158
+ paused = uncertain or item.get("_paused_after_stop") is True
91159
+ goals.append({
91160
+ "queued_id": str(item["queued_id"]), "condition": condition,
91161
+ "position": position, "paused": paused,
91162
+ "pause_reason": "delivery_uncertain" if uncertain else "stopped" if paused else None,
91163
+ })
91164
+ return {**goals[0], "queued_count": len(goals)} if goals else None
91165
+
91166
+
91167
+ async def start_claude_goal_command(
91168
+ session_id: str, argument: str, *, queue_if_busy: bool = False,
91169
+ ) -> dict[str, Any]:
90077
91170
  session = require_claude_goal_session(session_id)
90078
91171
  snapshot, inventory = await discover_session_provider_commands(session_id, session)
90079
91172
  command = next((record for record in inventory.records
@@ -90130,7 +91223,7 @@ async def start_claude_goal_command(session_id: str, argument: str) -> dict[str,
90130
91223
  prompt=f"/goal {argument}",
90131
91224
  skill_selection=SkillSelection(id=command.public["id"], revision=inventory.revision),
90132
91225
  client_capabilities=[CLAUDE_SDK_INTERACTIVE_CLIENT_CAPABILITY],
90133
- ), queue_if_busy=False)
91226
+ ), queue_if_busy=queue_if_busy)
90134
91227
 
90135
91228
 
90136
91229
  class ClaudeGoalRequest(BaseModel):
@@ -90141,10 +91234,13 @@ class ClaudeGoalRequest(BaseModel):
90141
91234
  async def put_claude_goal(session_id: str, req: ClaudeGoalRequest) -> dict[str, Any]:
90142
91235
  require_claude_goal_session(session_id)
90143
91236
  condition = req.condition.strip()
90144
- if not condition or condition.lower() in {"clear", "stop", "off", "reset", "none", "cancel"}:
91237
+ if not condition or condition.lower() in CLAUDE_GOAL_CLEAR_ARGUMENTS:
90145
91238
  raise HTTPException(status_code=400, detail="Enter a completion condition for Claude")
90146
91239
  previous = await refresh_claude_goal(session_id, notify=False)
90147
- accepted = await start_claude_goal_command(session_id, condition)
91240
+ # Loaded SDK owners use native goal delivery at their safe boundary.
91241
+ # During admission without a loaded owner, retain ordinary durable queue
91242
+ # cancellation/recovery instead of interrupting or rejecting existing work.
91243
+ accepted = await start_claude_goal_command(session_id, condition, queue_if_busy=True)
90148
91244
  # Bind pending display state only after actual admission. A competing
90149
91245
  # request or an older run's cleanup cannot clear the winner's operation.
90150
91246
  async with ACTIVE_LOCK:
@@ -90246,6 +91342,7 @@ async def claude_runtime_snapshot(session_id: str) -> dict[str, Any]:
90246
91342
  "goal_starting": bool(session_id in CLAUDE_GOAL_PENDING
90247
91343
  and not CLAUDE_GOAL_PENDING[session_id].get("delivery_uncertain")),
90248
91344
  "goal_error": CLAUDE_GOAL_ERRORS.get(session_id),
91345
+ "queued_goal": await queued_claude_goal(session_id) if is_claude else None,
90249
91346
  "goal_loading": bool(is_claude and claude_provider_id_for_session(session)
90250
91347
  and not getattr(CLAUDE_GOAL_PROJECTIONS.get(session_id), "caught_up", False)),
90251
91348
  "stop_fence_pending": session_id in CLAUDE_STOP_FENCE_SESSIONS,
@@ -90597,7 +91694,7 @@ async def _put_codex_goal_locked(
90597
91694
  blocker = await turn_start_blocker(ignore_session_id=session_id)
90598
91695
  if blocker:
90599
91696
  raise HTTPException(status_code=503, detail=f"agent launch deferred: {blocker}")
90600
- operation_id = f"run_goal_{uuid.uuid4().hex[:16]}"
91697
+ operation_id = f"run_codexgoal_{uuid.uuid4().hex[:16]}"
90601
91698
  subscription = manager.subscribe_thread(thread_id)
90602
91699
  provider_model, provider_effort, provider_service_tier = codex_runtime_settings(stored_session)
90603
91700
  async with ACTIVE_LOCK:
@@ -98296,6 +99393,17 @@ workspace_git.register_workspace_git_routes(
98296
99393
  )
98297
99394
 
98298
99395
 
99396
+ WORKSPACE_INTELLIGENCE = workspace_intelligence.register_workspace_intelligence_routes(
99397
+ app, authorize=require_native_admin_control,
99398
+ authorize_websocket=lambda ws: (
99399
+ not privileged_native_browser_request_forbidden(ws)
99400
+ and port_tunnel_websocket_authorized(ws)
99401
+ ),
99402
+ protocols=port_tunnel_requested_protocols,
99403
+ workspace_root=session_workspace_root, environment=runner_env,
99404
+ )
99405
+
99406
+
98299
99407
  @app.put("/api/sessions/{session_id}/workspace/absolute-file")
98300
99408
  async def put_session_absolute_file(session_id: str, req: WorkspaceWriteRequest) -> dict[str, Any]:
98301
99409
  return await asyncio.to_thread(