@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.
@@ -0,0 +1,123 @@
1
+ #!/usr/bin/env python3
2
+ """Send a run-scoped notification whose level is chosen by the agent."""
3
+
4
+ from __future__ import annotations
5
+
6
+ import argparse
7
+ import json
8
+ import re
9
+ import sys
10
+ import urllib.error
11
+ import urllib.parse
12
+ import urllib.request
13
+ import uuid
14
+ from typing import Any
15
+
16
+ from agentsdock_emergency import (
17
+ EmergencyCLIError,
18
+ NoRedirectHandler,
19
+ clean_emergency_message,
20
+ nonempty_chat_id,
21
+ required_environment,
22
+ )
23
+
24
+
25
+ def send_notification(
26
+ level: str,
27
+ message: str,
28
+ *,
29
+ authority_file: str | None = None,
30
+ chat_id: str | None = None,
31
+ request_id: str | None = None,
32
+ ) -> dict[str, Any]:
33
+ clean_message = clean_emergency_message(message)
34
+ if not clean_message or len(clean_message) > 500:
35
+ raise EmergencyCLIError("--message must contain 1 to 500 characters")
36
+ if level not in {"normal", "important", "emergency"}:
37
+ raise EmergencyCLIError("--level must be normal, important, or emergency")
38
+ server_url, authority_chat_id, token = required_environment(authority_file, chat_id)
39
+ request_id = request_id or f"note_{uuid.uuid4().hex}"
40
+ if not re.fullmatch(r"[A-Za-z0-9._:-]{8,128}", request_id):
41
+ raise EmergencyCLIError("--request-id is invalid")
42
+ body = json.dumps({"request_id": request_id, "level": level, "message": clean_message},
43
+ separators=(",", ":")).encode("utf-8")
44
+ url = f"{server_url}/api/agent/sessions/{urllib.parse.quote(authority_chat_id, safe='')}/notifications"
45
+ opener = urllib.request.build_opener(urllib.request.ProxyHandler({}), NoRedirectHandler())
46
+ decoded: Any = None
47
+ ambiguous_error: BaseException | None = None
48
+ for attempt in range(2):
49
+ request = urllib.request.Request(
50
+ url, data=body,
51
+ headers={
52
+ "Accept": "application/json",
53
+ "Content-Type": "application/json",
54
+ "X-AgentsDock-Provider-Capability": token,
55
+ **({"X-AgentsDock-Notification-Retry": "1"} if attempt else {}),
56
+ },
57
+ method="POST",
58
+ )
59
+ try:
60
+ with opener.open(request, timeout=30) as response:
61
+ decoded = json.loads(response.read().decode("utf-8"))
62
+ ambiguous_error = None
63
+ break
64
+ except urllib.error.HTTPError as exc:
65
+ raw = exc.read().decode("utf-8", errors="replace")
66
+ try:
67
+ detail = json.loads(raw).get("detail") or raw
68
+ except json.JSONDecodeError:
69
+ detail = raw
70
+ raise EmergencyCLIError(
71
+ f"server rejected notification ({exc.code}): {detail or exc.reason}"
72
+ ) from exc
73
+ except (urllib.error.URLError, TimeoutError, OSError, json.JSONDecodeError) as exc:
74
+ ambiguous_error = exc
75
+ if ambiguous_error is not None:
76
+ reason = getattr(ambiguous_error, "reason", ambiguous_error)
77
+ raise EmergencyCLIError(f"could not confirm whether the notification was sent: {reason}") from ambiguous_error
78
+ if (
79
+ not isinstance(decoded, dict)
80
+ or decoded.get("ok") is not True
81
+ or decoded.get("chat_id") != authority_chat_id
82
+ or decoded.get("level") != level
83
+ or not isinstance(decoded.get("event_id"), str)
84
+ or not decoded["event_id"]
85
+ or not isinstance(decoded.get("event_seq"), int)
86
+ or isinstance(decoded["event_seq"], bool)
87
+ or decoded["event_seq"] <= 0
88
+ or not isinstance(decoded.get("duplicate"), bool)
89
+ ):
90
+ raise EmergencyCLIError("AgentsServer returned an invalid notification receipt")
91
+ return decoded
92
+
93
+
94
+ def build_parser() -> argparse.ArgumentParser:
95
+ parser = argparse.ArgumentParser(description="Notify the user from the current AgentsDock turn", allow_abbrev=False)
96
+ parser.add_argument("--authority-file")
97
+ parser.add_argument("--chat-id", type=nonempty_chat_id)
98
+ commands = parser.add_subparsers(dest="command", required=True)
99
+ send = commands.add_parser("send", allow_abbrev=False)
100
+ send.add_argument("--level", required=True, choices=("normal", "important", "emergency"))
101
+ send.add_argument("--message", required=True)
102
+ send.add_argument("--request-id")
103
+ return parser
104
+
105
+
106
+ def main(argv: list[str] | None = None) -> int:
107
+ args = build_parser().parse_args(argv)
108
+ try:
109
+ result = send_notification(
110
+ args.level, args.message,
111
+ authority_file=args.authority_file,
112
+ chat_id=args.chat_id,
113
+ request_id=args.request_id,
114
+ )
115
+ except EmergencyCLIError as exc:
116
+ print(f"error: {exc}", file=sys.stderr)
117
+ return 1
118
+ print(json.dumps(result, indent=2, sort_keys=True))
119
+ return 0
120
+
121
+
122
+ if __name__ == "__main__":
123
+ raise SystemExit(main())
@@ -136,6 +136,17 @@ def _message(row: sqlite3.Row) -> dict:
136
136
  return message
