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

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.
@@ -176,7 +176,7 @@ def _authority_path(path: str | None) -> Path:
176
176
  return Path(selected).expanduser()
177
177
 
178
178
 
179
- def authority(path: str | None) -> str:
179
+ def authority_with_run(path: str | None) -> tuple[str, str]:
180
180
  authority_path = _authority_path(path)
181
181
  try:
182
182
  mode = authority_path.stat().st_mode & 0o777
@@ -194,7 +194,11 @@ def authority(path: str | None) -> str:
194
194
  raise ChatsCLIError(
195
195
  "AGENTSDOCK_CHAT_ID does not match the authority file"
196
196
  )
197
- return token
197
+ return token, str(payload.get("source_run_id") or "").strip()
198
+
199
+
200
+ def authority(path: str | None) -> str:
201
+ return authority_with_run(path)[0]
198
202
 
199
203
 
200
204
  def positive_target_index(value: str) -> int:
@@ -626,6 +630,51 @@ def list_routes(args: argparse.Namespace) -> dict[str, Any]:
626
630
  return result
627
631
 
628
632
 
633
+ def create_chat(args: argparse.Namespace) -> dict[str, Any]:
634
+ """Create an independent chat and return its connection to the creator."""
635
+ title = str(args.title or "").strip()
636
+ if not title:
637
+ raise ChatsCLIError("--title must not be empty")
638
+ payload: dict[str, Any] = {"title": title}
639
+ for name in ("folder", "cwd", "backend", "model", "effort", "provider_connection"):
640
+ value = getattr(args, name, None)
641
+ if value is not None:
642
+ payload[name] = value
643
+ key = getattr(args, "idempotency_key", None)
644
+ if key is not None:
645
+ key = key.strip()
646
+ if not 8 <= len(key) <= 128:
647
+ raise ChatsCLIError("--idempotency-key must contain 8 to 128 characters")
648
+ capability, source_run_id = authority_with_run(args.authority_file)
649
+ if key is None:
650
+ if not source_run_id:
651
+ raise ChatsCLIError("authority file has no source run for the default chat creation key")
652
+ # Scope automatic keys to the logical run without depending on a
653
+ # rotating capability. Explicit keys remain reusable across runs.
654
+ key = "cli_" + hashlib.sha256(
655
+ (f"create\0{source_run_id}\0" + json.dumps(payload, sort_keys=True, ensure_ascii=False)).encode("utf-8")
656
+ ).hexdigest()
657
+ payload["idempotency_key"] = key
658
+ result = post_json("/api/agent/chats", payload, capability)
659
+ session = result.get("session")
660
+ route = result.get("route")
661
+ if (
662
+ result.get("ok") is not True
663
+ or type(result.get("created")) is not bool
664
+ or type(result.get("duplicate")) is not bool
665
+ or result["created"] == result["duplicate"]
666
+ or not isinstance(session, dict)
667
+ or not isinstance(session.get("id"), str)
668
+ or not session["id"]
669
+ or not isinstance(route, dict)
670
+ or not isinstance(route.get("route_id"), str)
671
+ or not route["route_id"]
672
+ or route.get("mode") != "async_route_v1"
673
+ ):
674
+ raise ChatsCLIError("AgentsServer returned an invalid chat creation receipt")
675
+ return result
676
+
677
+
629
678
  def inbox(args: argparse.Namespace) -> dict[str, Any]:
630
679
  """List body-free pending senders; never claim or start their messages."""
631
680
  capability = authority(args.authority_file)
@@ -709,10 +758,9 @@ def send_action(args: argparse.Namespace, action: str) -> dict[str, Any]:
709
758
  raise ChatsCLIError("--reply-to requires an exact asynchronous route and message ID from the inbox")
710
759
  if requested_mode and not route:
711
760
  raise ChatsCLIError("conversation mode requires an exact route")
