@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.
@@ -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())
@@ -140,8 +142,19 @@ def _async_delivery_identity(event: dict) -> tuple | None:
140
142
 
141
143
 
142
144
  def _mailbox_wake_identity(event: dict) -> tuple | None:
145
+ # Both forms are internal inputs. The exact native source, run ownership,
146
+ # and checkpoint still have to match before either one can be hidden.
143
147
  claim, cutoff, digest = (event.get(key) for key in (
144
148
  "mailbox_wake_id", "mailbox_wake_through_seq", "provider_input_sha256"))
149
+ if (event.get("purpose") == "server_update_continuation"
150
+ and event.get("provider_generated") is True and event.get("prompt") == ""
151
+ and event.get("provider_user_authored") is not True
152
+ and not any(event.get(key) for key in (
153
+ "clientUserMessageId", "clientId", "client_user_message_id", "client_id"))
154
+ and isinstance(event.get("queued_id"), str)
155
+ and re.fullmatch(r"queued_[a-f0-9]{16}", event["queued_id"])
156
+ and isinstance(digest, str) and _DIGEST.fullmatch(digest)):
157
+ return event["queued_id"], 0, digest
145
158
  if (event.get("purpose") != "chat_mailbox_wake" or event.get("provider_generated") is not True
146
159
  or event.get("prompt") != ""
147
160
  or event.get("provider_user_authored") is True
@@ -163,6 +176,9 @@ class _AssistantReplays:
163
176
  self.source_display, self.source_message_counts = {}, {}
164
177
  self.source_parents, self.source_users, self.source_input = OrderedDict(), {}, {}
165
178
  self.source_commands, self.local_command_prompts = {}, {}
179
+ self.goal_history = ClaudeGoalHistoryNormalizer()
180
+ self.goal_input_parents = {}
181
+ self.goal_input_prompts = {}
166
182
 
167
183
  def display_key(self, text: str) -> str | None:
168
184
  if self.normalize_assistant is None:
@@ -206,9 +222,18 @@ class _AssistantReplays:
206
222
  part["text"] for part in content if isinstance(part, dict) and part.get("type") == "text"
207
223
  and isinstance(part.get("text"), str)) if isinstance(content, list) else ""
208
224
  parent_input = self.source_parents.get(event.get("parentUuid"))
225
+ normalized_goal = self.goal_history.consume(event)
209
226
  tool_result = isinstance(content, list) and any(isinstance(part, dict) and part.get("type") == "tool_result" for part in content)
210
227
  if event.get("type") == "user" and event.get("isMeta") is not True and text.strip() and not tool_result:
211
228
  self.source_users.setdefault(identity, []).append((offset, _text_key(text.strip())))
229
+ if normalized_goal is not event:
230
+ self.goal_input_prompts[identity] = normalized_goal["message"]["content"]
231
+ if normalized_goal is not event and parent_input is not None:
232
+ # A native goal command may sit between a submitted question
233
+ # and its first reply without creating another server run.
234
+ # Retain only the sentinel-proven command's exact ancestry;
235
+ # ordinary user input or slash-looking quotes are boundaries.
236
+ self.goal_input_parents[identity] = parent_input
212
237
  command = re.fullmatch(
213
238
  r"<command-name>/([A-Za-z0-9_][A-Za-z0-9_.:-]{0,127})</command-name>\s*"
214
239
  r"<command-message>\1</command-message>\s*<command-args>([\s\S]*)</command-args>",
@@ -302,10 +327,25 @@ class _AssistantReplays:
302
327
  (CLAUDE_SDK_LITERAL_MESSAGE_PREFIX + matches[0]).strip()))
303
328
  # A native local-command result owns its XML input only when the
304
329
  # 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])
330
+ command_match = ((identity in self.local_command_prompts
331
+ and self.local_command_prompts[identity] == matches[0])
332
+ or (source_input in self.goal_input_prompts
333
+ and self.goal_input_prompts[source_input] == matches[0]))
334
+ visited = set()
335
+ while (len(inputs) == 1 and inputs[0][1] not in expected_inputs and not command_match
336
+ and source_input in self.goal_input_parents and source_input not in visited
337
+ and len(visited) < 32):
338
+ visited.add(source_input)
339
+ source_input = self.goal_input_parents[source_input]
340
+ inputs = self.source_users.get(source_input, ())
307
341
  if len(inputs) == 1 and (inputs[0][1] in expected_inputs or command_match):