137
137
 
138
138
 
139
+ def validate_message_response_size(message: dict, *, now: str) -> None:
140
+ """Require the complete readable message to fit with response metadata."""
141
+ readable = {**message, "read_id": "mailread_" + "0" * 32, "read_at": now}
142
+ try:
143
+ size = len(json.dumps(readable, ensure_ascii=False, separators=(",", ":")).encode("utf-8"))
144
+ except UnicodeEncodeError as exc:
145
+ raise MailboxConflict("Message and user delegation must be valid UTF-8") from exc
146
+ if 8192 + size > MAX_PAGE_BYTES:
147
+ raise MailboxConflict("Message and source user instruction exceed the bounded mailbox response")
148
+
149
+
139
150
  def store_message(connection: sqlite3.Connection, message_id: str, *, now: str,
140
151
  in_reply_to_message_id: str | None = None) -> dict:
141
152
  """Register one already-authorized stored envelope in the same transaction."""
@@ -173,13 +184,7 @@ def store_message(connection: sqlite3.Connection, message_id: str, *, now: str,
173
184
  raise MailboxConflict("Stored mailbox identity changed")
174
185
  message = _message(row)
175
186
  # Include all provenance in the same bounded response before accepting.
176
- readable = {**message, "read_id": "mailread_" + "0" * 32, "read_at": now}
177
- try:
178
- size = len(json.dumps(readable, ensure_ascii=False, separators=(",", ":")).encode("utf-8"))
179
- except UnicodeEncodeError as exc:
180
- raise MailboxConflict("Message and user delegation must be valid UTF-8") from exc
181
- if 8192 + size > MAX_PAGE_BYTES:
182
- raise MailboxConflict("Message and source user instruction exceed the bounded mailbox response")
187
+ validate_message_response_size(message, now=now)
183
188
  return message
184
189
 
185
190
 
@@ -0,0 +1,158 @@
1
+ """Keep native Claude child messages separate from AgentsDock chat routes.
2
+
3
+ Native SendMessage also accepts local/cloud sessions and display names. Only
4
+ identities observed in the provider's SubagentStart hooks may use that tool;
5
+ AgentsDock recipients must use the separately authorized provider helper.
6
+ The same policy runs as SDK callbacks and as print-mode command hooks.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import hashlib
12
+ import json
13
+ import os
14
+ from pathlib import Path
15
+ import shlex
16
+ import stat
17
+ import sys
18
+ from typing import Any
19
+
20
+
21
+ NATIVE_CHAT_TOOL_MATCHER = "^(ListAgents|ListPeers|SendMessage)$"
22
+ CHAT_ROUTING_REASON = (
23
+ "Not sent or listed. Native Claude messaging is not AgentsDock chat routing. "
24
+ "For an AgentsDock @Chat, use the run-bound AgentsDock provider tool with "
25
+ "helper=chats and the exact server-issued route/target index (or the authorized "
26
+ "helper CLI in print mode). Never substitute a similarly named Claude session. "
27
+ "Native SendMessage is only for a child of this Claude session: use its exact "
28
+ "agent ID from Agent/Task, or main when replying from that child. A native "
29
+ "success is not an AgentsDock delivery receipt."
30
+ )
31
+
32
+
33
+ def denied() -> dict[str, Any]:
34
+ return {"hookSpecificOutput": {
35
+ "hookEventName": "PreToolUse",
36
+ "permissionDecision": "deny",
37
+ "permissionDecisionReason": CHAT_ROUTING_REASON,
38
+ }}
39
+
40
+
41
+ def identity(value: Any) -> str:
42
+ # These are provider hook fields, never IDs asserted in the message body.
43
+ if not isinstance(value, str) or not value or len(value) > 200:
44
+ return ""
45
+ if any(not (c.isascii() and (c.isalnum() or c in "_-")) for c in value):
46
+ return ""
47
+ return value
48
+
49
+
50
+ class ClaudeChatRouting:
51
+ def __init__(self, registry: Path | None = None) -> None:
52
+ self.registry = registry
53
+ self.children: set[tuple[str, str]] = set()
54
+
55
+ def _marker(self, session: str, agent: str) -> Path:
56
+ assert self.registry is not None
57
+ digest = hashlib.sha256(f"{session}\0{agent}".encode()).hexdigest()
58
+ return self.registry / digest
59
+
60
+ def _private_registry(self) -> None:
61
+ assert self.registry is not None
62
+ self.registry.mkdir(mode=0o700, exist_ok=True)
63
+ info = self.registry.lstat()
64
+ if not stat.S_ISDIR(info.st_mode):
65
+ raise ValueError("Invalid Claude child registry")
66
+ if os.name != "nt" and (info.st_uid != os.getuid() or info.st_mode & 0o077):
67
+ raise ValueError("Claude child registry must be private")
68
+
69
+ def record_child(self, event: dict[str, Any]) -> dict[str, Any]:
70
+ session, agent = identity(event.get("session_id")), identity(event.get("agent_id"))
71
+ if event.get("hook_event_name") != "SubagentStart" or not session or not agent:
72
+ return {}
73
+ if self.registry is None:
74
+ self.children.add((session, agent))
75
+ else:
76
+ self._private_registry()
77
+ # One immutable empty marker per provider-owned child. Concurrent
78
+ # hooks do not overwrite one another or store conversation text.
79
+ try:
80
+ fd = os.open(self._marker(session, agent), os.O_CREAT | os.O_EXCL | os.O_WRONLY,
81
+ 0o600)
82
+ except FileExistsError:
83
+ pass
84
+ else:
85
+ os.close(fd)
86
+ return {}
87
+
88
+ def _owns(self, session: str, agent: str) -> bool:
89
+ if not session or not agent:
90
+ return False
91
+ if self.registry is None:
92
+ return (session, agent) in self.children
93
+ self._private_registry()
94
+ try:
95
+ info = self._marker(session, agent).lstat()
96
+ except FileNotFoundError:
97
+ return False
98
+ return (stat.S_ISREG(info.st_mode) and info.st_size == 0 and info.st_nlink == 1
99
+ and (os.name == "nt" or (info.st_uid == os.getuid() and not info.st_mode & 0o077)))
100
+
101
+ def before_tool(self, event: dict[str, Any]) -> dict[str, Any]:
102
+ name = event.get("tool_name")
103
+ if name not in {"SendMessage", "ListAgents", "ListPeers"}:
104
+ return {}
105
+ if name != "SendMessage":
106
+ return denied()
107
+ data = event.get("tool_input")
108
+ if not isinstance(data, dict):
109
+ return denied()
110
+ # Claude changed recipient/content to to/message. Do not accept
111
+ # disagreeing legacy fields, broadcasts, socket addresses or names.
112
+ target = data.get("to", data.get("recipient"))
113
+ if "to" in data and "recipient" in data and data["to"] != data["recipient"]:
114
+ return denied()
115
+ session = identity(event.get("session_id"))
116
+ sender = identity(event.get("agent_id"))
117
+ try:
118
+ if target == "main" and self._owns(session, sender):
119
+ return {}
120
+ if self._owns(session, identity(target)):
121
+ # Defer to native permissions; never auto-approve a child tool.
122
+ return {}
123
+ except (OSError, ValueError):
124
+ pass
125
+ return denied()
126
+
127
+ async def subagent_start(self, event: dict[str, Any], *_: Any) -> dict[str, Any]:
128
+ return self.record_child(event)
129
+
130
+ async def pre_tool_use(self, event: dict[str, Any], *_: Any) -> dict[str, Any]:
131
+ return self.before_tool(event)
132
+
133
+
134
+ def print_routing_settings(manifest: Path) -> dict[str, Any]:
135
+ registry = manifest.with_name("claude-child-routing")
136
+ # Claude command hooks run through the user's shell. No authority or
137
+ # endpoint credentials appear in this command or in its registry.
138
+ command = shlex.join([sys.executable, str(Path(__file__).resolve()), str(registry)])
139
+ hook = {"type": "command", "command": command, "timeout": 5}
140
+ return {"hooks": {
141
+ "SubagentStart": [{"hooks": [hook]}],
142
+ "PreToolUse": [{"matcher": NATIVE_CHAT_TOOL_MATCHER, "hooks": [hook]}],
143
+ }}
144
+
145
+
146
+ def main() -> None:
147
+ try:
148
+ event = json.loads(sys.stdin.buffer.read(1024 * 1024 + 1))
149
+ policy = ClaudeChatRouting(Path(sys.argv[1]))
150
+ result = (policy.record_child(event) if event.get("hook_event_name") == "SubagentStart"
151
+ else policy.before_tool(event))
152
+ except (OSError, ValueError, TypeError, AttributeError, IndexError):
153
+ result = denied()
154
+ print(json.dumps(result))
155
+
156
+
157
+ if __name__ == "__main__":
158
+ main()
@@ -117,7 +117,8 @@ class ClaudeGoalProjection:
117
117
  A native set sentinel establishes the goal. Evaluator and clear records
118
118
  update that exact condition; unrelated sessions/sidechains cannot establish
119
119
  or finish it. A fork starts empty until its own native set evidence arrives.
120
- No failure, pause, or success is inferred from a result/assistant message.
120
+ Native failed evaluations are terminal. No failure, pause, or success is
121
+ inferred from a result/assistant message.
121
122
  """
122
123
 
123
124
  def __init__(self, provider_session_id: str):
@@ -162,6 +163,7 @@ class ClaudeGoalProjection:
162
163
  timestamp = _timestamp_ms(event.get("timestamp"))
163
164
  condition = attachment.get("condition")
164
165
  met = attachment.get("met")
166
+ failed = attachment.get("failed", False)
165
167
  sentinel = attachment.get("sentinel", False)
166
168
  if (
167
169
  timestamp is None or timestamp < self._last_timestamp
@@ -169,6 +171,7 @@ class ClaudeGoalProjection:
169
171
  or not isinstance(condition, str) or not condition.strip()
170
172
  or len(condition) > 16_384
171
173
  or type(met) is not bool or type(sentinel) is not bool
174
+ or type(failed) is not bool or failed and (met or sentinel)
172
175
  ):
173
176
  return False
174
177
  previous = self.goal
@@ -180,7 +183,7 @@ class ClaudeGoalProjection:
180
183
  if not sentinel and previous["status"] != "active":
181
184
  return False
182
185
  goal = dict(previous)
183
- goal["status"] = "cleared" if sentinel else "achieved" if met else "active"
186
+ goal["status"] = "cleared" if sentinel else "failed" if failed else "achieved" if met else "active"
184
187
  if stopped:
185
188
  goal["execution_stop_reason"] = "continuation_limit"
186
189
  goal["execution_stopped_at"] = timestamp
@@ -72,15 +72,17 @@ def _stamp(path: Path) -> tuple[int, int, int, int]:
72
72
  return value
73
73
 
74
74
 
75
- def _records(path: Path, expected: tuple[int, int, int, int]):
75
+ def _records(path: Path, expected: tuple[int, int, int, int], *, allow_nul_padding=False):
76
76
  descriptor = os.open(path, os.O_RDONLY | getattr(os, "O_NOFOLLOW", 0))
77
77
  with os.fdopen(descriptor, "rb") as stream:
78
78
  info = os.fstat(stream.fileno())
79
79
  if (info.st_dev, info.st_ino, info.st_size, info.st_mtime_ns) != expected:
80
80
  raise _Unproven()
81
81
  try:
82
- yield from jsonl_records(stream, end=expected[2], strict=True,
83
- max_records=MAX_RECORDS, max_retained_bytes=MAX_LINE_BYTES)
82
+ for event, offset, raw in jsonl_records(stream, end=expected[2], strict=True,
83
+ max_records=MAX_RECORDS, max_retained_bytes=MAX_LINE_BYTES,
84
+ allow_nul_padding=allow_nul_padding):
85
+ yield event if event is not None else {}, offset, raw
84
86
  except ValueError as exc:
85
87
  raise _Unproven() from exc
86
88
  final = os.fstat(stream.fileno())
@@ -163,6 +165,9 @@ class _AssistantReplays:
163
165
  self.source_display, self.source_message_counts = {}, {}
164
166
  self.source_parents, self.source_users, self.source_input = OrderedDict(), {}, {}
165
167
  self.source_commands, self.local_command_prompts = {}, {}
168
+ self.goal_history = ClaudeGoalHistoryNormalizer()
169
+ self.goal_input_parents = {}
170
+ self.goal_input_prompts = {}
166
171
 
167
172
  def display_key(self, text: str) -> str | None:
168
173
  if self.normalize_assistant is None:
@@ -206,9 +211,18 @@ class _AssistantReplays:
206
211
  part["text"] for part in content if isinstance(part, dict) and part.get("type") == "text"
207
212
  and isinstance(part.get("text"), str)) if isinstance(content, list) else ""