712
- discover_mode = bool(requested_mode or reply_to) or (
713
- _bounded_runtime_value("AGENTSDOCK_CROSS_CHAT_MODE") == "async_route_v1"
714
- )
715
- mode = negotiated_route_mode(capability, route, requested_mode) if route and discover_mode else ""
761
+ # A create can add the first route after this shell's environment was
762
+ # captured. Negotiate exact routes from the current server capability.
763
+ mode = negotiated_route_mode(capability, route, requested_mode) if route else ""
716
764
  if reply_to and mode != "async_route_v1":
717
765
  raise ChatsCLIError("--reply-to is not supported by legacy exchanges")
718
766
  if mode == "async_route_v1":
@@ -1046,7 +1094,7 @@ def add_message_arguments(command: argparse.ArgumentParser) -> None:
1046
1094
 
1047
1095
  def parser() -> argparse.ArgumentParser:
1048
1096
  root = argparse.ArgumentParser(
1049
- description="Contact an eligible chat on this AgentsDock server.",
1097
+ description="Create or contact a chat on this AgentsDock server.",
1050
1098
  allow_abbrev=False,
1051
1099
  )
1052
1100
  root.add_argument(
@@ -1057,6 +1105,30 @@ def parser() -> argparse.ArgumentParser:
1057
1105
  ),
1058
1106
  )
1059
1107
  commands = root.add_subparsers(dest="command", required=True)
