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

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.
@@ -71,13 +71,32 @@ def _digest(path: Path) -> str:
71
71
 
72
72
  def _interpreter_digest(path: Path) -> str:
73
73
  if not path.is_absolute() or path.resolve(strict=True) != path:
74
- raise ValueError("recovery interpreter must be a resolved executable")
74
+ raise ValueError(f"recovery interpreter must be a resolved executable: {path}")
75
75
  descriptor = os.open(path, os.O_RDONLY | os.O_NOFOLLOW)
76
76
  try:
77
77
  info = os.fstat(descriptor)
78
- if (not stat.S_ISREG(info.st_mode) or info.st_uid not in {0, os.getuid()}
79
- or info.st_mode & 0o022 or not info.st_mode & 0o111):
80
- raise PermissionError("recovery interpreter is not a trusted executable")
78
+ # The acceptance predicate below is unchanged; each rejection now
79
+ # names the failed requirement plus the observed path, owner and mode
80
+ # so an operator can act on it without guessing.
81
+ if not stat.S_ISREG(info.st_mode):
82
+ raise PermissionError(
83
+ f"recovery interpreter is not a trusted executable: {path} is not a regular file"
84
+ )
85
+ if info.st_uid not in {0, os.getuid()}:
86
+ raise PermissionError(
87
+ f"recovery interpreter is not a trusted executable: {path} is owned by uid "
88
+ f"{info.st_uid}, expected root or the current uid {os.getuid()}"
89
+ )
90
+ if info.st_mode & 0o022:
91
+ raise PermissionError(
92
+ f"recovery interpreter is not a trusted executable: {path} is group- or "
93
+ f"world-writable (mode {info.st_mode & 0o7777:04o})"
94
+ )
95
+ if not info.st_mode & 0o111:
96
+ raise PermissionError(
97
+ f"recovery interpreter is not a trusted executable: {path} has no execute "
98
+ f"bits (mode {info.st_mode & 0o7777:04o})"
99
+ )
81
100
  digest = hashlib.sha256()
82
101
  while block := os.read(descriptor, 1024 * 1024):
83
102
  digest.update(block)
@@ -16,6 +16,7 @@ import json
16
16
  import logging
17
17
  import os
18
18
  from pathlib import Path
19
+ import resource
19
20
  import socket
20
21
  import stat
21
22
  import time