308
342
  users.add((source_input, inputs[0][1], inputs[0][0]))
343
+ if command_match:
344
+ # Goal history can already contain the canonical slash
345
+ # command instead of the source XML. The exact native
346
+ # output UUID, input ancestry and commandRun/goal sentinel
347
+ # prove this alias; another equal occurrence cannot.
348
+ users.add((source_input, _text_key(matches[0]), inputs[0][0]))
309
349
  return assistants, users
310
350
 
311
351
  def prove(self, eligible: dict) -> frozenset:
@@ -490,6 +530,81 @@ class _AsyncDeliveryInputs:
490
530
  return targets
491
531
 
492
532
 
533
+ class _ScheduledJobInputs(_AsyncDeliveryInputs):
534
+ """Complete scheduled occurrence plus exact source identity and full input."""
535
+
536
+ def __init__(self, *args):
537
+ super().__init__(*args)
538
+ self.prompt_hashes = None
539
+
540
+ def source(self, event, offset):
541
+ if self.prompt_hashes is None:
542
+ self.prompt_hashes = {_text_key(" ".join(start["prompt"].split()))
543
+ for starts in self.native.starts.values() for start in starts
544
+ if start.get("purpose") == "scheduled_job" and start.get("job_id")
545
+ and isinstance(start.get("prompt"), str) and len(start["prompt"]) <= MAX_TEXT_CHARS}
546
+ if not self.prompt_hashes:
547
+ return
548
+ if event.get("type") != "user" or event.get("sessionId") != self.provider_id or self.normalize_full_user is None:
549
+ return
550
+ identity = (event.get("uuid"), self.provider_id, event.get("timestamp"))
551
+ if not all(isinstance(value, str) and 0 < len(value) <= 256 for value in identity):
552
+ return
553
+ self.source_counts[identity] = self.source_counts.get(identity, 0) + 1
554
+ if len(self.source_counts) > MAX_KEYS:
555
+ raise _Unproven()
556
+ if (any(event.get(key) is True for key in ("isMeta", "isCompactSummary", "isSidechain", "provider_user_authored"))
557
+ or any(event.get(key) for key in ("clientUserMessageId", "clientId", "client_user_message_id", "client_id"))):
558
+ return
559
+ full, display = self.normalize_full_user(event), self.normalize_user(event)
560
+ if (isinstance(full, str) and full and len(full) <= MAX_TEXT_CHARS
561
+ and isinstance(display, str) and display and _timestamp(identity[2]) is not None):
562
+ digest = _text_key(" ".join(full.split()))
563
+ if digest in self.prompt_hashes:
564
+ self.sources.setdefault(digest, []).append((identity, _text_key(display), offset))
565
+ if len(self.source_counts) + len(self.sources) > MAX_KEYS:
566
+ raise _Unproven()
567
+
568
+ def prove(self, eligible):
569
+ matches, credits, candidate_counts = {}, {}, {}
570
+ for target, identity in self.candidates:
571
+ candidate_counts[(target[1], identity)] = candidate_counts.get((target[1], identity), 0) + 1
572
+ for run, starts in self.native.starts.items():
573
+ ends = self.native.ends.get(run, ())
574
+ if len(starts) != 1 or len(ends) != 1:
575
+ continue
576
+ start, end = starts[0], ends[0]
577
+ owners = (start, end, *self.native.owners.get(run, ()))
578
+ provider_ids = {row.get("provider_session_id") for row in owners
579
+ if row.get("provider_session_id") not in (None, "")}
580
+ first, last = _timestamp(start.get("ts")), _timestamp(end.get("ts"))
581
+ prompt = start.get("prompt")
582
+ if (start.get("purpose") != "scheduled_job" or not start.get("job_id")
583
+ or not isinstance(prompt, str) or not prompt or len(prompt) > MAX_TEXT_CHARS
584
+ or provider_ids != {self.provider_id}
585
+ or first is None or last is None or first > last
586
+ or type(start.get("seq")) is not int or type(end.get("seq")) is not int
587
+ or start["seq"] >= end["seq"]
588
+ or any(type(row.get("seq")) is not int or not start["seq"] <= row["seq"] <= end["seq"]
589
+ for row in self.native.owners.get(run, ()))):
590
+ continue
591
+ for identity, key, offset in self.sources.get(_text_key(" ".join(prompt.split())), ()):
592
+ timestamp = _timestamp(identity[2])
593
+ if self.source_counts.get(identity) != 1 or timestamp is None or not first <= timestamp <= last:
594
+ continue
595
+ matches.setdefault((identity, key), []).append((run, offset))
596
+ credits[run] = credits.get(run, 0) + 1
597
+ targets = set()
598
+ for target, identity in self.candidates:
599
+ seq, run, key = target
600
+ batch, matched = eligible.get(run), matches.get((identity, key), ())
601
+ if batch and len(matched) == 1 and candidate_counts[(run, identity)] == 1 and credits.get(matched[0][0]) == 1:
602
+ first, last, start, end = batch[:4]
603
+ if first < seq < last and start < matched[0][1] <= end:
604
+ targets.add(target)
605
+ return targets
606
+
607
+
493
608
  class _MailboxWakeInputs(_AsyncDeliveryInputs):