1108
+ create_command = commands.add_parser(
1109
+ "create",
1110
+ help="create an independent AgentsDock chat and automatically connect it to this chat",
1111
+ description=(
1112
+ "Create an independent AgentsDock chat and automatically connect the creator and new chat. "
1113
+ "Omitted settings inherit from the creator. Use send with the returned route to send a message."
1114
+ ),
1115
+ allow_abbrev=False,
1116
+ )
1117
+ create_command.add_argument("--title", required=True)
1118
+ create_command.add_argument("--folder", help="folder for the new chat; inherits when omitted")
1119
+ create_command.add_argument("--cwd", help="working directory on the server; inherits when omitted")
1120
+ create_command.add_argument("--backend", help="agent backend; inherits when omitted")
1121
+ create_command.add_argument("--model", help="model; inherits when omitted")
1122
+ create_command.add_argument("--effort", help="reasoning effort; inherits when omitted")
1123
+ create_command.add_argument("--provider-connection", choices=["default", "custom"])
1124
+ create_command.add_argument(
1125
+ "--idempotency-key",
1126
+ help=(
1127
+ "8 to 128 character retry key; defaults to the same key for identical settings in this run. "
1128
+ "Explicit keys can be reused across runs. Use a different key to intentionally create another chat"
1129
+ ),
1130
+ )
1131
+ create_command.set_defaults(handler=create_chat)
1060
1132
  list_command = commands.add_parser(
1061
1133
  "list",
1062
1134
  help="list one page of eligible same-server chats for this live run",
@@ -97,6 +97,126 @@ class ClaudeGoalHistoryNormalizer:
97
97
  self._parents.popitem(last=False)
98
98
 
99
99
 
100
+ CLAUDE_LOCAL_COMMAND_OUTPUT = re.compile(
101
+ r"\A<local-command-(stdout|stderr)>([\s\S]*)</local-command-\1>\Z"
102
+ )
103
+ CLAUDE_LOCAL_COMMAND_WRAPPER = re.compile(
104
+ r"\A<command-name>/([A-Za-z0-9_][A-Za-z0-9_.:-]{0,127})</command-name>\s*"
105
+ r"<command-message>\1</command-message>\s*<command-args>([\s\S]*)</command-args>\Z"
106
+ )
107
+
108
+
109
+ def claude_local_command_output(content: Any) -> str | None:
110
+ """Return the text of a native local-command output record, or None."""
111
+ if not isinstance(content, str) or len(content) > 1024 * 1024:
112
+ return None
113
+ match = CLAUDE_LOCAL_COMMAND_OUTPUT.fullmatch(content)
114
+ return match[2].strip() if match else None
115
+
116
+
117
+ class ClaudeLocalCommandHistoryNormalizer:
118
+ """Project native local slash commands (e.g. /compact) as Claude shows them.
119
+
120
+ Claude records a local command as user-role rows: a metadata caveat, the
121
+ ``<command-name>`` wrapper, then ``<local-command-stdout>`` output (and
122
+ optionally stderr), all sharing one ``promptId``. Native Claude Code
123
+ renders these as the typed command and its output, not as human messages.
124
+ Only rows proven by that parent chain within the same command occurrence
125
+ are rewritten. A human quoting the markup starts a new prompt (or lacks the
126
+ chain) and stays unchanged. ``/goal`` remains owned by
127
+ ClaudeGoalHistoryNormalizer.
128
+ """
129
+
130
+ # Seeding must recover the complete records preceding an incremental
131
+ # cursor: a command's arguments can make its wrapper far larger than a
132
+ # fixed lookback. Bounded by the transcript reader's own record limit.
133
+ SEED_MAX_RECORDS = 8
134
+ SEED_MAX_BYTES = 32 * 1024 * 1024 + 64 * 1024
135
+ SEED_CHUNK_BYTES = 1024 * 1024
136
+
137
+ def __init__(self):
138
+ self._caveats: OrderedDict[str, dict] = OrderedDict()
139
+ # Wrapper and output rows of one occurrence; the value is shared.
140
+ self._commands: OrderedDict[str, dict] = OrderedDict()
141
+
142
+ def seed(self, path: Path, offset: int) -> None:
143
+ if offset <= 0:
144
+ return
145
+ try:
146
+ with path.open("rb") as stream:
147
+ lines = self._records_before(stream, offset)
148
+ except OSError:
149
+ return
150
+ for line in lines:
151
+ try:
152
+ self.consume(json.loads(line))
153
+ except (ValueError, RecursionError):
154
+ continue
155
+
156
+ @classmethod
157
+ def _records_before(cls, stream, offset: int) -> list[bytes]:
158
+ """Return up to SEED_MAX_RECORDS complete lines ending at ``offset``."""
159
+ position, region = offset, b""
160
+ while position > 0 and region.count(b"\n") <= cls.SEED_MAX_RECORDS:
161
+ if offset - position >= cls.SEED_MAX_BYTES:
162
+ break
163
+ size = min(cls.SEED_CHUNK_BYTES, position, cls.SEED_MAX_BYTES - (offset - position))
164
+ position -= size
165
+ stream.seek(position)
166
+ region = stream.read(size) + region
167
+ if position > 0:
168
+ # The first line may be partial; only complete records are trusted.
169
+ region = region.partition(b"\n")[2]
170
+ return [line for line in region.splitlines() if line.strip()][-cls.SEED_MAX_RECORDS:]
171
+
172
+ def consume(self, event: Any) -> Any:
173
+ if (not isinstance(event, dict) or event.get("isSidechain") is True
174
+ or event.get("type") != "user"):
175
+ return event
176
+ identity, session = event.get("uuid"), event.get("sessionId")
177
+ if not isinstance(identity, str) or not isinstance(session, str):
178
+ return event
179
+ message = event.get("message")
180
+ content = message.get("content") if isinstance(message, dict) else None
181
+ if not isinstance(content, str) or message.get("role") != "user":
182
+ return event
183
+ parent_id, prompt = event.get("parentUuid"), event.get("promptId")
184
+ if event.get("isMeta") is True:
185
+ if content.startswith("<local-command-caveat>"):
186
+ self._remember(self._caveats, identity, {"sessionId": session, "promptId": prompt})
187
+ return event
188
+ caveat = self._caveats.get(parent_id)
189
+ if caveat is not None and caveat["sessionId"] == session and caveat["promptId"] == prompt:
190
+ match = CLAUDE_LOCAL_COMMAND_WRAPPER.fullmatch(content)
191
+ if match and match[1] != "goal":
192
+ self._remember(self._commands, identity,
193
+ {"sessionId": session, "promptId": prompt, "outputs": set()})
194
+ args = match[2].strip()
195
+ return {**event, "message": {**message, "content": f"/{match[1]}" + (f" {args}" if args else "")}}
196
+ return event
197
+ occurrence = self._commands.get(parent_id)
198
+ output = (CLAUDE_LOCAL_COMMAND_OUTPUT.fullmatch(content)
199
+ if occurrence is not None and len(content) <= 1024 * 1024 else None)
200
+ if (output is None or occurrence["sessionId"] != session or occurrence["promptId"] != prompt
201
+ or output[1] in occurrence["outputs"]):
202
+ return event
203
+ # At most one stdout and one stderr per occurrence, chained in order.
204
+ occurrence["outputs"].add(output[1])
205
+ self._remember(self._commands, identity, occurrence)
206
+ text = output[2].strip()
207
+ if not text:
208
+ return {**event, "isMeta": True}
209
+ return {**event, "type": "assistant",
210
+ "message": {"role": "assistant", "content": [{"type": "text", "text": text}]}}
211
+
212
+ @staticmethod
213
+ def _remember(store: OrderedDict, identity: str, value: dict) -> None:
214
+ store[identity] = value
215
+ store.move_to_end(identity)
216
+ while len(store) > 32:
217
+ store.popitem(last=False)
218
+
219
+
100
220
  def _timestamp_ms(value: Any) -> int | None:
101
221
  if not isinstance(value, str) or len(value) > 64:
102
222
  return None
@@ -142,8 +142,19 @@ def _async_delivery_identity(event: dict) -> tuple | None:
142
142
 
143
143
 
144
144
  def _mailbox_wake_identity(event: dict) -> tuple | None:
145
+ # Both forms are internal inputs. The exact native source, run ownership,
146
+ # and checkpoint still have to match before either one can be hidden.
145
147
  claim, cutoff, digest = (event.get(key) for key in (
146
148
  "mailbox_wake_id", "mailbox_wake_through_seq", "provider_input_sha256"))
149
+ if (event.get("purpose") == "server_update_continuation"
150
+ and event.get("provider_generated") is True and event.get("prompt") == ""
151
+ and event.get("provider_user_authored") is not True
152
+ and not any(event.get(key) for key in (
153
+ "clientUserMessageId", "clientId", "client_user_message_id", "client_id"))
154
+ and isinstance(event.get("queued_id"), str)
155
+ and re.fullmatch(r"queued_[a-f0-9]{16}", event["queued_id"])
156
+ and isinstance(digest, str) and _DIGEST.fullmatch(digest)):
157
+ return event["queued_id"], 0, digest
147
158
  if (event.get("purpose") != "chat_mailbox_wake" or event.get("provider_generated") is not True
148
159
  or event.get("prompt") != ""
149
160
  or event.get("provider_user_authored") is True
@@ -95,7 +95,13 @@ def parse_native_models(info: Any) -> list[dict[str, str]]:
95
95
 
96
96
 
97
97
 
98
- CACHE_TTL_SECONDS = 300.0
98
+ # Native labels (e.g. "Opus 5.5") are learned only when a real chat connects,
99
+ # and Claude chat processes stay connected for hours. A short lifetime made
100
+ # most periodic catalog reads (desktop: every 15 minutes) fall back to bare
101
+ # aliases. The key already changes with the CLI binary, provider environment,
102
+ # user/managed settings and account identity; every new connection replaces
103
+ # the entry and native authentication failure clears it.
104
+ CACHE_TTL_SECONDS = 24 * 60 * 60.0
99
105
  CACHE_LIMIT = 16
100
106
  _CACHE_LOCK = threading.Lock()
101
107
  _CACHE: OrderedDict[str, tuple[float, list[dict[str, str]]]] = OrderedDict()
@@ -136,8 +142,12 @@ def native_catalog_key(executable: str, env: dict[str, str]) -> str:
136
142
  """Fingerprint runtime/config identity without reading native credentials.
137
143
 
138
144
  Environment credentials are hashed, never retained in plaintext. Native
139
- credential rotation alone is not evidence of login or logout; this cache
140
- is short lived and is never used as authentication/authorization evidence.
145
+ credential rotation alone is not evidence of login or logout, so the
146
+ native credential file contributes only its presence (login/logout), never
147
+ its revision: OAuth renewal rewrites it for the same account, and the
148
+ labels are only re-learned when a new chat connects. Account switches are
149
+ covered by the account identity. This cache is never used as
150
+ authentication/authorization evidence.
141
151
  """
142
152
  home = Path(env.get("HOME") or str(Path.home()))
143
153
  config = Path(env.get("CLAUDE_CONFIG_DIR") or home / ".claude")
@@ -146,11 +156,11 @@ def native_catalog_key(executable: str, env: dict[str, str]) -> str:
146
156
  resolved = shutil.which(executable, path=env.get("PATH")) or executable
147
157
  revisions = [_file_revision(Path(resolved)), *(
148
158
  _file_revision(path) for path in (
149
- config / "settings.json", config / ".credentials.json",
159
+ config / "settings.json",
150
160
  Path("/Library/Application Support/ClaudeCode/managed-settings.json"),
151
161
  Path("/etc/claude-code/managed-settings.json"),
152
162
  )
153
- )]
163
+ ), ["native-credentials-present", (config / ".credentials.json").exists()]]
154
164
  return hashlib.sha256(json.dumps([relevant, revisions, _account_identity(config, home)], sort_keys=True).encode()).hexdigest()
