@agentsdock/server 1.0.12-beta.1 → 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.
@@ -275,6 +275,78 @@ def _native_assistant_item_owners(assistant_items: dict, completed_runs: set[str
275
275
  return owners
276
276
 
277
277
 
278
+ class _NativeGoalAssistantReplays:
279
+ """Match goal output by its exact native item/turn and one local owner.
280
+
281
+ Older goal consumers recorded the thread only on their promptless start.
282
+ Do not promote that boundary into general turn ownership: another public
283
+ item may legitimately repeat the same words within that native turn.
284
+ """
285
+ def __init__(self, provider_id: str):
286
+ self.provider_id = provider_id
287
+ self.starts: dict[str, tuple[int, str] | None] = {}
288
+ self.items: dict[tuple[str, str, str], list[tuple[str, dict]]] = {}
289
+ self.count = 0
290
+
291
+ def event(self, event: dict) -> None:
292
+ run = event.get("run_id")
293
+ if not isinstance(run, str) or not 0 < len(run) <= 256 or run.startswith("import_"):
294
+ return
295
+ if event.get("type") == "turn_started":
296
+ if run in self.starts:
297
+ self.starts[run] = None
298
+ return
299
+ self.count += 1
300
+ thread = event.get("thread_id")
301
+ valid = (event.get("backend") == "codex" and event.get("purpose") == "codex_goal_resume"
302
+ and event.get("imported") is not True and event.get("forked") is not True
303
+ and event.get("prompt") in (None, "") and not _runtime_human_provenance(event)
304
+ and isinstance(thread, str) and _PROVIDER_ID.fullmatch(thread)
305
+ and event.get("provider_thread_id") in (None, "", thread)
306
+ and isinstance(event.get("id"), str) and 0 < len(event["id"]) <= 256
307
+ and type(event.get("seq")) is int and event["seq"] > 0)
308
+ self.starts[run] = (event["seq"], thread) if valid else None
309
+ return
310
+ item_id = _public_assistant_item_id(event)
311
+ turn = event.get("provider_turn_id")
312
+ body = event.get("text")
313
+ if (event.get("purpose") != "codex_goal_resume" or item_id is None
314
+ or event.get("imported") is True or event.get("forked") is True
315
+ or event.get("backend") not in (None, "codex")
316
+ or not isinstance(turn, str) or not 0 < len(turn) <= 256
317
+ or not isinstance(body, str) or not 0 < len(body) <= NATIVE_PROOF_TEXT_CHARS
318
+ or not isinstance(event.get("id"), str) or not 0 < len(event["id"]) <= 256
319
+ or type(event.get("seq")) is not int or event["seq"] <= 0):
320
+ return
321
+ key = (turn, item_id, _text_key(body))
322
+ entries = self.items.setdefault(key, [])
323
+ if len(entries) < 2:
324
+ entries.append((run, _native_event_identity(event)))
325
+ self.count += 1
326
+
327
+ def match(self, origin: dict, text_key: str, *, before_seq: int | None = None,
328
+ provider_id: str | None = None) -> dict | None:
329
+ provider_id = provider_id or self.provider_id
330
+ if (origin.get("provider") != "codex" or origin.get("kind") != "assistant"
331
+ or origin.get("session_id", provider_id) != provider_id):
332
+ return None
333
+ entries = self.items.get((origin.get("turn_id"), origin.get("event_id"), text_key), ())
334
+ if len(entries) != 1:
335
+ return None
336
+ run, event = entries[0]
337
+ start = self.starts.get(run)
338
+ if (event.get("provider_thread_id") not in (None, "", provider_id)
339
+ or before_seq is not None and event["seq"] >= before_seq):
340
+ return None
341
+ if event.get("provider_thread_id") == provider_id:
342
+ # New output carries its own thread receipt, including inline goal
343
+ # continuations whose original start was an ordinary human turn.
344
+ return event
345
+ if start is not None and start[1] == provider_id and start[0] < event["seq"]:
346
+ return event
347
+ return None
348
+
349
+
278
350
  @dataclass
279
351
  class _SourceBudget:
280
352
  bytes_remaining: int
@@ -640,12 +712,19 @@ def _native_mailbox_wake_hash(event: dict) -> str | None:
640
712
  """A server-authored hidden input, not a text-based provider classification."""
641
713
  digest = event.get("provider_input_sha256")
642
714
  wake_id = event.get("mailbox_wake_id")
643
- if (event.get("type") == "turn_started" and event.get("imported") is not True
644
- and event.get("purpose") == "chat_mailbox_wake" and event.get("prompt") == ""
645
- 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"
646
721
  and isinstance(wake_id, str) and re.fullmatch(r"mailwake_[a-f0-9]{32}", wake_id)
647
- and type(event.get("mailbox_wake_through_seq")) is int and 0 < event["mailbox_wake_through_seq"] < 2**63
648
- 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)):
649
728
  return digest
650
729
  return None
651
730
 
@@ -974,6 +1053,7 @@ def _prove_native_replays(session_id: str, provider_id: str, events: Path, sourc
974
1053
  stamp = _native_stamp(events)
975
1054
  batches, terminals, candidates, native, owners = {}, {}, [], {}, {}
976
1055
  deliveries = _AsyncDeliveryIndex()
1056
+ goal_assistants = _NativeGoalAssistantReplays(provider_id)
977
1057
  previous_seq, retained = 0, 0
978
1058
  for event, _offset, _line in _native_records(events, stamp, budget):
979
1059
  seq = event.get("seq")
@@ -983,7 +1063,8 @@ def _prove_native_replays(session_id: str, provider_id: str, events: Path, sourc
983
1063
  if event.get("session_id") not in (None, "", session_id):
984
1064
  continue
985
1065
  deliveries.observe(event)
986
- if len(candidates) + len(batches) + len(terminals) + retained + deliveries.count > MAX_KEYS:
1066
+ goal_assistants.event(event)
1067
+ if len(candidates) + len(batches) + len(terminals) + retained + deliveries.count + goal_assistants.count > MAX_KEYS:
987
1068
  raise CodexNativeHistoryProofCapacityExceeded("native history proof key budget exceeded")
988
1069
  run = event.get("run_id")
989
1070
  if not isinstance(run, str) or not 0 < len(run) <= 256:
@@ -1009,6 +1090,10 @@ def _prove_native_replays(session_id: str, provider_id: str, events: Path, sourc
1009
1090
  owned = owners.setdefault((thread, turn), set())
1010
1091
  retained += run not in owned
1011
1092
  owned.add(run)
1093
+ if event.get("purpose") == "codex_goal_resume" and not _native_goal_steer_turn(event):
1094
+ # Goal replies use exact item/turn proof, never run-wide text
1095
+ # credit. Accepted user steers still need source-occurrence proof.
1096
+ continue
1012
1097
  kind = "user" if event.get("type") == "turn_started" or _native_goal_steer_turn(event) else "assistant" if event.get("type") in ("assistant_text", "reasoning_summary", "turn_finished") else None
1013
1098
  body = event.get("prompt") if kind == "user" else event.get("result_text") if event.get("type") == "turn_finished" else event.get("text")
1014
1099
  if kind and isinstance(body, str) and body and len(body) <= 4 * 1024 * 1024:
@@ -1017,7 +1102,7 @@ def _prove_native_replays(session_id: str, provider_id: str, events: Path, sourc
1017
1102
  elif kind == "user" and (wake_hash := _native_mailbox_wake_hash(event)):
1018
1103
  native.setdefault((run, kind, wake_hash), []).append(_native_event_identity(event))
1019
1104
  retained += 1
1020
- if len(candidates) + len(batches) + len(terminals) + retained + deliveries.count > MAX_KEYS:
1105
+ if len(candidates) + len(batches) + len(terminals) + retained + deliveries.count + goal_assistants.count > MAX_KEYS:
1021
1106
  raise CodexNativeHistoryProofCapacityExceeded("native history proof key budget exceeded")
1022
1107
  if not candidates:
1023
1108
  return _NativeProof(provider_id)
@@ -1043,7 +1128,7 @@ def _prove_native_replays(session_id: str, provider_id: str, events: Path, sourc
1043
1128
  proofs = {}
1044
1129
  for thread, path in selected:
1045
1130
  proofs.update(_prove_native_source(thread, Path(path), root, groups[(thread, path)], candidates, native, owners, parse_item, budget,
1046
- session_id=session_id, deliveries=deliveries))
1131
+ session_id=session_id, deliveries=deliveries, goal_assistants=goal_assistants))
1047
1132
  budget.check()
1048
1133
  return _NativeProof(provider_id, proofs)
1049
1134
 
@@ -1051,7 +1136,8 @@ def _prove_native_replays(session_id: str, provider_id: str, events: Path, sourc
1051
1136
  def _prove_native_source(thread: str, source: Path, root: Path, batches: dict, candidates: list,
1052
1137
  native: dict, owners: dict, parse_item: Callable, budget: _NativeReadBudget,
1053
1138
  *, session_id: str, deliveries: _AsyncDeliveryIndex,
1054
- require_verified_checkpoint: bool = False) -> dict:
1139
+ require_verified_checkpoint: bool = False,
1140
+ goal_assistants: _NativeGoalAssistantReplays | None = None) -> dict:
1055
1141
  if (not source.is_absolute() or source.is_symlink() or source.suffix != ".jsonl"
1056
1142
  or not (source.stem == thread or source.stem.endswith("-" + thread))):
1057
1143
  raise _Unproven()
@@ -1241,6 +1327,15 @@ def _prove_native_source(thread: str, source: Path, root: Path, batches: dict, c
1241
1327
  if len(proofs) > MAX_TARGETS:
1242
1328
  raise _Unproven()
1243
1329
  continue
1330
+ goal_origin = timestamp_origins[0] if len(timestamp_origins) == 1 else None
1331
+ goal_match = goal_assistants.match(goal_origin, assistant_native_keys.get(key, ""),
1332
+ before_seq=first, provider_id=thread) if (
1333
+ goal_assistants and goal_origin and kind == "assistant" and source_hash is None) else None
1334
+ if goal_match is not None:
1335
+ proofs[target] = {**goal_origin, "native_event_id": goal_match["id"], "source_text_sha256": body_key}
1336
+ if len(proofs) > MAX_TARGETS:
1337
+ raise _Unproven()
1338
+ continue
1244
1339
  if len(source_ids) != 1 or source_hash is not None and key not in full_user_keys:
1245
1340
  continue
1246
1341
  source_origin = next(iter(source_ids.values()))
@@ -1450,6 +1545,7 @@ def filter_native_codex_history_items(session_id: str, provider_id: str, events:
1450
1545
  owners, native, assistant_items, wake_keys, native_count = {}, {}, {}, set(), 0
1451
1546
  native_inputs, steered_inputs = {}, {}
1452
1547
  deliveries = _AsyncDeliveryIndex()
1548
+ goal_assistants = _NativeGoalAssistantReplays(provider_id)
1453
1549
  prove_deliveries = (source_path is not None and root is not None
1454
1550
  and isinstance(sync_checkpoint, dict) and callable(parse_item)
1455
1551
  and any(item.get("kind") == "user" and isinstance(item.get("text"), str) for item in items))
@@ -1460,6 +1556,10 @@ def filter_native_codex_history_items(session_id: str, provider_id: str, events:
1460
1556
  raise _Unproven()
1461
1557
  previous_seq = seq
1462
1558
  run = event.get("run_id")
1559
+ if event.get("session_id") in (None, "", session_id):
1560
+ goal_assistants.event(event)
1561
+ if native_count + owner_count + len(assistant_items) + deliveries.count + goal_assistants.count > MAX_KEYS:
1562
+ raise _Unproven()
1463
1563
  if prove_deliveries and event.get("session_id") in (None, "", session_id):
1464
1564
  deliveries.observe(event)
1465
1565
  if native_count + owner_count + len(assistant_items) + deliveries.count > MAX_KEYS:
@@ -1475,6 +1575,16 @@ def filter_native_codex_history_items(session_id: str, provider_id: str, events:
1475
1575
  owner_count += run not in owned
1476
1576
  owned.add(run)
1477
1577
  steer_turn = _native_goal_steer_turn(event)
1578
+ if event.get("purpose") == "codex_goal_resume" and not steer_turn:
1579
+ # Keep exact public reply identity for source-prefix ownership,
1580
+ # without granting equal-text credit to every reply in the goal.
1581
+ item_id = _public_assistant_item_id(event)
1582
+ body = event.get("text")
1583
+ if item_id is not None and isinstance(body, str) and body:
1584
+ assistant_items[(run, item_id, _text_key(body))] = _native_event_identity(event)
1585
+ if native_count + owner_count + len(assistant_items) + deliveries.count + goal_assistants.count > MAX_KEYS:
1586
+ raise _Unproven()
1587
+ continue
1478
1588
  kind = "user" if event.get("type") == "turn_started" or steer_turn else "assistant" if event.get("type") in ("assistant_text", "reasoning_summary", "turn_finished") else None
1479
1589
  body = event.get("prompt") if kind == "user" else event.get("result_text") if event.get("type") == "turn_finished" else event.get("text")
1480
1590
  wake_hash = _native_mailbox_wake_hash(event) if kind == "user" else None
@@ -1499,7 +1609,7 @@ def filter_native_codex_history_items(session_id: str, provider_id: str, events:
1499
1609
  item_id = _public_assistant_item_id(event)
1500
1610
  if item_id is not None and key is not None:
1501
1611
  assistant_items[(run, item_id, key[1])] = _native_event_identity(event)
1502
- if native_count + owner_count + len(assistant_items) + deliveries.count > MAX_KEYS:
1612
+ if native_count + owner_count + len(assistant_items) + deliveries.count + goal_assistants.count > MAX_KEYS:
1503
1613
  raise _Unproven()
1504
1614
  assistant_item_owners = _native_assistant_item_owners(
1505
1615
  assistant_items, {run for runs in owners.values() for run in runs}, provider_id,
@@ -1545,6 +1655,10 @@ def filter_native_codex_history_items(session_id: str, provider_id: str, events:
1545
1655
  for index, item in enumerate(items):
1546
1656
  budget.check()
1547
1657
  origin = item.get("provider_origin")
1658
+ if (item.get("kind") == "assistant" and isinstance(origin, dict)
1659
+ and isinstance(item.get("text"), str) and item.get("source_text_sha256") is None
1660
+ and goal_assistants.match(origin, _text_key(_native_assistant_text(item["text"]))) is not None):
1661
+ continue
1548
1662
  runs = owners.get(origin.get("turn_id"), set()) if isinstance(origin, dict) else set()
1549
1663
  owned = (isinstance(origin, dict) and origin.get("provider") == "codex"
1550
1664
  and origin.get("kind") == item.get("kind") and isinstance(origin.get("event_id"), str)
@@ -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,
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 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 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
@@ -3761,6 +3761,7 @@ validate_staged_release_runtime() (
3761
3761
  "$STAGE_DIR/provider_usage.py" \
3762
3762
  "$STAGE_DIR/session_unread.py" \
3763
3763
  "$STAGE_DIR/claude_sdk_client.py" \
3764
+ "$STAGE_DIR/claude_chat_routing.py" \
3764
3765
  "$STAGE_DIR/claude_model_catalog.py" \
3765
3766
  "$STAGE_DIR/claude_goals.py" \
3766
3767
  "$STAGE_DIR/claude_background_reconciliation.py" \
@@ -3770,6 +3771,7 @@ validate_staged_release_runtime() (
3770
3771
  "$STAGE_DIR/provider_connections.py" "$STAGE_DIR/cursor_api_key.py" \
3771
3772
  "$STAGE_DIR/side_questions.py" \
3772
3773
  "$STAGE_DIR/workspace_git.py" \
3774
+ "$STAGE_DIR/workspace_intelligence.py" \
3773
3775
  "$STAGE_DIR/codex_side_question.py" \
3774
3776
  "$STAGE_DIR/codex_side_chat_progress.py" \
3775
3777
  "$STAGE_DIR/title_generation.py" \
@@ -3806,7 +3808,7 @@ validate_staged_release_runtime() (
3806
3808
  "$STAGE_DIR/update_runner.py"
3807
3809
  "$STAGE_DIR/.venv/bin/python" -m py_compile "$STAGE_DIR/server_instances.py"
3808
3810
  "$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
3811
+ 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, 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
3810
3812
  )
3811
3813
 
3812
3814
  abort_unclaimed_team_hub_reactivation() {
@@ -7017,15 +7019,31 @@ fi
7017
7019
  # links or configuration. Legacy runners can report a failed installer, so an
7018
7020
  # unfinished journal must never leave their old, unfenced API accepting work.
7019
7021
  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
7022
+ # Name the quiesce boundary that actually failed. Arming the activation
7023
+ # recovery owner validates the recovery interpreter's ownership and
7024
+ # permission bits, which needs a different operator response than a native
7025
+ # service-stop failure; the single generic message below previously blamed
7026
+ # the service stop for every failure in this chain.
7027
+ ACTIVATION_QUIESCE_BOUNDARY=""
7028
+ if ! execution_activation_command durability "$STAGE_DIR"; then
7029
+ ACTIVATION_QUIESCE_BOUNDARY="recording activation durability evidence"
7030
+ elif ! execution_recovery_arm "$STAGE_DIR"; then
7031
+ ACTIVATION_QUIESCE_BOUNDARY="arming the activation recovery owner"
7032
+ elif ! record_activation_phase quiescing "$STAGE_DIR"; then
7033
+ ACTIVATION_QUIESCE_BOUNDARY="journaling the quiescing phase"
7034
+ elif ! execution_stop_services "$STAGE_DIR" preflight; then
7035
+ ACTIVATION_QUIESCE_BOUNDARY="preflighting the admitted execution service"
7036
+ elif ! execution_activation_command suppress "$STAGE_DIR"; then
7037
+ ACTIVATION_QUIESCE_BOUNDARY="suppressing the admitted execution service"
7038
+ elif ! execution_stop_services "$STAGE_DIR" stop; then
7039
+ ACTIVATION_QUIESCE_BOUNDARY="stopping the admitted execution service"
7040
+ elif ! record_activation_phase quiesced "$STAGE_DIR"; then
7041
+ ACTIVATION_QUIESCE_BOUNDARY="journaling the quiesced phase"
7042
+ fi
7043
+ if [[ -n "$ACTIVATION_QUIESCE_BOUNDARY" ]]; then
7027
7044
  [[ "$COLD_TEAM_HUB_HANDOFF" != "true" ]] || resume_install_signals
7028
7045
  echo "The admitted execution service could not be durably stopped before takeover." >&2
7046
+ echo " The failure occurred while $ACTIVATION_QUIESCE_BOUNDARY; the error above identifies the specific cause." >&2
7029
7047
  exit 1
7030
7048
  fi
7031
7049
  fi
@@ -242,7 +242,7 @@ class ConnectionStore:
242
242
  except HTTPException:
243
243
  return {"configured": False, "available": False, "models": [], "efforts": [], "model": None, "base_url": None}
244
244
 
245
- def claude_overrides(self, session: dict) -> tuple[dict, str | None]:
245
+ def claude_overrides(self, session: dict, *, runtime_settings: dict | None = None) -> tuple[dict, str | None]:
246
246
  value = self.for_session(session)
247
247
  if not value:
248
248
  return {}, None
@@ -259,7 +259,7 @@ class ConnectionStore:
259
259
  env["CLAUDE_CODE_MAX_CONCURRENT_SUBAGENTS"] = str(session["subagent_limit"])
260
260
  # Flag settings outrank project/user settings. Pass a private file path,
261
261
  # never a key-bearing JSON argument visible in process listings.
262
- content = json.dumps({"env": env, "apiKeyHelper": ""}, sort_keys=True)
262
+ content = json.dumps({**(runtime_settings or {}), "env": env, "apiKeyHelper": ""}, sort_keys=True)
263
263
  digest = hashlib.sha256(content.encode()).hexdigest()
264
264
  path = self.root / f"claude-runtime-{digest}.json"
265
265
  with self.lock:
@@ -281,7 +281,7 @@ class _RecordParser:
281
281
  def jsonl_records(stream: BinaryIO, *, end: int, project=True, strict=False,
282
282
  require_newline=True, max_records=250_000, deadline=None,
283
283
  cancelled=None, max_retained_bytes=MAX_RETAINED_BYTES, retained_fields=None,
284
- max_nodes=-1, max_depth=None):
284
+ max_nodes=-1, max_depth=None, allow_nul_padding=False):
285
285
  """Yield (projected object or None, ending offset, RawRecord).
286
286
 
287
287
  Malformed provider lines may be represented by None, as before. Resource
@@ -289,6 +289,8 @@ def jsonl_records(stream: BinaryIO, *, end: int, project=True, strict=False,
289
289
  A fixed end excludes concurrent appends; callers own file identity checks.
290
290
  Native-import work budgets remain the default. Durable metadata-only scans
291
291
  can supply separate structural limits without imposing import caps on logs.
292
+ Native Claude recovery can explicitly accept NUL-only padding lines. They
293
+ provide no event or ownership evidence, but retain their exact raw receipt.
292
294
  """
293
295
  # Externally supplied deadlines can belong to a larger operation. Do not
294
296
  # invent a duration for them; the caller can provide its own timeout detail.
@@ -306,14 +308,23 @@ def jsonl_records(stream: BinaryIO, *, end: int, project=True, strict=False,
306
308
  parser = _RecordParser(stream, end, deadline, cancelled, project, max_retained_bytes, budget_seconds, retained_fields, max_nodes, max_depth)
307
309
  blank = False
308
310
  malformed = False
311
+ nul_padding = False
309
312
  try:
310
313
  try:
311
- parser.space()
312
- blank = parser.peek() is None
313
- value = None if blank else parser.value()
314
- parser.space()
315
- if parser.peek() is not None:
316
- raise InvalidRecord('trailing JSON content')
314
+ if allow_nul_padding and parser.peek() == 0:
315
+ while parser.peek() == 0:
316
+ parser.index += 1
317
+ if parser.take() != 10 or parser.peek() is not None:
318
+ raise InvalidRecord('invalid NUL padding record')
319
+ nul_padding = malformed = True
320
+ value = None
321
+ else:
322
+ parser.space()
323
+ blank = parser.peek() is None
324
+ value = None if blank else parser.value()
325
+ parser.space()
326
+ if parser.peek() is not None:
327
+ raise InvalidRecord('trailing JSON content')
317
328
  except (InvalidRecord, UnicodeDecodeError, json.JSONDecodeError) as error:
318
329
  if strict:
319
330
  raise ValueError('malformed transcript record') from error
@@ -329,6 +340,6 @@ def jsonl_records(stream: BinaryIO, *, end: int, project=True, strict=False,
329
340
  raise ValueError('transcript cursor does not end on a complete line')
330
341
  raw = RawRecord(stream, start, stop, parser.complete, blank, malformed or blank,
331
342
  deadline, cancelled, count, budget_seconds)
332
- if strict and not isinstance(value, dict):
343
+ if strict and not isinstance(value, dict) and not nul_padding:
333
344
  raise ValueError('transcript object expected')
334
345
  yield value if isinstance(value, dict) else None, stop, raw