@agentsdock/server 1.0.11 → 1.0.12-beta.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/package.json +1 -1
- package/server/VERSION +1 -1
- package/server/agent_server.py +2781 -464
- package/server/agentsdock_notify.py +123 -0
- package/server/chat_mailbox.py +12 -7
- package/server/claude_chat_routing.py +158 -0
- package/server/claude_goals.py +5 -2
- package/server/claude_history_repair.py +125 -14
- package/server/claude_sdk_client.py +1181 -322
- package/server/codex_app_server.py +19 -10
- package/server/codex_history_repair.py +112 -5
- package/server/codex_side_question.py +85 -7
- package/server/cursor_agent_client.py +22 -2
- package/server/execution_recovery.py +23 -4
- package/server/execution_service.py +24 -0
- package/server/execution_transport.py +23 -7
- package/server/install.sh +30 -10
- package/server/provider_connections.py +2 -2
- package/server/public_chat_transcript.py +11 -3
- package/server/session_unread.py +184 -0
- package/server/side_questions.py +46 -14
- package/server/transcript_reader.py +19 -8
- package/server/workspace_intelligence.py +309 -0
|
@@ -2369,17 +2369,20 @@ class CodexAppServerClient:
|
|
|
2369
2369
|
validated["turn"] = _protocol_turn(method, result.get("turn"))
|
|
2370
2370
|
return validated
|
|
2371
2371
|
|
|
2372
|
-
async def run_thread_shell_command(
|
|
2372
|
+
async def run_thread_shell_command(
|
|
2373
|
+
self, thread_id: str, command: str, *,
|
|
2374
|
+
before_send: Callable[[], bool] | None = None,
|
|
2375
|
+
) -> None:
|
|
2373
2376
|
thread_id = _require_nonempty_string(thread_id, "thread_id")
|
|
2374
2377
|
command = _require_nonempty_string(command, "command")
|
|
2375
2378
|
method = "thread/shellCommand"
|
|
2376
|
-
|
|
2377
|
-
|
|
2378
|
-
await self.request(
|
|
2379
|
-
|
|
2380
|
-
|
|
2381
|
-
)
|
|
2382
|
-
)
|
|
2379
|
+
params = {"threadId": thread_id, "command": command}
|
|
2380
|
+
if before_send is None:
|
|
2381
|
+
result = await self.request(method, params)
|
|
2382
|
+
else:
|
|
2383
|
+
await self.start()
|
|
2384
|
+
result = await self._request_connected(method, params, before_send=before_send)
|
|
2385
|
+
_protocol_empty_object(method, result)
|
|
2383
2386
|
|
|
2384
2387
|
async def list_background_terminals(
|
|
2385
2388
|
self,
|
|
@@ -3011,8 +3014,14 @@ class CodexAppServerManager:
|
|
|
3011
3014
|
delivery=delivery,
|
|
3012
3015
|
)
|
|
3013
3016
|
|
|
3014
|
-
async def run_thread_shell_command(
|
|
3015
|
-
|
|
3017
|
+
async def run_thread_shell_command(
|
|
3018
|
+
self, thread_id: str, command: str, *,
|
|
3019
|
+
before_send: Callable[[], bool] | None = None,
|
|
3020
|
+
) -> None:
|
|
3021
|
+
if before_send is None:
|
|
3022
|
+
await self.client.run_thread_shell_command(thread_id, command)
|
|
3023
|
+
else:
|
|
3024
|
+
await self.client.run_thread_shell_command(thread_id, command, before_send=before_send)
|
|
3016
3025
|
|
|
3017
3026
|
async def list_background_terminals(
|
|
3018
3027
|
self,
|
|
@@ -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
|
|
@@ -974,6 +1046,7 @@ def _prove_native_replays(session_id: str, provider_id: str, events: Path, sourc
|
|
|
974
1046
|
stamp = _native_stamp(events)
|
|
975
1047
|
batches, terminals, candidates, native, owners = {}, {}, [], {}, {}
|
|
976
1048
|
deliveries = _AsyncDeliveryIndex()
|
|
1049
|
+
goal_assistants = _NativeGoalAssistantReplays(provider_id)
|
|
977
1050
|
previous_seq, retained = 0, 0
|
|
978
1051
|
for event, _offset, _line in _native_records(events, stamp, budget):
|
|
979
1052
|
seq = event.get("seq")
|
|
@@ -983,7 +1056,8 @@ def _prove_native_replays(session_id: str, provider_id: str, events: Path, sourc
|
|
|
983
1056
|
if event.get("session_id") not in (None, "", session_id):
|
|
984
1057
|
continue
|
|
985
1058
|
deliveries.observe(event)
|
|
986
|
-
|
|
1059
|
+
goal_assistants.event(event)
|
|
1060
|
+
if len(candidates) + len(batches) + len(terminals) + retained + deliveries.count + goal_assistants.count > MAX_KEYS:
|
|
987
1061
|
raise CodexNativeHistoryProofCapacityExceeded("native history proof key budget exceeded")
|
|
988
1062
|
run = event.get("run_id")
|
|
989
1063
|
if not isinstance(run, str) or not 0 < len(run) <= 256:
|
|
@@ -1009,6 +1083,10 @@ def _prove_native_replays(session_id: str, provider_id: str, events: Path, sourc
|
|
|
1009
1083
|
owned = owners.setdefault((thread, turn), set())
|
|
1010
1084
|
retained += run not in owned
|
|
1011
1085
|
owned.add(run)
|
|
1086
|
+
if event.get("purpose") == "codex_goal_resume" and not _native_goal_steer_turn(event):
|
|
1087
|
+
# Goal replies use exact item/turn proof, never run-wide text
|
|
1088
|
+
# credit. Accepted user steers still need source-occurrence proof.
|
|
1089
|
+
continue
|
|
1012
1090
|
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
1091
|
body = event.get("prompt") if kind == "user" else event.get("result_text") if event.get("type") == "turn_finished" else event.get("text")
|
|
1014
1092
|
if kind and isinstance(body, str) and body and len(body) <= 4 * 1024 * 1024:
|
|
@@ -1017,7 +1095,7 @@ def _prove_native_replays(session_id: str, provider_id: str, events: Path, sourc
|
|
|
1017
1095
|
elif kind == "user" and (wake_hash := _native_mailbox_wake_hash(event)):
|
|
1018
1096
|
native.setdefault((run, kind, wake_hash), []).append(_native_event_identity(event))
|
|
1019
1097
|
retained += 1
|
|
1020
|
-
if len(candidates) + len(batches) + len(terminals) + retained + deliveries.count > MAX_KEYS:
|
|
1098
|
+
if len(candidates) + len(batches) + len(terminals) + retained + deliveries.count + goal_assistants.count > MAX_KEYS:
|
|
1021
1099
|
raise CodexNativeHistoryProofCapacityExceeded("native history proof key budget exceeded")
|
|
1022
1100
|
if not candidates:
|
|
1023
1101
|
return _NativeProof(provider_id)
|
|
@@ -1043,7 +1121,7 @@ def _prove_native_replays(session_id: str, provider_id: str, events: Path, sourc
|
|
|
1043
1121
|
proofs = {}
|
|
1044
1122
|
for thread, path in selected:
|
|
1045
1123
|
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))
|
|
1124
|
+
session_id=session_id, deliveries=deliveries, goal_assistants=goal_assistants))
|
|
1047
1125
|
budget.check()
|
|
1048
1126
|
return _NativeProof(provider_id, proofs)
|
|
1049
1127
|
|
|
@@ -1051,7 +1129,8 @@ def _prove_native_replays(session_id: str, provider_id: str, events: Path, sourc
|
|
|
1051
1129
|
def _prove_native_source(thread: str, source: Path, root: Path, batches: dict, candidates: list,
|
|
1052
1130
|
native: dict, owners: dict, parse_item: Callable, budget: _NativeReadBudget,
|
|
1053
1131
|
*, session_id: str, deliveries: _AsyncDeliveryIndex,
|
|
1054
|
-
require_verified_checkpoint: bool = False
|
|
1132
|
+
require_verified_checkpoint: bool = False,
|
|
1133
|
+
goal_assistants: _NativeGoalAssistantReplays | None = None) -> dict:
|
|
1055
1134
|
if (not source.is_absolute() or source.is_symlink() or source.suffix != ".jsonl"
|
|
1056
1135
|
or not (source.stem == thread or source.stem.endswith("-" + thread))):
|
|
1057
1136
|
raise _Unproven()
|
|
@@ -1241,6 +1320,15 @@ def _prove_native_source(thread: str, source: Path, root: Path, batches: dict, c
|
|
|
1241
1320
|
if len(proofs) > MAX_TARGETS:
|
|
1242
1321
|
raise _Unproven()
|
|
1243
1322
|
continue
|
|
1323
|
+
goal_origin = timestamp_origins[0] if len(timestamp_origins) == 1 else None
|
|
1324
|
+
goal_match = goal_assistants.match(goal_origin, assistant_native_keys.get(key, ""),
|
|
1325
|
+
before_seq=first, provider_id=thread) if (
|
|
1326
|
+
goal_assistants and goal_origin and kind == "assistant" and source_hash is None) else None
|
|
1327
|
+
if goal_match is not None:
|
|
1328
|
+
proofs[target] = {**goal_origin, "native_event_id": goal_match["id"], "source_text_sha256": body_key}
|
|
1329
|
+
if len(proofs) > MAX_TARGETS:
|
|
1330
|
+
raise _Unproven()
|
|
1331
|
+
continue
|
|
1244
1332
|
if len(source_ids) != 1 or source_hash is not None and key not in full_user_keys:
|
|
1245
1333
|
continue
|
|
1246
1334
|
source_origin = next(iter(source_ids.values()))
|
|
@@ -1450,6 +1538,7 @@ def filter_native_codex_history_items(session_id: str, provider_id: str, events:
|
|
|
1450
1538
|
owners, native, assistant_items, wake_keys, native_count = {}, {}, {}, set(), 0
|
|
1451
1539
|
native_inputs, steered_inputs = {}, {}
|
|
1452
1540
|
deliveries = _AsyncDeliveryIndex()
|
|
1541
|
+
goal_assistants = _NativeGoalAssistantReplays(provider_id)
|
|
1453
1542
|
prove_deliveries = (source_path is not None and root is not None
|
|
1454
1543
|
and isinstance(sync_checkpoint, dict) and callable(parse_item)
|
|
1455
1544
|
and any(item.get("kind") == "user" and isinstance(item.get("text"), str) for item in items))
|
|
@@ -1460,6 +1549,10 @@ def filter_native_codex_history_items(session_id: str, provider_id: str, events:
|
|
|
1460
1549
|
raise _Unproven()
|
|
1461
1550
|
previous_seq = seq
|
|
1462
1551
|
run = event.get("run_id")
|
|
1552
|
+
if event.get("session_id") in (None, "", session_id):
|
|
1553
|
+
goal_assistants.event(event)
|
|
1554
|
+
if native_count + owner_count + len(assistant_items) + deliveries.count + goal_assistants.count > MAX_KEYS:
|
|
1555
|
+
raise _Unproven()
|
|
1463
1556
|
if prove_deliveries and event.get("session_id") in (None, "", session_id):
|
|
1464
1557
|
deliveries.observe(event)
|
|
1465
1558
|
if native_count + owner_count + len(assistant_items) + deliveries.count > MAX_KEYS:
|
|
@@ -1475,6 +1568,16 @@ def filter_native_codex_history_items(session_id: str, provider_id: str, events:
|
|
|
1475
1568
|
owner_count += run not in owned
|
|
1476
1569
|
owned.add(run)
|
|
1477
1570
|
steer_turn = _native_goal_steer_turn(event)
|
|
1571
|
+
if event.get("purpose") == "codex_goal_resume" and not steer_turn:
|
|
1572
|
+
# Keep exact public reply identity for source-prefix ownership,
|
|
1573
|
+
# without granting equal-text credit to every reply in the goal.
|
|
1574
|
+
item_id = _public_assistant_item_id(event)
|
|
1575
|
+
body = event.get("text")
|
|
1576
|
+
if item_id is not None and isinstance(body, str) and body:
|
|
1577
|
+
assistant_items[(run, item_id, _text_key(body))] = _native_event_identity(event)
|
|
1578
|
+
if native_count + owner_count + len(assistant_items) + deliveries.count + goal_assistants.count > MAX_KEYS:
|
|
1579
|
+
raise _Unproven()
|
|
1580
|
+
continue
|
|
1478
1581
|
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
1582
|
body = event.get("prompt") if kind == "user" else event.get("result_text") if event.get("type") == "turn_finished" else event.get("text")
|
|
1480
1583
|
wake_hash = _native_mailbox_wake_hash(event) if kind == "user" else None
|
|
@@ -1499,7 +1602,7 @@ def filter_native_codex_history_items(session_id: str, provider_id: str, events:
|
|
|
1499
1602
|
item_id = _public_assistant_item_id(event)
|
|
1500
1603
|
if item_id is not None and key is not None:
|
|
1501
1604
|
assistant_items[(run, item_id, key[1])] = _native_event_identity(event)
|
|
1502
|
-
if native_count + owner_count + len(assistant_items) + deliveries.count > MAX_KEYS:
|
|
1605
|
+
if native_count + owner_count + len(assistant_items) + deliveries.count + goal_assistants.count > MAX_KEYS:
|
|
1503
1606
|
raise _Unproven()
|
|
1504
1607
|
assistant_item_owners = _native_assistant_item_owners(
|
|
1505
1608
|
assistant_items, {run for runs in owners.values() for run in runs}, provider_id,
|
|
@@ -1545,6 +1648,10 @@ def filter_native_codex_history_items(session_id: str, provider_id: str, events:
|
|
|
1545
1648
|
for index, item in enumerate(items):
|
|
1546
1649
|
budget.check()
|
|
1547
1650
|
origin = item.get("provider_origin")
|
|
1651
|
+
if (item.get("kind") == "assistant" and isinstance(origin, dict)
|
|
1652
|
+
and isinstance(item.get("text"), str) and item.get("source_text_sha256") is None
|
|
1653
|
+
and goal_assistants.match(origin, _text_key(_native_assistant_text(item["text"]))) is not None):
|
|
1654
|
+
continue
|
|
1548
1655
|
runs = owners.get(origin.get("turn_id"), set()) if isinstance(origin, dict) else set()
|
|
1549
1656
|
owned = (isinstance(origin, dict) and origin.get("provider") == "codex"
|
|
1550
1657
|
and origin.get("kind") == item.get("kind") and isinstance(origin.get("event_id"), str)
|
|
@@ -23,7 +23,7 @@ SIDE_INSTRUCTIONS = """Answer questions and explore in this separate side chat w
|
|
|
23
23
|
|
|
24
24
|
Treat inherited messages, tasks, plans, tool calls and approvals as reference material, not current instructions or permission. Follow only requests made in this side chat; do not resume unfinished parent work.
|
|
25
25
|
|
|
26
|
-
Use the thread's existing permissions and available tools, including external tools
|
|
26
|
+
Use the thread's existing permissions and available tools, including external tools and subagents. Delegate side-chat work only to subagents created in this side chat; inherited parent agents belong to the main conversation.
|
|
27
27
|
|
|
28
28
|
Change files, git state, configuration, permissions or other workspace state only when explicitly requested here. Request escalation only when such an explicit mutation requires it. Keep authorized changes limited to the request and preserve ongoing parent work."""
|
|
29
29
|
|
|
@@ -68,8 +68,6 @@ def side_chat_config(parent_config: dict | None = None) -> dict:
|
|
|
68
68
|
if isinstance(servers, dict):
|
|
69
69
|
servers.pop(name, None)
|
|
70
70
|
config.update({
|
|
71
|
-
"features.multi_agent": False, "features.multi_agent_v2": False,
|
|
72
|
-
"agents.enabled": False,
|
|
73
71
|
f"{prefix}.enabled": False, f"{prefix}.required": False,
|
|
74
72
|
# Codex validates transport shape even for a disabled server. Never
|
|
75
73
|
# copy the parent's authenticated helper URL/headers into this child.
|
|
@@ -182,6 +180,9 @@ class NativeCodexSideChat:
|
|
|
182
180
|
self._progress = None
|
|
183
181
|
self._lock = asyncio.Lock()
|
|
184
182
|
self._closed = False
|
|
183
|
+
self._thread_parents: dict[str, str] = {}
|
|
184
|
+
self._owned_threads: set[str] = set()
|
|
185
|
+
self._work_revision = 0
|
|
185
186
|
|
|
186
187
|
@property
|
|
187
188
|
def closed(self) -> bool:
|
|
@@ -193,12 +194,88 @@ class NativeCodexSideChat:
|
|
|
193
194
|
return None
|
|
194
195
|
return deepcopy(list(self._progress.items.values()))
|
|
195
196
|
|
|
197
|
+
def owns_thread(self, thread_id: str) -> bool:
|
|
198
|
+
"""Only the side fork and provider-verified descendants own approvals."""
|
|
199
|
+
return bool(not self._closed and self.thread_id and thread_id != self.parent_thread_id
|
|
200
|
+
and (thread_id == self.thread_id or thread_id in self._owned_threads))
|
|
201
|
+
|
|
202
|
+
def _remember_thread(self, thread):
|
|
203
|
+
if not isinstance(thread, dict):
|
|
204
|
+
return
|
|
205
|
+
thread_id = thread.get("id")
|
|
206
|
+
source = thread.get("source")
|
|
207
|
+
subagent = source.get("subAgent") if isinstance(source, dict) else None
|
|
208
|
+
spawn = subagent.get("thread_spawn") if isinstance(subagent, dict) else None
|
|
209
|
+
parent = spawn.get("parent_thread_id") if isinstance(spawn, dict) else None
|
|
210
|
+
if isinstance(thread_id, str) and isinstance(parent, str) and parent:
|
|
211
|
+
self._thread_parents[thread_id] = parent
|
|
212
|
+
|
|
213
|
+
def _remember_notification(self, notification):
|
|
214
|
+
if notification.get("method") in {"thread/started", "thread/closed", "thread/status/changed", "turn/started", "turn/completed"}:
|
|
215
|
+
self._work_revision += 1
|
|
216
|
+
if notification.get("method") == "thread/started":
|
|
217
|
+
self._remember_thread((notification.get("params") or {}).get("thread"))
|
|
218
|
+
|
|
219
|
+
def background_work_scope(self):
|
|
220
|
+
client = self._client
|
|
221
|
+
if self._closed or client is None or not client.ready or not self.thread_id:
|
|
222
|
+
return None
|
|
223
|
+
return (self, client, client.generation, self.thread_id, self._work_revision)
|
|
224
|
+
|
|
225
|
+
async def has_background_work(self):
|
|
226
|
+
scope = self.background_work_scope()
|
|
227
|
+
if scope is None:
|
|
228
|
+
return False
|
|
229
|
+
_owner, client, _generation, thread_id, _revision = scope
|
|
230
|
+
descendants = await client.list_descendant_threads(thread_id)
|
|
231
|
+
if self.background_work_scope() != scope:
|
|
232
|
+
raise SideQuestionError(409, "Side chat changed during background inspection")
|
|
233
|
+
# This native relationship-filtered API sees descendants even when
|
|
234
|
+
# app-server omitted their thread/started notification.
|
|
235
|
+
for child in descendants:
|
|
236
|
+
child_id = child.get("id")
|
|
237
|
+
status = child.get("status")
|
|
238
|
+
kind = status.get("type") if isinstance(status, dict) else None
|
|
239
|
+
if child_id in {thread_id, self.parent_thread_id} or not isinstance(child_id, str):
|
|
240
|
+
raise SideQuestionError(502, "Codex returned an invalid side descendant")
|
|
241
|
+
if kind == "active":
|
|
242
|
+
return True
|
|
243
|
+
if kind not in {"idle", "notLoaded"}:
|
|
244
|
+
raise SideQuestionError(502, "Codex side descendant activity is unknown")
|
|
245
|
+
return False
|
|
246
|
+
|
|
247
|
+
async def _verify_owned_thread(self, thread_id: str) -> bool:
|
|
248
|
+
if self.owns_thread(thread_id):
|
|
249
|
+
return True
|
|
250
|
+
if not self.thread_id or self._client is None or self._closed:
|
|
251
|
+
return False
|
|
252
|
+
path: set[str] = set()
|
|
253
|
+
current = thread_id
|
|
254
|
+
while current and current not in path and current != self.parent_thread_id:
|
|
255
|
+
if self.owns_thread(current):
|
|
256
|
+
self._owned_threads.update(path)
|
|
257
|
+
return True
|
|
258
|
+
path.add(current)
|
|
259
|
+
if current not in self._thread_parents:
|
|
260
|
+
try:
|
|
261
|
+
thread = await self._client.read_thread(current, include_turns=False)
|
|
262
|
+
except CodexAppServerError:
|
|
263
|
+
return False
|
|
264
|
+
if self._closed or not isinstance(thread, dict) or thread.get("id") != current:
|
|
265
|
+
return False
|
|
266
|
+
self._remember_thread(thread)
|
|
267
|
+
current = self._thread_parents.get(current, "")
|
|
268
|
+
return False
|
|
269
|
+
|
|
196
270
|
async def _handle_server_request(self, request_id, method, params):
|
|
197
|
-
#
|
|
198
|
-
#
|
|
271
|
+
# Provider lineage permits side-chat descendants without granting a
|
|
272
|
+
# parent's inherited tool request or unrelated thread any authority.
|
|
199
273
|
if (self.server_request_handler is not None and not self._closed
|
|
200
|
-
and self.
|
|
201
|
-
and params.get("threadId")
|
|
274
|
+
and self.thread_id is not None
|
|
275
|
+
and isinstance(params.get("threadId"), str)
|
|
276
|
+
and await self._verify_owned_thread(params["threadId"])
|
|
277
|
+
and not self._closed
|
|
278
|
+
and (self._active is not None or params["threadId"] != self.thread_id)):
|
|
202
279
|
return await self.server_request_handler(request_id, method, params)
|
|
203
280
|
return await decline_server_request(request_id, method, params)
|
|
204
281
|
|
|
@@ -241,6 +318,7 @@ class NativeCodexSideChat:
|
|
|
241
318
|
on_process_started=lambda _pid, _group: self._process_started.set(),
|
|
242
319
|
**client_options,
|
|
243
320
|
)
|
|
321
|
+
self._client.add_notification_handler(self._remember_notification)
|
|
244
322
|
await self._client.start()
|
|
245
323
|
if self._closed:
|
|
246
324
|
raise SideQuestionError(409, "Side chat was closed; open a new side chat")
|
|
@@ -18,6 +18,7 @@ draining; this module deliberately contains no process lifecycle state.
|
|
|
18
18
|
|
|
19
19
|
from __future__ import annotations
|
|
20
20
|
|
|
21
|
+
import hashlib
|
|
21
22
|
import json
|
|
22
23
|
import re
|
|
23
24
|
from typing import Any, Iterator
|
|
@@ -31,6 +32,13 @@ CURSOR_SESSION_IDENTIFIER_RE = re.compile(
|
|
|
31
32
|
r"^[A-Za-z0-9][A-Za-z0-9._:-]{0,255}$"
|
|
32
33
|
)
|
|
33
34
|
CURSOR_CALL_ID_MAX_CHARS = 240
|
|
35
|
+
# Cursor 2026.10.22 emits this compound correlation key even for a normal
|
|
36
|
+
# file-read tool. LF is part of the opaque ID, not a second stream event.
|
|
37
|
+
_CURSOR_UUID_PATTERN = r"[0-9a-fA-F]{8}(?:-[0-9a-fA-F]{4}){3}-[0-9a-fA-F]{12}"
|
|
38
|
+
_CURSOR_COMPOSITE_CALL_ID_RE = re.compile(
|
|
39
|
+
rf"call-{_CURSOR_UUID_PATTERN}-[0-9]+\nfc_{_CURSOR_UUID_PATTERN}_[0-9]+"
|
|
40
|
+
)
|
|
41
|
+
_CURSOR_ENCODED_CALL_ID_PREFIX = "cursor-call-sha256:"
|
|
34
42
|
CURSOR_LIFECYCLE_VALUE_MAX = 2_147_483_647
|
|
35
43
|
CURSOR_ANSI_ESCAPE_RE = re.compile(r"\x1b(?:\[[0-?]*[ -/]*[@-~]|\][^\x07]*(?:\x07|\x1b\\))")
|
|
36
44
|
CURSOR_TOOL_SUCCESS_OUTCOMES = (
|
|
@@ -90,7 +98,13 @@ def canonical_cursor_session_id(value: Any) -> str | None:
|
|
|
90
98
|
|
|
91
99
|
|
|
92
100
|
def canonical_cursor_call_id(value: Any) -> str:
|
|
93
|
-
"""
|
|
101
|
+
"""Bound an opaque tool key and encode the observed compound CLI format.
|
|
102
|
+
|
|
103
|
+
Keep the complete key in the digest: stripping LF, keeping only one half,
|
|
104
|
+
or assigning a fresh ID per event could merge distinct tools or orphan a
|
|
105
|
+
completion. The encoded namespace is reserved so literal provider IDs
|
|
106
|
+
cannot collide with it. Arbitrary control characters remain invalid.
|
|
107
|
+
"""
|
|
94
108
|
|
|
95
109
|
if not isinstance(value, str):
|
|
96
110
|
raise CursorEventParseError("tool_call call_id must be a string")
|
|
@@ -98,11 +112,17 @@ def canonical_cursor_call_id(value: Any) -> str:
|
|
|
98
112
|
not value
|
|
99
113
|
or value != value.strip()
|
|
100
114
|
or len(value) > CURSOR_CALL_ID_MAX_CHARS
|
|
101
|
-
or any(ord(character) < 32 or ord(character) == 127 for character in value)
|
|
102
115
|
):
|
|
103
116
|
raise CursorEventParseError(
|
|
104
117
|
"tool_call call_id must be a bounded nonempty identifier"
|
|
105
118
|
)
|
|
119
|
+
composite = _CURSOR_COMPOSITE_CALL_ID_RE.fullmatch(value) is not None
|
|
120
|
+
if not composite and any(ord(character) < 32 or ord(character) == 127 for character in value):
|
|
121
|
+
raise CursorEventParseError(
|
|
122
|
+
"tool_call call_id must be a bounded nonempty identifier"
|
|
123
|
+
)
|
|
124
|
+
if composite or value.startswith(_CURSOR_ENCODED_CALL_ID_PREFIX):
|
|
125
|
+
return _CURSOR_ENCODED_CALL_ID_PREFIX + hashlib.sha256(value.encode("utf-8", "surrogatepass")).hexdigest()
|
|
106
126
|
return value
|
|
107
127
|
|
|
108
128
|
|
|
@@ -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
|
-
|
|
79
|
-
|
|
80
|
-
|
|
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
|
|
404
|
-
# buffered response
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
520
|
-
|
|
533
|
+
try:
|
|
534
|
+
await _close_writer(writer)
|
|
535
|
+
finally:
|
|
536
|
+
self._writers.discard(writer)
|
|
521
537
|
|
|
522
538
|
|
|
523
539
|
class ExecutionGateway:
|