@@ -33,6 +34,28 @@ from execution_transport import (
33
34
 
34
35
  PROTOCOL_VERSION = 1
35
36
  MAX_HEALTH_BYTES = 1024 * 1024
37
+ FILE_DESCRIPTOR_HEADROOM = 8192
38
+
39
+
40
+ def ensure_file_descriptor_headroom() -> None:
41
+ """Raise a small inherited soft limit without replacing OS/user policy.
42
+
43
+ In particular, existing launchd jobs can inherit only 256 descriptors for
44
+ all client sockets, provider pipes, databases and listeners combined. Do
45
+ this in the entrypoint so an updated runtime also fixes older service
46
+ definitions; never lower a larger limit or increase the hard limit.
47
+ """
48
+ try:
49
+ soft, hard = resource.getrlimit(resource.RLIMIT_NOFILE)
50
+ if soft == resource.RLIM_INFINITY or soft >= FILE_DESCRIPTOR_HEADROOM:
51
+ return
52
+ target = FILE_DESCRIPTOR_HEADROOM if hard == resource.RLIM_INFINITY else min(FILE_DESCRIPTOR_HEADROOM, hard)
53
+ if target > soft:
54
+ resource.setrlimit(resource.RLIMIT_NOFILE, (target, hard))
55
+ except (OSError, ValueError) as error:
56
+ # A restricted host remains usable with its existing limit. Failure to
57
+ # gain headroom is diagnostic information, not a startup/admission gate.
58
+ logging.warning("Could not raise execution file-descriptor soft limit: %s", error)
36
59
 
37
60
 
38
61
  class ProcessLease:
@@ -374,6 +397,7 @@ def main() -> int:
374
397
  parser.error("Invalid listener port")
375
398
  if args.role == "gateway" and args.application != "agent_server:app":
376
399
  parser.error("Only workers load applications")
400
+ ensure_file_descriptor_headroom()
377
401
  try:
378
402
  with ProcessLease(args.runtime_dir, args.role) as lease:
379
403
  asyncio.run(serve_worker(args, lease) if args.role == "worker" else serve_gateway(args, lease))
@@ -400,8 +400,8 @@ class ExecutionTransportServer:
400
400
  _done, pending = await asyncio.wait(tuple(self._connections), timeout=max(0.0, timeout))
401
401
  for task in pending:
402
402
  task.cancel()
403
- # A peer that stopped reading can prevent close() from flushing its
404
- # buffered response indefinitely. Only explicit worker shutdown aborts
403
+ # A connected peer that stopped reading can prevent close() from
404
+ # flushing its buffered response. Explicit worker shutdown aborts
405
405
  # those remaining transports after the drain window.
406
406
  for writer in writers:
407
407
  connection = writer.get_extra_info("socket")
@@ -431,6 +431,16 @@ class ExecutionTransportServer:
431
431
  accepted = False
432
432
  disconnected = asyncio.Event()
433
433
  incoming: asyncio.Queue[dict[str, Any]] = asyncio.Queue(maxsize=4)
434
+
435
+ def disconnect_ingress() -> None:
436
+ disconnected.set()
437
+ # The accepted application keeps its task and queued input, but
438
+ # a departed ingress no longer needs an IPC descriptor or output.
439
+ # Abort also retires a socket with buffered, undeliverable output.
440
+ connection = writer.get_extra_info("socket")
441
+ if connection is not None and connection.fileno() >= 0:
442
+ writer.transport.abort()
443
+
434
444
  try:
435
445
  opening = await asyncio.wait_for(_read_frame(reader), HANDSHAKE_TIMEOUT)
436
446
  _fields(opening, {"v", "kind", "secret", "scope"})
@@ -453,14 +463,18 @@ class ExecutionTransportServer:
453
463
  if frame["kind"] != "event":
454
464
  raise ExecutionTransportError("Unexpected private protocol message")
455
465
  event = _event(frame["event"], encode=False, kind=kind, direction="request")
456
- await incoming.put(event)
457
466
  if event["type"].endswith(".disconnect"):
467
+ # Do not wait behind a full input queue to release
468
+ # the dead socket. receive() still drains every
469
+ # accepted body event before this disconnect.
470
+ disconnect.update(event)
458
471
  break
472
+ await incoming.put(event)
459
473
  except (ExecutionTransportError, asyncio.IncompleteReadError, ConnectionError, OSError):
460
474
  pass
461
475
  # Cancellation by our own completed app's cleanup is not peer
462
476
  # disconnection: leave its bounded input drain enabled.
463
- disconnected.set()
477
+ disconnect_ingress()
464
478
 
465
479
  async def receive() -> dict[str, Any]:
466
480
  if not incoming.empty():
@@ -486,7 +500,7 @@ class ExecutionTransportServer:
486
500
  try:
487
501
  await _write_frame(writer, {"kind": "event", "event": event})
488
502
  except (ConnectionError, OSError):
489
- disconnected.set()
503
+ disconnect_ingress()
490
504
  return
491
505
 
492
506
  pump = asyncio.create_task(read_events(), name="execution-request-reader")
@@ -516,8 +530,10 @@ class ExecutionTransportServer:
516
530
 
517
531
  with suppress(asyncio.TimeoutError, ConnectionError, OSError):
518
532
  await asyncio.wait_for(drain_ingress(), 1.0)
519
- self._writers.discard(writer)
520
- await _close_writer(writer)
533
+ try:
534
+ await _close_writer(writer)
535
+ finally:
536
+ self._writers.discard(writer)
521
537
 
522
538
 
523
539
  class ExecutionGateway:
@@ -544,6 +560,7 @@ class ExecutionGateway:
544
560
  pump: asyncio.Task[Any] | None = None
545
561
  response_started = False
546
562
  expects_trailers = False
563
+ client_disconnected = False
547
564
  try:
548
565
  secret = _read_secret(self.secret_path)
549
566
  identity = _socket_identity(self.socket_path)
@@ -558,11 +575,14 @@ class ExecutionGateway:
558
575
  raise ExecutionTransportError("Execution handshake failed")
559
576
 
560
577
  async def forward_requests() -> None:
578
+ nonlocal client_disconnected
561
579
  try:
562
580
  while True:
563
581
  message = await receive()
564
582
  for chunk in _chunks(message):
565
583
  event = _event(chunk, encode=True, kind=scope["type"], direction="request")
584
+ if event["type"].endswith(".disconnect"):
585
+ client_disconnected = True
566
586
  await _write_frame(writer, {"kind": "event", "event": event})
567
587
  if message["type"].endswith(".disconnect"):
568
588
  writer.close()
@@ -603,6 +623,12 @@ class ExecutionGateway:
603
623
  return
604
624
  except (ExecutionTransportError, asyncio.IncompleteReadError, ConnectionError,
605
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
606
632
  if not response_started:
607
633
  if scope["type"] == "http":
608
634
  await send({"type": "http.response.start", "status": 503,
@@ -0,0 +1,224 @@
1
+ """Explicitly approved external mailbox principals. No sessions or provider runs.
2
+
3
+ The owner provisions a private config out of band; an absent, malformed, or
4
+ revoked config grants nothing. HTTP callers cannot provision or change policy.
5
+ Ledger functions execute in the caller's existing cross-chat transaction.
6
+ """
7
+ from __future__ import annotations
8
+
9
+ import base64
10
+ import hashlib
11
+ import hmac
12
+ import json
13
+ import os
14
+ from pathlib import Path
15
+ import re
16
+ import sqlite3
17
+ import stat
18
+ import uuid
19
+
20
+ import chat_mailbox
21
+
22
+ MAX_CONFIG_BYTES = 128 * 1024
23
+ MAX_TEXT_CHARS = 16000
24
+ PEER_RE = re.compile(r"extpeer_[0-9a-f]{32}\Z")
25
+ SESSION_RE = re.compile(r"sess_[A-Za-z0-9_-]{1,100}\Z")
26
+
27
+
28
+ class PeerUnauthorized(ValueError):
29
+ pass
30
+
31
+
32
+ class PeerConflict(ValueError):
33
+ pass
34
+
35
+
36
+ def _text(value, *, maximum=16000):
37
+ if not isinstance(value, str) or not value.strip() or len(value) > maximum:
38
+ raise ValueError("Invalid external peer text")
39
+ value.encode("utf-8", "strict")
40
+ return value
41
+
42
+
43
+ def validate_peer(raw: dict) -> dict:
44
+ expected = {"peer_id", "display_name", "target_session_id", "credential_sha256",
45
+ "revision", "pair_id", "route_id", "inbound_route_id", "enabled", "policy"}
46
+ if not isinstance(raw, dict) or set(raw) != expected or type(raw["enabled"]) is not bool:
47
+ raise ValueError("Invalid external peer config")
48
+ for key, pattern in (("peer_id", PEER_RE), ("target_session_id", SESSION_RE),
49
+ ("credential_sha256", re.compile(r"[0-9a-f]{64}\Z")),
50
+ ("revision", re.compile(r"rev_[0-9a-f]{32}\Z")),
51
+ ("pair_id", re.compile(r"pair_[0-9a-f]{32}\Z")),
52
+ ("route_id", re.compile(r"route_[0-9a-f]{32}\Z")),
53
+ ("inbound_route_id", re.compile(r"route_[0-9a-f]{32}\Z"))):
54
+ if not isinstance(raw[key], str) or not pattern.fullmatch(raw[key]):
55
+ raise ValueError("Invalid external peer identity")
56
+ if raw["route_id"] == raw["inbound_route_id"]:
57
+ raise ValueError("External route members must differ")
58
+ if not _text(raw["display_name"], maximum=80).isprintable():
59
+ raise ValueError("Invalid external peer label")
60
+ policy = raw["policy"]
61
+ if not isinstance(policy, dict) or set(policy) != {"approval_id", "approved_at", "delegated_by", "source_user_instruction"}:
62
+ raise ValueError("External peer requires explicit owner approval")
63
+ for key in ("approval_id", "approved_at", "delegated_by"):
64
+ if not _text(policy[key], maximum=160).isprintable():
65
+ raise ValueError("Invalid external peer approval identity")
66
+ _text(policy["source_user_instruction"], maximum=16000)
67
+ return {**raw, "policy": dict(policy)}
68
+
69
+
70
+ def load_peers(path: Path | None) -> list[dict]:
71
+ """Bounded, owner-private, no-follow reads; malformed policy fails closed."""
72
+ if path is None:
73
+ return []
74
+ try:
75
+ fd = os.open(path, os.O_RDONLY | os.O_NOFOLLOW | os.O_NONBLOCK)
76
+ with os.fdopen(fd, "rb") as stream:
77
+ info = os.fstat(stream.fileno())
78
+ if (not stat.S_ISREG(info.st_mode) or info.st_uid != os.getuid()
79
+ or stat.S_IMODE(info.st_mode) != 0o600 or info.st_nlink != 1
80
+ or not 0 < info.st_size <= MAX_CONFIG_BYTES):
81
+ return []
82
+ data = json.loads(stream.read(MAX_CONFIG_BYTES + 1))
83
+ if not isinstance(data, dict) or set(data) != {"version", "peers"} or data["version"] != 1:
84
+ return []
85
+ if not isinstance(data["peers"], list) or len(data["peers"]) > 8:
86
+ return []
87
+ peers = [validate_peer(raw) for raw in data["peers"]]
88
+ for key in ("peer_id", "credential_sha256", "pair_id", "route_id", "inbound_route_id"):
89
+ if len({peer[key] for peer in peers}) != len(peers):
90
+ return []
91
+ if len({p[k] for p in peers for k in ("route_id", "inbound_route_id")}) != 2 * len(peers):
92
+ return []
93
+ return peers
94
+ except (OSError, ValueError, UnicodeError, TypeError, RecursionError):
95
+ return []
96
+
97
+
98
+ def authenticate(path: Path | None, credential: str) -> dict:
99
+ if not isinstance(credential, str) or not 32 <= len(credential) <= 512 or not credential.isascii():
100
+ raise PeerUnauthorized("External peer credential is invalid")
101
+ digest = hashlib.sha256(credential.encode()).hexdigest()
102
+ matches = [peer for peer in load_peers(path)
103
+ if peer["enabled"] and hmac.compare_digest(peer["credential_sha256"], digest)]
104
+ if len(matches) != 1:
105
+ raise PeerUnauthorized("External peer credential is invalid")
106
+ return matches[0]
107
+
108
+
109
+ def principal(path: Path | None, peer_id: str) -> dict | None:
110
+ return next((peer for peer in load_peers(path) if peer["peer_id"] == peer_id and peer["enabled"]), None)
111
+
112
+
113
+ def route(peer: dict) -> dict:
114
+ return {"route_id": peer["route_id"], "revision": peer["revision"],
115
+ "alias": "external-" + peer["peer_id"][8:20], "target_session_id": peer["peer_id"],
116
+ "target_kind": "external_peer", "actions": ["instruction"],
117
+ "pair_id": peer["pair_id"], "paired_route_id": peer["inbound_route_id"],
118
+ "created_at": peer["policy"]["approved_at"], "updated_at": peer["policy"]["approved_at"]}
119
+
120
+
121
+ def routes(path: Path | None, session_id: str) -> list[dict]:
122
+ return [route(peer) for peer in load_peers(path)
123
+ if peer["enabled"] and peer["target_session_id"] == session_id]
124
+
125
+
126
+ def live_route(path: Path | None, session_id: str, issued: dict) -> dict | None:
127
+ peer = principal(path, str(issued.get("target_session_id") or ""))
128
+ if peer is None or peer["target_session_id"] != session_id:
129
+ return None
130
+ current = route(peer)
131
+ return current if all(issued.get(key) == value for key, value in current.items()) else None
132
+
133
+
134
+ def _admission_provenance(peer: dict, admission_id: str) -> dict:
135
+ return {"version": 2, "origin_kind": "external_peer", "external_peer_id": peer["peer_id"],
136
+ "source": peer["display_name"], "delegated_by": peer["policy"]["delegated_by"],
137
+ "target_session_id": peer["target_session_id"], "external_admission_id": admission_id,
138
+ "reference_action": "external_peer_policy", "policy_revision": peer["revision"],
139
+ "approval_id": peer["policy"]["approval_id"], "approved_at": peer["policy"]["approved_at"],
140
+ "source_user_instruction": peer["policy"]["source_user_instruction"]}
141
+
142
+
143
+ def accept(connection: sqlite3.Connection, path: Path, credential: str,
144
+ expected_peer: dict, *, text: str, idempotency_key: str, now: str) -> tuple[dict, bool]:
145
+ if not connection.in_transaction:
146
+ raise RuntimeError("External admission requires the caller's transaction")
147
+ peer = authenticate(path, credential)
148
+ if peer != expected_peer:
149
+ raise PeerUnauthorized("External peer policy changed")
150
+ _text(text)
151
+ if len(text.encode()) > 64 * 1024:
152
+ raise ValueError("External message is too large")
153
+ if (not isinstance(idempotency_key, str) or not 8 <= len(idempotency_key) <= 128
154
+ or not idempotency_key.isascii() or not idempotency_key.isprintable()):
155
+ raise ValueError("Invalid external idempotency key")
156
+ # External admission has no provider run. A separately namespaced durable
157
+ # request identity avoids inventing one to satisfy the old envelope index.
158
+ key = "external:" + hashlib.sha256(json.dumps(
159
+ [peer["peer_id"], peer["revision"], idempotency_key], separators=(",", ":")).encode()).hexdigest()
160
+ prior = connection.execute("SELECT * FROM cross_chat_envelopes WHERE source_run_id='' AND idempotency_key=?", (key,)).fetchone()
161
+ if prior is not None:
162
+ prior = dict(prior)
163
+ if (prior["body"] != text or prior["source_session_id"] != peer["peer_id"]
164
+ or prior["target_session_id"] != peer["target_session_id"]
165
+ or prior["authorization_pair_id"] != peer["pair_id"]):
166
+ raise PeerConflict("Idempotency key already used for another message")
167
+ return prior, False
168
+ message_id = "handoff_" + uuid.uuid4().hex
169
+ admission_id = "extadmission_" + uuid.uuid4().hex
170
+ connection.execute("""INSERT INTO cross_chat_envelopes
171
+ (id,kind,source_session_id,source_run_id,target_session_id,action,body,idempotency_key,
172
+ authorization_kind,authorization_route_id,authorization_pair_id,status,created_at,updated_at,delivery_mode)
173
+ VALUES(?,'instruction',?,'',?,'instruction',?,?,'configured_route',?,?,'stored',?,?,'mailbox')""",
174
+ (message_id, peer["peer_id"], peer["target_session_id"], text, key,
175
+ peer["inbound_route_id"], peer["pair_id"], now, now))
176
+ connection.execute("INSERT INTO external_chat_admissions(message_id,admission_id,provenance_json) VALUES(?,?,?)",
177
+ (message_id, admission_id, json.dumps(_admission_provenance(peer, admission_id), ensure_ascii=False)))
178
+ chat_mailbox.store_message(connection, message_id, now=now)
179
+ return dict(connection.execute("SELECT * FROM cross_chat_envelopes WHERE id=?", (message_id,)).fetchone()), True
180
+
181
+
182
+ def _cursor(peer: dict, sequence: int) -> str:
183
+ data = json.dumps([peer["peer_id"], peer["revision"], peer["pair_id"], sequence], separators=(",", ":")).encode()
184
+ signature = hmac.new(bytes.fromhex(peer["credential_sha256"]), data, hashlib.sha256).digest()
185
+ return base64.urlsafe_b64encode(data + signature).decode().rstrip("=")
186
+
187
+
188
+ def _sequence(peer: dict, cursor: str) -> int:
189
+ if not cursor:
190
+ return 0
191
+ try:
192
+ if not isinstance(cursor, str) or len(cursor) > 1024 or not re.fullmatch(r"[A-Za-z0-9_-]+", cursor):
193
+ raise ValueError()
194
+ decoded = base64.urlsafe_b64decode(cursor + "=" * (-len(cursor) % 4))
195
+ if base64.urlsafe_b64encode(decoded).decode().rstrip("=") != cursor:
196
+ raise ValueError()
197
+ data, signature = decoded[:-32], decoded[-32:]
198
+ expected = hmac.new(bytes.fromhex(peer["credential_sha256"]), data, hashlib.sha256).digest()
199
+ if not hmac.compare_digest(signature, expected):
200
+ raise ValueError()
201
+ value = json.loads(data)
202
+ if (not isinstance(value, list) or len(value) != 4
203
+ or value[:3] != [peer["peer_id"], peer["revision"], peer["pair_id"]]
204
+ or type(value[3]) is not int or not 0 <= value[3] <= (1 << 63) - 1):
205
+ raise ValueError()
206
+ return value[3]
207
+ except (ValueError, TypeError, UnicodeError):
208
+ raise ValueError("Invalid external reply cursor") from None
209
+
210
+
211
+ def replies(connection: sqlite3.Connection, path: Path, credential: str, expected_peer: dict,
212
+ *, since: str = "", limit: int = 25) -> dict:
213
+ peer = authenticate(path, credential)
214
+ if peer != expected_peer:
215
+ raise PeerUnauthorized("External peer policy changed")
216
+ sequence = _sequence(peer, since)
217
+ page = chat_mailbox.list_messages(connection, peer["peer_id"], peer["target_session_id"],
218
+ [peer["pair_id"]], after_seq=sequence, limit=limit)
219
+ messages = page["messages"]
220
+ return {"messages": [{"message_id": row["message_id"], "text": row["body"],
221
+ "created_at": row["created_at"], "reply_to": row["in_reply_to_message_id"]}
222
+ for row in messages],
223
+ "next_cursor": _cursor(peer, messages[-1]["mailbox_seq"] if messages else sequence),
224
+ "has_more": bool(page["has_more"])}
@@ -52,6 +52,13 @@ def parse_models(value):
52
52
  model = str(item.get("name") or "").removeprefix("models/")
53
53
  if not MODEL.fullmatch(model) or "generateContent" not in item.get("supportedGenerationMethods", []):
54
54
  continue
55
+ # generateContent also lists audio-only products. These cannot satisfy
56
+ # the text/tool contract of Gemini CLI. Unknown chat families stay in
57
+ # the inventory; do not use a version/deprecation blacklist.
58
+ modalities = item.get("outputModalities")
59
+ if (isinstance(modalities, list) and modalities and "TEXT" not in modalities
60
+ or re.search(r"(?:^|-)tts(?:-|$)", model) or model.startswith("lyria-")):
61
+ continue
55
62
  label = item.get("displayName") or model
56
63
  if not isinstance(label, str) or not label or len(label) > 256 or any(ord(c) < 32 or ord(c) == 127 for c in label):
57
64
  label = model
@@ -107,6 +114,7 @@ async def probe(selected):
107
114
  async with client.stream(method, target, headers=headers, **kwargs) as response:
108
115
  if response.status_code in {400, 401, 403}: return "authentication_failed" if not model or response.status_code != 400 else "unsupported"
109
116
  if response.status_code == 429: return "rate_limited"
117
+ if response.status_code == 404 and model: return "model_unavailable"
110
118
  if response.status_code != 200: return "connection_failed"
111
119
  raw = bytearray()
112
120
  async for chunk in response.aiter_bytes():
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"
@@ -1846,7 +1846,7 @@ if [[ "$TEAM_HUB_MODE" == "host" && "$TEAM_HUB_OPERATION_PENDING" != "true" \
1846
1846
  fi
1847
1847
  fi
1848
1848
 
1849
- RELEASE_FILES=(activation_transaction.py execution_activation.py execution_legacy_runner.py execution_preparation.py update_preparation.py update_handoff.py update_recovery.py execution_update_status.py execution_uninstall.py execution_recovery.py execution_recovery_status.py execution_http.py execution_durability.py execution_control.py execution_install.py execution_maintenance.py execution_manage.py execution_ownership.py execution_service.py execution_transport.py agent_server.py local_session_ownership.py cursor_history.py workspace_git.py team_hub_host.py secure_peer_runtime.py team_mail_runtime.py team_mail_websocket.py team_mail_grants.py secure_peer_delivery.py agentsdock_jobs.py agentsdock_chats.py chat_mailbox.py agentsdock_emergency.py agentsdock_notify.py agentsdock_publish.py agentsdock_mail.py agentsdock_team.py provider_commands.py provider_usage.py session_unread.py claude_sdk_client.py claude_model_catalog.py claude_goals.py claude_background_reconciliation.py codex_app_server.py codex_auth.py codex_provider.py codex_response_stream.py provider_connections.py cursor_api_key.py side_questions.py title_generation.py codex_side_question.py codex_side_chat_progress.py claude_side_question.py cursor_agent_client.py cursor_provider_mcp.py opencode_agent_client.py gemini_acp_client.py gemini_history.py gemini_content.py gemini_import.py gemini_runtime.py gemini_runner.py gemini_permissions.py gemini_api.py cursor_process_guard.py transcript_reader.py claude_history_repair.py claude_history_provenance.py codex_history_repair.py public_chat_shares.py public_chat_transcript.py public_chat_share_routes.py interactive_chat_shares.py interactive_chat_share_routes.py interactive_chat_share_web.py interactive_chat_projection.py interactive_chat_runtime.py interactive_chat_native.py shared_chat_videos.py shared_chat_analytics_web.py shared_chat_video_stream.py interactive_chat_controls.py install.sh uninstall.sh instances.sh server_instances.py npm/agentsdock/pair.cjs npm/agentsdock/qr-renderer.cjs npm/agentsdock/QR-NOTICES.txt update_runner.py pyproject.toml uv.lock VERSION release-public-key.pem LICENSE NOTICE)
1849
+ RELEASE_FILES=(activation_transaction.py execution_activation.py execution_legacy_runner.py execution_preparation.py update_preparation.py update_handoff.py update_recovery.py execution_update_status.py execution_uninstall.py execution_recovery.py execution_recovery_status.py execution_http.py execution_durability.py execution_control.py execution_install.py execution_maintenance.py execution_manage.py execution_ownership.py execution_service.py execution_transport.py agent_server.py local_session_ownership.py cursor_history.py workspace_git.py workspace_intelligence.py team_hub_host.py secure_peer_runtime.py team_mail_runtime.py team_mail_websocket.py team_mail_grants.py secure_peer_delivery.py agentsdock_jobs.py agentsdock_chats.py chat_mailbox.py external_chat_peers.py agentsdock_emergency.py agentsdock_notify.py agentsdock_publish.py agentsdock_mail.py agentsdock_team.py provider_commands.py provider_usage.py session_unread.py claude_sdk_client.py claude_chat_routing.py claude_model_catalog.py claude_goals.py claude_background_reconciliation.py codex_app_server.py codex_auth.py codex_provider.py codex_response_stream.py provider_connections.py cursor_api_key.py side_questions.py workspace_layouts.py title_generation.py codex_side_question.py codex_side_chat_progress.py claude_side_question.py cursor_agent_client.py cursor_provider_mcp.py opencode_agent_client.py gemini_acp_client.py gemini_history.py gemini_content.py gemini_import.py gemini_runtime.py gemini_runner.py gemini_permissions.py gemini_api.py cursor_process_guard.py transcript_reader.py claude_history_repair.py claude_history_provenance.py codex_history_repair.py public_chat_shares.py public_chat_transcript.py public_chat_share_routes.py interactive_chat_shares.py interactive_chat_share_routes.py interactive_chat_share_web.py interactive_chat_projection.py interactive_chat_runtime.py interactive_chat_native.py shared_chat_videos.py shared_chat_analytics_web.py shared_chat_video_stream.py interactive_chat_controls.py install.sh uninstall.sh instances.sh server_instances.py npm/agentsdock/pair.cjs npm/agentsdock/qr-renderer.cjs npm/agentsdock/QR-NOTICES.txt update_runner.py pyproject.toml uv.lock VERSION release-public-key.pem LICENSE NOTICE)
1850
1850
  RELEASE_DIRECTORIES=(agentsdock_team_hub)
1851
1851
  TEAM_HUB_RELEASE_FILES=(
1852
1852
  __init__.py
@@ -3752,6 +3752,7 @@ validate_staged_release_runtime() (
3752
3752
  "$STAGE_DIR/agentsdock_jobs.py" \
3753
3753
  "$STAGE_DIR/agentsdock_chats.py" \
3754
3754
  "$STAGE_DIR/chat_mailbox.py" \
3755
+ "$STAGE_DIR/external_chat_peers.py" \
3755
3756
  "$STAGE_DIR/agentsdock_emergency.py" \
3756
3757
  "$STAGE_DIR/agentsdock_notify.py" \
3757
3758
  "$STAGE_DIR/agentsdock_publish.py" \
@@ -3761,6 +3762,7 @@ validate_staged_release_runtime() (
3761
3762
  "$STAGE_DIR/provider_usage.py" \
3762
3763
  "$STAGE_DIR/session_unread.py" \
3763
3764
  "$STAGE_DIR/claude_sdk_client.py" \
3765
+ "$STAGE_DIR/claude_chat_routing.py" \
3764
3766
  "$STAGE_DIR/claude_model_catalog.py" \
3765
3767
  "$STAGE_DIR/claude_goals.py" \
3766
3768
  "$STAGE_DIR/claude_background_reconciliation.py" \
@@ -3769,7 +3771,9 @@ validate_staged_release_runtime() (
3769
3771
  "$STAGE_DIR/codex_provider.py" "$STAGE_DIR/codex_response_stream.py" \
3770
3772
  "$STAGE_DIR/provider_connections.py" "$STAGE_DIR/cursor_api_key.py" \
3771
3773
  "$STAGE_DIR/side_questions.py" \
3774
+ "$STAGE_DIR/workspace_layouts.py" \
3772
3775
  "$STAGE_DIR/workspace_git.py" \
3776
+ "$STAGE_DIR/workspace_intelligence.py" \
3773
3777
  "$STAGE_DIR/codex_side_question.py" \
3774
3778
  "$STAGE_DIR/codex_side_chat_progress.py" \
3775
3779
  "$STAGE_DIR/title_generation.py" \
@@ -3806,7 +3810,7 @@ validate_staged_release_runtime() (
3806
3810
  "$STAGE_DIR/update_runner.py"
3807
3811
  "$STAGE_DIR/.venv/bin/python" -m py_compile "$STAGE_DIR/server_instances.py"
3808
3812
  "$STAGE_DIR/.venv/bin/python" -m compileall -q "$STAGE_DIR/agentsdock_team_hub"
3809
- PYTHONPATH="$STAGE_DIR" "$STAGE_DIR/.venv/bin/python" -c 'import execution_activation, execution_preparation, update_preparation, update_handoff, update_recovery, execution_update_status, execution_uninstall, execution_recovery, execution_recovery_status, execution_http, execution_durability, execution_control, execution_install, execution_maintenance, execution_manage, execution_ownership, execution_service, execution_transport; import workspace_git, claude_model_catalog, server_instances, local_session_ownership, cursor_history; import codex_auth, codex_provider, codex_response_stream, provider_connections, cursor_api_key, side_questions, title_generation, codex_side_question, codex_side_chat_progress, claude_side_question, agentsdock_team_hub, cursor_agent_client, cursor_provider_mcp, opencode_agent_client, gemini_acp_client, gemini_history, gemini_content, gemini_import, gemini_runtime, gemini_runner, gemini_permissions, gemini_api, cursor_process_guard, secure_peer_delivery, secure_peer_runtime, team_mail_runtime, team_mail_websocket, team_mail_grants, team_hub_host, agentsdock_mail, agentsdock_team, transcript_reader, claude_history_repair, claude_history_provenance, claude_goals, claude_background_reconciliation, codex_history_repair, public_chat_shares, public_chat_transcript, public_chat_share_routes, interactive_chat_shares, interactive_chat_share_routes, interactive_chat_share_web, interactive_chat_projection, interactive_chat_runtime, interactive_chat_native, shared_chat_videos, shared_chat_analytics_web, shared_chat_video_stream, interactive_chat_controls, chat_mailbox, provider_commands, provider_usage; from agentsdock_team_hub import secure_peer, secure_peer_hub' >/dev/null
3813
+ PYTHONPATH="$STAGE_DIR" "$STAGE_DIR/.venv/bin/python" -c 'import execution_activation, execution_preparation, update_preparation, update_handoff, update_recovery, execution_update_status, execution_uninstall, execution_recovery, execution_recovery_status, execution_http, execution_durability, execution_control, execution_install, execution_maintenance, execution_manage, execution_ownership, execution_service, execution_transport; import workspace_git, workspace_intelligence, claude_model_catalog, claude_chat_routing, server_instances, local_session_ownership, cursor_history; import codex_auth, codex_provider, codex_response_stream, provider_connections, cursor_api_key, side_questions, workspace_layouts, title_generation, codex_side_question, codex_side_chat_progress, claude_side_question, agentsdock_team_hub, cursor_agent_client, cursor_provider_mcp, opencode_agent_client, gemini_acp_client, gemini_history, gemini_content, gemini_import, gemini_runtime, gemini_runner, gemini_permissions, gemini_api, cursor_process_guard, secure_peer_delivery, secure_peer_runtime, team_mail_runtime, team_mail_websocket, team_mail_grants, team_hub_host, agentsdock_mail, agentsdock_team, transcript_reader, claude_history_repair, claude_history_provenance, claude_goals, claude_background_reconciliation, codex_history_repair, public_chat_shares, public_chat_transcript, public_chat_share_routes, interactive_chat_shares, interactive_chat_share_routes, interactive_chat_share_web, interactive_chat_projection, interactive_chat_runtime, interactive_chat_native, shared_chat_videos, shared_chat_analytics_web, shared_chat_video_stream, interactive_chat_controls, chat_mailbox, external_chat_peers, provider_commands, provider_usage; from agentsdock_team_hub import secure_peer, secure_peer_hub' >/dev/null
3810
3814
  )
3811
3815
 
3812
3816
  abort_unclaimed_team_hub_reactivation() {
@@ -7017,15 +7021,31 @@ fi
7017
7021
  # links or configuration. Legacy runners can report a failed installer, so an
7018
7022
  # unfinished journal must never leave their old, unfenced API accepting work.
7019
7023
  if [[ "${EXECUTION_MODE:-legacy}" == "split" ]]; then
7020
- if ! execution_activation_command durability "$STAGE_DIR" \
7021
- || ! execution_recovery_arm "$STAGE_DIR" \
7022
- || ! record_activation_phase quiescing "$STAGE_DIR" \
7023
- || ! execution_stop_services "$STAGE_DIR" preflight \
7024
- || ! execution_activation_command suppress "$STAGE_DIR" \
7025
- || ! execution_stop_services "$STAGE_DIR" stop \
7026
- || ! record_activation_phase quiesced "$STAGE_DIR"; then
7024
+ # Name the quiesce boundary that actually failed. Arming the activation
7025
+ # recovery owner validates the recovery interpreter's ownership and
7026
+ # permission bits, which needs a different operator response than a native
7027
+ # service-stop failure; the single generic message below previously blamed
7028
+ # the service stop for every failure in this chain.
7029
+ ACTIVATION_QUIESCE_BOUNDARY=""
7030
+ if ! execution_activation_command durability "$STAGE_DIR"; then
7031
+ ACTIVATION_QUIESCE_BOUNDARY="recording activation durability evidence"
7032
+ elif ! execution_recovery_arm "$STAGE_DIR"; then
7033
+ ACTIVATION_QUIESCE_BOUNDARY="arming the activation recovery owner"
7034
+ elif ! record_activation_phase quiescing "$STAGE_DIR"; then
7035
+ ACTIVATION_QUIESCE_BOUNDARY="journaling the quiescing phase"
7036
+ elif ! execution_stop_services "$STAGE_DIR" preflight; then
7037
+ ACTIVATION_QUIESCE_BOUNDARY="preflighting the admitted execution service"
7038
+ elif ! execution_activation_command suppress "$STAGE_DIR"; then
7039
+ ACTIVATION_QUIESCE_BOUNDARY="suppressing the admitted execution service"
7040
+ elif ! execution_stop_services "$STAGE_DIR" stop; then
7041
+ ACTIVATION_QUIESCE_BOUNDARY="stopping the admitted execution service"
7042
+ elif ! record_activation_phase quiesced "$STAGE_DIR"; then
7043
+ ACTIVATION_QUIESCE_BOUNDARY="journaling the quiesced phase"
7044
+ fi
7045
+ if [[ -n "$ACTIVATION_QUIESCE_BOUNDARY" ]]; then
7027
7046
  [[ "$COLD_TEAM_HUB_HANDOFF" != "true" ]] || resume_install_signals
7028
7047
  echo "The admitted execution service could not be durably stopped before takeover." >&2
7048
+ echo " The failure occurred while $ACTIVATION_QUIESCE_BOUNDARY; the error above identifies the specific cause." >&2
7029
7049
  exit 1
7030
7050
  fi
7031
7051
  fi