208
213
  parent_input = self.source_parents.get(event.get("parentUuid"))
214
+ normalized_goal = self.goal_history.consume(event)
209
215
  tool_result = isinstance(content, list) and any(isinstance(part, dict) and part.get("type") == "tool_result" for part in content)
210
216
  if event.get("type") == "user" and event.get("isMeta") is not True and text.strip() and not tool_result:
211
217
  self.source_users.setdefault(identity, []).append((offset, _text_key(text.strip())))
218
+ if normalized_goal is not event:
219
+ self.goal_input_prompts[identity] = normalized_goal["message"]["content"]
220
+ if normalized_goal is not event and parent_input is not None:
221
+ # A native goal command may sit between a submitted question
222
+ # and its first reply without creating another server run.
223
+ # Retain only the sentinel-proven command's exact ancestry;
224
+ # ordinary user input or slash-looking quotes are boundaries.
225
+ self.goal_input_parents[identity] = parent_input
212
226
  command = re.fullmatch(
213
227
  r"<command-name>/([A-Za-z0-9_][A-Za-z0-9_.:-]{0,127})</command-name>\s*"
214
228
  r"<command-message>\1</command-message>\s*<command-args>([\s\S]*)</command-args>",
@@ -302,10 +316,25 @@ class _AssistantReplays:
302
316
  (CLAUDE_SDK_LITERAL_MESSAGE_PREFIX + matches[0]).strip()))