494
609
  """Exact generated native input hash, current provider and checkpoint identity."""
495
610
  def __init__(self, *args):
@@ -615,20 +730,24 @@ def filter_native_claude_mailbox_wake_items(
615
730
  or not isinstance(previous, str) or not _DIGEST.fullmatch(previous))):
616
731
  return items
617
732
  proof = _MailboxWakeInputs(provider_id, native, normalize_user, normalize_full_user)
733
+ scheduled = _ScheduledJobInputs(provider_id, native, normalize_user, normalize_full_user)
618
734
  # Temporary proof coordinates only; no synthetic event is persisted.
619
735
  batch = "import_mailbox_wake_filter"
620
736
  assistant_targets = {}
621
737
  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")})
738
+ if item.get("kind") == "user":
739
+ candidate = {**item, "seq": index, "run_id": batch, "type": "turn_started",
740
+ "backend": "claude", "imported": True, "prompt": item.get("text")}
741
+ scheduled.event(candidate)
742
+ if item.get("source_text_sha256") is None:
743
+ proof.event(candidate)
625
744
  elif item.get("kind") == "assistant":
626
745
  candidate = {**item, "seq": index, "run_id": batch, "type": "assistant_text",
627
746
  "backend": "claude", "imported": True}
628
747
  native.event(candidate)
629
748
  assistant_targets[index] = _assistant_target(candidate)
630
749
  digest, verified = hashlib.sha256(), set()
631
- for event, offset, line in _records(source, source_stamp):
750
+ for event, offset, line in _records(source, source_stamp, allow_nul_padding=True):
632
751
  line.update_hash(digest)
633
752
  if offset == start and hmac.compare_digest(digest.hexdigest(), previous):
634
753
  verified.add(start)
