@agentsdock/server 1.0.12-beta.1 → 1.0.12-beta.10
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/package.json +1 -1
- package/server/VERSION +1 -1
- package/server/agent_server.py +2555 -304
- package/server/agentsdock_chats.py +79 -7
- package/server/claude_chat_routing.py +158 -0
- package/server/claude_goals.py +125 -2
- package/server/claude_history_repair.py +136 -14
- package/server/claude_model_catalog.py +19 -6
- package/server/claude_sdk_client.py +605 -21
- package/server/codex_history_repair.py +194 -25
- package/server/codex_provider.py +58 -0
- package/server/cursor_api_key.py +3 -1
- package/server/execution_recovery.py +23 -4
- package/server/execution_service.py +24 -0
- package/server/execution_transport.py +33 -7
- package/server/gemini_api.py +8 -0
- package/server/install.sh +31 -13
- package/server/provider_connections.py +97 -16
- package/server/side_questions.py +168 -33
- package/server/transcript_reader.py +19 -8
- package/server/workspace_intelligence.py +309 -0
|
@@ -28,6 +28,7 @@ from collections import OrderedDict
|
|
|
28
28
|
from collections.abc import Mapping
|
|
29
29
|
from contextlib import suppress
|
|
30
30
|
from dataclasses import dataclass
|
|
31
|
+
from pathlib import Path
|
|
31
32
|
from types import MappingProxyType
|
|
32
33
|
from typing import (
|
|
33
34
|
Any,
|
|
@@ -38,6 +39,7 @@ from typing import (
|
|
|
38
39
|
Protocol,
|
|
39
40
|
runtime_checkable,
|
|
40
41
|
)
|
|
42
|
+
from claude_chat_routing import ClaudeChatRouting, NATIVE_CHAT_TOOL_MATCHER
|
|
41
43
|
|
|
42
44
|
|
|
43
45
|
logger = logging.getLogger(__name__)
|
|
@@ -178,6 +180,19 @@ class ClaudeSDKRunActive(ClaudeSDKSupervisorError):
|
|
|
178
180
|
safe_to_requeue = True
|
|
179
181
|
|
|
180
182
|
|
|
183
|
+
class ClaudeSDKNativeWakeDeferred(ClaudeSDKRunActive):
|
|
184
|
+
"""An observed native wake won before this human prompt was submitted."""
|
|
185
|
+
|
|
186
|
+
def __init__(self, *, blocking_run_id: str | None, native_wake_id: str | None,
|
|
187
|
+
settled: asyncio.Event | None = None) -> None:
|
|
188
|
+
super().__init__("Claude is completing an already-started native wake before this prompt")
|
|
189
|
+
self.blocking_run_id = blocking_run_id
|
|
190
|
+
self.native_wake_id = native_wake_id
|
|
191
|
+
self.settled = settled if settled is not None else asyncio.Event()
|
|
192
|
+
if settled is None:
|
|
193
|
+
self.settled.set()
|
|
194
|
+
|
|
195
|
+
|
|
181
196
|
class ClaudeSDKConfigurationConflict(ClaudeSDKSupervisorError):
|
|
182
197
|
"""A connected chat cannot be reconfigured while its run is active."""
|
|
183
198
|
|
|
@@ -629,6 +644,12 @@ def default_claude_sdk_client_factory(options: Any) -> ClaudeSDKClientProtocol:
|
|
|
629
644
|
except Exception:
|
|
630
645
|
pass # Do not log raw initialization/account data.
|
|
631
646
|
|
|
647
|
+
def get_cached_server_info(self) -> dict[str, Any] | None:
|
|
648
|
+
# The pinned SDK's async getter reads this same initialization
|
|
649
|
+
# object. An admission callback may need it while holding the
|
|
650
|
+
# supervisor actor, so expose the read without another actor RPC.
|
|
651
|
+
return getattr(self._query, "_initialization_result", None)
|
|
652
|
+
|
|
632
653
|
async def receive_messages(self) -> AsyncIterator[Any]:
|
|
633
654
|
# SDK 0.2.130 drops local-command provenance and active_goal. Keep
|
|
634
655
|
# those native fields without changing parsing of normal messages.
|
|
@@ -728,11 +749,17 @@ async def reject_subagent_provider_tool_hook(
|
|
|
728
749
|
}
|
|
729
750
|
|
|
730
751
|
|
|
731
|
-
def claude_background_tracking_hooks(
|
|
752
|
+
def claude_background_tracking_hooks(
|
|
753
|
+
child_registry: Path | None = None,
|
|
754
|
+
) -> dict[str, list[ClaudeSDKHookMatcher]]:
|
|
732
755
|
"""Keep native task receipts and exact AgentsDock tool ownership."""
|
|
733
756
|
|
|
734
757
|
mail_hint = _PendingMailHintHook()
|
|
758
|
+
chat_routing = ClaudeChatRouting(child_registry)
|
|
735
759
|
return {
|
|
760
|
+
"SubagentStart": [ClaudeSDKHookMatcher(
|
|
761
|
+
matcher=None, hooks=[chat_routing.subagent_start], timeout=5.0,
|
|
762
|
+
)],
|
|
736
763
|
"PostToolUse": [ClaudeSDKHookMatcher(matcher=None, hooks=[mail_hint], timeout=5.0)],
|
|
737
764
|
"PostToolUseFailure": [ClaudeSDKHookMatcher(matcher=None, hooks=[mail_hint], timeout=5.0)],
|
|
738
765
|
"UserPromptSubmit": [ClaudeSDKHookMatcher(
|
|
@@ -744,6 +771,11 @@ def claude_background_tracking_hooks() -> dict[str, list[ClaudeSDKHookMatcher]]:
|
|
|
744
771
|
hooks=[reject_subagent_provider_tool_hook],
|
|
745
772
|
timeout=5.0,
|
|
746
773
|
),
|
|
774
|
+
ClaudeSDKHookMatcher(
|
|
775
|
+
matcher=NATIVE_CHAT_TOOL_MATCHER,
|
|
776
|
+
hooks=[chat_routing.pre_tool_use],
|
|
777
|
+
timeout=5.0,
|
|
778
|
+
),
|
|
747
779
|
]
|
|
748
780
|
}
|
|
749
781
|
|
|
@@ -818,6 +850,20 @@ class ClaudeSDKRunHandle:
|
|
|
818
850
|
self._background_task_reconciliation_consumed = False
|
|
819
851
|
self._background_reconciliation_progress_observed = False
|
|
820
852
|
self._background_reconciliation_aborted = False
|
|
853
|
+
self._native_continuation_callback: NativeContinuationCallback | None = None
|
|
854
|
+
self._provider_session_id: str | None = None
|
|
855
|
+
self._pending_mail_hint: Callable[[], str | None] | None = None
|
|
856
|
+
self._native_continuation_pending = False
|
|
857
|
+
self._native_owner_order = 0
|
|
858
|
+
self._is_native_continuation = False
|
|
859
|
+
self._native_wake_id: str | None = None
|
|
860
|
+
self._native_schedule_progress = False
|
|
861
|
+
|
|
862
|
+
@property
|
|
863
|
+
def native_continuation_pending(self) -> bool:
|
|
864
|
+
"""Terminal snapshot: this connection can still emit an owned task wake."""
|
|
865
|
+
|
|
866
|
+
return self._native_continuation_pending
|
|
821
867
|
|
|
822
868
|
@property
|
|
823
869
|
def background_task_receipts(self) -> tuple[MappingProxyType, ...]:
|
|
@@ -922,6 +968,14 @@ class ClaudeSDKRunHandle:
|
|
|
922
968
|
self._check_loop()
|
|
923
969
|
return await self._interrupt_callback(self.run_id)
|
|
924
970
|
|
|
971
|
+
def set_pending_mail_hint(self, callback: Callable[[], str | None]) -> None:
|
|
972
|
+
"""Bind the admitted native continuation's mailbox to its new run owner."""
|
|
973
|
+
|
|
974
|
+
self._check_loop()
|
|
975
|
+
if self.done:
|
|
976
|
+
raise ClaudeSDKSupervisorClosed("Cannot bind a completed Claude run")
|
|
977
|
+
self._pending_mail_hint = callback
|
|
978
|
+
|
|
925
979
|
def __aiter__(self) -> ClaudeSDKRunHandle:
|
|
926
980
|
return self
|
|
927
981
|
|
|
@@ -953,12 +1007,13 @@ class ClaudeSDKRunHandle:
|
|
|
953
1007
|
return True
|
|
954
1008
|
|
|
955
1009
|
def _mark_acknowledged_without_replay(self) -> None:
|
|
956
|
-
"""Open the stream gate for
|
|
1010
|
+
"""Open the stream gate for an independently proven native owner.
|
|
957
1011
|
|
|
958
1012
|
Claude Code local commands bypass the ordinary query replay loop and
|
|
959
1013
|
therefore do not emit the UUID-bearing ``UserMessage`` used as the
|
|
960
|
-
ownership fence for normal prompts.
|
|
961
|
-
|
|
1014
|
+
ownership fence for normal prompts. Task notification turns similarly
|
|
1015
|
+
have no submitted query UUID. The actor requires either a validated
|
|
1016
|
+
accepted command or an exact same-connection task origin and new init.
|
|
962
1017
|
"""
|
|
963
1018
|
|
|
964
1019
|
if self._acknowledged:
|
|
@@ -998,6 +1053,65 @@ class ClaudeSDKSupervisorSnapshot:
|
|
|
998
1053
|
last_used_at: float
|
|
999
1054
|
|
|
1000
1055
|
|
|
1056
|
+
@dataclass(frozen=True)
|
|
1057
|
+
class ClaudeSDKNativeContinuation:
|
|
1058
|
+
"""Observed native task wake; admission never submits another user prompt."""
|
|
1059
|
+
|
|
1060
|
+
chat_id: str
|
|
1061
|
+
run_id: str
|
|
1062
|
+
parent_run_id: str
|
|
1063
|
+
parent_run_ids: tuple[str, ...]
|
|
1064
|
+
provider_session_id: str
|
|
1065
|
+
ownership_token: str
|
|
1066
|
+
control_generation: str
|
|
1067
|
+
task_id: str
|
|
1068
|
+
task_ids: tuple[str, ...]
|
|
1069
|
+
task_type: str
|
|
1070
|
+
tool_use_id: str
|
|
1071
|
+
handle: ClaudeSDKRunHandle
|
|
1072
|
+
wake_kind: str = "task"
|
|
1073
|
+
schedule_id: str | None = None
|
|
1074
|
+
native_wake_id: str | None = None
|
|
1075
|
+
schedule_ids: tuple[str, ...] = ()
|
|
1076
|
+
concurrent_task_ids: tuple[str, ...] = ()
|
|
1077
|
+
|
|
1078
|
+
|
|
1079
|
+
NativeContinuationCallback = Callable[[ClaudeSDKNativeContinuation], Awaitable[bool]]
|
|
1080
|
+
|
|
1081
|
+
|
|
1082
|
+
@dataclass(frozen=True)
|
|
1083
|
+
class _NativeTaskOrigin:
|
|
1084
|
+
parent_run_id: str
|
|
1085
|
+
owner_order: int
|
|
1086
|
+
provider_session_id: str
|
|
1087
|
+
task_id: str
|
|
1088
|
+
task_type: str
|
|
1089
|
+
tool_use_id: str
|
|
1090
|
+
callback: NativeContinuationCallback
|
|
1091
|
+
|
|
1092
|
+
|
|
1093
|
+
@dataclass(frozen=True)
|
|
1094
|
+
class _NativeScheduleOrigin(_NativeTaskOrigin):
|
|
1095
|
+
schedule_id: str
|
|
1096
|
+
prompt_digest: str
|
|
1097
|
+
recurring: bool
|
|
1098
|
+
|
|
1099
|
+
|
|
1100
|
+
@dataclass(frozen=True)
|
|
1101
|
+
class _NativeScheduleTool:
|
|
1102
|
+
name: str
|
|
1103
|
+
argument: str
|
|
1104
|
+
owner: _NativeTaskOrigin
|
|
1105
|
+
|
|
1106
|
+
|
|
1107
|
+
@dataclass(frozen=True)
|
|
1108
|
+
class _NativeSchedulePrompt:
|
|
1109
|
+
generation: int
|
|
1110
|
+
provider_session_id: str
|
|
1111
|
+
prompt_id: str
|
|
1112
|
+
prompt_digest: str
|
|
1113
|
+
|
|
1114
|
+
|
|
1001
1115
|
@dataclass
|
|
1002
1116
|
class _StartRun:
|
|
1003
1117
|
prompt: str
|
|
@@ -1009,6 +1123,7 @@ class _StartRun:
|
|
|
1009
1123
|
response: asyncio.Future[ClaudeSDKRunHandle]
|
|
1010
1124
|
background_task_reconciliation: dict[str, Any] | None = None
|
|
1011
1125
|
pending_mail_hint: Callable[[], str | None] | None = None
|
|
1126
|
+
native_continuation_callback: NativeContinuationCallback | None = None
|
|
1012
1127
|
|
|
1013
1128
|
|
|
1014
1129
|
@dataclass
|
|
@@ -1186,6 +1301,18 @@ class ClaudeSDKSupervisor:
|
|
|
1186
1301
|
self._goal_stop_result: Any | None = None
|
|
1187
1302
|
self._inflight_tasks: set[str] = set()
|
|
1188
1303
|
self._live_background_tasks: set[str] = set()
|
|
1304
|
+
self._native_task_origins: OrderedDict[str, _NativeTaskOrigin] = OrderedDict()
|
|
1305
|
+
self._pending_native_wake: list[_NativeTaskOrigin] = []
|
|
1306
|
+
self._native_schedule_origins: OrderedDict[str, _NativeScheduleOrigin] = OrderedDict()
|
|
1307
|
+
self._native_schedule_tools: OrderedDict[str, _NativeScheduleTool] = OrderedDict()
|
|
1308
|
+
self._native_schedule_command: tuple[str, str] | None = None
|
|
1309
|
+
self._native_schedule_prompt: tuple[_NativeSchedulePrompt, str] | None = None
|
|
1310
|
+
self._native_schedule_settled = asyncio.Event()
|
|
1311
|
+
self._native_schedule_settled.set()
|
|
1312
|
+
self._native_schedule_wake_ids: OrderedDict[str, None] = OrderedDict()
|
|
1313
|
+
self._native_schedule_prompt_ids: OrderedDict[str, None] = OrderedDict()
|
|
1314
|
+
self._native_admission_gate: asyncio.Event | None = None
|
|
1315
|
+
self._native_owner_order = 0
|
|
1189
1316
|
self._background_work_revision = 0
|
|
1190
1317
|
self._background_reconciliation_hook: _BackgroundReconciliationHook | None = None
|
|
1191
1318
|
self._pending_mail_hint_hook: _PendingMailHintHook | None = None
|
|
@@ -1283,6 +1410,7 @@ class ClaudeSDKSupervisor:
|
|
|
1283
1410
|
on_supervisor_ready: SupervisorReadyCallback | None = None,
|
|
1284
1411
|
background_task_reconciliation: dict[str, Any] | None = None,
|
|
1285
1412
|
pending_mail_hint: Callable[[], str | None] | None = None,
|
|
1413
|
+
native_continuation_callback: NativeContinuationCallback | None = None,
|
|
1286
1414
|
) -> ClaudeSDKRunHandle:
|
|
1287
1415
|
"""Submit one prompt and return after the SDK accepts ``query()``."""
|
|
1288
1416
|
|
|
@@ -1314,6 +1442,7 @@ class ClaudeSDKSupervisor:
|
|
|
1314
1442
|
response=response,
|
|
1315
1443
|
background_task_reconciliation=_normalized_task_reconciliation(background_task_reconciliation),
|
|
1316
1444
|
pending_mail_hint=pending_mail_hint,
|
|
1445
|
+
native_continuation_callback=native_continuation_callback,
|
|
1317
1446
|
)
|
|
1318
1447
|
)
|
|
1319
1448
|
return await asyncio.shield(response)
|
|
@@ -1666,6 +1795,32 @@ class ClaudeSDKSupervisor:
|
|
|
1666
1795
|
client_options, background_hook = _connection_background_hook(self.options)
|
|
1667
1796
|
self._background_reconciliation_hook = background_hook
|
|
1668
1797
|
client_options, self._pending_mail_hint_hook = _connection_mail_hint_hook(client_options)
|
|
1798
|
+
# Native SDK cron turns omit their user frame. The native prompt
|
|
1799
|
+
# hook supplies its exact input before init, without changing it.
|
|
1800
|
+
generation = self._generation + 1
|
|
1801
|
+
async def observe_schedule_prompt(data, _tool_use_id, _context):
|
|
1802
|
+
if (self._closed or self._generation != generation or self._commands is None
|
|
1803
|
+
or not isinstance(data, dict) or data.get("hook_event_name") != "UserPromptSubmit"
|
|
1804
|
+
or data.get("agent_id") or data.get("parent_tool_use_id")):
|
|
1805
|
+
return {}
|
|
1806
|
+
provider_id = _receipt_field(data.get("session_id"))
|
|
1807
|
+
prompt_id = _receipt_field(data.get("prompt_id"))
|
|
1808
|
+
prompt = data.get("prompt")
|
|
1809
|
+
if provider_id and prompt_id and isinstance(prompt, str):
|
|
1810
|
+
self._commands.put_nowait(_NativeSchedulePrompt(
|
|
1811
|
+
generation, provider_id, prompt_id,
|
|
1812
|
+
hashlib.sha256(prompt.encode("utf-8", "surrogatepass")).hexdigest(),
|
|
1813
|
+
))
|
|
1814
|
+
return {}
|
|
1815
|
+
client_options = copy.copy(client_options)
|
|
1816
|
+
hooks = (client_options.get("hooks") if isinstance(client_options, dict)
|
|
1817
|
+
else getattr(client_options, "hooks", None)) or {}
|
|
1818
|
+
hooks = {**hooks, "UserPromptSubmit": [*hooks.get("UserPromptSubmit", []),
|
|
1819
|
+
ClaudeSDKHookMatcher(None, [observe_schedule_prompt], timeout=5.0)]}
|
|
1820
|
+
if isinstance(client_options, dict):
|
|
1821
|
+
client_options["hooks"] = hooks
|
|
1822
|
+
else:
|
|
1823
|
+
client_options.hooks = hooks
|
|
1669
1824
|
candidate = self._client_factory(client_options)
|
|
1670
1825
|
client = await candidate if inspect.isawaitable(candidate) else candidate
|
|
1671
1826
|
self._connecting_client = client
|
|
@@ -1779,6 +1934,11 @@ class ClaudeSDKSupervisor:
|
|
|
1779
1934
|
)
|
|
1780
1935
|
|
|
1781
1936
|
async def _disconnect_current_client(self) -> None:
|
|
1937
|
+
self._clear_native_continuations()
|
|
1938
|
+
self._native_schedule_origins.clear()
|
|
1939
|
+
self._native_schedule_tools.clear()
|
|
1940
|
+
self._native_schedule_wake_ids.clear()
|
|
1941
|
+
self._native_schedule_prompt_ids.clear()
|
|
1782
1942
|
self._supports_send_now = False
|
|
1783
1943
|
self._supports_command_lifecycle = False
|
|
1784
1944
|
self._fail_pending_steer("Claude disconnected before confirming Force Send")
|
|
@@ -1798,6 +1958,7 @@ class ClaudeSDKSupervisor:
|
|
|
1798
1958
|
self._background_reconciliation_hook.retire()
|
|
1799
1959
|
self._background_reconciliation_hook = None
|
|
1800
1960
|
bind_provider_tool_owner(self.options, "", "")
|
|
1961
|
+
self._release_native_admission_gate()
|
|
1801
1962
|
client = self._client
|
|
1802
1963
|
receiver = self._receiver_task
|
|
1803
1964
|
self._client = None
|
|
@@ -1811,12 +1972,14 @@ class ClaudeSDKSupervisor:
|
|
|
1811
1972
|
await self._cancel_task_bounded(receiver)
|
|
1812
1973
|
|
|
1813
1974
|
def _fail_active(self, error: BaseException) -> None:
|
|
1975
|
+
self._clear_native_continuations()
|
|
1814
1976
|
self._fail_pending_steer("Claude ended before confirming Force Send")
|
|
1815
1977
|
self._fail_pending_goal("Claude ended before applying the queued goal")
|
|
1816
1978
|
self._cancel_ack_timeout()
|
|
1817
1979
|
active = self._active_run
|
|
1818
1980
|
self._active_run = None
|
|
1819
1981
|
bind_provider_tool_owner(self.options, "", "")
|
|
1982
|
+
self._release_native_admission_gate()
|
|
1820
1983
|
self._inflight_tasks.clear()
|
|
1821
1984
|
self._goal_stop_run_id = None
|
|
1822
1985
|
self._goal_stop_tasks.clear()
|
|
@@ -1921,12 +2084,22 @@ class ClaudeSDKSupervisor:
|
|
|
1921
2084
|
if self._active_run is not None and not self._active_run.done:
|
|
1922
2085
|
if not command.response.done():
|
|
1923
2086
|
command.response.set_exception(
|
|
1924
|
-
|
|
2087
|
+
ClaudeSDKNativeWakeDeferred(
|
|
2088
|
+
blocking_run_id=self._active_run.run_id,
|
|
2089
|
+
native_wake_id=self._active_run._native_wake_id,
|
|
2090
|
+
) if self._active_run._is_native_continuation else ClaudeSDKRunActive(
|
|
1925
2091
|
f"Claude SDK chat {self.chat_id} already has active run "
|
|
1926
2092
|
f"{self._active_run.run_id}"
|
|
1927
2093
|
)
|
|
1928
2094
|
)
|
|
1929
2095
|
return
|
|
2096
|
+
if self._pending_native_schedule_is_proven():
|
|
2097
|
+
if not command.response.done():
|
|
2098
|
+
command.response.set_exception(ClaudeSDKNativeWakeDeferred(
|
|
2099
|
+
blocking_run_id=None, native_wake_id=self._native_schedule_command[0],
|
|
2100
|
+
settled=self._native_schedule_settled,
|
|
2101
|
+
))
|
|
2102
|
+
return
|
|
1930
2103
|
self._active_run = None
|
|
1931
2104
|
raw_provider_command = command.validated_provider_command_name is not None
|
|
1932
2105
|
if raw_provider_command and not _prompt_invokes_validated_claude_command(
|
|
@@ -1975,6 +2148,7 @@ class ClaudeSDKSupervisor:
|
|
|
1975
2148
|
return await self.interrupt(run_id=run_id)
|
|
1976
2149
|
|
|
1977
2150
|
correlation_id = str(uuid.uuid4())
|
|
2151
|
+
self._remember_native_schedule_command(correlation_id)
|
|
1978
2152
|
handle = ClaudeSDKRunHandle(
|
|
1979
2153
|
self.chat_id,
|
|
1980
2154
|
command.run_id,
|
|
@@ -1983,6 +2157,15 @@ class ClaudeSDKSupervisor:
|
|
|
1983
2157
|
interrupt_this_run,
|
|
1984
2158
|
)
|
|
1985
2159
|
handle._background_task_reconciliation = command.background_task_reconciliation
|
|
2160
|
+
handle._native_continuation_callback = command.native_continuation_callback
|
|
2161
|
+
handle._provider_session_id = _receipt_field(self._query_provider_session_id(command.query_session_id))
|
|
2162
|
+
handle._pending_mail_hint = command.pending_mail_hint
|
|
2163
|
+
self._native_owner_order += 1
|
|
2164
|
+
handle._native_owner_order = self._native_owner_order
|
|
2165
|
+
# A user submission consumes any pending native notification batch.
|
|
2166
|
+
# Older still-running tasks retain their exact original authority.
|
|
2167
|
+
self._pending_native_wake.clear()
|
|
2168
|
+
self._clear_native_schedule_wake()
|
|
1986
2169
|
self._active_run = handle
|
|
1987
2170
|
self._superseded_query_ids.clear()
|
|
1988
2171
|
self._current_query_id = correlation_id
|
|
@@ -2015,6 +2198,7 @@ class ClaudeSDKSupervisor:
|
|
|
2015
2198
|
self.ownership_token,
|
|
2016
2199
|
command.run_id,
|
|
2017
2200
|
)
|
|
2201
|
+
self._release_native_admission_gate()
|
|
2018
2202
|
background_hook = self._background_reconciliation_hook
|
|
2019
2203
|
mail_hook = self._pending_mail_hint_hook
|
|
2020
2204
|
if mail_hook is not None:
|
|
@@ -2231,6 +2415,7 @@ class ClaudeSDKSupervisor:
|
|
|
2231
2415
|
))
|
|
2232
2416
|
return
|
|
2233
2417
|
command.generation = generation
|
|
2418
|
+
self._clear_native_continuations()
|
|
2234
2419
|
self._pending_goal_clear = command
|
|
2235
2420
|
active._background_reconciliation_aborted = True
|
|
2236
2421
|
|
|
@@ -2298,6 +2483,7 @@ class ClaudeSDKSupervisor:
|
|
|
2298
2483
|
)
|
|
2299
2484
|
return
|
|
2300
2485
|
active._background_reconciliation_aborted = True
|
|
2486
|
+
self._clear_native_continuations()
|
|
2301
2487
|
stopping_queued_goal = self._pending_goal is not None or self._goal_stop_run_id == active.run_id
|
|
2302
2488
|
if stopping_queued_goal:
|
|
2303
2489
|
self._goal_stop_run_id = active.run_id
|
|
@@ -2553,8 +2739,8 @@ class ClaudeSDKSupervisor:
|
|
|
2553
2739
|
return
|
|
2554
2740
|
try:
|
|
2555
2741
|
if not self.connected and command.expected_provider_id is not None:
|
|
2556
|
-
resume = (self.
|
|
2557
|
-
else getattr(self.
|
|
2742
|
+
resume = (self._reconnect_options.get("resume") if isinstance(self._reconnect_options, dict)
|
|
2743
|
+
else getattr(self._reconnect_options, "resume", None))
|
|
2558
2744
|
if not resume or resume != command.expected_provider_id:
|
|
2559
2745
|
raise ClaudeSDKUnavailable(
|
|
2560
2746
|
"The native Claude conversation is not available to resume"
|
|
@@ -2825,9 +3011,317 @@ class ClaudeSDKSupervisor:
|
|
|
2825
3011
|
if not command.response.done():
|
|
2826
3012
|
command.response.set_result((value, generation))
|
|
2827
3013
|
|
|
3014
|
+
def _hold_native_admission_gate(self) -> None:
|
|
3015
|
+
if self._native_admission_gate is not None:
|
|
3016
|
+
return
|
|
3017
|
+
gate = asyncio.Event()
|
|
3018
|
+
self._native_admission_gate = gate
|
|
3019
|
+
binder = (self.options.get("_agentsdock_bind_native_admission_gate")
|
|
3020
|
+
if isinstance(self.options, dict)
|
|
3021
|
+
else getattr(self.options, "_agentsdock_bind_native_admission_gate", None))
|
|
3022
|
+
if callable(binder):
|
|
3023
|
+
binder(gate)
|
|
3024
|
+
|
|
3025
|
+
def _release_native_admission_gate(self) -> None:
|
|
3026
|
+
gate = self._native_admission_gate
|
|
3027
|
+
self._native_admission_gate = None
|
|
3028
|
+
if gate is not None:
|
|
3029
|
+
gate.set()
|
|
3030
|
+
binder = (self.options.get("_agentsdock_bind_native_admission_gate")
|
|
3031
|
+
if isinstance(self.options, dict)
|
|
3032
|
+
else getattr(self.options, "_agentsdock_bind_native_admission_gate", None))
|
|
3033
|
+
if callable(binder):
|
|
3034
|
+
binder(None)
|
|
3035
|
+
|
|
3036
|
+
def _clear_native_continuations(self) -> None:
|
|
3037
|
+
self._native_task_origins.clear()
|
|
3038
|
+
self._pending_native_wake.clear()
|
|
3039
|
+
self._native_schedule_tools.clear()
|
|
3040
|
+
self._clear_native_schedule_wake()
|
|
3041
|
+
if self._active_run is not None:
|
|
3042
|
+
self._active_run._native_continuation_callback = None
|
|
3043
|
+
|
|
3044
|
+
def _observe_native_schedule_tool(self, message: Any, active: ClaudeSDKRunHandle) -> None:
|
|
3045
|
+
"""Record only an exact root CronCreate/CronDelete success receipt."""
|
|
3046
|
+
if (_message_field(message, "parent_tool_use_id") or active._background_reconciliation_aborted
|
|
3047
|
+
or active._native_continuation_callback is None or active._provider_session_id is None):
|
|
3048
|
+
return
|
|
3049
|
+
provider_id = _message_field(message, "session_id")
|
|
3050
|
+
if provider_id is not None and provider_id != active._provider_session_id:
|
|
3051
|
+
return
|
|
3052
|
+
blocks = _message_field(message, "content")
|
|
3053
|
+
if blocks is None:
|
|
3054
|
+
blocks = _message_field(_message_field(message, "message", {}), "content")
|
|
3055
|
+
if not isinstance(blocks, list):
|
|
3056
|
+
return
|
|
3057
|
+
kind = _message_type(message)
|
|
3058
|
+
for block in blocks:
|
|
3059
|
+
block_kind = _message_field(block, "type") or type(block).__name__
|
|
3060
|
+
if kind in {"assistant", "assistantmessage"} and block_kind in {"tool_use", "ToolUseBlock"}:
|
|
3061
|
+
name, tool_id = _message_field(block, "name"), _receipt_field(_message_field(block, "id"))
|
|
3062
|
+
values = _message_field(block, "input", {})
|
|
3063
|
+
if name not in {"CronCreate", "CronDelete"} or tool_id is None or not isinstance(values, dict):
|
|
3064
|
+
continue
|
|
3065
|
+
argument = values.get("prompt" if name == "CronCreate" else "id")
|
|
3066
|
+
if not isinstance(argument, str) or not argument:
|
|
3067
|
+
continue
|
|
3068
|
+
if name == "CronCreate":
|
|
3069
|
+
argument = hashlib.sha256(argument.encode("utf-8", "surrogatepass")).hexdigest()
|
|
3070
|
+
self._native_schedule_tools[tool_id] = _NativeScheduleTool(name, argument, _NativeTaskOrigin(
|
|
3071
|
+
active.run_id, active._native_owner_order, active._provider_session_id,
|
|
3072
|
+
"", "", tool_id, active._native_continuation_callback,
|
|
3073
|
+
))
|
|
3074
|
+
elif kind in {"user", "usermessage"} and block_kind in {"tool_result", "ToolResultBlock"}:
|
|
3075
|
+
tool_id = _receipt_field(_message_field(block, "tool_use_id"))
|
|
3076
|
+
tool = self._native_schedule_tools.pop(tool_id, None)
|
|
3077
|
+
result = _message_field(message, "tool_use_result")
|
|
3078
|
+
if (tool is None or tool.owner.parent_run_id != active.run_id
|
|
3079
|
+
or _message_field(block, "is_error") is True or not isinstance(result, dict)):
|
|
3080
|
+
continue
|
|
3081
|
+
schedule_id = _receipt_field(result.get("id"))
|
|
3082
|
+
if schedule_id is None:
|
|
3083
|
+
continue
|
|
3084
|
+
if tool.name == "CronDelete":
|
|
3085
|
+
if schedule_id == tool.argument:
|
|
3086
|
+
self._native_schedule_origins.pop(schedule_id, None)
|
|
3087
|
+
continue
|
|
3088
|
+
if type(result.get("recurring")) is not bool:
|
|
3089
|
+
continue
|
|
3090
|
+
owner = tool.owner
|
|
3091
|
+
self._native_schedule_origins[schedule_id] = _NativeScheduleOrigin(
|
|
3092
|
+
owner.parent_run_id, owner.owner_order, owner.provider_session_id,
|
|
3093
|
+
"", "", tool_id, owner.callback, schedule_id, tool.argument, result["recurring"],
|
|
3094
|
+
)
|
|
3095
|
+
|
|
3096
|
+
def _observe_native_schedule_prompt(self, command: _NativeSchedulePrompt) -> None:
|
|
3097
|
+
if command.generation != self._generation or self._closed:
|
|
3098
|
+
return
|
|
3099
|
+
if command.prompt_id in self._native_schedule_prompt_ids:
|
|
3100
|
+
return
|
|
3101
|
+
self._native_schedule_prompt_ids[command.prompt_id] = None
|
|
3102
|
+
while len(self._native_schedule_prompt_ids) > CLAUDE_BACKGROUND_TASK_RECEIPT_LIMIT:
|
|
3103
|
+
self._native_schedule_prompt_ids.popitem(last=False)
|
|
3104
|
+
# An acknowledged user owns new activity, including identical text.
|
|
3105
|
+
# Before its ACK, the CLI can still be running an earlier native cron
|
|
3106
|
+
# and fold the queued human input into that turn after a tool result.
|
|
3107
|
+
if (self._active_run is not None and not self._active_run.done and self._active_run.acknowledged
|
|
3108
|
+
or self._native_schedule_command is None
|
|
3109
|
+
or self._native_schedule_command[1] != command.provider_session_id):
|
|
3110
|
+
return
|
|
3111
|
+
if self._native_schedule_prompt is not None:
|
|
3112
|
+
# A second distinct hook invalidates the exact proof on which an
|
|
3113
|
+
# unsubmitted human may already be waiting.
|
|
3114
|
+
self._clear_native_schedule_wake()
|
|
3115
|
+
return
|
|
3116
|
+
if any(origin.provider_session_id == command.provider_session_id
|
|
3117
|
+
and origin.prompt_digest == command.prompt_digest
|
|
3118
|
+
for origin in self._native_schedule_origins.values()):
|
|
3119
|
+
# Native prompt_id and command_uuid are independent UUIDs. Bind
|
|
3120
|
+
# this one-use hook to the observed started command, not equality.
|
|
3121
|
+
self._native_schedule_prompt = (command, self._native_schedule_command[0])
|
|
3122
|
+
|
|
3123
|
+
def _remember_native_schedule_command(self, command_id: str) -> None:
|
|
3124
|
+
self._native_schedule_wake_ids[command_id] = None
|
|
3125
|
+
while len(self._native_schedule_wake_ids) > CLAUDE_BACKGROUND_TASK_RECEIPT_LIMIT:
|
|
3126
|
+
self._native_schedule_wake_ids.popitem(last=False)
|
|
3127
|
+
|
|
3128
|
+
def _clear_native_schedule_wake(self) -> None:
|
|
3129
|
+
self._native_schedule_settled.set()
|
|
3130
|
+
self._native_schedule_command = None
|
|
3131
|
+
self._native_schedule_prompt = None
|
|
3132
|
+
|
|
3133
|
+
def _pending_native_schedule_is_proven(self) -> bool:
|
|
3134
|
+
command, proof = self._native_schedule_command, self._native_schedule_prompt
|
|
3135
|
+
return bool(command is not None and proof is not None and command[0] == proof[1]
|
|
3136
|
+
and command[1] == proof[0].provider_session_id
|
|
3137
|
+
and command[0] not in self._native_schedule_wake_ids
|
|
3138
|
+
and any(origin.provider_session_id == command[1]
|
|
3139
|
+
and origin.prompt_digest == proof[0].prompt_digest
|
|
3140
|
+
for origin in self._native_schedule_origins.values()))
|
|
3141
|
+
|
|
3142
|
+
def _consume_native_schedule_wake(self, provider_id: str | None) -> tuple[list[_NativeScheduleOrigin], str | None]:
|
|
3143
|
+
command, proof = self._native_schedule_command, self._native_schedule_prompt
|
|
3144
|
+
self._clear_native_schedule_wake()
|
|
3145
|
+
if (command is None or proof is None or provider_id != command[1]
|
|
3146
|
+
or provider_id != proof[0].provider_session_id or command[0] != proof[1]
|
|
3147
|
+
or command[0] in self._native_schedule_wake_ids):
|
|
3148
|
+
return [], None
|
|
3149
|
+
prompt = proof[0]
|
|
3150
|
+
origins = [origin for origin in self._native_schedule_origins.values()
|
|
3151
|
+
if origin.provider_session_id == provider_id and origin.prompt_digest == prompt.prompt_digest]
|
|
3152
|
+
if not origins:
|
|
3153
|
+
return [], None
|
|
3154
|
+
self._remember_native_schedule_command(command[0])
|
|
3155
|
+
# SDK mode exposes the prompt, not a schedule ID. Identical prompts
|
|
3156
|
+
# retain all candidates; do not falsely consume a particular one-shot.
|
|
3157
|
+
if len(origins) == 1 and not origins[0].recurring:
|
|
3158
|
+
self._native_schedule_origins.pop(origins[0].schedule_id, None)
|
|
3159
|
+
return origins, command[0]
|
|
3160
|
+
|
|
3161
|
+
def _observe_native_task_origin(self, message: Any, active: ClaudeSDKRunHandle) -> None:
|
|
3162
|
+
subtype, task_id, task_type, _status = _task_lifecycle_fields(message)
|
|
3163
|
+
if subtype == "task_notification":
|
|
3164
|
+
origin = self._native_task_origins.get(task_id)
|
|
3165
|
+
if origin is not None and origin.parent_run_id == active.run_id:
|
|
3166
|
+
# A completion can beat its parent's final Result. Retain the
|
|
3167
|
+
# exact receipt until the next init proves which turn owns it.
|
|
3168
|
+
self._record_native_notification(message)
|
|
3169
|
+
else:
|
|
3170
|
+
# A newer user turn already owns this notification. It must
|
|
3171
|
+
# not authorize another later run under the old instruction.
|
|
3172
|
+
self._native_task_origins.pop(task_id, None)
|
|
3173
|
+
return
|
|
3174
|
+
if (subtype != "task_started" or task_type not in {*_DEFERRING_TASK_TYPES, "local_bash"}
|
|
3175
|
+
or active._native_continuation_callback is None
|
|
3176
|
+
or active._background_reconciliation_aborted):
|
|
3177
|
+
return
|
|
3178
|
+
data = _message_field(message, "data", {})
|
|
3179
|
+
data = data if isinstance(data, dict) else {}
|
|
3180
|
+
provider_id = _receipt_field(_message_field(message, "session_id") or data.get("session_id"))
|
|
3181
|
+
tool_id = _receipt_field(_message_field(message, "tool_use_id") or data.get("tool_use_id"))
|
|
3182
|
+
if (not _receipt_field(task_id) or not provider_id or not tool_id
|
|
3183
|
+
or provider_id != active._provider_session_id):
|
|
3184
|
+
return
|
|
3185
|
+
if task_id in self._native_task_origins:
|
|
3186
|
+
return
|
|
3187
|
+
if len(self._native_task_origins) + len(self._pending_native_wake) >= CLAUDE_BACKGROUND_TASK_RECEIPT_LIMIT:
|
|
3188
|
+
return
|
|
3189
|
+
self._native_task_origins[task_id] = _NativeTaskOrigin(
|
|
3190
|
+
active.run_id, active._native_owner_order, provider_id, task_id, task_type, tool_id,
|
|
3191
|
+
active._native_continuation_callback,
|
|
3192
|
+
)
|
|
3193
|
+
|
|
3194
|
+
def _record_native_notification(self, message: Any) -> None:
|
|
3195
|
+
data = _message_field(message, "data", {})
|
|
3196
|
+
data = data if isinstance(data, dict) else {}
|
|
3197
|
+
_subtype, task_id, _task_type, status = _task_lifecycle_fields(message)
|
|
3198
|
+
origin = self._native_task_origins.get(task_id)
|
|
3199
|
+
provider_id = _receipt_field(_message_field(message, "session_id") or data.get("session_id"))
|
|
3200
|
+
tool_id = _receipt_field(_message_field(message, "tool_use_id") or data.get("tool_use_id"))
|
|
3201
|
+
if (origin is not None and status in _TERMINAL_TASK_STATUSES
|
|
3202
|
+
and provider_id == origin.provider_session_id and tool_id == origin.tool_use_id):
|
|
3203
|
+
self._native_task_origins.pop(task_id)
|
|
3204
|
+
self._pending_native_wake.append(origin)
|
|
3205
|
+
|
|
3206
|
+
async def _receive_idle_native_wake(self, message: Any) -> None:
|
|
3207
|
+
"""Admit a fresh init only after an owned task or scheduled prompt."""
|
|
3208
|
+
|
|
3209
|
+
data = _message_field(message, "data", {})
|
|
3210
|
+
data = data if isinstance(data, dict) else {}
|
|
3211
|
+
provider_id = _receipt_field(_message_field(message, "session_id") or data.get("session_id"))
|
|
3212
|
+
subtype, task_id, _task_type, status = _task_lifecycle_fields(message)
|
|
3213
|
+
if _message_type(message) == "command_lifecycle":
|
|
3214
|
+
command_id = _receipt_field(_message_field(message, "command_uuid"))
|
|
3215
|
+
state = _message_field(message, "state")
|
|
3216
|
+
if state == "started":
|
|
3217
|
+
if not command_id or not provider_id or command_id in self._native_schedule_wake_ids:
|
|
3218
|
+
self._clear_native_schedule_wake()
|
|
3219
|
+
else:
|
|
3220
|
+
if self._native_schedule_command != (command_id, provider_id):
|
|
3221
|
+
self._clear_native_schedule_wake()
|
|
3222
|
+
self._native_schedule_settled = asyncio.Event()
|
|
3223
|
+
self._native_schedule_command = (command_id, provider_id)
|
|
3224
|
+
elif state in {"completed", "cancelled", "failed", "discarded", "refused"} and self._native_schedule_command == (command_id, provider_id):
|
|
3225
|
+
self._clear_native_schedule_wake()
|
|
3226
|
+
return
|
|
3227
|
+
if self._is_result_message(message):
|
|
3228
|
+
# A native turn that already ended without a matching init cannot
|
|
3229
|
+
# leave notification credit for a later unrelated turn.
|
|
3230
|
+
self._pending_native_wake.clear()
|
|
3231
|
+
self._clear_native_schedule_wake()
|
|
3232
|
+
if not self._native_task_origins and not self._native_schedule_origins:
|
|
3233
|
+
self._release_native_admission_gate()
|
|
3234
|
+
return
|
|
3235
|
+
if subtype == "task_notification":
|
|
3236
|
+
self._record_native_notification(message)
|
|
3237
|
+
return
|
|
3238
|
+
if subtype != "init":
|
|
3239
|
+
return
|
|
3240
|
+
schedules, native_wake_id = self._consume_native_schedule_wake(provider_id)
|
|
3241
|
+
concurrent_tasks = self._pending_native_wake if schedules else []
|
|
3242
|
+
origins = schedules or self._pending_native_wake
|
|
3243
|
+
self._pending_native_wake = []
|
|
3244
|
+
if not origins:
|
|
3245
|
+
return
|
|
3246
|
+
# Native notifications share the current conversation. If several
|
|
3247
|
+
# already-authorized parents wake together, use the most recent owner
|
|
3248
|
+
# just as notifications received during a newer human turn do. Keep
|
|
3249
|
+
# every provenance ID, but never combine their capability grants.
|
|
3250
|
+
first = max(origins, key=lambda item: item.owner_order)
|
|
3251
|
+
if (provider_id != first.provider_session_id
|
|
3252
|
+
or any(item.provider_session_id != provider_id for item in origins)):
|
|
3253
|
+
# A different native session cannot inherit this chat's authority.
|
|
3254
|
+
await self._disconnect_current_client()
|
|
3255
|
+
return
|
|
3256
|
+
assert self._loop is not None
|
|
3257
|
+
generation = self.control_generation
|
|
3258
|
+
if generation is None:
|
|
3259
|
+
return
|
|
3260
|
+
self._hold_native_admission_gate()
|
|
3261
|
+
handle = ClaudeSDKRunHandle(
|
|
3262
|
+
self.chat_id, f"run_{uuid.uuid4().hex[:16]}", str(uuid.uuid4()), self._loop,
|
|
3263
|
+
lambda run_id: self.interrupt(run_id=run_id),
|
|
3264
|
+
)
|
|
3265
|
+
handle._native_continuation_callback = first.callback
|
|
3266
|
+
handle._provider_session_id = provider_id
|
|
3267
|
+
handle._is_native_continuation = True
|
|
3268
|
+
handle._native_wake_id = native_wake_id
|
|
3269
|
+
self._native_owner_order += 1
|
|
3270
|
+
handle._native_owner_order = self._native_owner_order
|
|
3271
|
+
handle._mark_accepted()
|
|
3272
|
+
handle._mark_acknowledged_without_replay()
|
|
3273
|
+
self._active_run = handle
|
|
3274
|
+
self._current_query_id = None
|
|
3275
|
+
self._superseded_query_ids.clear()
|
|
3276
|
+
self._last_used_at = time.monotonic()
|
|
3277
|
+
bind_provider_tool_owner(self.options, self.ownership_token, handle.run_id)
|
|
3278
|
+
receipt = ClaudeSDKNativeContinuation(
|
|
3279
|
+
self.chat_id, handle.run_id, first.parent_run_id,
|
|
3280
|
+
tuple(dict.fromkeys(item.parent_run_id for item in sorted(
|
|
3281
|
+
[*origins, *concurrent_tasks], key=lambda item: item.owner_order))),
|
|
3282
|
+
provider_id,
|
|
3283
|
+
self.ownership_token, generation, first.task_id,
|
|
3284
|
+
tuple(item.task_id for item in origins if item.task_id), first.task_type, first.tool_use_id, handle,
|
|
3285
|
+
wake_kind="schedule" if schedules else "task",
|
|
3286
|
+
schedule_id=schedules[0].schedule_id if len(schedules) == 1 else None,
|
|
3287
|
+
native_wake_id=native_wake_id,
|
|
3288
|
+
schedule_ids=tuple(item.schedule_id for item in schedules),
|
|
3289
|
+
concurrent_task_ids=tuple(item.task_id for item in concurrent_tasks),
|
|
3290
|
+
)
|
|
3291
|
+
try:
|
|
3292
|
+
admitted = await asyncio.wait_for(first.callback(receipt), self._control_timeout_seconds)
|
|
3293
|
+
except asyncio.CancelledError:
|
|
3294
|
+
self._fail_active(ClaudeSDKSupervisorClosed("Claude native continuation admission was cancelled"))
|
|
3295
|
+
raise
|
|
3296
|
+
except Exception:
|
|
3297
|
+
admitted = False
|
|
3298
|
+
logger.warning("Claude native continuation admission failed for chat %s", self.chat_id)
|
|
3299
|
+
if admitted is not True or self._closed:
|
|
3300
|
+
self._fail_active(ClaudeSDKSupervisorClosed("Claude native continuation was not admitted"))
|
|
3301
|
+
await self._disconnect_current_client()
|
|
3302
|
+
return
|
|
3303
|
+
mail_hook = self._pending_mail_hint_hook
|
|
3304
|
+
if mail_hook is not None and callable(handle._pending_mail_hint):
|
|
3305
|
+
mail_hook.bind(
|
|
3306
|
+
handle, handle._pending_mail_hint, provider_id,
|
|
3307
|
+
lambda: self._active_run is handle and not self._closed
|
|
3308
|
+
and self.control_generation == generation and self._pending_mail_hint_hook is mail_hook,
|
|
3309
|
+
)
|
|
3310
|
+
self._release_native_admission_gate()
|
|
3311
|
+
|
|
2828
3312
|
async def _handle_received(self, command: _ReceivedMessage) -> None:
|
|
2829
3313
|
if command.generation != self._generation:
|
|
2830
3314
|
return
|
|
3315
|
+
if self._active_run is not None and _message_type(command.message) == "command_lifecycle":
|
|
3316
|
+
command_id = _receipt_field(_message_field(command.message, "command_uuid"))
|
|
3317
|
+
if (not self._active_run.acknowledged
|
|
3318
|
+
and command_id != self._active_run.correlation_id):
|
|
3319
|
+
# Query() may have written a human input just before the
|
|
3320
|
+
# receiver observed a cron start. It is already delivered, so
|
|
3321
|
+
# retain exact native proof without retrying that human input.
|
|
3322
|
+
await self._receive_idle_native_wake(command.message)
|
|
3323
|
+
elif command_id and _message_field(command.message, "state") in {"queued", "started"}:
|
|
3324
|
+
self._remember_native_schedule_command(command_id)
|
|
2831
3325
|
data = _message_field(command.message, "data", {})
|
|
2832
3326
|
if _message_field(command.message, "subtype") == "init":
|
|
2833
3327
|
capabilities = _message_field(command.message, "capabilities")
|
|
@@ -2867,7 +3361,24 @@ class ClaudeSDKSupervisor:
|
|
|
2867
3361
|
return
|
|
2868
3362
|
active = self._active_run
|
|
2869
3363
|
if active is None or active.done:
|
|
2870
|
-
|
|
3364
|
+
await self._receive_idle_native_wake(command.message)
|
|
3365
|
+
active = self._active_run
|
|
3366
|
+
if active is None or active.done:
|
|
3367
|
+
return
|
|
3368
|
+
if _message_field(command.message, "subtype") == "init" and active._provider_session_id is None:
|
|
3369
|
+
active._provider_session_id = _receipt_field(
|
|
3370
|
+
_message_field(command.message, "session_id")
|
|
3371
|
+
or (data.get("session_id") if isinstance(data, dict) else None)
|
|
3372
|
+
)
|
|
3373
|
+
if _message_field(command.message, "subtype") == "init":
|
|
3374
|
+
self._pending_native_wake.clear()
|
|
3375
|
+
if not active.acknowledged:
|
|
3376
|
+
provider_id = _receipt_field(_message_field(command.message, "session_id")
|
|
3377
|
+
or (data.get("session_id") if isinstance(data, dict) else None))
|
|
3378
|
+
schedules, native_wake_id = self._consume_native_schedule_wake(provider_id)
|
|
3379
|
+
active._native_schedule_progress = bool(schedules and provider_id == active._provider_session_id)
|
|
3380
|
+
if active._native_schedule_progress and native_wake_id:
|
|
3381
|
+
self._superseded_query_ids.add(native_wake_id)
|
|
2871
3382
|
if self._goal_stop_run_id == active.run_id:
|
|
2872
3383
|
await self._receive_goal_stop(command.message, active)
|
|
2873
3384
|
return
|
|
@@ -2931,16 +3442,33 @@ class ClaudeSDKSupervisor:
|
|
|
2931
3442
|
))
|
|
2932
3443
|
return
|
|
2933
3444
|
if active._acknowledge(command.message):
|
|
3445
|
+
active._native_schedule_progress = False
|
|
2934
3446
|
self._cancel_ack_timeout()
|
|
2935
3447
|
return
|
|
3448
|
+
if self._is_result_message(command.message):
|
|
3449
|
+
active._native_schedule_progress = False
|
|
3450
|
+
self._clear_native_schedule_wake()
|
|
3451
|
+
return
|
|
2936
3452
|
# The persistent stream may contain resumed-session output from
|
|
2937
|
-
# before this query.
|
|
2938
|
-
#
|
|
2939
|
-
|
|
3453
|
+
# before this query. Only a proven same-connection cron may add
|
|
3454
|
+
# nonterminal progress to the accepted human run before its ACK.
|
|
3455
|
+
# Keep both the exact human ACK and Result ownership fences.
|
|
3456
|
+
if not active._native_schedule_progress:
|
|
3457
|
+
return
|
|
3458
|
+
if _message_type(command.message) == "user":
|
|
3459
|
+
blocks = _message_field(command.message, "content")
|
|
3460
|
+
if blocks is None:
|
|
3461
|
+
blocks = _message_field(_message_field(command.message, "message", {}), "content")
|
|
3462
|
+
if not isinstance(blocks, list) or not any(
|
|
3463
|
+
(_message_field(block, "type") or type(block).__name__) in {"tool_result", "ToolResultBlock"}
|
|
3464
|
+
for block in blocks
|
|
3465
|
+
):
|
|
3466
|
+
return
|
|
2940
3467
|
|
|
2941
3468
|
active._observe_reconciliation_progress(command.message)
|
|
2942
3469
|
if self._pending_mail_hint_hook is not None:
|
|
2943
3470
|
self._pending_mail_hint_hook.observe(command.message)
|
|
3471
|
+
self._observe_native_schedule_tool(command.message, active)
|
|
2944
3472
|
if self._is_result_message(command.message):
|
|
2945
3473
|
result_query_id = str(_message_field(command.message, "user_message_uuid") or "")
|
|
2946
3474
|
if goal is not None:
|
|
@@ -2977,6 +3505,18 @@ class ClaudeSDKSupervisor:
|
|
|
2977
3505
|
forced_run_end = _result_forces_run_end(command.message)
|
|
2978
3506
|
if had_inflight_tasks and not forced_run_end:
|
|
2979
3507
|
return
|
|
3508
|
+
if forced_run_end:
|
|
3509
|
+
self._clear_native_continuations()
|
|
3510
|
+
if self._native_task_origins or self._pending_native_wake or self._native_schedule_origins:
|
|
3511
|
+
# Permission/MCP callbacks run outside this actor. Fence them
|
|
3512
|
+
# before the idle interval so a native wake cannot use stale
|
|
3513
|
+
# authority while the server admits its new logical run.
|
|
3514
|
+
self._hold_native_admission_gate()
|
|
3515
|
+
active._native_continuation_pending = True
|
|
3516
|
+
self._native_schedule_tools = OrderedDict(
|
|
3517
|
+
(tool_id, tool) for tool_id, tool in self._native_schedule_tools.items()
|
|
3518
|
+
if tool.owner.parent_run_id != active.run_id
|
|
3519
|
+
)
|
|
2980
3520
|
active._deliver(command.message)
|
|
2981
3521
|
self._cancel_ack_timeout()
|
|
2982
3522
|
active._finish(command.message)
|
|
@@ -3002,6 +3542,7 @@ class ClaudeSDKSupervisor:
|
|
|
3002
3542
|
command.message
|
|
3003
3543
|
)
|
|
3004
3544
|
active._observe_background_task(command.message)
|
|
3545
|
+
self._observe_native_task_origin(command.message, active)
|
|
3005
3546
|
if task_id:
|
|
3006
3547
|
if subtype == "task_started" and task_type in _DEFERRING_TASK_TYPES:
|
|
3007
3548
|
self._inflight_tasks.add(task_id)
|
|
@@ -3098,6 +3639,8 @@ class ClaudeSDKSupervisor:
|
|
|
3098
3639
|
await self._handle_mutate_mcp_server(command)
|
|
3099
3640
|
elif isinstance(command, _ReceivedMessage):
|
|
3100
3641
|
await self._handle_received(command)
|
|
3642
|
+
elif isinstance(command, _NativeSchedulePrompt):
|
|
3643
|
+
self._observe_native_schedule_prompt(command)
|
|
3101
3644
|
elif isinstance(command, _AckTimeout):
|
|
3102
3645
|
await self._handle_ack_timeout(command)
|
|
3103
3646
|
elif isinstance(command, _ReceiverStopped):
|
|
@@ -3282,16 +3825,9 @@ class ClaudeSDKSupervisorManager:
|
|
|
3282
3825
|
# newer persisted resume/fork binding merely because this client
|
|
3283
3826
|
# is connected. Its actor may need to reconnect after this lookup.
|
|
3284
3827
|
supervisor._reconnect_options = options
|
|
3285
|
-
#
|
|
3286
|
-
#
|
|
3287
|
-
#
|
|
3288
|
-
# process-configuration key used by healthy persistent clients.
|
|
3289
|
-
if not supervisor.connected and not supervisor.is_active:
|
|
3290
|
-
supervisor.options = options
|
|
3291
|
-
bind_permission_owner(
|
|
3292
|
-
supervisor.options,
|
|
3293
|
-
supervisor.ownership_token,
|
|
3294
|
-
)
|
|
3828
|
+
# _new_client selects the options for each connection. While
|
|
3829
|
+
# connect() is awaiting, its MCP callbacks already captured them;
|
|
3830
|
+
# replacing them here would bind the owner into another closure.
|
|
3295
3831
|
self._supervisors.move_to_end(chat_id)
|
|
3296
3832
|
return supervisor, old_to_close
|
|
3297
3833
|
|
|
@@ -3335,6 +3871,7 @@ class ClaudeSDKSupervisorManager:
|
|
|
3335
3871
|
on_supervisor_ready: SupervisorReadyCallback | None = None,
|
|
3336
3872
|
background_task_reconciliation: dict[str, Any] | None = None,
|
|
3337
3873
|
pending_mail_hint: Callable[[], str | None] | None = None,
|
|
3874
|
+
native_continuation_callback: NativeContinuationCallback | None = None,
|
|
3338
3875
|
) -> ClaudeSDKRunHandle:
|
|
3339
3876
|
"""Pin a chat through query acceptance, then return its run handle."""
|
|
3340
3877
|
|
|
@@ -3367,6 +3904,7 @@ class ClaudeSDKSupervisorManager:
|
|
|
3367
3904
|
on_supervisor_ready=on_supervisor_ready,
|
|
3368
3905
|
background_task_reconciliation=background_task_reconciliation,
|
|
3369
3906
|
pending_mail_hint=pending_mail_hint,
|
|
3907
|
+
native_continuation_callback=native_continuation_callback,
|
|
3370
3908
|
)
|
|
3371
3909
|
except (ClaudeSDKUnavailable, asyncio.CancelledError):
|
|
3372
3910
|
# A cold-connect failure or a Stop that cancels start_run before
|
|
@@ -3409,6 +3947,34 @@ class ClaudeSDKSupervisorManager:
|
|
|
3409
3947
|
and supervisor.active_run_id == str(run_id)
|
|
3410
3948
|
)
|
|
3411
3949
|
|
|
3950
|
+
def has_pending_native_continuations(self, chat_id: str) -> bool:
|
|
3951
|
+
"""Whether explicit idle Stop must retire retained native task authority."""
|
|
3952
|
+
|
|
3953
|
+
supervisor = self._supervisors.get(str(chat_id))
|
|
3954
|
+
return bool(
|
|
3955
|
+
supervisor is not None and not supervisor.closed
|
|
3956
|
+
and (supervisor._native_task_origins or supervisor._pending_native_wake)
|
|
3957
|
+
)
|
|
3958
|
+
|
|
3959
|
+
def get_cached_server_info(
|
|
3960
|
+
self, chat_id: str, *, configuration_key: str,
|
|
3961
|
+
) -> tuple[dict[str, Any], str] | None:
|
|
3962
|
+
"""Read commands from the exact loaded connection without actor RPC."""
|
|
3963
|
+
|
|
3964
|
+
supervisor = self._supervisors.get(str(chat_id))
|
|
3965
|
+
if (supervisor is None or supervisor.closed or not supervisor._connected
|
|
3966
|
+
or supervisor.configuration_key != str(configuration_key)):
|
|
3967
|
+
return None
|
|
3968
|
+
generation = supervisor.control_generation
|
|
3969
|
+
getter = getattr(supervisor._client, "get_cached_server_info", None)
|
|
3970
|
+
if generation is None or not callable(getter):
|
|
3971
|
+
return None
|
|
3972
|
+
try:
|
|
3973
|
+
value = supervisor._provider_commands_from_server_info(getter())
|
|
3974
|
+
except ClaudeSDKSupervisorError:
|
|
3975
|
+
return None
|
|
3976
|
+
return value, generation
|
|
3977
|
+
|
|
3412
3978
|
async def interrupt(self, chat_id: str, *, run_id: str | None = None) -> bool:
|
|
3413
3979
|
self._bind_loop()
|
|
3414
3980
|
assert self._lock is not None
|
|
@@ -3902,6 +4468,24 @@ class ClaudeSDKSupervisorManager:
|
|
|
3902
4468
|
and not supervisor.closed
|
|
3903
4469
|
)
|
|
3904
4470
|
|
|
4471
|
+
def subagent_tracking_snapshot(self, chat_id: str) -> dict[str, Any]:
|
|
4472
|
+
"""Copy the exact existing task owner without connecting or issuing RPCs.
|
|
4473
|
+
|
|
4474
|
+
Call on the manager's event loop. An idle connected supervisor is not
|
|
4475
|
+
evidence that tasks from an earlier run are still being tracked.
|
|
4476
|
+
"""
|
|
4477
|
+
supervisor = self._supervisors.get(str(chat_id))
|
|
4478
|
+
if supervisor is None or supervisor.closed or not supervisor.connected:
|
|
4479
|
+
return {"run_id": "", "tasks": ()}
|
|
4480
|
+
active = supervisor._active_run
|
|
4481
|
+
if active is None or active.done:
|
|
4482
|
+
return {"run_id": "", "tasks": ()}
|
|
4483
|
+
return {
|
|
4484
|
+
"run_id": active.run_id,
|
|
4485
|
+
"generation": supervisor.control_generation,
|
|
4486
|
+
"tasks": tuple(dict(task) for task in active.background_task_receipts),
|
|
4487
|
+
}
|
|
4488
|
+
|
|
3905
4489
|
def usage_generation(self, chat_id: str, *, run_id: str | None = None) -> str | None:
|
|
3906
4490
|
"""Identify the existing native owner without connecting or issuing RPCs."""
|
|
3907
4491
|
supervisor = self._supervisors.get(str(chat_id))
|