303
317
  # A native local-command result owns its XML input only when the
304
318
  # commandRun metadata, source wrapper and original prompt agree.
305
- command_match = (identity in self.local_command_prompts
306
- and self.local_command_prompts[identity] == matches[0])
319
+ command_match = ((identity in self.local_command_prompts
320
+ and self.local_command_prompts[identity] == matches[0])
321
+ or (source_input in self.goal_input_prompts
322
+ and self.goal_input_prompts[source_input] == matches[0]))
323
+ visited = set()
324
+ while (len(inputs) == 1 and inputs[0][1] not in expected_inputs and not command_match
325
+ and source_input in self.goal_input_parents and source_input not in visited
326
+ and len(visited) < 32):
327
+ visited.add(source_input)
328
+ source_input = self.goal_input_parents[source_input]
329
+ inputs = self.source_users.get(source_input, ())
307
330
  if len(inputs) == 1 and (inputs[0][1] in expected_inputs or command_match):
308
331
  users.add((source_input, inputs[0][1], inputs[0][0]))
332
+ if command_match:
333
+ # Goal history can already contain the canonical slash
334
+ # command instead of the source XML. The exact native
335
+ # output UUID, input ancestry and commandRun/goal sentinel
336
+ # prove this alias; another equal occurrence cannot.
337
+ users.add((source_input, _text_key(matches[0]), inputs[0][0]))
309
338
  return assistants, users