155
165
 
156
166
 
@@ -2739,8 +2739,8 @@ class ClaudeSDKSupervisor:
2739
2739
  return
2740
2740
  try:
2741
2741
  if not self.connected and command.expected_provider_id is not None:
2742
- resume = (self.options.get("resume") if isinstance(self.options, dict)
2743
- else getattr(self.options, "resume", None))
2742
+ resume = (self._reconnect_options.get("resume") if isinstance(self._reconnect_options, dict)
2743
+ else getattr(self._reconnect_options, "resume", None))
2744
2744
  if not resume or resume != command.expected_provider_id:
2745
2745
  raise ClaudeSDKUnavailable(
2746
2746
  "The native Claude conversation is not available to resume"
@@ -3825,16 +3825,9 @@ class ClaudeSDKSupervisorManager:
3825
3825
  # newer persisted resume/fork binding merely because this client
3826
3826
  # is connected. Its actor may need to reconnect after this lookup.
3827
3827
  supervisor._reconnect_options = options
3828
- # A disconnected actor has no live provider state. Refresh its
3829
- # lazy reconnect options so a newly persisted resume/fork binding
3830
- # is honored after a stream failure without changing the stable
3831
- # process-configuration key used by healthy persistent clients.
3832
- if not supervisor.connected and not supervisor.is_active:
3833
- supervisor.options = options
3834
- bind_permission_owner(
3835
- supervisor.options,
3836
- supervisor.ownership_token,
3837
- )
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.
3838
3831
  self._supervisors.move_to_end(chat_id)
3839
3832
  return supervisor, old_to_close
3840
3833
 
@@ -712,12 +712,19 @@ def _native_mailbox_wake_hash(event: dict) -> str | None:
712
712
  """A server-authored hidden input, not a text-based provider classification."""
713
713
  digest = event.get("provider_input_sha256")
714
714
  wake_id = event.get("mailbox_wake_id")
715
- if (event.get("type") == "turn_started" and event.get("imported") is not True
716
- and event.get("purpose") == "chat_mailbox_wake" and event.get("prompt") == ""
717
- and event.get("provider_generated") is True and not _runtime_human_provenance(event)
715
+ if (event.get("type") != "turn_started" or event.get("imported") is True
716
+ or event.get("prompt") != "" or event.get("provider_generated") is not True
717
+ or _runtime_human_provenance(event) or not isinstance(digest, str)
718
+ or not _DIGEST.fullmatch(digest)):
719
+ return None
720
+ if (event.get("purpose") == "chat_mailbox_wake"
718
721
  and isinstance(wake_id, str) and re.fullmatch(r"mailwake_[a-f0-9]{32}", wake_id)
719
- and type(event.get("mailbox_wake_through_seq")) is int and 0 < event["mailbox_wake_through_seq"] < 2**63
720
- and isinstance(digest, str) and _DIGEST.fullmatch(digest)):
722
+ and type(event.get("mailbox_wake_through_seq")) is int
723
+ and 0 < event["mailbox_wake_through_seq"] < 2**63):
724
+ return digest
725
+ queued_id = event.get("queued_id")
726
+ if (event.get("purpose") == "server_update_continuation"
727
+ and isinstance(queued_id, str) and re.fullmatch(r"queued_[a-f0-9]{16}", queued_id)):
721
728
  return digest
722
729
  return None
723
730
 
@@ -560,6 +560,7 @@ class ExecutionGateway:
560
560
  pump: asyncio.Task[Any] | None = None
561
561
  response_started = False
562
562
  expects_trailers = False
563
+ client_disconnected = False
563
564
  try:
564
565
  secret = _read_secret(self.secret_path)
565
566
  identity = _socket_identity(self.socket_path)
@@ -574,11 +575,14 @@ class ExecutionGateway:
574
575
  raise ExecutionTransportError("Execution handshake failed")
575
576
 
576
577
  async def forward_requests() -> None:
578
+ nonlocal client_disconnected
577
579
  try:
578
580
  while True:
579
581
  message = await receive()
580
582
  for chunk in _chunks(message):
581
583
  event = _event(chunk, encode=True, kind=scope["type"], direction="request")
584
+ if event["type"].endswith(".disconnect"):
585
+ client_disconnected = True
582
586
  await _write_frame(writer, {"kind": "event", "event": event})
583
587
  if message["type"].endswith(".disconnect"):
584
588
  writer.close()
@@ -619,6 +623,12 @@ class ExecutionGateway:
619
623
  return
620
624
  except (ExecutionTransportError, asyncio.IncompleteReadError, ConnectionError,
621
625
  OSError, asyncio.TimeoutError):
626
+ if client_disconnected:
627
+ # Closing ingress also closes IPC. Its resulting EOF is normal
628
+ # after an explicit client disconnect; the worker still owns
629
+ # accepted work. Do not report it as an execution failure or
630
+ # synthesize a response to a client that has already left.
631
+ return
622
632
  if not response_started:
623
633
  if scope["type"] == "http":
624
634
  await send({"type": "http.response.start", "status": 503,
package/server/install.sh CHANGED
@@ -89,16 +89,16 @@ INSTANCE_EXPLICIT="false"
89
89
  LABEL="com.agentsdock.server"
90
90
  INSTANCE_LOG_DIR="$HOME/Library/Logs/AgentsServer"
91
91
  LEGACY_SERVICE_NAME="zenithbot-agent"
92
- # AgentsServer's cooperative shutdown has 18 independently bounded cleanup
92
+ # AgentsServer's cooperative shutdown has 19 independently bounded cleanup
93
93
  # phases in addition to uvicorn's graceful window. Five seconds was shorter
94
94
  # than even an ordinary slow shutdown: launchctl had already accepted bootout,
95
95
  # then the installer abandoned activation/rollback and could leave the service
96
96
  # unloaded. Keep this wait bounded, but long enough for the server's complete
97
97
  # worst-case graceful budget before declaring the exact launchd job wedged.
98
- # AgentsServer caps the configurable uvicorn window at 60 seconds; 185 seconds
99
- # covers that window, all 18 five-second teardown phases, the watchdog margin,
98
+ # AgentsServer caps the configurable uvicorn window at 60 seconds; 190 seconds
99
+ # covers that window, all 19 five-second teardown phases, the watchdog margin,
100
100
  # and another 30 seconds for launchd to reap the terminated process.
101
- LAUNCHCTL_STOP_ATTEMPTS=1850
101
+ LAUNCHCTL_STOP_ATTEMPTS=1900
102
102
  LAUNCHCTL_STOP_DELAY=0.1
103
103
  LAUNCHCTL_BOOTSTRAP_ATTEMPTS=3
104
104
  NON_INTERACTIVE="false"