@@ -636,11 +755,13 @@ def filter_native_claude_mailbox_wake_items(
636
755
  verified.add(end)
637
756
  if offset <= end:
638
757
  proof.source(event, offset)
758
+ scheduled.source(event, offset)
639
759
  native.source(event, offset)
640
760
  if end not in verified or start and start not in verified:
641
761
  return items
642
762
  eligible = {batch: (0, len(items) + 1, start, end)}
643
763
  targets, assistant_replays = proof.prove(eligible), native.prove(eligible)
764
+ targets.update(scheduled.prove(eligible))
644
765
  _assistants, owned_inputs = native.exact_owned_sources()
645
766
  projected = []
646
767
  for index, item in enumerate(items, 1):
@@ -956,7 +1077,7 @@ def _prove(session_id: str, provider_id: str, events: Path, root: Path,
956
1077
  if start_time is not None and end_time is not None and start_time <= end_time:
957
1078
  scheduled_ranges.setdefault(key, []).append((run, start_time, end_time))
958
1079
  scheduled_sources, scheduled_counts = {}, {}
959
- for event, offset, line in _records(source, source_stamp):
1080
+ for event, offset, line in _records(source, source_stamp, allow_nul_padding=True):
960
1081
  line.update_hash(digest)
961
1082
  for wanted in prefix_digests.get(offset, ()):
962
1083
  if hmac.compare_digest(digest.hexdigest(), wanted):
@@ -1119,7 +1240,7 @@ def _prove(session_id: str, provider_id: str, events: Path, root: Path,
1119
1240
  tuple(corrected), frozenset(companions), proven_assistants, tuple(goal_commands))
1120
1241
 
1121
1242
 
1122
- def _bounded_records(path: Path, expected, start: int, end: int):
1243
+ def _bounded_records(path: Path, expected, start: int, end: int, *, allow_nul_padding=False):
1123
1244
  """Read complete records in one fixed window, never the oversized prefix."""
1124
1245
  if not 0 <= start < end <= expected[2] or end - start > MAX_EVENTS_BYTES:
1125
1246
  raise _Unproven()
@@ -1144,8 +1265,9 @@ def _bounded_records(path: Path, expected, start: int, end: int):
1144
1265
  raise _Unproven()
1145
1266
  try:
1146
1267
  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
1268
+ deadline=deadline, max_records=MAX_RECORDS, max_retained_bytes=MAX_LINE_BYTES,
1269
+ allow_nul_padding=allow_nul_padding):
1270
+ yield event if event is not None else {}, offset
1149
1271
  except ValueError as exc:
1150
1272
  raise _Unproven() from exc
1151
1273
  final = os.fstat(stream.fileno())
@@ -1280,7 +1402,7 @@ def _prove_recent_scheduled(session_id: str, provider_id: str, events: Path, roo
1280
1402
  if start_time is not None and end_time is not None and start_time <= end_time:
1281
1403
  ranges.setdefault(key, []).append((run, start_time, end_time))
1282
1404
  source_matches, occurrence_counts, identity_counts, source_metadata = {}, {}, {}, {}
1283
- for event, offset in _bounded_records(source, source_stamp, window_start, checkpoint_end):
1405
+ for event, offset in _bounded_records(source, source_stamp, window_start, checkpoint_end, allow_nul_padding=True):
1284
1406
  assistant_replays.source(event, offset)
1285
1407
  async_inputs.source(event, offset)
1286
1408
  wake_inputs.source(event, offset)
@@ -95,7 +95,13 @@ def parse_native_models(info: Any) -> list[dict[str, str]]:
95
95
 
96
96
 
97
97
 
98
- CACHE_TTL_SECONDS = 300.0
98
+ # Native labels (e.g. "Opus 5.5") are learned only when a real chat connects,
99
+ # and Claude chat processes stay connected for hours. A short lifetime made
100
+ # most periodic catalog reads (desktop: every 15 minutes) fall back to bare
101
+ # aliases. The key already changes with the CLI binary, provider environment,
102
+ # user/managed settings and account identity; every new connection replaces
103
+ # the entry and native authentication failure clears it.
104
+ CACHE_TTL_SECONDS = 24 * 60 * 60.0
99
105
  CACHE_LIMIT = 16
100
106
  _CACHE_LOCK = threading.Lock()
101
107
  _CACHE: OrderedDict[str, tuple[float, list[dict[str, str]]]] = OrderedDict()
@@ -136,8 +142,12 @@ def native_catalog_key(executable: str, env: dict[str, str]) -> str:
136
142
  """Fingerprint runtime/config identity without reading native credentials.
137
143
 
138
144
  Environment credentials are hashed, never retained in plaintext. Native
139
- credential rotation alone is not evidence of login or logout; this cache
140
- is short lived and is never used as authentication/authorization evidence.
145
+ credential rotation alone is not evidence of login or logout, so the
146
+ native credential file contributes only its presence (login/logout), never
147
+ its revision: OAuth renewal rewrites it for the same account, and the
148
+ labels are only re-learned when a new chat connects. Account switches are
149
+ covered by the account identity. This cache is never used as
150
+ authentication/authorization evidence.
141
151
  """
142
152
  home = Path(env.get("HOME") or str(Path.home()))
143
153
  config = Path(env.get("CLAUDE_CONFIG_DIR") or home / ".claude")
@@ -146,11 +156,11 @@ def native_catalog_key(executable: str, env: dict[str, str]) -> str:
146
156
  resolved = shutil.which(executable, path=env.get("PATH")) or executable
147
157
  revisions = [_file_revision(Path(resolved)), *(
148
158
  _file_revision(path) for path in (
149
- config / "settings.json", config / ".credentials.json",
159
+ config / "settings.json",
150
160
  Path("/Library/Application Support/ClaudeCode/managed-settings.json"),
151
161
  Path("/etc/claude-code/managed-settings.json"),
152
162
  )
153
- )]
163
+ ), ["native-credentials-present", (config / ".credentials.json").exists()]]
154
164
  return hashlib.sha256(json.dumps([relevant, revisions, _account_identity(config, home)], sort_keys=True).encode()).hexdigest()
155
165
 
156
166