310
339
 
311
340
  def prove(self, eligible: dict) -> frozenset:
@@ -490,6 +519,81 @@ class _AsyncDeliveryInputs:
490
519
  return targets
491
520
 
492
521
 
522
+ class _ScheduledJobInputs(_AsyncDeliveryInputs):
523
+ """Complete scheduled occurrence plus exact source identity and full input."""
524
+
525
+ def __init__(self, *args):
526
+ super().__init__(*args)
527
+ self.prompt_hashes = None
528
+
529
+ def source(self, event, offset):
530
+ if self.prompt_hashes is None:
531
+ self.prompt_hashes = {_text_key(" ".join(start["prompt"].split()))
532
+ for starts in self.native.starts.values() for start in starts
533
+ if start.get("purpose") == "scheduled_job" and start.get("job_id")
534
+ and isinstance(start.get("prompt"), str) and len(start["prompt"]) <= MAX_TEXT_CHARS}
535
+ if not self.prompt_hashes:
536
+ return
537
+ if event.get("type") != "user" or event.get("sessionId") != self.provider_id or self.normalize_full_user is None:
538
+ return
539
+ identity = (event.get("uuid"), self.provider_id, event.get("timestamp"))
540
+ if not all(isinstance(value, str) and 0 < len(value) <= 256 for value in identity):
541
+ return
542
+ self.source_counts[identity] = self.source_counts.get(identity, 0) + 1
543
+ if len(self.source_counts) > MAX_KEYS:
544
+ raise _Unproven()
545
+ if (any(event.get(key) is True for key in ("isMeta", "isCompactSummary", "isSidechain", "provider_user_authored"))
546
+ or any(event.get(key) for key in ("clientUserMessageId", "clientId", "client_user_message_id", "client_id"))):
547
+ return
548
+ full, display = self.normalize_full_user(event), self.normalize_user(event)
549
+ if (isinstance(full, str) and full and len(full) <= MAX_TEXT_CHARS
550
+ and isinstance(display, str) and display and _timestamp(identity[2]) is not None):
551
+ digest = _text_key(" ".join(full.split()))
552
+ if digest in self.prompt_hashes:
553
+ self.sources.setdefault(digest, []).append((identity, _text_key(display), offset))
554
+ if len(self.source_counts) + len(self.sources) > MAX_KEYS:
555
+ raise _Unproven()
556
+
557
+ def prove(self, eligible):
558
+ matches, credits, candidate_counts = {}, {}, {}
559
+ for target, identity in self.candidates:
560
+ candidate_counts[(target[1], identity)] = candidate_counts.get((target[1], identity), 0) + 1
561
+ for run, starts in self.native.starts.items():
562
+ ends = self.native.ends.get(run, ())
563
+ if len(starts) != 1 or len(ends) != 1:
564
+ continue
565
+ start, end = starts[0], ends[0]
566
+ owners = (start, end, *self.native.owners.get(run, ()))
567
+ provider_ids = {row.get("provider_session_id") for row in owners
568
+ if row.get("provider_session_id") not in (None, "")}
569
+ first, last = _timestamp(start.get("ts")), _timestamp(end.get("ts"))
570
+ prompt = start.get("prompt")
571
+ if (start.get("purpose") != "scheduled_job" or not start.get("job_id")
572
+ or not isinstance(prompt, str) or not prompt or len(prompt) > MAX_TEXT_CHARS
573
+ or provider_ids != {self.provider_id}
574
+ or first is None or last is None or first > last
575
+ or type(start.get("seq")) is not int or type(end.get("seq")) is not int
576
+ or start["seq"] >= end["seq"]
577
+ or any(type(row.get("seq")) is not int or not start["seq"] <= row["seq"] <= end["seq"]
578
+ for row in self.native.owners.get(run, ()))):
579
+ continue
580
+ for identity, key, offset in self.sources.get(_text_key(" ".join(prompt.split())), ()):
581
+ timestamp = _timestamp(identity[2])
582
+ if self.source_counts.get(identity) != 1 or timestamp is None or not first <= timestamp <= last:
583
+ continue
584
+ matches.setdefault((identity, key), []).append((run, offset))
585
+ credits[run] = credits.get(run, 0) + 1
586
+ targets = set()
587
+ for target, identity in self.candidates:
588
+ seq, run, key = target
589
+ batch, matched = eligible.get(run), matches.get((identity, key), ())
590
+ if batch and len(matched) == 1 and candidate_counts[(run, identity)] == 1 and credits.get(matched[0][0]) == 1:
591
+ first, last, start, end = batch[:4]
592
+ if first < seq < last and start < matched[0][1] <= end:
593
+ targets.add(target)
594
+ return targets
595
+
596
+
493
597
  class _MailboxWakeInputs(_AsyncDeliveryInputs):
