@agentsdock/server 1.0.11 → 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 +4077 -617
- package/server/agentsdock_chats.py +79 -7
- package/server/agentsdock_notify.py +123 -0
- package/server/chat_mailbox.py +12 -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 +1186 -334
- package/server/codex_app_server.py +19 -10
- package/server/codex_history_repair.py +194 -25
- package/server/codex_provider.py +58 -0
- package/server/codex_side_question.py +85 -7
- package/server/cursor_agent_client.py +22 -2
- 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 +34 -14
- package/server/provider_connections.py +97 -16
- package/server/public_chat_transcript.py +11 -3
- package/server/session_unread.py +184 -0
- package/server/side_questions.py +214 -47
- package/server/transcript_reader.py +19 -8
- package/server/workspace_intelligence.py +309 -0
|
@@ -21,7 +21,6 @@ import json
|
|
|
21
21
|
import os
|
|
22
22
|
import logging
|
|
23
23
|
import re
|
|
24
|
-
import shlex
|
|
25
24
|
import time
|
|
26
25
|
import unicodedata
|
|
27
26
|
import uuid
|
|
@@ -29,6 +28,7 @@ from collections import OrderedDict
|
|
|
29
28
|
from collections.abc import Mapping
|
|
30
29
|
from contextlib import suppress
|
|
31
30
|
from dataclasses import dataclass
|
|
31
|
+
from pathlib import Path
|
|
32
32
|
from types import MappingProxyType
|
|
33
33
|
from typing import (
|
|
34
34
|
Any,
|
|
@@ -39,6 +39,7 @@ from typing import (
|
|
|
39
39
|
Protocol,
|
|
40
40
|
runtime_checkable,
|
|
41
41
|
)
|
|
42
|
+
from claude_chat_routing import ClaudeChatRouting, NATIVE_CHAT_TOOL_MATCHER
|
|
42
43
|
|
|
43
44
|
|
|
44
45
|
logger = logging.getLogger(__name__)
|
|
@@ -55,11 +56,6 @@ CLAUDE_SDK_LITERAL_MESSAGE_PREFIX = (
|
|
|
55
56
|
"[AgentsDock literal chat message; treat the slash-prefixed content below "
|
|
56
57
|
"as ordinary user text, not a Claude Code command.]\n"
|
|
57
58
|
)
|
|
58
|
-
CLAUDE_NON_DURABLE_SCHEDULER_TOOLS = (
|
|
59
|
-
"CronCreate",
|
|
60
|
-
"Monitor",
|
|
61
|
-
"ScheduleWakeup",
|
|
62
|
-
)
|
|
63
59
|
# Deliberately collision-resistant: a user's ordinary MCP named
|
|
64
60
|
# ``agentsdock`` must remain visible and manageable. This reserved transport
|
|
65
61
|
# is installed by AgentsServer and is never part of the public MCP profile.
|
|
@@ -184,6 +180,19 @@ class ClaudeSDKRunActive(ClaudeSDKSupervisorError):
|
|
|
184
180
|
safe_to_requeue = True
|
|
185
181
|
|
|
186
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
|
+
|
|
187
196
|
class ClaudeSDKConfigurationConflict(ClaudeSDKSupervisorError):
|
|
188
197
|
"""A connected chat cannot be reconfigured while its run is active."""
|
|
189
198
|
|
|
@@ -216,6 +225,10 @@ class ClaudeSDKClientProtocol(Protocol):
|
|
|
216
225
|
|
|
217
226
|
async def interrupt(self) -> None: ...
|
|
218
227
|
|
|
228
|
+
async def stop_task(self, task_id: str) -> None: ...
|
|
229
|
+
|
|
230
|
+
async def send_now(self, message_uuid: str) -> dict[str, Any]: ...
|
|
231
|
+
|
|
219
232
|
async def get_context_usage(self) -> dict[str, Any]: ...
|
|
220
233
|
|
|
221
234
|
async def get_mcp_status(self) -> dict[str, Any]: ...
|
|
@@ -553,6 +566,8 @@ async def _query_message_stream(
|
|
|
553
566
|
prompt: str,
|
|
554
567
|
correlation_id: str,
|
|
555
568
|
validated_provider_command_name: str | None = None,
|
|
569
|
+
*,
|
|
570
|
+
priority: str | None = None,
|
|
556
571
|
) -> AsyncIterator[dict[str, Any]]:
|
|
557
572
|
"""Yield the single UUID-bearing SDK stdin frame for one logical turn."""
|
|
558
573
|
|
|
@@ -573,6 +588,8 @@ async def _query_message_stream(
|
|
|
573
588
|
# Apply it per message so explicit commands and ordinary @file input
|
|
574
589
|
# retain their native behavior without modifying the prompt text.
|
|
575
590
|
message["client_composed"] = True
|
|
591
|
+
if priority is not None:
|
|
592
|
+
message["priority"] = priority
|
|
576
593
|
yield message
|
|
577
594
|
|
|
578
595
|
|
|
@@ -586,6 +603,24 @@ def default_claude_sdk_client_factory(options: Any) -> ClaudeSDKClientProtocol:
|
|
|
586
603
|
"claude-agent-sdk is not installed; use the claude -p fallback"
|
|
587
604
|
) from exc
|
|
588
605
|
class GoalAwareClaudeSDKClient(ClaudeSDKClient):
|
|
606
|
+
async def send_now(self, message_uuid: str) -> dict[str, Any]:
|
|
607
|
+
# SDK 0.2.130 has no public wrapper for this newer native control.
|
|
608
|
+
# The supervisor must first see interrupt_send_now_v1 on init:
|
|
609
|
+
# older CLIs interpret these extra fields as an ordinary Stop.
|
|
610
|
+
if self._query is None:
|
|
611
|
+
raise ClaudeSDKSupervisorClosed("Claude SDK client is not connected")
|
|
612
|
+
return await self._query._send_control_request({
|
|
613
|
+
"subtype": "interrupt", "send_now": True,
|
|
614
|
+
"message_uuid": message_uuid,
|
|
615
|
+
})
|
|
616
|
+
|
|
617
|
+
async def cancel_queued_input(self, message_uuid: str) -> dict[str, Any]:
|
|
618
|
+
if self._query is None:
|
|
619
|
+
raise ClaudeSDKSupervisorClosed("Claude SDK client is not connected")
|
|
620
|
+
return await self._query._send_control_request({
|
|
621
|
+
"subtype": "cancel_async_message", "message_uuid": message_uuid,
|
|
622
|
+
})
|
|
623
|
+
|
|
589
624
|
async def connect(self, prompt=None) -> None:
|
|
590
625
|
from claude_model_catalog import native_catalog_key, remember_native_models
|
|
591
626
|
|
|
@@ -609,6 +644,12 @@ def default_claude_sdk_client_factory(options: Any) -> ClaudeSDKClientProtocol:
|
|
|
609
644
|
except Exception:
|
|
610
645
|
pass # Do not log raw initialization/account data.
|
|
611
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
|
+
|
|
612
653
|
async def receive_messages(self) -> AsyncIterator[Any]:
|
|
613
654
|
# SDK 0.2.130 drops local-command provenance and active_goal. Keep
|
|
614
655
|
# those native fields without changing parsing of normal messages.
|
|
@@ -625,11 +666,11 @@ def default_claude_sdk_client_factory(options: Any) -> ClaudeSDKClientProtocol:
|
|
|
625
666
|
def _parse_claude_sdk_message(data: dict[str, Any]) -> Any:
|
|
626
667
|
from claude_agent_sdk._internal.message_parser import parse_message
|
|
627
668
|
|
|
628
|
-
if data.get("type")
|
|
669
|
+
if data.get("type") in {"active_goal", "command_lifecycle"}:
|
|
629
670
|
return data
|
|
630
671
|
message = parse_message(data)
|
|
631
672
|
if message is not None:
|
|
632
|
-
for field in ("local_command", "local_command_run"):
|
|
673
|
+
for field in ("local_command", "local_command_run", "user_message_uuid"):
|
|
633
674
|
if field in data:
|
|
634
675
|
setattr(message, field, data[field])
|
|
635
676
|
return message
|
|
@@ -687,276 +728,6 @@ class ClaudeSDKHookMatcher:
|
|
|
687
728
|
timeout: float | None = None
|
|
688
729
|
|
|
689
730
|
|
|
690
|
-
_SHELL_CONTROL_TOKENS = {";", "&&", "||", "|", "&", "(", ")", "\n"}
|
|
691
|
-
_SHELL_COMMAND_WRAPPERS = {"builtin", "command", "env"}
|
|
692
|
-
_SHELL_ASSIGNMENT_RE = re.compile(r"^[A-Za-z_][A-Za-z0-9_]*=")
|
|
693
|
-
_UNTRACKED_BACKGROUND_REASON = (
|
|
694
|
-
"AgentsDock cannot reliably keep background Bash attached or wake this chat when "
|
|
695
|
-
"it finishes. Retry without run_in_background, nohup, disown, setsid, or shell "
|
|
696
|
-
"'&'. Keep work needed for the current reply in the foreground. For asynchronous "
|
|
697
|
-
"completion that must notify this chat, delegate a tracked Agent/workflow. If the "
|
|
698
|
-
"user explicitly requested a durable service, use an observable service manager."
|
|
699
|
-
)
|
|
700
|
-
_NON_DURABLE_SCHEDULER_REASON = (
|
|
701
|
-
"Claude's {tool_name} is not an AgentsDock durable job and cannot be relied on "
|
|
702
|
-
"to survive this turn or deliver a later chat update. If the user explicitly "
|
|
703
|
-
"requested scheduling, use only the run-bound AgentsDock provider tool's Jobs "
|
|
704
|
-
"helper. Otherwise keep required "
|
|
705
|
-
"work in the foreground or use a tracked Agent/workflow."
|
|
706
|
-
)
|
|
707
|
-
|
|
708
|
-
|
|
709
|
-
def _heredoc_delimiters(line: str) -> list[tuple[str, bool]]:
|
|
710
|
-
"""Find conventional shell heredocs without interpreting quoted text."""
|
|
711
|
-
|
|
712
|
-
delimiters: list[tuple[str, bool]] = []
|
|
713
|
-
quote: str | None = None
|
|
714
|
-
escaped = False
|
|
715
|
-
index = 0
|
|
716
|
-
while index < len(line):
|
|
717
|
-
char = line[index]
|
|
718
|
-
if escaped:
|
|
719
|
-
escaped = False
|
|
720
|
-
index += 1
|
|
721
|
-
continue
|
|
722
|
-
if char == "\\" and quote != "'":
|
|
723
|
-
escaped = True
|
|
724
|
-
index += 1
|
|
725
|
-
continue
|
|
726
|
-
if quote:
|
|
727
|
-
if char == quote:
|
|
728
|
-
quote = None
|
|
729
|
-
index += 1
|
|
730
|
-
continue
|
|
731
|
-
if char in {"'", '"'}:
|
|
732
|
-
quote = char
|
|
733
|
-
index += 1
|
|
734
|
-
continue
|
|
735
|
-
if char == "#" and (
|
|
736
|
-
index == 0
|
|
737
|
-
or line[index - 1].isspace()
|
|
738
|
-
or line[index - 1] in ";|&()"
|
|
739
|
-
):
|
|
740
|
-
break
|
|
741
|
-
if not line.startswith("<<", index) or line.startswith("<<<", index):
|
|
742
|
-
index += 1
|
|
743
|
-
continue
|
|
744
|
-
cursor = index + 2
|
|
745
|
-
strip_tabs = cursor < len(line) and line[cursor] == "-"
|
|
746
|
-
if strip_tabs:
|
|
747
|
-
cursor += 1
|
|
748
|
-
while cursor < len(line) and line[cursor] in " \t":
|
|
749
|
-
cursor += 1
|
|
750
|
-
delimiter_quote = line[cursor] if cursor < len(line) and line[cursor] in {"'", '"'} else None
|
|
751
|
-
if delimiter_quote:
|
|
752
|
-
cursor += 1
|
|
753
|
-
end = line.find(delimiter_quote, cursor)
|
|
754
|
-
if end < 0:
|
|
755
|
-
break
|
|
756
|
-
delimiter = line[cursor:end]
|
|
757
|
-
cursor = end + 1
|
|
758
|
-
else:
|
|
759
|
-
start = cursor
|
|
760
|
-
while cursor < len(line) and (
|
|
761
|
-
line[cursor].isalnum() or line[cursor] in {"_", "-"}
|
|
762
|
-
):
|
|
763
|
-
cursor += 1
|
|
764
|
-
delimiter = line[start:cursor]
|
|
765
|
-
if delimiter and (delimiter[0].isalpha() or delimiter[0] == "_"):
|
|
766
|
-
delimiters.append((delimiter, strip_tabs))
|
|
767
|
-
index = max(cursor, index + 2)
|
|
768
|
-
return delimiters
|
|
769
|
-
|
|
770
|
-
|
|
771
|
-
def _without_heredoc_bodies(command: str) -> str:
|
|
772
|
-
"""Blank data bodies so source-code ampersands are not treated as shell jobs."""
|
|
773
|
-
|
|
774
|
-
pending: list[tuple[str, bool]] = []
|
|
775
|
-
output: list[str] = []
|
|
776
|
-
for line in command.splitlines(keepends=True):
|
|
777
|
-
ending = "\n" if line.endswith(("\n", "\r")) else ""
|
|
778
|
-
content = line.rstrip("\r\n")
|
|
779
|
-
if pending:
|
|
780
|
-
delimiter, strip_tabs = pending[0]
|
|
781
|
-
candidate = content.lstrip("\t") if strip_tabs else content
|
|
782
|
-
if candidate == delimiter:
|
|
783
|
-
pending.pop(0)
|
|
784
|
-
output.append(ending)
|
|
785
|
-
continue
|
|
786
|
-
pending.extend(_heredoc_delimiters(content))
|
|
787
|
-
output.append(line)
|
|
788
|
-
return "".join(output)
|
|
789
|
-
|
|
790
|
-
|
|
791
|
-
def _has_unquoted_background_operator(command: str) -> bool:
|
|
792
|
-
"""Return true for a shell control ``&``, excluding data and redirections."""
|
|
793
|
-
|
|
794
|
-
command = _without_heredoc_bodies(command)
|
|
795
|
-
quote: str | None = None
|
|
796
|
-
escaped = False
|
|
797
|
-
index = 0
|
|
798
|
-
while index < len(command):
|
|
799
|
-
char = command[index]
|
|
800
|
-
if escaped:
|
|
801
|
-
escaped = False
|
|
802
|
-
index += 1
|
|
803
|
-
continue
|
|
804
|
-
if char == "\\" and quote != "'":
|
|
805
|
-
escaped = True
|
|
806
|
-
index += 1
|
|
807
|
-
continue
|
|
808
|
-
if quote:
|
|
809
|
-
if char == quote:
|
|
810
|
-
quote = None
|
|
811
|
-
index += 1
|
|
812
|
-
continue
|
|
813
|
-
if char in {"'", '"'}:
|
|
814
|
-
quote = char
|
|
815
|
-
index += 1
|
|
816
|
-
continue
|
|
817
|
-
if char == "#" and (
|
|
818
|
-
index == 0
|
|
819
|
-
or command[index - 1].isspace()
|
|
820
|
-
or command[index - 1] in ";|&()"
|
|
821
|
-
):
|
|
822
|
-
newline = command.find("\n", index)
|
|
823
|
-
if newline < 0:
|
|
824
|
-
return False
|
|
825
|
-
index = newline + 1
|
|
826
|
-
continue
|
|
827
|
-
if char != "&":
|
|
828
|
-
index += 1
|
|
829
|
-
continue
|
|
830
|
-
previous = command[index - 1] if index else ""
|
|
831
|
-
following = command[index + 1] if index + 1 < len(command) else ""
|
|
832
|
-
if previous in {"&", ">", "<"} or following in {"&", ">"}:
|
|
833
|
-
index += 1
|
|
834
|
-
continue
|
|
835
|
-
return True
|
|
836
|
-
return False
|
|
837
|
-
|
|
838
|
-
|
|
839
|
-
def _shell_tokens(command: str) -> list[str]:
|
|
840
|
-
try:
|
|
841
|
-
lexer = shlex.shlex(command, posix=True, punctuation_chars=";&|<>()")
|
|
842
|
-
lexer.whitespace_split = True
|
|
843
|
-
lexer.commenters = ""
|
|
844
|
-
return list(lexer)
|
|
845
|
-
except ValueError:
|
|
846
|
-
# An incomplete command will fail in Bash itself. Do not turn a parser
|
|
847
|
-
# disagreement into a misleading policy denial.
|
|
848
|
-
return []
|
|
849
|
-
|
|
850
|
-
|
|
851
|
-
def claude_untracked_background_reason(
|
|
852
|
-
tool_name: str,
|
|
853
|
-
tool_input: dict[str, Any] | None,
|
|
854
|
-
) -> str | None:
|
|
855
|
-
"""Identify common shell detachment that bypasses SDK task tracking."""
|
|
856
|
-
|
|
857
|
-
if str(tool_name or "").strip().lower() != "bash":
|
|
858
|
-
return None
|
|
859
|
-
normalized_input = tool_input or {}
|
|
860
|
-
if normalized_input.get("run_in_background") is True:
|
|
861
|
-
return _UNTRACKED_BACKGROUND_REASON
|
|
862
|
-
command = str(normalized_input.get("command") or "")
|
|
863
|
-
if not command.strip():
|
|
864
|
-
return None
|
|
865
|
-
if _has_unquoted_background_operator(command):
|
|
866
|
-
return _UNTRACKED_BACKGROUND_REASON
|
|
867
|
-
|
|
868
|
-
tokens = _shell_tokens(command)
|
|
869
|
-
expect_command = True
|
|
870
|
-
wrapper_active = False
|
|
871
|
-
for index, token in enumerate(tokens):
|
|
872
|
-
if token in _SHELL_CONTROL_TOKENS:
|
|
873
|
-
expect_command = True
|
|
874
|
-
wrapper_active = False
|
|
875
|
-
continue
|
|
876
|
-
if not expect_command:
|
|
877
|
-
continue
|
|
878
|
-
if _SHELL_ASSIGNMENT_RE.match(token):
|
|
879
|
-
continue
|
|
880
|
-
executable = token.rsplit("/", 1)[-1]
|
|
881
|
-
if executable in _SHELL_COMMAND_WRAPPERS:
|
|
882
|
-
wrapper_active = True
|
|
883
|
-
continue
|
|
884
|
-
if wrapper_active and token.startswith("-"):
|
|
885
|
-
continue
|
|
886
|
-
if executable in {"nohup", "disown"}:
|
|
887
|
-
return _UNTRACKED_BACKGROUND_REASON
|
|
888
|
-
if executable in {"bash", "dash", "ksh", "sh", "zsh"}:
|
|
889
|
-
arguments = tokens[index + 1:]
|
|
890
|
-
for argument_index, argument in enumerate(arguments[:-1]):
|
|
891
|
-
if (
|
|
892
|
-
argument.startswith("-")
|
|
893
|
-
and not argument.startswith("--")
|
|
894
|
-
and "c" in argument[1:]
|
|
895
|
-
and claude_untracked_background_reason(
|
|
896
|
-
"Bash", {"command": arguments[argument_index + 1]}
|
|
897
|
-
) is not None
|
|
898
|
-
):
|
|
899
|
-
return _UNTRACKED_BACKGROUND_REASON
|
|
900
|
-
if executable == "setsid":
|
|
901
|
-
# Even without --fork, a new session can escape process-group
|
|
902
|
-
# cleanup if the provider/server disappears. Keep it out of the
|
|
903
|
-
# untracked Bash path entirely.
|
|
904
|
-
return _UNTRACKED_BACKGROUND_REASON
|
|
905
|
-
expect_command = False
|
|
906
|
-
return None
|
|
907
|
-
|
|
908
|
-
|
|
909
|
-
async def reject_untracked_background_hook(
|
|
910
|
-
hook_input: dict[str, Any],
|
|
911
|
-
_tool_use_id: str | None,
|
|
912
|
-
_context: dict[str, Any],
|
|
913
|
-
) -> dict[str, Any]:
|
|
914
|
-
"""Keep Claude background work attached to the SDK's task lifecycle."""
|
|
915
|
-
|
|
916
|
-
reason = claude_untracked_background_reason(
|
|
917
|
-
str(hook_input.get("tool_name") or ""),
|
|
918
|
-
hook_input.get("tool_input")
|
|
919
|
-
if isinstance(hook_input.get("tool_input"), dict)
|
|
920
|
-
else {},
|
|
921
|
-
)
|
|
922
|
-
if reason is None:
|
|
923
|
-
return {}
|
|
924
|
-
return {
|
|
925
|
-
"hookSpecificOutput": {
|
|
926
|
-
"hookEventName": "PreToolUse",
|
|
927
|
-
"permissionDecision": "deny",
|
|
928
|
-
"permissionDecisionReason": reason,
|
|
929
|
-
}
|
|
930
|
-
}
|
|
931
|
-
|
|
932
|
-
|
|
933
|
-
def claude_nondurable_scheduler_reason(tool_name: Any) -> str | None:
|
|
934
|
-
"""Reject only the exact Claude tools that cannot create durable Dock work."""
|
|
935
|
-
|
|
936
|
-
if tool_name not in CLAUDE_NON_DURABLE_SCHEDULER_TOOLS:
|
|
937
|
-
return None
|
|
938
|
-
return _NON_DURABLE_SCHEDULER_REASON.format(tool_name=tool_name)
|
|
939
|
-
|
|
940
|
-
|
|
941
|
-
async def reject_nondurable_scheduler_hook(
|
|
942
|
-
hook_input: dict[str, Any],
|
|
943
|
-
_tool_use_id: str | None,
|
|
944
|
-
_context: dict[str, Any],
|
|
945
|
-
) -> dict[str, Any]:
|
|
946
|
-
"""Fail closed before Claude can arm a provider-local scheduler."""
|
|
947
|
-
|
|
948
|
-
reason = claude_nondurable_scheduler_reason(hook_input.get("tool_name"))
|
|
949
|
-
if reason is None:
|
|
950
|
-
return {}
|
|
951
|
-
return {
|
|
952
|
-
"hookSpecificOutput": {
|
|
953
|
-
"hookEventName": "PreToolUse",
|
|
954
|
-
"permissionDecision": "deny",
|
|
955
|
-
"permissionDecisionReason": reason,
|
|
956
|
-
}
|
|
957
|
-
}
|
|
958
|
-
|
|
959
|
-
|
|
960
731
|
async def reject_subagent_provider_tool_hook(
|
|
961
732
|
hook_input: dict[str, Any],
|
|
962
733
|
_tool_use_id: str | None,
|
|
@@ -978,11 +749,17 @@ async def reject_subagent_provider_tool_hook(
|
|
|
978
749
|
}
|
|
979
750
|
|
|
980
751
|
|
|
981
|
-
def claude_background_tracking_hooks(
|
|
982
|
-
|
|
752
|
+
def claude_background_tracking_hooks(
|
|
753
|
+
child_registry: Path | None = None,
|
|
754
|
+
) -> dict[str, list[ClaudeSDKHookMatcher]]:
|
|
755
|
+
"""Keep native task receipts and exact AgentsDock tool ownership."""
|
|
983
756
|
|
|
984
757
|
mail_hint = _PendingMailHintHook()
|
|
758
|
+
chat_routing = ClaudeChatRouting(child_registry)
|
|
985
759
|
return {
|
|
760
|
+
"SubagentStart": [ClaudeSDKHookMatcher(
|
|
761
|
+
matcher=None, hooks=[chat_routing.subagent_start], timeout=5.0,
|
|
762
|
+
)],
|
|
986
763
|
"PostToolUse": [ClaudeSDKHookMatcher(matcher=None, hooks=[mail_hint], timeout=5.0)],
|
|
987
764
|
"PostToolUseFailure": [ClaudeSDKHookMatcher(matcher=None, hooks=[mail_hint], timeout=5.0)],
|
|
988
765
|
"UserPromptSubmit": [ClaudeSDKHookMatcher(
|
|
@@ -995,18 +772,10 @@ def claude_background_tracking_hooks() -> dict[str, list[ClaudeSDKHookMatcher]]:
|
|
|
995
772
|
timeout=5.0,
|
|
996
773
|
),
|
|
997
774
|
ClaudeSDKHookMatcher(
|
|
998
|
-
matcher=
|
|
999
|
-
hooks=[
|
|
775
|
+
matcher=NATIVE_CHAT_TOOL_MATCHER,
|
|
776
|
+
hooks=[chat_routing.pre_tool_use],
|
|
1000
777
|
timeout=5.0,
|
|
1001
778
|
),
|
|
1002
|
-
*[
|
|
1003
|
-
ClaudeSDKHookMatcher(
|
|
1004
|
-
matcher=tool_name,
|
|
1005
|
-
hooks=[reject_nondurable_scheduler_hook],
|
|
1006
|
-
timeout=5.0,
|
|
1007
|
-
)
|
|
1008
|
-
for tool_name in CLAUDE_NON_DURABLE_SCHEDULER_TOOLS
|
|
1009
|
-
],
|
|
1010
779
|
]
|
|
1011
780
|
}
|
|
1012
781
|
|
|
@@ -1081,6 +850,20 @@ class ClaudeSDKRunHandle:
|
|
|
1081
850
|
self._background_task_reconciliation_consumed = False
|
|
1082
851
|
self._background_reconciliation_progress_observed = False
|
|
1083
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
|
|
1084
867
|
|
|
1085
868
|
@property
|
|
1086
869
|
def background_task_receipts(self) -> tuple[MappingProxyType, ...]:
|
|
@@ -1185,6 +968,14 @@ class ClaudeSDKRunHandle:
|
|
|
1185
968
|
self._check_loop()
|
|
1186
969
|
return await self._interrupt_callback(self.run_id)
|
|
1187
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
|
+
|
|
1188
979
|
def __aiter__(self) -> ClaudeSDKRunHandle:
|
|
1189
980
|
return self
|
|
1190
981
|
|
|
@@ -1216,12 +1007,13 @@ class ClaudeSDKRunHandle:
|
|
|
1216
1007
|
return True
|
|
1217
1008
|
|
|
1218
1009
|
def _mark_acknowledged_without_replay(self) -> None:
|
|
1219
|
-
"""Open the stream gate for
|
|
1010
|
+
"""Open the stream gate for an independently proven native owner.
|
|
1220
1011
|
|
|
1221
1012
|
Claude Code local commands bypass the ordinary query replay loop and
|
|
1222
1013
|
therefore do not emit the UUID-bearing ``UserMessage`` used as the
|
|
1223
|
-
ownership fence for normal prompts.
|
|
1224
|
-
|
|
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.
|
|
1225
1017
|
"""
|
|
1226
1018
|
|
|
1227
1019
|
if self._acknowledged:
|
|
@@ -1261,6 +1053,65 @@ class ClaudeSDKSupervisorSnapshot:
|
|
|
1261
1053
|
last_used_at: float
|
|
1262
1054
|
|
|
1263
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
|
+
|
|
1264
1115
|
@dataclass
|
|
1265
1116
|
class _StartRun:
|
|
1266
1117
|
prompt: str
|
|
@@ -1272,6 +1123,7 @@ class _StartRun:
|
|
|
1272
1123
|
response: asyncio.Future[ClaudeSDKRunHandle]
|
|
1273
1124
|
background_task_reconciliation: dict[str, Any] | None = None
|
|
1274
1125
|
pending_mail_hint: Callable[[], str | None] | None = None
|
|
1126
|
+
native_continuation_callback: NativeContinuationCallback | None = None
|
|
1275
1127
|
|
|
1276
1128
|
|
|
1277
1129
|
@dataclass
|
|
@@ -1280,6 +1132,33 @@ class _Interrupt:
|
|
|
1280
1132
|
response: asyncio.Future[bool]
|
|
1281
1133
|
|
|
1282
1134
|
|
|
1135
|
+
@dataclass
|
|
1136
|
+
class _SteerRun:
|
|
1137
|
+
prompt: str
|
|
1138
|
+
run_id: str
|
|
1139
|
+
ownership_token: str
|
|
1140
|
+
query_session_id: str | None
|
|
1141
|
+
on_before_send: SupervisorReadyCallback | None
|
|
1142
|
+
response: asyncio.Future[str]
|
|
1143
|
+
correlation_id: str
|
|
1144
|
+
cancelled: bool = False
|
|
1145
|
+
delivery_attempted: bool = False
|
|
1146
|
+
send_now_requested: bool = False
|
|
1147
|
+
goal_condition: str | None = None
|
|
1148
|
+
goal_generation: str | None = None
|
|
1149
|
+
goal_started: bool = False
|
|
1150
|
+
predecessor_result: Any | None = None
|
|
1151
|
+
|
|
1152
|
+
|
|
1153
|
+
@dataclass(frozen=True)
|
|
1154
|
+
class ClaudeSDKGoalReceipt:
|
|
1155
|
+
"""Internal receipt for one provider-owned queued /goal command."""
|
|
1156
|
+
|
|
1157
|
+
command_id: str
|
|
1158
|
+
error: str | None = None
|
|
1159
|
+
cancelled_by_user: bool = False
|
|
1160
|
+
|
|
1161
|
+
|
|
1283
1162
|
@dataclass
|
|
1284
1163
|
class _ClearGoal:
|
|
1285
1164
|
run_id: str
|
|
@@ -1378,6 +1257,7 @@ class ClaudeSDKSupervisor:
|
|
|
1378
1257
|
raise ValueError("chat_id is required")
|
|
1379
1258
|
self.chat_id = clean_chat_id
|
|
1380
1259
|
self.options = options
|
|
1260
|
+
self._reconnect_options = options
|
|
1381
1261
|
self.configuration_key = str(configuration_key)
|
|
1382
1262
|
self.ownership_token = f"claudeowner_{uuid.uuid4().hex}"
|
|
1383
1263
|
bind_permission_owner(self.options, self.ownership_token)
|
|
@@ -1409,8 +1289,31 @@ class ClaudeSDKSupervisor:
|
|
|
1409
1289
|
self._receiver_task: asyncio.Task[None] | None = None
|
|
1410
1290
|
self._ack_timeout_task: asyncio.Task[None] | None = None
|
|
1411
1291
|
self._active_run: ClaudeSDKRunHandle | None = None
|
|
1292
|
+
self._pending_steer: _SteerRun | None = None
|
|
1293
|
+
self._superseded_query_ids: set[str] = set()
|
|
1294
|
+
self._current_query_id: str | None = None
|
|
1295
|
+
self._supports_send_now = False
|
|
1296
|
+
self._supports_command_lifecycle = False
|
|
1412
1297
|
self._pending_goal_clear: _ClearGoal | None = None
|
|
1298
|
+
self._pending_goal: _SteerRun | None = None
|
|
1299
|
+
self._goal_stop_run_id: str | None = None
|
|
1300
|
+
self._goal_stop_tasks: set[str] = set()
|
|
1301
|
+
self._goal_stop_result: Any | None = None
|
|
1413
1302
|
self._inflight_tasks: set[str] = set()
|
|
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
|
|
1316
|
+
self._background_work_revision = 0
|
|
1414
1317
|
self._background_reconciliation_hook: _BackgroundReconciliationHook | None = None
|
|
1415
1318
|
self._pending_mail_hint_hook: _PendingMailHintHook | None = None
|
|
1416
1319
|
self._generation = 0
|
|
@@ -1507,6 +1410,7 @@ class ClaudeSDKSupervisor:
|
|
|
1507
1410
|
on_supervisor_ready: SupervisorReadyCallback | None = None,
|
|
1508
1411
|
background_task_reconciliation: dict[str, Any] | None = None,
|
|
1509
1412
|
pending_mail_hint: Callable[[], str | None] | None = None,
|
|
1413
|
+
native_continuation_callback: NativeContinuationCallback | None = None,
|
|
1510
1414
|
) -> ClaudeSDKRunHandle:
|
|
1511
1415
|
"""Submit one prompt and return after the SDK accepts ``query()``."""
|
|
1512
1416
|
|
|
@@ -1538,6 +1442,7 @@ class ClaudeSDKSupervisor:
|
|
|
1538
1442
|
response=response,
|
|
1539
1443
|
background_task_reconciliation=_normalized_task_reconciliation(background_task_reconciliation),
|
|
1540
1444
|
pending_mail_hint=pending_mail_hint,
|
|
1445
|
+
native_continuation_callback=native_continuation_callback,
|
|
1541
1446
|
)
|
|
1542
1447
|
)
|
|
1543
1448
|
return await asyncio.shield(response)
|
|
@@ -1551,6 +1456,56 @@ class ClaudeSDKSupervisor:
|
|
|
1551
1456
|
await self._commands.put(_Interrupt(run_id=run_id, response=response))
|
|
1552
1457
|
return await asyncio.shield(response)
|
|
1553
1458
|
|
|
1459
|
+
async def steer_run(
|
|
1460
|
+
self,
|
|
1461
|
+
prompt: str,
|
|
1462
|
+
*,
|
|
1463
|
+
run_id: str,
|
|
1464
|
+
ownership_token: str,
|
|
1465
|
+
query_session_id: str | None = None,
|
|
1466
|
+
on_before_send: SupervisorReadyCallback | None = None,
|
|
1467
|
+
_goal_condition: str | None = None,
|
|
1468
|
+
_command_id: str | None = None,
|
|
1469
|
+
_goal_generation: str | None = None,
|
|
1470
|
+
) -> str:
|
|
1471
|
+
"""Send native follow-up input without stopping the owning run/tasks.
|
|
1472
|
+
|
|
1473
|
+
Return after exact replay, or native queue admission for /goal. Cancellation
|
|
1474
|
+
after a write attempt is delivery-uncertain and never retries or stops
|
|
1475
|
+
the live connection. Its ACK still settles the actor's pending lane.
|
|
1476
|
+
"""
|
|
1477
|
+
|
|
1478
|
+
loop = self._ensure_actor()
|
|
1479
|
+
response: asyncio.Future[str] = loop.create_future()
|
|
1480
|
+
command = _SteerRun(
|
|
1481
|
+
str(prompt), str(run_id), str(ownership_token), query_session_id,
|
|
1482
|
+
on_before_send, response, _command_id or str(uuid.uuid4()),
|
|
1483
|
+
goal_condition=_goal_condition,
|
|
1484
|
+
goal_generation=_goal_generation,
|
|
1485
|
+
)
|
|
1486
|
+
# An HTTP waiter may leave after delivery. Still consume any eventual
|
|
1487
|
+
# failure while preserving it for callers that remain attached.
|
|
1488
|
+
response.add_done_callback(
|
|
1489
|
+
lambda future: None if future.cancelled() else future.exception()
|
|
1490
|
+
)
|
|
1491
|
+
assert self._commands is not None
|
|
1492
|
+
await self._commands.put(command)
|
|
1493
|
+
try:
|
|
1494
|
+
return await asyncio.shield(response)
|
|
1495
|
+
except asyncio.CancelledError as exc:
|
|
1496
|
+
if not command.delivery_attempted:
|
|
1497
|
+
command.cancelled = True
|
|
1498
|
+
response.cancel()
|
|
1499
|
+
# Preserve asyncio cancellation while letting the queue owner
|
|
1500
|
+
# distinguish proven non-delivery from an uncertain write.
|
|
1501
|
+
exc.delivery_uncertain = False
|
|
1502
|
+
exc.safe_to_requeue = True
|
|
1503
|
+
raise
|
|
1504
|
+
raise ClaudeSDKQueryError(
|
|
1505
|
+
f"Claude {'goal request' if _goal_condition is not None else 'Force Send'} was cancelled after delivery was attempted; "
|
|
1506
|
+
"the message must not be replayed"
|
|
1507
|
+
) from exc
|
|
1508
|
+
|
|
1554
1509
|
async def clear_goal(
|
|
1555
1510
|
self, *, run_id: str, expected_generation: str | None = None,
|
|
1556
1511
|
) -> tuple[dict[str, Any], str]:
|
|
@@ -1581,7 +1536,11 @@ class ClaudeSDKSupervisor:
|
|
|
1581
1536
|
response: asyncio.Future[dict[str, Any] | None] = loop.create_future()
|
|
1582
1537
|
assert self._commands is not None
|
|
1583
1538
|
await self._commands.put(_GetContextUsage(response=response))
|
|
1584
|
-
|
|
1539
|
+
try:
|
|
1540
|
+
return await asyncio.shield(response)
|
|
1541
|
+
except asyncio.CancelledError:
|
|
1542
|
+
response.cancel()
|
|
1543
|
+
raise
|
|
1585
1544
|
|
|
1586
1545
|
async def get_mcp_status(self) -> tuple[dict[str, Any], str]:
|
|
1587
1546
|
"""Connect lazily and query MCP state on this chat-owned SDK actor."""
|
|
@@ -1828,9 +1787,40 @@ class ClaudeSDKSupervisor:
|
|
|
1828
1787
|
async def _new_client(self) -> ClaudeSDKClientProtocol:
|
|
1829
1788
|
client: ClaudeSDKClientProtocol | None = None
|
|
1830
1789
|
try:
|
|
1790
|
+
# A fork's saved native ID changes after its first turn. Keep the
|
|
1791
|
+
# latest supplied binding for reconnects that happen inside the
|
|
1792
|
+
# actor, without replacing callbacks on the still-live client.
|
|
1793
|
+
self.options = self._reconnect_options
|
|
1794
|
+
bind_permission_owner(self.options, self.ownership_token)
|
|
1831
1795
|
client_options, background_hook = _connection_background_hook(self.options)
|
|
1832
1796
|
self._background_reconciliation_hook = background_hook
|
|
1833
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
|
|
1834
1824
|
candidate = self._client_factory(client_options)
|
|
1835
1825
|
client = await candidate if inspect.isawaitable(candidate) else candidate
|
|
1836
1826
|
self._connecting_client = client
|
|
@@ -1886,6 +1876,27 @@ class ClaudeSDKSupervisor:
|
|
|
1886
1876
|
client = await self._new_client()
|
|
1887
1877
|
return client
|
|
1888
1878
|
|
|
1879
|
+
def _query_provider_session_id(self, supplied: str | None) -> str | None:
|
|
1880
|
+
if supplied is not None and supplied != "default":
|
|
1881
|
+
return supplied
|
|
1882
|
+
options = self._reconnect_options
|
|
1883
|
+
value = options.get if isinstance(options, dict) else lambda key: getattr(options, key, None)
|
|
1884
|
+
# A first fork submission runs in a newly assigned child UUID, not
|
|
1885
|
+
# its resume source. The exact process/query/prompt still owns its hook.
|
|
1886
|
+
return None if value("fork_session") else value("resume")
|
|
1887
|
+
|
|
1888
|
+
def _observe_live_background_work(self, message: Any) -> None:
|
|
1889
|
+
subtype, task_id, task_type, status = _task_lifecycle_fields(message)
|
|
1890
|
+
if not task_id:
|
|
1891
|
+
return
|
|
1892
|
+
before = task_id in self._live_background_tasks
|
|
1893
|
+
if subtype == "task_started" and task_type in {*_DEFERRING_TASK_TYPES, "local_bash"}:
|
|
1894
|
+
self._live_background_tasks.add(task_id)
|
|
1895
|
+
elif subtype == "task_notification" or (subtype == "task_updated" and status in _TERMINAL_TASK_STATUSES):
|
|
1896
|
+
self._live_background_tasks.discard(task_id)
|
|
1897
|
+
if before != (task_id in self._live_background_tasks):
|
|
1898
|
+
self._background_work_revision += 1
|
|
1899
|
+
|
|
1889
1900
|
async def _receive_loop(
|
|
1890
1901
|
self,
|
|
1891
1902
|
client: ClaudeSDKClientProtocol,
|
|
@@ -1900,6 +1911,11 @@ class ClaudeSDKSupervisor:
|
|
|
1900
1911
|
# activity, including packets arriving after side cancellation.
|
|
1901
1912
|
if is_native_side_question_progress(message):
|
|
1902
1913
|
continue
|
|
1914
|
+
if self._client is client and self._generation == generation:
|
|
1915
|
+
# Native Bash may outlive the logical Result. Observe its
|
|
1916
|
+
# lifecycle on this exact connection, even with no run or
|
|
1917
|
+
# while an auxiliary actor control is awaiting a reply.
|
|
1918
|
+
self._observe_live_background_work(message)
|
|
1903
1919
|
commands = self._commands
|
|
1904
1920
|
if commands is None:
|
|
1905
1921
|
return
|
|
@@ -1918,6 +1934,15 @@ class ClaudeSDKSupervisor:
|
|
|
1918
1934
|
)
|
|
1919
1935
|
|
|
1920
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()
|
|
1942
|
+
self._supports_send_now = False
|
|
1943
|
+
self._supports_command_lifecycle = False
|
|
1944
|
+
self._fail_pending_steer("Claude disconnected before confirming Force Send")
|
|
1945
|
+
self._fail_pending_goal("Claude disconnected before applying the queued goal")
|
|
1921
1946
|
pending = self._pending_goal_clear
|
|
1922
1947
|
self._pending_goal_clear = None
|
|
1923
1948
|
if pending is not None and not pending.response.done():
|
|
@@ -1933,22 +1958,34 @@ class ClaudeSDKSupervisor:
|
|
|
1933
1958
|
self._background_reconciliation_hook.retire()
|
|
1934
1959
|
self._background_reconciliation_hook = None
|
|
1935
1960
|
bind_provider_tool_owner(self.options, "", "")
|
|
1961
|
+
self._release_native_admission_gate()
|
|
1936
1962
|
client = self._client
|
|
1937
1963
|
receiver = self._receiver_task
|
|
1938
1964
|
self._client = None
|
|
1939
1965
|
self._receiver_task = None
|
|
1940
1966
|
self._connected = False
|
|
1967
|
+
self._live_background_tasks.clear()
|
|
1968
|
+
self._background_work_revision += 1
|
|
1941
1969
|
if client is not None:
|
|
1942
1970
|
await self._disconnect_client(client)
|
|
1943
1971
|
if receiver is not None and receiver is not asyncio.current_task():
|
|
1944
1972
|
await self._cancel_task_bounded(receiver)
|
|
1945
1973
|
|
|
1946
1974
|
def _fail_active(self, error: BaseException) -> None:
|
|
1975
|
+
self._clear_native_continuations()
|
|
1976
|
+
self._fail_pending_steer("Claude ended before confirming Force Send")
|
|
1977
|
+
self._fail_pending_goal("Claude ended before applying the queued goal")
|
|
1947
1978
|
self._cancel_ack_timeout()
|
|
1948
1979
|
active = self._active_run
|
|
1949
1980
|
self._active_run = None
|
|
1950
1981
|
bind_provider_tool_owner(self.options, "", "")
|
|
1982
|
+
self._release_native_admission_gate()
|
|
1951
1983
|
self._inflight_tasks.clear()
|
|
1984
|
+
self._goal_stop_run_id = None
|
|
1985
|
+
self._goal_stop_tasks.clear()
|
|
1986
|
+
self._goal_stop_result = None
|
|
1987
|
+
self._superseded_query_ids.clear()
|
|
1988
|
+
self._current_query_id = None
|
|
1952
1989
|
if self._background_reconciliation_hook is not None:
|
|
1953
1990
|
self._background_reconciliation_hook.retire()
|
|
1954
1991
|
if self._pending_mail_hint_hook is not None:
|
|
@@ -1956,6 +1993,23 @@ class ClaudeSDKSupervisor:
|
|
|
1956
1993
|
if active is not None:
|
|
1957
1994
|
active._fail(error)
|
|
1958
1995
|
|
|
1996
|
+
def _fail_pending_steer(self, message: str) -> None:
|
|
1997
|
+
pending = self._pending_steer
|
|
1998
|
+
self._pending_steer = None
|
|
1999
|
+
if pending is not None and not pending.response.done():
|
|
2000
|
+
pending.response.set_exception(ClaudeSDKQueryError(message))
|
|
2001
|
+
|
|
2002
|
+
def _fail_pending_goal(self, message: str, *, cancelled_by_user: bool = False) -> None:
|
|
2003
|
+
pending = self._pending_goal
|
|
2004
|
+
self._pending_goal = None
|
|
2005
|
+
if pending is not None:
|
|
2006
|
+
if self._active_run is not None:
|
|
2007
|
+
self._active_run._deliver(ClaudeSDKGoalReceipt(
|
|
2008
|
+
pending.correlation_id, message, cancelled_by_user=cancelled_by_user,
|
|
2009
|
+
))
|
|
2010
|
+
if not pending.response.done():
|
|
2011
|
+
pending.response.set_exception(ClaudeSDKQueryError(message))
|
|
2012
|
+
|
|
1959
2013
|
def _cancel_ack_timeout(self) -> None:
|
|
1960
2014
|
task = self._ack_timeout_task
|
|
1961
2015
|
self._ack_timeout_task = None
|
|
@@ -1986,10 +2040,10 @@ class ClaudeSDKSupervisor:
|
|
|
1986
2040
|
|
|
1987
2041
|
async def _deliver_query_bounded(
|
|
1988
2042
|
self,
|
|
1989
|
-
query: Awaitable[
|
|
2043
|
+
query: Awaitable[Any],
|
|
1990
2044
|
*,
|
|
1991
2045
|
run_id: str,
|
|
1992
|
-
) ->
|
|
2046
|
+
) -> Any:
|
|
1993
2047
|
"""Bound stdin delivery without awaiting cancellation-hostile SDK code."""
|
|
1994
2048
|
|
|
1995
2049
|
task = asyncio.create_task(
|
|
@@ -2018,7 +2072,7 @@ class ClaudeSDKSupervisor:
|
|
|
2018
2072
|
f"Claude SDK query delivery timed out for chat {self.chat_id}; "
|
|
2019
2073
|
"delivery is uncertain"
|
|
2020
2074
|
)
|
|
2021
|
-
await task
|
|
2075
|
+
return await task
|
|
2022
2076
|
|
|
2023
2077
|
async def _handle_start(self, command: _StartRun) -> None:
|
|
2024
2078
|
if self._pending_goal_clear is not None:
|
|
@@ -2030,12 +2084,22 @@ class ClaudeSDKSupervisor:
|
|
|
2030
2084
|
if self._active_run is not None and not self._active_run.done:
|
|
2031
2085
|
if not command.response.done():
|
|
2032
2086
|
command.response.set_exception(
|
|
2033
|
-
|
|
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(
|
|
2034
2091
|
f"Claude SDK chat {self.chat_id} already has active run "
|
|
2035
2092
|
f"{self._active_run.run_id}"
|
|
2036
2093
|
)
|
|
2037
2094
|
)
|
|
2038
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
|
|
2039
2103
|
self._active_run = None
|
|
2040
2104
|
raw_provider_command = command.validated_provider_command_name is not None
|
|
2041
2105
|
if raw_provider_command and not _prompt_invokes_validated_claude_command(
|
|
@@ -2084,6 +2148,7 @@ class ClaudeSDKSupervisor:
|
|
|
2084
2148
|
return await self.interrupt(run_id=run_id)
|
|
2085
2149
|
|
|
2086
2150
|
correlation_id = str(uuid.uuid4())
|
|
2151
|
+
self._remember_native_schedule_command(correlation_id)
|
|
2087
2152
|
handle = ClaudeSDKRunHandle(
|
|
2088
2153
|
self.chat_id,
|
|
2089
2154
|
command.run_id,
|
|
@@ -2092,7 +2157,18 @@ class ClaudeSDKSupervisor:
|
|
|
2092
2157
|
interrupt_this_run,
|
|
2093
2158
|
)
|
|
2094
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()
|
|
2095
2169
|
self._active_run = handle
|
|
2170
|
+
self._superseded_query_ids.clear()
|
|
2171
|
+
self._current_query_id = correlation_id
|
|
2096
2172
|
self._last_used_at = time.monotonic()
|
|
2097
2173
|
if command.on_supervisor_ready is not None:
|
|
2098
2174
|
try:
|
|
@@ -2122,14 +2198,13 @@ class ClaudeSDKSupervisor:
|
|
|
2122
2198
|
self.ownership_token,
|
|
2123
2199
|
command.run_id,
|
|
2124
2200
|
)
|
|
2201
|
+
self._release_native_admission_gate()
|
|
2125
2202
|
background_hook = self._background_reconciliation_hook
|
|
2126
2203
|
mail_hook = self._pending_mail_hint_hook
|
|
2127
2204
|
if mail_hook is not None:
|
|
2128
2205
|
mail_hook.retire()
|
|
2129
2206
|
if callable(command.pending_mail_hint):
|
|
2130
|
-
provider_id = command.query_session_id
|
|
2131
|
-
if provider_id is None or provider_id == "default":
|
|
2132
|
-
provider_id = self.options.get("resume") if isinstance(self.options, dict) else getattr(self.options, "resume", None)
|
|
2207
|
+
provider_id = self._query_provider_session_id(command.query_session_id)
|
|
2133
2208
|
generation = self._generation
|
|
2134
2209
|
mail_hook.bind(
|
|
2135
2210
|
handle, command.pending_mail_hint, _receipt_field(provider_id),
|
|
@@ -2137,9 +2212,7 @@ class ClaudeSDKSupervisor:
|
|
|
2137
2212
|
and self._generation == generation and self._pending_mail_hint_hook is mail_hook,
|
|
2138
2213
|
)
|
|
2139
2214
|
if background_hook is not None and command.background_task_reconciliation is not None:
|
|
2140
|
-
provider_id = command.query_session_id
|
|
2141
|
-
if provider_id is None or provider_id == "default":
|
|
2142
|
-
provider_id = self.options.get("resume") if isinstance(self.options, dict) else getattr(self.options, "resume", None)
|
|
2215
|
+
provider_id = self._query_provider_session_id(command.query_session_id)
|
|
2143
2216
|
background_hook.bind(
|
|
2144
2217
|
handle,
|
|
2145
2218
|
command.prompt,
|
|
@@ -2209,6 +2282,112 @@ class ClaudeSDKSupervisor:
|
|
|
2209
2282
|
if not command.response.done():
|
|
2210
2283
|
command.response.set_result(handle)
|
|
2211
2284
|
|
|
2285
|
+
async def _handle_steer(self, command: _SteerRun) -> None:
|
|
2286
|
+
if command.cancelled:
|
|
2287
|
+
return
|
|
2288
|
+
active = self._active_run
|
|
2289
|
+
client = self._client
|
|
2290
|
+
operation = "setting the goal" if command.goal_condition is not None else "Force Send"
|
|
2291
|
+
if (active is None or active.done or active.run_id != command.run_id
|
|
2292
|
+
or self.ownership_token != command.ownership_token
|
|
2293
|
+
or client is None or not self._connected):
|
|
2294
|
+
command.response.set_exception(ClaudeSDKGenerationChanged(
|
|
2295
|
+
f"The Claude run changed before {operation}"
|
|
2296
|
+
))
|
|
2297
|
+
return
|
|
2298
|
+
if ((not active.acknowledged and command.goal_condition is None)
|
|
2299
|
+
or (self._pending_goal is not None if command.goal_condition is not None else self._pending_steer is not None)
|
|
2300
|
+
or self._pending_goal_clear is not None or self._goal_stop_run_id is not None):
|
|
2301
|
+
command.response.set_exception(ClaudeSDKRunActive(
|
|
2302
|
+
"Claude is still confirming its previous input"
|
|
2303
|
+
))
|
|
2304
|
+
return
|
|
2305
|
+
send_now = getattr(client, "send_now", None)
|
|
2306
|
+
if command.goal_condition is not None and not self._supports_command_lifecycle:
|
|
2307
|
+
command.response.set_exception(ClaudeSDKConfigurationConflict(
|
|
2308
|
+
"Update Claude Code to set a goal while it is working"
|
|
2309
|
+
))
|
|
2310
|
+
return
|
|
2311
|
+
if command.goal_generation is not None and command.goal_generation != self.control_generation:
|
|
2312
|
+
command.response.set_exception(ClaudeSDKGenerationChanged(
|
|
2313
|
+
"The Claude command inventory changed before setting the goal"
|
|
2314
|
+
))
|
|
2315
|
+
return
|
|
2316
|
+
if command.goal_condition is None and (not self._supports_send_now or not callable(send_now)):
|
|
2317
|
+
command.response.set_exception(ClaudeSDKConfigurationConflict(
|
|
2318
|
+
"This Claude CLI cannot Force Send while preserving background work; "
|
|
2319
|
+
"update Claude Code or leave the message queued"
|
|
2320
|
+
))
|
|
2321
|
+
return
|
|
2322
|
+
try:
|
|
2323
|
+
if command.on_before_send is not None:
|
|
2324
|
+
await command.on_before_send(self.ownership_token)
|
|
2325
|
+
if command.cancelled:
|
|
2326
|
+
return
|
|
2327
|
+
if self._closed:
|
|
2328
|
+
raise ClaudeSDKSupervisorClosed(f"Claude closed before {operation}")
|
|
2329
|
+
except Exception as exc:
|
|
2330
|
+
if not command.response.done():
|
|
2331
|
+
command.response.set_exception(exc)
|
|
2332
|
+
return
|
|
2333
|
+
|
|
2334
|
+
# Keep the same run and MCP owner. Rebinding would let a delayed call
|
|
2335
|
+
# from the preceding model response borrow a successor's authority.
|
|
2336
|
+
# Install the receipt lane before writing: the receiver can enqueue
|
|
2337
|
+
# an interrupted predecessor Result or a child completion immediately.
|
|
2338
|
+
if command.goal_condition is not None:
|
|
2339
|
+
self._pending_goal = command
|
|
2340
|
+
else:
|
|
2341
|
+
self._pending_steer = command
|
|
2342
|
+
command.delivery_attempted = True
|
|
2343
|
+
try:
|
|
2344
|
+
kwargs = ({"session_id": command.query_session_id}
|
|
2345
|
+
if command.query_session_id is not None else {})
|
|
2346
|
+
await self._deliver_query_bounded(
|
|
2347
|
+
client.query(_query_message_stream(
|
|
2348
|
+
command.prompt, command.correlation_id,
|
|
2349
|
+
"goal" if command.goal_condition is not None else None,
|
|
2350
|
+
priority="now" if command.goal_condition is not None else "next",
|
|
2351
|
+
), **kwargs),
|
|
2352
|
+
run_id=command.run_id,
|
|
2353
|
+
)
|
|
2354
|
+
except Exception as exc:
|
|
2355
|
+
error = ClaudeSDKQueryError(
|
|
2356
|
+
f"Claude {'goal request' if command.goal_condition is not None else 'Force Send'} delivery is uncertain: {exc}"
|
|
2357
|
+
)
|
|
2358
|
+
if not command.response.done():
|
|
2359
|
+
command.response.set_exception(error)
|
|
2360
|
+
# The transport may have accepted the frame before reporting a
|
|
2361
|
+
# write failure. Keep its receipt lane and the existing tasks;
|
|
2362
|
+
# only an actual receiver failure or explicit Stop retires them.
|
|
2363
|
+
return
|
|
2364
|
+
self._last_used_at = time.monotonic()
|
|
2365
|
+
|
|
2366
|
+
async def _send_pending_input_now(self, command: _SteerRun) -> None:
|
|
2367
|
+
if command.send_now_requested:
|
|
2368
|
+
return
|
|
2369
|
+
command.send_now_requested = True
|
|
2370
|
+
try:
|
|
2371
|
+
# Wait for the exact queued receipt: a control sent while native
|
|
2372
|
+
# admission is pending intentionally does nothing. Once queued,
|
|
2373
|
+
# Send now releases the foreground tool wait while sparing native
|
|
2374
|
+
# background tasks. Plain interrupt remains the hard Stop path.
|
|
2375
|
+
assert self._client is not None
|
|
2376
|
+
receipt = await self._deliver_query_bounded(
|
|
2377
|
+
self._client.send_now(command.correlation_id), run_id=command.run_id,
|
|
2378
|
+
)
|
|
2379
|
+
if not isinstance(receipt, dict) or receipt.get("send_now") not in {
|
|
2380
|
+
"stopped", "delivering", "nothing_waiting",
|
|
2381
|
+
}:
|
|
2382
|
+
raise ClaudeSDKSupervisorError("Claude returned no Send now receipt")
|
|
2383
|
+
except Exception as exc:
|
|
2384
|
+
if not command.response.done():
|
|
2385
|
+
command.response.set_exception(ClaudeSDKQueryError(
|
|
2386
|
+
f"Claude Force Send delivery is uncertain: {exc}"
|
|
2387
|
+
))
|
|
2388
|
+
# The user frame was already written. Preserve its ACK lane and
|
|
2389
|
+
# live tasks; retrying or disconnecting would compound uncertainty.
|
|
2390
|
+
|
|
2212
2391
|
async def _handle_clear_goal(self, command: _ClearGoal) -> None:
|
|
2213
2392
|
if command.cancelled or command.response.done():
|
|
2214
2393
|
return
|
|
@@ -2224,6 +2403,11 @@ class ClaudeSDKSupervisor:
|
|
|
2224
2403
|
"Claude is already clearing its goal"
|
|
2225
2404
|
))
|
|
2226
2405
|
return
|
|
2406
|
+
if self._pending_steer is not None:
|
|
2407
|
+
command.response.set_exception(ClaudeSDKRunActive(
|
|
2408
|
+
"Claude is still applying a queued input"
|
|
2409
|
+
))
|
|
2410
|
+
return
|
|
2227
2411
|
generation = self.control_generation
|
|
2228
2412
|
if command.expected_generation is not None and command.expected_generation != generation:
|
|
2229
2413
|
command.response.set_exception(ClaudeSDKGenerationChanged(
|
|
@@ -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
|
|
|
@@ -2241,6 +2426,7 @@ class ClaudeSDKSupervisor:
|
|
|
2241
2426
|
}
|
|
2242
2427
|
|
|
2243
2428
|
try:
|
|
2429
|
+
await self._cancel_queued_goal(active.run_id)
|
|
2244
2430
|
# Priority-now interrupts model streaming but can wait behind a
|
|
2245
2431
|
# running tool. The SDK control channel cancels that tool first.
|
|
2246
2432
|
# Keep the receipt lane installed before interrupting: Claude may
|
|
@@ -2260,6 +2446,23 @@ class ClaudeSDKSupervisor:
|
|
|
2260
2446
|
f"Claude goal-clear delivery is uncertain: {exc}"
|
|
2261
2447
|
))
|
|
2262
2448
|
|
|
2449
|
+
async def _cancel_queued_goal(self, run_id: str) -> None:
|
|
2450
|
+
pending = self._pending_goal
|
|
2451
|
+
if pending is None:
|
|
2452
|
+
return
|
|
2453
|
+
# Plain interrupt deliberately keeps native queued inputs. Withdraw
|
|
2454
|
+
# this exact UUID first so explicit Stop/Clear cannot resurrect it.
|
|
2455
|
+
assert self._client is not None
|
|
2456
|
+
cancel = getattr(self._client, "cancel_queued_input", None)
|
|
2457
|
+
if not callable(cancel):
|
|
2458
|
+
raise ClaudeSDKSupervisorError("Claude cannot cancel its queued goal")
|
|
2459
|
+
receipt = await self._deliver_query_bounded(cancel(pending.correlation_id), run_id=run_id)
|
|
2460
|
+
if not isinstance(receipt, dict) or type(receipt.get("cancelled")) is not bool:
|
|
2461
|
+
raise ClaudeSDKSupervisorError("Claude did not confirm queued-goal cancellation")
|
|
2462
|
+
# False means already dequeued: the following explicit interrupt owns
|
|
2463
|
+
# that running command. No queued copy remains to start afterwards.
|
|
2464
|
+
self._fail_pending_goal("The queued goal was cancelled", cancelled_by_user=True)
|
|
2465
|
+
|
|
2263
2466
|
async def _handle_interrupt(self, command: _Interrupt) -> None:
|
|
2264
2467
|
active = self._active_run
|
|
2265
2468
|
if (
|
|
@@ -2280,6 +2483,30 @@ class ClaudeSDKSupervisor:
|
|
|
2280
2483
|
)
|
|
2281
2484
|
return
|
|
2282
2485
|
active._background_reconciliation_aborted = True
|
|
2486
|
+
self._clear_native_continuations()
|
|
2487
|
+
stopping_queued_goal = self._pending_goal is not None or self._goal_stop_run_id == active.run_id
|
|
2488
|
+
if stopping_queued_goal:
|
|
2489
|
+
self._goal_stop_run_id = active.run_id
|
|
2490
|
+
self._goal_stop_tasks.update(
|
|
2491
|
+
item["task_id"] for item in active.background_task_receipts
|
|
2492
|
+
if item["status"] == "running"
|
|
2493
|
+
)
|
|
2494
|
+
withdrawal_error: Exception | None = None
|
|
2495
|
+
try:
|
|
2496
|
+
if stopping_queued_goal and self._pending_steer is not None:
|
|
2497
|
+
# Both inputs may be queued on this owner. Withdrawing only
|
|
2498
|
+
# the goal could let Force Send wake while Stop drains tasks.
|
|
2499
|
+
cancel = getattr(client, "cancel_queued_input", None)
|
|
2500
|
+
if callable(cancel):
|
|
2501
|
+
await self._deliver_query_bounded(
|
|
2502
|
+
cancel(self._pending_steer.correlation_id), run_id=active.run_id,
|
|
2503
|
+
)
|
|
2504
|
+
self._fail_pending_steer("Claude was stopped before confirming Force Send")
|
|
2505
|
+
await self._cancel_queued_goal(active.run_id)
|
|
2506
|
+
except Exception as exc:
|
|
2507
|
+
withdrawal_error = exc
|
|
2508
|
+
self._fail_pending_steer("Stop could not confirm withdrawal of the Force Send input")
|
|
2509
|
+
self._fail_pending_goal("Stop could not confirm withdrawal of the queued goal")
|
|
2283
2510
|
try:
|
|
2284
2511
|
await client.interrupt()
|
|
2285
2512
|
except Exception as exc:
|
|
@@ -2290,6 +2517,21 @@ class ClaudeSDKSupervisor:
|
|
|
2290
2517
|
)
|
|
2291
2518
|
)
|
|
2292
2519
|
return
|
|
2520
|
+
if stopping_queued_goal:
|
|
2521
|
+
# Priority-now can register a foreground Bash as a background
|
|
2522
|
+
# task *after* interrupt returns. Keep this exact receiver alive
|
|
2523
|
+
# until the native terminal receipt and stop those exact tasks as
|
|
2524
|
+
# they appear. Disconnect alone does not terminate such a Bash.
|
|
2525
|
+
for task_id in tuple(self._goal_stop_tasks):
|
|
2526
|
+
await self._stop_goal_task(task_id, active.run_id)
|
|
2527
|
+
if not command.response.done():
|
|
2528
|
+
if withdrawal_error is not None:
|
|
2529
|
+
command.response.set_exception(ClaudeSDKQueryError(
|
|
2530
|
+
f"Claude Stop was sent but queued-input withdrawal is uncertain: {withdrawal_error}"
|
|
2531
|
+
))
|
|
2532
|
+
else:
|
|
2533
|
+
command.response.set_result(True)
|
|
2534
|
+
return
|
|
2293
2535
|
if not active.acknowledged:
|
|
2294
2536
|
error = ClaudeSDKQueryError(
|
|
2295
2537
|
f"Claude SDK query {active.run_id} for chat {self.chat_id} was "
|
|
@@ -2301,6 +2543,48 @@ class ClaudeSDKSupervisor:
|
|
|
2301
2543
|
if not command.response.done():
|
|
2302
2544
|
command.response.set_result(True)
|
|
2303
2545
|
|
|
2546
|
+
async def _stop_goal_task(self, task_id: str, run_id: str) -> None:
|
|
2547
|
+
if self._goal_stop_run_id != run_id or self._client is None:
|
|
2548
|
+
return
|
|
2549
|
+
try:
|
|
2550
|
+
await self._deliver_query_bounded(self._client.stop_task(task_id), run_id=run_id)
|
|
2551
|
+
except Exception as exc:
|
|
2552
|
+
# Do not invent a stopped receipt. Retain ownership and let the
|
|
2553
|
+
# existing Stop confirmation deadline/retry report the failure.
|
|
2554
|
+
logger.warning("Claude task Stop was not confirmed chat=%s task=%s: %s", self.chat_id, task_id, exc)
|
|
2555
|
+
|
|
2556
|
+
async def _receive_goal_stop(self, message: Any, active: ClaudeSDKRunHandle) -> None:
|
|
2557
|
+
if (self._is_result_message(message)
|
|
2558
|
+
and str(_message_field(message, "user_message_uuid") or "") in self._superseded_query_ids):
|
|
2559
|
+
return
|
|
2560
|
+
subtype, task_id, _task_type, status = _task_lifecycle_fields(message)
|
|
2561
|
+
active._observe_background_task(message)
|
|
2562
|
+
if subtype == "task_started" and task_id:
|
|
2563
|
+
self._goal_stop_tasks.add(task_id)
|
|
2564
|
+
await self._stop_goal_task(task_id, active.run_id)
|
|
2565
|
+
elif task_id and (subtype == "task_notification" or status in _TERMINAL_TASK_STATUSES):
|
|
2566
|
+
self._goal_stop_tasks.discard(task_id)
|
|
2567
|
+
if self._is_result_message(message):
|
|
2568
|
+
self._goal_stop_result = message
|
|
2569
|
+
elif _message_type(message) != "command_lifecycle":
|
|
2570
|
+
active._deliver(message)
|
|
2571
|
+
if self._goal_stop_result is None or self._goal_stop_tasks:
|
|
2572
|
+
return
|
|
2573
|
+
terminal = self._goal_stop_result
|
|
2574
|
+
self._cancel_ack_timeout()
|
|
2575
|
+
# Retire before releasing the handle: no queued input or stopping
|
|
2576
|
+
# task observer can cross into a successor on this connection.
|
|
2577
|
+
await self._disconnect_current_client()
|
|
2578
|
+
self._closed = True
|
|
2579
|
+
self._active_run = None
|
|
2580
|
+
self._goal_stop_run_id = None
|
|
2581
|
+
self._goal_stop_result = None
|
|
2582
|
+
self._inflight_tasks.clear()
|
|
2583
|
+
self._superseded_query_ids.clear()
|
|
2584
|
+
self._current_query_id = None
|
|
2585
|
+
active._deliver(terminal)
|
|
2586
|
+
active._finish(terminal)
|
|
2587
|
+
|
|
2304
2588
|
async def _handle_get_context_usage(
|
|
2305
2589
|
self,
|
|
2306
2590
|
command: _GetContextUsage,
|
|
@@ -2311,8 +2595,21 @@ class ClaudeSDKSupervisor:
|
|
|
2311
2595
|
if not command.response.done():
|
|
2312
2596
|
command.response.set_result(None)
|
|
2313
2597
|
return
|
|
2598
|
+
if command.response.cancelled():
|
|
2599
|
+
return
|
|
2600
|
+
operation = asyncio.create_task(getter())
|
|
2314
2601
|
try:
|
|
2315
|
-
|
|
2602
|
+
done, _ = await asyncio.wait(
|
|
2603
|
+
{operation, command.response}, timeout=self._control_timeout_seconds,
|
|
2604
|
+
return_when=asyncio.FIRST_COMPLETED,
|
|
2605
|
+
)
|
|
2606
|
+
if operation not in done:
|
|
2607
|
+
if not command.response.done():
|
|
2608
|
+
command.response.set_exception(ClaudeSDKControlTimeout(
|
|
2609
|
+
f"Claude SDK context usage timed out for {self.chat_id}"
|
|
2610
|
+
))
|
|
2611
|
+
return
|
|
2612
|
+
value = operation.result()
|
|
2316
2613
|
except Exception as exc:
|
|
2317
2614
|
if not command.response.done():
|
|
2318
2615
|
command.response.set_exception(
|
|
@@ -2321,6 +2618,9 @@ class ClaudeSDKSupervisor:
|
|
|
2321
2618
|
)
|
|
2322
2619
|
)
|
|
2323
2620
|
return
|
|
2621
|
+
finally:
|
|
2622
|
+
if not operation.done():
|
|
2623
|
+
await self._cancel_task_bounded(operation)
|
|
2324
2624
|
self._last_used_at = time.monotonic()
|
|
2325
2625
|
if not command.response.done():
|
|
2326
2626
|
command.response.set_result(dict(value) if isinstance(value, dict) else None)
|
|
@@ -2439,8 +2739,8 @@ class ClaudeSDKSupervisor:
|
|
|
2439
2739
|
return
|
|
2440
2740
|
try:
|
|
2441
2741
|
if not self.connected and command.expected_provider_id is not None:
|
|
2442
|
-
resume = (self.
|
|
2443
|
-
else getattr(self.
|
|
2742
|
+
resume = (self._reconnect_options.get("resume") if isinstance(self._reconnect_options, dict)
|
|
2743
|
+
else getattr(self._reconnect_options, "resume", None))
|
|
2444
2744
|
if not resume or resume != command.expected_provider_id:
|
|
2445
2745
|
raise ClaudeSDKUnavailable(
|
|
2446
2746
|
"The native Claude conversation is not available to resume"
|
|
@@ -2711,9 +3011,329 @@ class ClaudeSDKSupervisor:
|
|
|
2711
3011
|
if not command.response.done():
|
|
2712
3012
|
command.response.set_result((value, generation))
|
|
2713
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
|
+
|
|
2714
3312
|
async def _handle_received(self, command: _ReceivedMessage) -> None:
|
|
2715
3313
|
if command.generation != self._generation:
|
|
2716
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)
|
|
3325
|
+
data = _message_field(command.message, "data", {})
|
|
3326
|
+
if _message_field(command.message, "subtype") == "init":
|
|
3327
|
+
capabilities = _message_field(command.message, "capabilities")
|
|
3328
|
+
if capabilities is None and isinstance(data, dict):
|
|
3329
|
+
capabilities = data.get("capabilities")
|
|
3330
|
+
self._supports_send_now = isinstance(capabilities, list) and all(
|
|
3331
|
+
capability in capabilities
|
|
3332
|
+
for capability in ("interrupt_send_now_v1", "msg_lifecycle_v1")
|
|
3333
|
+
)
|
|
3334
|
+
self._supports_command_lifecycle = (
|
|
3335
|
+
isinstance(capabilities, list) and "msg_lifecycle_v1" in capabilities
|
|
3336
|
+
)
|
|
2717
3337
|
if _message_type(command.message) in {"ratelimitevent", "rate_limit_event"} and self._usage_observer is not None:
|
|
2718
3338
|
generation = self.control_generation
|
|
2719
3339
|
if generation is not None:
|
|
@@ -2741,8 +3361,76 @@ class ClaudeSDKSupervisor:
|
|
|
2741
3361
|
return
|
|
2742
3362
|
active = self._active_run
|
|
2743
3363
|
if active is None or active.done:
|
|
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)
|
|
3382
|
+
if self._goal_stop_run_id == active.run_id:
|
|
3383
|
+
await self._receive_goal_stop(command.message, active)
|
|
2744
3384
|
return
|
|
2745
3385
|
self._last_used_at = time.monotonic()
|
|
3386
|
+
steer = self._pending_steer
|
|
3387
|
+
goal = self._pending_goal
|
|
3388
|
+
if _message_type(command.message) == "command_lifecycle":
|
|
3389
|
+
goal_matches = goal is not None and _message_field(command.message, "command_uuid") == goal.correlation_id
|
|
3390
|
+
queued = goal if goal_matches else steer
|
|
3391
|
+
if (queued is not None
|
|
3392
|
+
and _message_field(command.message, "command_uuid") == queued.correlation_id):
|
|
3393
|
+
state = _message_field(command.message, "state")
|
|
3394
|
+
if state == "queued":
|
|
3395
|
+
if goal_matches:
|
|
3396
|
+
if not queued.response.done():
|
|
3397
|
+
queued.response.set_result(queued.correlation_id)
|
|
3398
|
+
else:
|
|
3399
|
+
await self._send_pending_input_now(queued)
|
|
3400
|
+
elif state == "started":
|
|
3401
|
+
queued.goal_started = True
|
|
3402
|
+
elif state in {"cancelled", "discarded", "refused"}:
|
|
3403
|
+
previous = queued.predecessor_result
|
|
3404
|
+
if goal_matches:
|
|
3405
|
+
self._fail_pending_goal(f"Claude {state} the queued goal before applying it")
|
|
3406
|
+
else:
|
|
3407
|
+
self._fail_pending_steer("Claude cancelled the Force Send input before confirming it")
|
|
3408
|
+
if previous is not None:
|
|
3409
|
+
await self._handle_received(_ReceivedMessage(command.generation, previous))
|
|
3410
|
+
return
|
|
3411
|
+
goal_matches = goal is not None and _is_matching_replay_ack(command.message, goal.correlation_id)
|
|
3412
|
+
accepted = goal if goal_matches else steer
|
|
3413
|
+
if accepted is not None and _is_matching_replay_ack(command.message, accepted.correlation_id):
|
|
3414
|
+
if self._current_query_id is not None:
|
|
3415
|
+
self._superseded_query_ids.add(self._current_query_id)
|
|
3416
|
+
self._current_query_id = accepted.correlation_id
|
|
3417
|
+
if goal_matches:
|
|
3418
|
+
self._pending_goal = None
|
|
3419
|
+
if not active.acknowledged:
|
|
3420
|
+
active._mark_acknowledged_without_replay()
|
|
3421
|
+
self._cancel_ack_timeout()
|
|
3422
|
+
active._deliver(ClaudeSDKGoalReceipt(accepted.correlation_id))
|
|
3423
|
+
else:
|
|
3424
|
+
self._pending_steer = None
|
|
3425
|
+
if not accepted.response.done():
|
|
3426
|
+
accepted.response.set_result(accepted.correlation_id)
|
|
3427
|
+
return
|
|
3428
|
+
message_uuid = str(_message_field(command.message, "uuid") or "")
|
|
3429
|
+
if (active.acknowledged and (message_uuid == self._current_query_id
|
|
3430
|
+
or message_uuid in self._superseded_query_ids)
|
|
3431
|
+
and _is_matching_replay_ack(command.message, message_uuid)):
|
|
3432
|
+
# Duplicate receipts are protocol metadata, never user bubbles.
|
|
3433
|
+
return
|
|
2746
3434
|
if not active.acknowledged:
|
|
2747
3435
|
if (pending is not None and self._is_result_message(command.message)
|
|
2748
3436
|
and _result_forces_run_end(command.message)):
|
|
@@ -2754,24 +3442,59 @@ class ClaudeSDKSupervisor:
|
|
|
2754
3442
|
))
|
|
2755
3443
|
return
|
|
2756
3444
|
if active._acknowledge(command.message):
|
|
3445
|
+
active._native_schedule_progress = False
|
|
2757
3446
|
self._cancel_ack_timeout()
|
|
2758
3447
|
return
|
|
3448
|
+
if self._is_result_message(command.message):
|
|
3449
|
+
active._native_schedule_progress = False
|
|
3450
|
+
self._clear_native_schedule_wake()
|
|
3451
|
+
return
|
|
2759
3452
|
# The persistent stream may contain resumed-session output from
|
|
2760
|
-
# before this query.
|
|
2761
|
-
#
|
|
2762
|
-
|
|
2763
|
-
|
|
2764
|
-
|
|
2765
|
-
|
|
2766
|
-
|
|
2767
|
-
|
|
2768
|
-
|
|
2769
|
-
|
|
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
|
|
2770
3467
|
|
|
2771
3468
|
active._observe_reconciliation_progress(command.message)
|
|
2772
3469
|
if self._pending_mail_hint_hook is not None:
|
|
2773
3470
|
self._pending_mail_hint_hook.observe(command.message)
|
|
3471
|
+
self._observe_native_schedule_tool(command.message, active)
|
|
2774
3472
|
if self._is_result_message(command.message):
|
|
3473
|
+
result_query_id = str(_message_field(command.message, "user_message_uuid") or "")
|
|
3474
|
+
if goal is not None:
|
|
3475
|
+
if (result_query_id == goal.correlation_id
|
|
3476
|
+
or (_message_field(command.message, "local_command") == "goal"
|
|
3477
|
+
and goal.goal_started and not result_query_id)):
|
|
3478
|
+
# A successful /goal starts a model query and replays its
|
|
3479
|
+
# UUID. A text-only local result is a native refusal (even
|
|
3480
|
+
# when is_error=False), not the active parent's Result.
|
|
3481
|
+
previous = goal.predecessor_result
|
|
3482
|
+
self._fail_pending_goal(str(_message_field(command.message, "result")
|
|
3483
|
+
or _message_field(command.message, "errors")
|
|
3484
|
+
or "Claude did not confirm the queued goal"))
|
|
3485
|
+
if previous is not None:
|
|
3486
|
+
await self._handle_received(_ReceivedMessage(command.generation, previous))
|
|
3487
|
+
return
|
|
3488
|
+
if result_query_id not in self._superseded_query_ids:
|
|
3489
|
+
goal.predecessor_result = command.message
|
|
3490
|
+
if goal is not None or steer is not None or result_query_id in self._superseded_query_ids:
|
|
3491
|
+
# A Send now input preempts one model response while its
|
|
3492
|
+
# native Agent/workflow tasks remain alive. Before its exact
|
|
3493
|
+
# ACK, Results still belong to the preceding response. Newer
|
|
3494
|
+
# CLIs also identify that input explicitly, fencing delayed
|
|
3495
|
+
# predecessor Results after the ACK without discarding task
|
|
3496
|
+
# notification turns (which may have their own UUID).
|
|
3497
|
+
return
|
|
2775
3498
|
# A Claude Result ends one model turn, not necessarily the logical
|
|
2776
3499
|
# run. Delegated local agents/workflows can outlive that Result;
|
|
2777
3500
|
# their completion wakes Claude for a follow-up model turn and a
|
|
@@ -2782,6 +3505,18 @@ class ClaudeSDKSupervisor:
|
|
|
2782
3505
|
forced_run_end = _result_forces_run_end(command.message)
|
|
2783
3506
|
if had_inflight_tasks and not forced_run_end:
|
|
2784
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
|
+
)
|
|
2785
3520
|
active._deliver(command.message)
|
|
2786
3521
|
self._cancel_ack_timeout()
|
|
2787
3522
|
active._finish(command.message)
|
|
@@ -2790,6 +3525,8 @@ class ClaudeSDKSupervisor:
|
|
|
2790
3525
|
self._active_run = None
|
|
2791
3526
|
bind_provider_tool_owner(self.options, "", "")
|
|
2792
3527
|
self._inflight_tasks.clear()
|
|
3528
|
+
self._superseded_query_ids.clear()
|
|
3529
|
+
self._current_query_id = None
|
|
2793
3530
|
if had_inflight_tasks and forced_run_end:
|
|
2794
3531
|
# An interrupted/error response can strand provider-side task
|
|
2795
3532
|
# frames after this logical run has ended. Retire only this
|
|
@@ -2805,6 +3542,7 @@ class ClaudeSDKSupervisor:
|
|
|
2805
3542
|
command.message
|
|
2806
3543
|
)
|
|
2807
3544
|
active._observe_background_task(command.message)
|
|
3545
|
+
self._observe_native_task_origin(command.message, active)
|
|
2808
3546
|
if task_id:
|
|
2809
3547
|
if subtype == "task_started" and task_type in _DEFERRING_TASK_TYPES:
|
|
2810
3548
|
self._inflight_tasks.add(task_id)
|
|
@@ -2883,6 +3621,8 @@ class ClaudeSDKSupervisor:
|
|
|
2883
3621
|
)
|
|
2884
3622
|
if isinstance(command, _StartRun):
|
|
2885
3623
|
await self._handle_start(command)
|
|
3624
|
+
elif isinstance(command, _SteerRun):
|
|
3625
|
+
await self._handle_steer(command)
|
|
2886
3626
|
elif isinstance(command, _Interrupt):
|
|
2887
3627
|
await self._handle_interrupt(command)
|
|
2888
3628
|
elif isinstance(command, _GetContextUsage):
|
|
@@ -2899,6 +3639,8 @@ class ClaudeSDKSupervisor:
|
|
|
2899
3639
|
await self._handle_mutate_mcp_server(command)
|
|
2900
3640
|
elif isinstance(command, _ReceivedMessage):
|
|
2901
3641
|
await self._handle_received(command)
|
|
3642
|
+
elif isinstance(command, _NativeSchedulePrompt):
|
|
3643
|
+
self._observe_native_schedule_prompt(command)
|
|
2902
3644
|
elif isinstance(command, _AckTimeout):
|
|
2903
3645
|
await self._handle_ack_timeout(command)
|
|
2904
3646
|
elif isinstance(command, _ReceiverStopped):
|
|
@@ -2940,15 +3682,15 @@ class ClaudeSDKSupervisor:
|
|
|
2940
3682
|
|
|
2941
3683
|
|
|
2942
3684
|
class ClaudeSDKSupervisorManager:
|
|
2943
|
-
"""Lazy
|
|
3685
|
+
"""Lazy registry with optional operator limits for chat-scoped supervisors."""
|
|
2944
3686
|
|
|
2945
3687
|
def __init__(
|
|
2946
3688
|
self,
|
|
2947
3689
|
*,
|
|
2948
3690
|
client_factory: ClientFactory = default_claude_sdk_client_factory,
|
|
2949
3691
|
is_result_message: ResultPredicate = default_is_result_message,
|
|
2950
|
-
max_clients: int =
|
|
2951
|
-
idle_ttl_seconds: float | None =
|
|
3692
|
+
max_clients: int = 0,
|
|
3693
|
+
idle_ttl_seconds: float | None = None,
|
|
2952
3694
|
connect_timeout_seconds: float = 30.0,
|
|
2953
3695
|
disconnect_timeout_seconds: float = 2.0,
|
|
2954
3696
|
ack_timeout_seconds: float = 60.0,
|
|
@@ -2956,15 +3698,15 @@ class ClaudeSDKSupervisorManager:
|
|
|
2956
3698
|
control_timeout_seconds: float = 15.0,
|
|
2957
3699
|
usage_observer: Callable[[str, str, Any], Awaitable[None]] | None = None,
|
|
2958
3700
|
) -> None:
|
|
2959
|
-
if max_clients <
|
|
2960
|
-
raise ValueError("max_clients must be
|
|
3701
|
+
if max_clients < 0:
|
|
3702
|
+
raise ValueError("max_clients must be non-negative")
|
|
2961
3703
|
if idle_ttl_seconds is not None and idle_ttl_seconds < 0:
|
|
2962
3704
|
raise ValueError("idle_ttl_seconds must be non-negative or None")
|
|
2963
3705
|
self._client_factory = client_factory
|
|
2964
3706
|
self._is_result_message = is_result_message
|
|
2965
3707
|
self._usage_observer = usage_observer
|
|
2966
3708
|
self._max_clients = int(max_clients)
|
|
2967
|
-
self._idle_ttl_seconds = idle_ttl_seconds
|
|
3709
|
+
self._idle_ttl_seconds = idle_ttl_seconds or None
|
|
2968
3710
|
if connect_timeout_seconds <= 0:
|
|
2969
3711
|
raise ValueError("connect_timeout_seconds must be positive")
|
|
2970
3712
|
self._connect_timeout_seconds = float(connect_timeout_seconds)
|
|
@@ -3079,16 +3821,13 @@ class ClaudeSDKSupervisorManager:
|
|
|
3079
3821
|
)
|
|
3080
3822
|
self._supervisors[chat_id] = supervisor
|
|
3081
3823
|
else:
|
|
3082
|
-
#
|
|
3083
|
-
#
|
|
3084
|
-
# is
|
|
3085
|
-
|
|
3086
|
-
|
|
3087
|
-
|
|
3088
|
-
|
|
3089
|
-
supervisor.options,
|
|
3090
|
-
supervisor.ownership_token,
|
|
3091
|
-
)
|
|
3824
|
+
# Preserve current callbacks and owned work, but never discard a
|
|
3825
|
+
# newer persisted resume/fork binding merely because this client
|
|
3826
|
+
# is connected. Its actor may need to reconnect after this lookup.
|
|
3827
|
+
supervisor._reconnect_options = options
|
|
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.
|
|
3092
3831
|
self._supervisors.move_to_end(chat_id)
|
|
3093
3832
|
return supervisor, old_to_close
|
|
3094
3833
|
|
|
@@ -3132,6 +3871,7 @@ class ClaudeSDKSupervisorManager:
|
|
|
3132
3871
|
on_supervisor_ready: SupervisorReadyCallback | None = None,
|
|
3133
3872
|
background_task_reconciliation: dict[str, Any] | None = None,
|
|
3134
3873
|
pending_mail_hint: Callable[[], str | None] | None = None,
|
|
3874
|
+
native_continuation_callback: NativeContinuationCallback | None = None,
|
|
3135
3875
|
) -> ClaudeSDKRunHandle:
|
|
3136
3876
|
"""Pin a chat through query acceptance, then return its run handle."""
|
|
3137
3877
|
|
|
@@ -3164,6 +3904,7 @@ class ClaudeSDKSupervisorManager:
|
|
|
3164
3904
|
on_supervisor_ready=on_supervisor_ready,
|
|
3165
3905
|
background_task_reconciliation=background_task_reconciliation,
|
|
3166
3906
|
pending_mail_hint=pending_mail_hint,
|
|
3907
|
+
native_continuation_callback=native_continuation_callback,
|
|
3167
3908
|
)
|
|
3168
3909
|
except (ClaudeSDKUnavailable, asyncio.CancelledError):
|
|
3169
3910
|
# A cold-connect failure or a Stop that cancels start_run before
|
|
@@ -3206,6 +3947,34 @@ class ClaudeSDKSupervisorManager:
|
|
|
3206
3947
|
and supervisor.active_run_id == str(run_id)
|
|
3207
3948
|
)
|
|
3208
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
|
+
|
|
3209
3978
|
async def interrupt(self, chat_id: str, *, run_id: str | None = None) -> bool:
|
|
3210
3979
|
self._bind_loop()
|
|
3211
3980
|
assert self._lock is not None
|
|
@@ -3215,6 +3984,62 @@ class ClaudeSDKSupervisorManager:
|
|
|
3215
3984
|
return False
|
|
3216
3985
|
return await supervisor.interrupt(run_id=run_id)
|
|
3217
3986
|
|
|
3987
|
+
async def steer_run(
|
|
3988
|
+
self,
|
|
3989
|
+
chat_id: str,
|
|
3990
|
+
prompt: str,
|
|
3991
|
+
*,
|
|
3992
|
+
run_id: str,
|
|
3993
|
+
ownership_token: str,
|
|
3994
|
+
query_session_id: str | None = None,
|
|
3995
|
+
on_before_send: SupervisorReadyCallback | None = None,
|
|
3996
|
+
) -> str:
|
|
3997
|
+
"""Steer only the exact existing live owner, without a new authority."""
|
|
3998
|
+
|
|
3999
|
+
self._bind_loop()
|
|
4000
|
+
assert self._lock is not None
|
|
4001
|
+
async with self._lock:
|
|
4002
|
+
supervisor = self._supervisors.get(str(chat_id))
|
|
4003
|
+
if (supervisor is None or supervisor.closed
|
|
4004
|
+
or supervisor.ownership_token != str(ownership_token)
|
|
4005
|
+
or supervisor.active_run_id != str(run_id)):
|
|
4006
|
+
raise ClaudeSDKGenerationChanged(
|
|
4007
|
+
"The Claude run changed before Force Send"
|
|
4008
|
+
)
|
|
4009
|
+
return await supervisor.steer_run(
|
|
4010
|
+
prompt, run_id=run_id, ownership_token=ownership_token,
|
|
4011
|
+
query_session_id=query_session_id, on_before_send=on_before_send,
|
|
4012
|
+
)
|
|
4013
|
+
|
|
4014
|
+
async def queue_goal(
|
|
4015
|
+
self, chat_id: str, condition: str, *, run_id: str,
|
|
4016
|
+
ownership_token: str, command_id: str,
|
|
4017
|
+
expected_generation: str | None = None,
|
|
4018
|
+
on_before_send: SupervisorReadyCallback | None = None,
|
|
4019
|
+
) -> str:
|
|
4020
|
+
"""Queue native /goal on its current owner, without interrupting work.
|
|
4021
|
+
|
|
4022
|
+
Return its exact queued UUID. Applied/refused receipts remain on the
|
|
4023
|
+
existing run stream, which stays alive across the predecessor Result.
|
|
4024
|
+
"""
|
|
4025
|
+
condition = str(condition).strip()
|
|
4026
|
+
if (not condition or len(condition) > 4000
|
|
4027
|
+
or condition.lower() in {"clear", "stop", "off", "reset", "none", "cancel"}):
|
|
4028
|
+
raise ValueError("Enter a completion condition for Claude")
|
|
4029
|
+
self._bind_loop()
|
|
4030
|
+
assert self._lock is not None
|
|
4031
|
+
async with self._lock:
|
|
4032
|
+
supervisor = self._supervisors.get(str(chat_id))
|
|
4033
|
+
if (supervisor is None or supervisor.closed
|
|
4034
|
+
or supervisor.ownership_token != str(ownership_token)
|
|
4035
|
+
or supervisor.active_run_id != str(run_id)):
|
|
4036
|
+
raise ClaudeSDKGenerationChanged("The Claude run changed before setting its goal")
|
|
4037
|
+
return await asyncio.wait_for(supervisor.steer_run(
|
|
4038
|
+
"/goal " + condition, run_id=run_id, ownership_token=ownership_token,
|
|
4039
|
+
on_before_send=on_before_send, _goal_condition=condition,
|
|
4040
|
+
_command_id=command_id, _goal_generation=expected_generation,
|
|
4041
|
+
), timeout=supervisor._control_timeout_seconds)
|
|
4042
|
+
|
|
3218
4043
|
async def clear_goal(
|
|
3219
4044
|
self, chat_id: str, *, run_id: str,
|
|
3220
4045
|
expected_generation: str | None = None,
|
|
@@ -3255,6 +4080,15 @@ class ClaudeSDKSupervisorManager:
|
|
|
3255
4080
|
)
|
|
3256
4081
|
await self._unpin_mcp_supervisor(clean_chat_id, supervisor)
|
|
3257
4082
|
|
|
4083
|
+
def background_work_snapshot(self) -> tuple[tuple[str, str, int, int, bool], ...]:
|
|
4084
|
+
"""Connection-bound live work; schedules without running tasks are idle."""
|
|
4085
|
+
return tuple(
|
|
4086
|
+
(chat_id, supervisor.ownership_token, supervisor._generation,
|
|
4087
|
+
supervisor._background_work_revision, bool(supervisor._live_background_tasks))
|
|
4088
|
+
for chat_id, supervisor in self._supervisors.items()
|
|
4089
|
+
if supervisor.connected and not supervisor.closed
|
|
4090
|
+
)
|
|
4091
|
+
|
|
3258
4092
|
async def get_context_usage(
|
|
3259
4093
|
self,
|
|
3260
4094
|
chat_id: str,
|
|
@@ -3634,6 +4468,24 @@ class ClaudeSDKSupervisorManager:
|
|
|
3634
4468
|
and not supervisor.closed
|
|
3635
4469
|
)
|
|
3636
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
|
+
|
|
3637
4489
|
def usage_generation(self, chat_id: str, *, run_id: str | None = None) -> str | None:
|
|
3638
4490
|
"""Identify the existing native owner without connecting or issuing RPCs."""
|
|
3639
4491
|
supervisor = self._supervisors.get(str(chat_id))
|
|
@@ -3712,7 +4564,7 @@ class ClaudeSDKSupervisorManager:
|
|
|
3712
4564
|
for chat_id, supervisor in idle_candidates:
|
|
3713
4565
|
if now - supervisor.last_used_at >= self._idle_ttl_seconds:
|
|
3714
4566
|
selected_ids.add(chat_id)
|
|
3715
|
-
overflow = max(0, len(self._supervisors) - self._max_clients)
|
|
4567
|
+
overflow = max(0, len(self._supervisors) - self._max_clients) if self._max_clients else 0
|
|
3716
4568
|
if overflow:
|
|
3717
4569
|
for chat_id, _supervisor in idle_candidates:
|
|
3718
4570
|
if len(selected_ids) >= overflow:
|