494
598
  """Exact generated native input hash, current provider and checkpoint identity."""
495
599
  def __init__(self, *args):
@@ -615,20 +719,24 @@ def filter_native_claude_mailbox_wake_items(
615
719
  or not isinstance(previous, str) or not _DIGEST.fullmatch(previous))):
616
720
  return items
617
721
  proof = _MailboxWakeInputs(provider_id, native, normalize_user, normalize_full_user)
722
+ scheduled = _ScheduledJobInputs(provider_id, native, normalize_user, normalize_full_user)
618
723
  # Temporary proof coordinates only; no synthetic event is persisted.
619
724
  batch = "import_mailbox_wake_filter"
620
725
  assistant_targets = {}
621
726
  for index, item in enumerate(items, 1):
622
- if item.get("kind") == "user" and item.get("source_text_sha256") is None:
623
- proof.event({**item, "seq": index, "run_id": batch, "type": "turn_started",
624
- "backend": "claude", "imported": True, "prompt": item.get("text")})
727
+ if item.get("kind") == "user":
728
+ candidate = {**item, "seq": index, "run_id": batch, "type": "turn_started",
729
+ "backend": "claude", "imported": True, "prompt": item.get("text")}
730
+ scheduled.event(candidate)
731
+ if item.get("source_text_sha256") is None:
732
+ proof.event(candidate)
625
733
  elif item.get("kind") == "assistant":
626
734
  candidate = {**item, "seq": index, "run_id": batch, "type": "assistant_text",
627
735
  "backend": "claude", "imported": True}
628
736
  native.event(candidate)
629
737
  assistant_targets[index] = _assistant_target(candidate)
630
738
  digest, verified = hashlib.sha256(), set()
631
- for event, offset, line in _records(source, source_stamp):
739
+ for event, offset, line in _records(source, source_stamp, allow_nul_padding=True):
632
740
  line.update_hash(digest)
633
741
  if offset == start and hmac.compare_digest(digest.hexdigest(), previous):
634
742
  verified.add(start)
@@ -636,11 +744,13 @@ def filter_native_claude_mailbox_wake_items(
636
744
  verified.add(end)
637
745
  if offset <= end:
638
746
  proof.source(event, offset)
747
+ scheduled.source(event, offset)
639
748
  native.source(event, offset)
640
749
  if end not in verified or start and start not in verified:
641
750
  return items
642
751
  eligible = {batch: (0, len(items) + 1, start, end)}
643
752
  targets, assistant_replays = proof.prove(eligible), native.prove(eligible)
753
+ targets.update(scheduled.prove(eligible))
644
754
  _assistants, owned_inputs = native.exact_owned_sources()
645
755
  projected = []
646
756
  for index, item in enumerate(items, 1):
@@ -956,7 +1066,7 @@ def _prove(session_id: str, provider_id: str, events: Path, root: Path,
956
1066
  if start_time is not None and end_time is not None and start_time <= end_time:
957
1067
  scheduled_ranges.setdefault(key, []).append((run, start_time, end_time))
958
1068
  scheduled_sources, scheduled_counts = {}, {}
959
- for event, offset, line in _records(source, source_stamp):
1069
+ for event, offset, line in _records(source, source_stamp, allow_nul_padding=True):
960
1070
  line.update_hash(digest)
961
1071
  for wanted in prefix_digests.get(offset, ()):
962
1072
  if hmac.compare_digest(digest.hexdigest(), wanted):
@@ -1119,7 +1229,7 @@ def _prove(session_id: str, provider_id: str, events: Path, root: Path,
1119
1229
  tuple(corrected), frozenset(companions), proven_assistants, tuple(goal_commands))
1120
1230
 
1121
1231
 
1122
- def _bounded_records(path: Path, expected, start: int, end: int):
1232
+ def _bounded_records(path: Path, expected, start: int, end: int, *, allow_nul_padding=False):
1123
1233
  """Read complete records in one fixed window, never the oversized prefix."""
1124
1234
  if not 0 <= start < end <= expected[2] or end - start > MAX_EVENTS_BYTES:
1125
1235
  raise _Unproven()
@@ -1144,8 +1254,9 @@ def _bounded_records(path: Path, expected, start: int, end: int):
1144
1254
  raise _Unproven()
1145
1255
  try:
1146
1256
  for event, offset, _raw in jsonl_records(stream, end=end, strict=True,
1147
- deadline=deadline, max_records=MAX_RECORDS, max_retained_bytes=MAX_LINE_BYTES):
1148
- yield event, offset
1257
+ deadline=deadline, max_records=MAX_RECORDS, max_retained_bytes=MAX_LINE_BYTES,
1258
+ allow_nul_padding=allow_nul_padding):
1259
+ yield event if event is not None else {}, offset
1149
1260
  except ValueError as exc:
1150
1261
  raise _Unproven() from exc
1151
1262
  final = os.fstat(stream.fileno())
@@ -1280,7 +1391,7 @@ def _prove_recent_scheduled(session_id: str, provider_id: str, events: Path, roo
1280
1391
  if start_time is not None and end_time is not None and start_time <= end_time:
1281
1392
  ranges.setdefault(key, []).append((run, start_time, end_time))
1282
1393
  source_matches, occurrence_counts, identity_counts, source_metadata = {}, {}, {}, {}
1283
- for event, offset in _bounded_records(source, source_stamp, window_start, checkpoint_end):
1394
+ for event, offset in _bounded_records(source, source_stamp, window_start, checkpoint_end, allow_nul_padding=True):
1284
1395
  assistant_replays.source(event, offset)
1285
1396
  async_inputs.source(event, offset)
1286
1397
  wake_inputs.source(event, offset)