@agentsdock/server 1.0.11 → 1.0.12-beta.10

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.
@@ -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(self, thread_id: str, command: str) -> None:
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
- _protocol_empty_object(
2377
- method,
2378
- await self.request(
2379
- method,
2380
- {"threadId": thread_id, "command": command},
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(self, thread_id: str, command: str) -> None:
3015
- await self.client.run_thread_shell_command(thread_id, command)
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,
@@ -250,6 +250,16 @@ def _native_assistant_text(text: str) -> str:
250
250
  return _NATIVE_LEADING_DECORATION_RE.sub("", str(text or "")).strip()
251
251
 
252
252
 
253
+ def _native_user_import_text(text: str) -> str:
254
+ """Mirror untrimmed import presentation only to select exact source proof.
255
+
256
+ Display equality is not replay evidence: the verified provider record must
257
+ still contain the original native input bytes. Never normalize indentation
258
+ or truncate a user message here.
259
+ """
260
+ return re.sub(r"\n{3,}", "\n\n", text.strip())
261
+
262
+
253
263
  def _public_assistant_item_id(event: dict) -> str | None:
254
264
  item_id = event.get("item_id")
255
265
  public = event.get("type") == "assistant_text" or (
@@ -275,6 +285,78 @@ def _native_assistant_item_owners(assistant_items: dict, completed_runs: set[str
275
285
  return owners
276
286
 
277
287
 
288
+ class _NativeGoalAssistantReplays:
289
+ """Match goal output by its exact native item/turn and one local owner.
290
+
291
+ Older goal consumers recorded the thread only on their promptless start.
292
+ Do not promote that boundary into general turn ownership: another public
293
+ item may legitimately repeat the same words within that native turn.
294
+ """
295
+ def __init__(self, provider_id: str):
296
+ self.provider_id = provider_id
297
+ self.starts: dict[str, tuple[int, str] | None] = {}
298
+ self.items: dict[tuple[str, str, str], list[tuple[str, dict]]] = {}
299
+ self.count = 0
300
+
301
+ def event(self, event: dict) -> None:
302
+ run = event.get("run_id")
303
+ if not isinstance(run, str) or not 0 < len(run) <= 256 or run.startswith("import_"):
304
+ return
305
+ if event.get("type") == "turn_started":
306
+ if run in self.starts:
307
+ self.starts[run] = None
308
+ return
309
+ self.count += 1
310
+ thread = event.get("thread_id")
311
+ valid = (event.get("backend") == "codex" and event.get("purpose") == "codex_goal_resume"
312
+ and event.get("imported") is not True and event.get("forked") is not True
313
+ and event.get("prompt") in (None, "") and not _runtime_human_provenance(event)
314
+ and isinstance(thread, str) and _PROVIDER_ID.fullmatch(thread)
315
+ and event.get("provider_thread_id") in (None, "", thread)
316
+ and isinstance(event.get("id"), str) and 0 < len(event["id"]) <= 256
317
+ and type(event.get("seq")) is int and event["seq"] > 0)
318
+ self.starts[run] = (event["seq"], thread) if valid else None
319
+ return
320
+ item_id = _public_assistant_item_id(event)
321
+ turn = event.get("provider_turn_id")
322
+ body = event.get("text")
323
+ if (event.get("purpose") != "codex_goal_resume" or item_id is None
324
+ or event.get("imported") is True or event.get("forked") is True
325
+ or event.get("backend") not in (None, "codex")
326
+ or not isinstance(turn, str) or not 0 < len(turn) <= 256
327
+ or not isinstance(body, str) or not 0 < len(body) <= NATIVE_PROOF_TEXT_CHARS
328
+ or not isinstance(event.get("id"), str) or not 0 < len(event["id"]) <= 256
329
+ or type(event.get("seq")) is not int or event["seq"] <= 0):
330
+ return
331
+ key = (turn, item_id, _text_key(body))
332
+ entries = self.items.setdefault(key, [])
333
+ if len(entries) < 2:
334
+ entries.append((run, _native_event_identity(event)))
335
+ self.count += 1
336
+
337
+ def match(self, origin: dict, text_key: str, *, before_seq: int | None = None,
338
+ provider_id: str | None = None) -> dict | None:
339
+ provider_id = provider_id or self.provider_id
340
+ if (origin.get("provider") != "codex" or origin.get("kind") != "assistant"
341
+ or origin.get("session_id", provider_id) != provider_id):
342
+ return None
343
+ entries = self.items.get((origin.get("turn_id"), origin.get("event_id"), text_key), ())
344
+ if len(entries) != 1:
345
+ return None
346
+ run, event = entries[0]
347
+ start = self.starts.get(run)
348
+ if (event.get("provider_thread_id") not in (None, "", provider_id)
349
+ or before_seq is not None and event["seq"] >= before_seq):
350
+ return None
351
+ if event.get("provider_thread_id") == provider_id:
352
+ # New output carries its own thread receipt, including inline goal
353
+ # continuations whose original start was an ordinary human turn.
354
+ return event
355
+ if start is not None and start[1] == provider_id and start[0] < event["seq"]:
356
+ return event
357
+ return None
358
+
359
+
278
360
  @dataclass
279
361
  class _SourceBudget:
280
362
  bytes_remaining: int
@@ -640,12 +722,19 @@ def _native_mailbox_wake_hash(event: dict) -> str | None:
640
722
  """A server-authored hidden input, not a text-based provider classification."""
641
723
  digest = event.get("provider_input_sha256")
642
724
  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)
725
+ if (event.get("type") != "turn_started" or event.get("imported") is True
726
+ or event.get("prompt") != "" or event.get("provider_generated") is not True
727
+ or _runtime_human_provenance(event) or not isinstance(digest, str)
728
+ or not _DIGEST.fullmatch(digest)):
729
+ return None
730
+ if (event.get("purpose") == "chat_mailbox_wake"
646
731
  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)):
732
+ and type(event.get("mailbox_wake_through_seq")) is int
733
+ and 0 < event["mailbox_wake_through_seq"] < 2**63):
734
+ return digest
735
+ queued_id = event.get("queued_id")
736
+ if (event.get("purpose") == "server_update_continuation"
737
+ and isinstance(queued_id, str) and re.fullmatch(r"queued_[a-f0-9]{16}", queued_id)):
649
738
  return digest
650
739
  return None
651
740
 
@@ -974,6 +1063,7 @@ def _prove_native_replays(session_id: str, provider_id: str, events: Path, sourc
974
1063
  stamp = _native_stamp(events)
975
1064
  batches, terminals, candidates, native, owners = {}, {}, [], {}, {}
976
1065
  deliveries = _AsyncDeliveryIndex()
1066
+ goal_assistants = _NativeGoalAssistantReplays(provider_id)
977
1067
  previous_seq, retained = 0, 0
978
1068
  for event, _offset, _line in _native_records(events, stamp, budget):
979
1069
  seq = event.get("seq")
@@ -983,7 +1073,8 @@ def _prove_native_replays(session_id: str, provider_id: str, events: Path, sourc
983
1073
  if event.get("session_id") not in (None, "", session_id):
984
1074
  continue
985
1075
  deliveries.observe(event)
986
- if len(candidates) + len(batches) + len(terminals) + retained + deliveries.count > MAX_KEYS:
1076
+ goal_assistants.event(event)
1077
+ if len(candidates) + len(batches) + len(terminals) + retained + deliveries.count + goal_assistants.count > MAX_KEYS:
987
1078
  raise CodexNativeHistoryProofCapacityExceeded("native history proof key budget exceeded")
988
1079
  run = event.get("run_id")
989
1080
  if not isinstance(run, str) or not 0 < len(run) <= 256:
@@ -1009,6 +1100,10 @@ def _prove_native_replays(session_id: str, provider_id: str, events: Path, sourc
1009
1100
  owned = owners.setdefault((thread, turn), set())
1010
1101
  retained += run not in owned
1011
1102
  owned.add(run)
1103
+ if event.get("purpose") == "codex_goal_resume" and not _native_goal_steer_turn(event):
1104
+ # Goal replies use exact item/turn proof, never run-wide text
1105
+ # credit. Accepted user steers still need source-occurrence proof.
1106
+ continue
1012
1107
  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
1108
  body = event.get("prompt") if kind == "user" else event.get("result_text") if event.get("type") == "turn_finished" else event.get("text")
1014
1109
  if kind and isinstance(body, str) and body and len(body) <= 4 * 1024 * 1024:
@@ -1017,7 +1112,7 @@ def _prove_native_replays(session_id: str, provider_id: str, events: Path, sourc
1017
1112
  elif kind == "user" and (wake_hash := _native_mailbox_wake_hash(event)):
1018
1113
  native.setdefault((run, kind, wake_hash), []).append(_native_event_identity(event))
1019
1114
  retained += 1
1020
- if len(candidates) + len(batches) + len(terminals) + retained + deliveries.count > MAX_KEYS:
1115
+ if len(candidates) + len(batches) + len(terminals) + retained + deliveries.count + goal_assistants.count > MAX_KEYS:
1021
1116
  raise CodexNativeHistoryProofCapacityExceeded("native history proof key budget exceeded")
1022
1117
  if not candidates:
1023
1118
  return _NativeProof(provider_id)
@@ -1043,7 +1138,7 @@ def _prove_native_replays(session_id: str, provider_id: str, events: Path, sourc
1043
1138
  proofs = {}
1044
1139
  for thread, path in selected:
1045
1140
  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))
1141
+ session_id=session_id, deliveries=deliveries, goal_assistants=goal_assistants))
1047
1142
  budget.check()
1048
1143
  return _NativeProof(provider_id, proofs)
1049
1144
 
@@ -1051,7 +1146,8 @@ def _prove_native_replays(session_id: str, provider_id: str, events: Path, sourc
1051
1146
  def _prove_native_source(thread: str, source: Path, root: Path, batches: dict, candidates: list,
1052
1147
  native: dict, owners: dict, parse_item: Callable, budget: _NativeReadBudget,
1053
1148
  *, session_id: str, deliveries: _AsyncDeliveryIndex,
1054
- require_verified_checkpoint: bool = False) -> dict:
1149
+ require_verified_checkpoint: bool = False,
1150
+ goal_assistants: _NativeGoalAssistantReplays | None = None) -> dict:
1055
1151
  if (not source.is_absolute() or source.is_symlink() or source.suffix != ".jsonl"
1056
1152
  or not (source.stem == thread or source.stem.endswith("-" + thread))):
1057
1153
  raise _Unproven()
@@ -1169,8 +1265,8 @@ def _prove_native_source(thread: str, source: Path, root: Path, batches: dict, c
1169
1265
  raise _Unproven()
1170
1266
  if (item["kind"], key[2], key[3]) not in candidate_keys:
1171
1267
  continue
1172
- if item["kind"] == "user" and key[3] is not None:
1173
- # A display-trimmed input still has its complete source in this
1268
+ if item["kind"] == "user":
1269
+ # A display-compacted input still has its complete source in this
1174
1270
  # checkpoint-verified record. Compare those bytes to the original
1175
1271
  # native input, never a shared preview or an unverified hash.
1176
1272
  full_text = None
@@ -1181,8 +1277,10 @@ def _prove_native_source(thread: str, source: Path, root: Path, batches: dict, c
1181
1277
  if (isinstance(blocks, list) and len(blocks) == 1 and isinstance(blocks[0], dict)
1182
1278
  and blocks[0].get("type") == "input_text"):
1183
1279
  full_text = blocks[0].get("text")
1184
- if (isinstance(full_text, str) and full_text
1185
- and _text_key(" ".join(full_text.split())) == key[3]):
1280
+ if (isinstance(full_text, str) and full_text and (
1281
+ key[3] is not None and _text_key(" ".join(full_text.split())) == key[3]
1282
+ or key[3] is None and _native_user_import_text(full_text) == item["text"]
1283
+ )):
1186
1284
  full_user_keys[key] = _text_key(full_text)
1187
1285
  if item["kind"] == "user" and (body := _cross_chat_delivery_body(item["text"])):
1188
1286
  delivery_bodies[key] = body
@@ -1192,10 +1290,11 @@ def _prove_native_source(thread: str, source: Path, root: Path, batches: dict, c
1192
1290
  assistant_native_keys[key] = _text_key(cleaned)
1193
1291
  if origin:
1194
1292
  candidate_assistants.add((origin["event_id"], origin["turn_id"], origin["timestamp"]))
1195
- if origin:
1293
+ if origin or item["kind"] == "user":
1196
1294
  ids = canonical.setdefault(key, {})
1197
- retained += origin["event_id"] not in ids
1198
- ids[origin["event_id"]] = origin
1295
+ if origin:
1296
+ retained += origin["event_id"] not in ids
1297
+ ids[origin["event_id"]] = origin
1199
1298
  occurrences.setdefault((item["kind"], key[2], timestamp, key[3]), []).append((offset, key))
1200
1299
  retained += 1
1201
1300
  if retained > MAX_KEYS:
@@ -1203,6 +1302,28 @@ def _prove_native_source(thread: str, source: Path, root: Path, batches: dict, c
1203
1302
  if require_verified_checkpoint and any((offset, expected) not in verified
1204
1303
  for offset, expectations in wanted.items() for expected in expectations):
1205
1304
  raise _Unproven()
1305
+ # One logical run may own its initial turn and later continuations. Display
1306
+ # compaction must not let its original input consume a genuine repeat in
1307
+ # another owned turn. Keep at most two source identities per display key;
1308
+ # unknown or ambiguous ownership cannot establish this additional proof.
1309
+ compacted_user_sources: dict = {}
1310
+ uncertain_user_sources: set[str] = set()
1311
+ for source_key, source_ids in canonical.items():
1312
+ budget.check()
1313
+ if source_key[1] != "user" or source_key[3] is not None:
1314
+ continue
1315
+ source_owners = set(owners.get((thread, source_key[0]), set()))
1316
+ for _offset, item_key in assistant_owner_evidence.get(source_key[0], ()):
1317
+ if len(assistant_source_turns[item_key]) == 1:
1318
+ source_owners.update(assistant_item_owners[item_key])
1319
+ if len(source_owners) != 1 or not source_ids:
1320
+ uncertain_user_sources.add(source_key[2])
1321
+ continue
1322
+ identities = compacted_user_sources.setdefault((next(iter(source_owners)), source_key[2]), set())
1323
+ for source_id in source_ids:
1324
+ if len(identities) >= 2:
1325
+ break
1326
+ identities.add((source_key[0], source_id))
1206
1327
  proofs = {}
1207
1328
  for target in candidates:
1208
1329
  budget.check()
@@ -1241,6 +1362,15 @@ def _prove_native_source(thread: str, source: Path, root: Path, batches: dict, c
1241
1362
  if len(proofs) > MAX_TARGETS:
1242
1363
  raise _Unproven()
1243
1364
  continue
1365
+ goal_origin = timestamp_origins[0] if len(timestamp_origins) == 1 else None
1366
+ goal_match = goal_assistants.match(goal_origin, assistant_native_keys.get(key, ""),
1367
+ before_seq=first, provider_id=thread) if (
1368
+ goal_assistants and goal_origin and kind == "assistant" and source_hash is None) else None
1369
+ if goal_match is not None:
1370
+ proofs[target] = {**goal_origin, "native_event_id": goal_match["id"], "source_text_sha256": body_key}
1371
+ if len(proofs) > MAX_TARGETS:
1372
+ raise _Unproven()
1373
+ continue
1244
1374
  if len(source_ids) != 1 or source_hash is not None and key not in full_user_keys:
1245
1375
  continue
1246
1376
  source_origin = next(iter(source_ids.values()))
@@ -1253,9 +1383,17 @@ def _prove_native_source(thread: str, source: Path, root: Path, batches: dict, c
1253
1383
  if len(owned_runs) != 1:
1254
1384
  continue
1255
1385
  native_run = next(iter(owned_runs))
1256
- native_body_key = full_user_keys.get(key, body_key)
1386
+ native_body_key = full_user_keys.get(key, body_key) if source_hash is not None else body_key
1257
1387
  native_matches = [event for event in native.get((native_run, kind, native_body_key), [])
1258
1388
  if event.get("type") != "turn_steered" or event.get("provider_turn_id") == key[0]]
1389
+ if (not native_matches and kind == "user" and source_hash is None and key in full_user_keys
1390
+ and body_key not in uncertain_user_sources
1391
+ and len(compacted_user_sources.get((native_run, body_key), ())) == 1):
1392
+ original_key = full_user_keys[key]
1393
+ original_matches = [event for event in native.get((native_run, kind, original_key), [])
1394
+ if event.get("type") != "turn_steered" or event.get("provider_turn_id") == key[0]]
1395
+ if original_matches:
1396
+ native_body_key, native_matches = original_key, original_matches
1259
1397
  if not native_matches and kind == "user" and source_hash is None:
1260
1398
  delivery = deliveries.match(session_id, thread, native_run, source_origin,
1261
1399
  delivery_bodies.get(key), delivery_source_ids.get(key[0], set()), body_key)
@@ -1371,7 +1509,8 @@ class CodexNativeHistoryRepairCache(CodexGoalHistoryRepairCache):
1371
1509
  def _prove_pending_native_inputs(session_id: str, provider_id: str, items: list[dict],
1372
1510
  source: Path, root: Path, checkpoint: dict, parse_item: Callable,
1373
1511
  previous_seq: int, owners: dict, deliveries: _AsyncDeliveryIndex,
1374
- budget: _NativeReadBudget, native_inputs: dict | None = None) -> dict:
1512
+ budget: _NativeReadBudget, native_inputs: dict | None = None,
1513
+ compacted_input_keys: set[str] | None = None) -> dict:
1375
1514
  """Reuse pinned-prefix proof before broadcast; the synthetic batch is never stored."""
1376
1515
  cursor = checkpoint.get("cursor")
1377
1516
  if (checkpoint.get("version") != 1 or not isinstance(cursor, dict) or cursor.get("version") != 1
@@ -1390,7 +1529,8 @@ def _prove_pending_native_inputs(session_id: str, provider_id: str, items: list[
1390
1529
  or origin.get("session_id", provider_id) != provider_id
1391
1530
  or not (item.get("source_text_sha256") is not None
1392
1531
  or _cross_chat_delivery_body(item["text"]) or _text_key(item["text"]) in deliveries.status_body_keys
1393
- or _text_key(item["text"]) in steer_keys)):
1532
+ or _text_key(item["text"]) in steer_keys
1533
+ or _text_key(item["text"]) in (compacted_input_keys or set()))):
1394
1534
  continue
1395
1535
  candidate = _replay_target({"seq": previous_seq + index + 2, "id": f"pending:{index}", "run_id": run,
1396
1536
  "type": "turn_started", "backend": "codex", "imported": True, "prompt": item["text"],
@@ -1449,7 +1589,9 @@ def filter_native_codex_history_items(session_id: str, provider_id: str, events:
1449
1589
  and isinstance(item.get("text"), str))
1450
1590
  owners, native, assistant_items, wake_keys, native_count = {}, {}, {}, set(), 0
1451
1591
  native_inputs, steered_inputs = {}, {}
1592
+ compacted_input_keys: set[str] = set()
1452
1593
  deliveries = _AsyncDeliveryIndex()
1594
+ goal_assistants = _NativeGoalAssistantReplays(provider_id)
1453
1595
  prove_deliveries = (source_path is not None and root is not None
1454
1596
  and isinstance(sync_checkpoint, dict) and callable(parse_item)
1455
1597
  and any(item.get("kind") == "user" and isinstance(item.get("text"), str) for item in items))
@@ -1460,6 +1602,10 @@ def filter_native_codex_history_items(session_id: str, provider_id: str, events:
1460
1602
  raise _Unproven()
1461
1603
  previous_seq = seq
1462
1604
  run = event.get("run_id")
1605
+ if event.get("session_id") in (None, "", session_id):
1606
+ goal_assistants.event(event)
1607
+ if native_count + owner_count + len(assistant_items) + deliveries.count + goal_assistants.count > MAX_KEYS:
1608
+ raise _Unproven()
1463
1609
  if prove_deliveries and event.get("session_id") in (None, "", session_id):
1464
1610
  deliveries.observe(event)
1465
1611
  if native_count + owner_count + len(assistant_items) + deliveries.count > MAX_KEYS:
@@ -1475,16 +1621,35 @@ def filter_native_codex_history_items(session_id: str, provider_id: str, events:
1475
1621
  owner_count += run not in owned
1476
1622
  owned.add(run)
1477
1623
  steer_turn = _native_goal_steer_turn(event)
1624
+ if event.get("purpose") == "codex_goal_resume" and not steer_turn:
1625
+ # Keep exact public reply identity for source-prefix ownership,
1626
+ # without granting equal-text credit to every reply in the goal.
1627
+ item_id = _public_assistant_item_id(event)
1628
+ body = event.get("text")
1629
+ if item_id is not None and isinstance(body, str) and body:
1630
+ assistant_items[(run, item_id, _text_key(body))] = _native_event_identity(event)
1631
+ if native_count + owner_count + len(assistant_items) + deliveries.count + goal_assistants.count > MAX_KEYS:
1632
+ raise _Unproven()
1633
+ continue
1478
1634
  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
1635
  body = event.get("prompt") if kind == "user" else event.get("result_text") if event.get("type") == "turn_finished" else event.get("text")
1480
1636
  wake_hash = _native_mailbox_wake_hash(event) if kind == "user" else None
1481
1637
  key = (kind, wake_hash or _text_key(body)) if kind and (isinstance(body, str) and body or wake_hash) else None
1482
- if key in candidate_keys or (isinstance(body, str) and
1638
+ compacted_key = (_text_key(_native_user_import_text(body))
1639
+ if prove_deliveries and kind == "user" and event.get("type") == "turn_started"
1640
+ and isinstance(body, str) and body and wake_hash is None else None)
1641
+ compacted_candidate = (compacted_key is not None and key != ("user", compacted_key)
1642
+ and ("user", compacted_key) in candidate_keys)
1643
+ if key in candidate_keys or compacted_candidate or (isinstance(body, str) and
1483
1644
  (kind, _text_key(" ".join(body.split()))) in source_keys):
1484
1645
  keys = steered_inputs.setdefault((run, steer_turn), {}) if steer_turn else native.setdefault(run, {})
1485
1646
  native_count += key not in keys
1486
1647
  if isinstance(event.get("id"), str) and 0 < len(event["id"]) <= 256:
1487
1648
  keys.setdefault(key, event["id"])
1649
+ if compacted_candidate:
1650
+ # Only select a source-proof candidate. The native maps
1651
+ # retain the original bytes, never a display-text alias.
1652
+ compacted_input_keys.add(compacted_key)
1488
1653
  if prove_deliveries and kind == "user" and isinstance(body, str) and body:
1489
1654
  inputs = native_inputs.setdefault((run, kind, key[1]), [])
1490
1655
  if not any(prior.get("type") == event.get("type")
@@ -1499,7 +1664,7 @@ def filter_native_codex_history_items(session_id: str, provider_id: str, events:
1499
1664
  item_id = _public_assistant_item_id(event)
1500
1665
  if item_id is not None and key is not None:
1501
1666
  assistant_items[(run, item_id, key[1])] = _native_event_identity(event)
1502
- if native_count + owner_count + len(assistant_items) + deliveries.count > MAX_KEYS:
1667
+ if native_count + owner_count + len(assistant_items) + deliveries.count + goal_assistants.count > MAX_KEYS:
1503
1668
  raise _Unproven()
1504
1669
  assistant_item_owners = _native_assistant_item_owners(
1505
1670
  assistant_items, {run for runs in owners.values() for run in runs}, provider_id,
@@ -1520,16 +1685,16 @@ def filter_native_codex_history_items(session_id: str, provider_id: str, events:
1520
1685
  for item_key, turns in assistant_source_turns.items():
1521
1686
  if len(turns) == 1:
1522
1687
  owners.setdefault(next(iter(turns)), set()).update(assistant_item_owners[item_key])
1523
- if prove_deliveries and steered_inputs:
1688
+ if prove_deliveries and (steered_inputs or compacted_input_keys):
1524
1689
  # The unmatched import can contain only follow-ups: its assistant
1525
1690
  # messages were already reconciled. Preserve public item identities
1526
- # for the source scan to recover earlier turns of a long goal run.
1691
+ # for the source scan to recover earlier turns of a long native run.
1527
1692
  for (run, _item_id, body_key), event in assistant_items.items():
1528
1693
  native_inputs.setdefault((run, "assistant", body_key), []).append(event)
1529
1694
  delivery_proofs = _prove_pending_native_inputs(
1530
1695
  session_id, provider_id, items, source_path, root, sync_checkpoint, parse_item,
1531
- previous_seq, owners, deliveries, budget, native_inputs,
1532
- ) if prove_deliveries and (deliveries.starts or steered_inputs or any(
1696
+ previous_seq, owners, deliveries, budget, native_inputs, compacted_input_keys,
1697
+ ) if prove_deliveries and (deliveries.starts or steered_inputs or compacted_input_keys or any(
1533
1698
  item.get("kind") == "user" and item.get("source_text_sha256") is not None for item in items)) else {}
1534
1699
  # A hidden wake has no public prompt body. Require a single exact source
1535
1700
  # item in this verified import range, in addition to native turn ownership.
@@ -1545,6 +1710,10 @@ def filter_native_codex_history_items(session_id: str, provider_id: str, events:
1545
1710
  for index, item in enumerate(items):
1546
1711
  budget.check()
1547
1712
  origin = item.get("provider_origin")
1713
+ if (item.get("kind") == "assistant" and isinstance(origin, dict)
1714
+ and isinstance(item.get("text"), str) and item.get("source_text_sha256") is None
1715
+ and goal_assistants.match(origin, _text_key(_native_assistant_text(item["text"]))) is not None):
1716
+ continue
1548
1717
  runs = owners.get(origin.get("turn_id"), set()) if isinstance(origin, dict) else set()
1549
1718
  owned = (isinstance(origin, dict) and origin.get("provider") == "codex"
1550
1719
  and origin.get("kind") == item.get("kind") and isinstance(origin.get("event_id"), str)
@@ -32,6 +32,7 @@ ENV_KEY = "AGENTSDOCK_CODEX_PROVIDER_API_KEY"
32
32
  MAX_BODY_BYTES = 16 * 1024
33
33
  MAX_SUMMARY_CAPABILITIES_BYTES = 192 * 1024
34
34
  MAX_MODEL_CATALOG_BYTES = 384 * 1024
35
+ MODEL_CATALOG_TTL_SECONDS = 300
35
36
  TEST_TIMEOUT_SECONDS = 45
36
37
  TEST_TOOL = "agentsdock_compatibility_ping"
37
38
  TEST_INSTRUCTIONS = (
@@ -198,6 +199,40 @@ def session_choice(value) -> str:
198
199
  RUNTIME_FIELDS = ("codex_provider", "codex_provider_revision", "codex_provider_binding", "model", "effort", "_codex_provider_removed")
199
200
 
200
201
 
202
+ def context_has_encrypted_items(path: Path | None) -> bool | None:
203
+ """Inspect one native rollout without exposing or modifying its contents.
204
+
205
+ Native compaction replaces model-visible history, while the original
206
+ timeline stays on disk. Unknown/legacy checkpoints and rollbacks are
207
+ deliberately inconclusive; they must not authorize a ciphertext handoff.
208
+ """
209
+ if path is None:
210
+ return None
211
+
212
+ def encrypted(value):
213
+ if isinstance(value, dict):
214
+ return bool(value.get("encrypted_content")) or any(encrypted(item) for item in value.values())
215
+ return isinstance(value, list) and any(encrypted(item) for item in value)
216
+
217
+ found: bool | None = False
218
+ try:
219
+ with path.open(encoding="utf-8") as stream:
220
+ for line in stream:
221
+ record = json.loads(line)
222
+ payload = record.get("payload")
223
+ if record.get("type") == "compacted":
224
+ replacement = payload.get("replacement_history") if isinstance(payload, dict) else None
225
+ found = encrypted(replacement) if isinstance(replacement, list) else None
226
+ elif record.get("type") == "response_item" and encrypted(payload):
227
+ found = True
228
+ elif (record.get("type") == "event_msg" and isinstance(payload, dict)
229
+ and payload.get("type") == "thread_rolled_back"):
230
+ found = None
231
+ except (OSError, ValueError, TypeError, AttributeError):
232
+ return None
233
+ return found
234
+
235
+
201
236
  def requested_session(session: dict) -> dict:
202
237
  """Desired runtime is separate from the owner of an in-flight turn."""
203
238
  pending = session.get("_codex_provider_pending")
@@ -434,7 +469,9 @@ class ProviderStore:
434
469
  capabilities[model] = model_capability({**capabilities.get(model, {}), "reasoning_summary_supported": supported})
435
470
  if selected and selected.get("model"):
436
471
  capabilities.setdefault(selected["model"], model_capability())
472
+ age = time.time() - cached.get("fetched_at", 0)
437
473
  return {"models": cached.get("models", []), "efforts": [],
474
+ "discovery_status": cached.get("discovery_status", "unavailable") if 0 <= age < MODEL_CATALOG_TTL_SECONDS else "unavailable",
438
475
  "model_efforts": {model: [option for option in EFFORT_OPTIONS if option["value"] in capability["reasoning_efforts"]]
439
476
  for model, capability in capabilities.items()},
440
477
  "model_capabilities": capabilities,
@@ -445,8 +482,13 @@ class ProviderStore:
445
482
  with self.lock:
446
483
  previous = self._saved_model_catalog(selected)
447
484
  legacy_default = previous.get("legacy_default_model") or (previous.get("default_model") if not selected.get("model") else None)
485
+ status = catalog.get("discovery_status", "ready")
486
+ if status not in {"ready", "empty", "partial"}:
487
+ # Retain only this credential's previous inventory on failure.
488
+ catalog = {**previous, "discovery_status": status}
448
489
  models = catalog.get("models", [])
449
490
  self._catalogs[catalog_key(selected)] = {"models": models,
491
+ "fetched_at": time.time(), "discovery_status": status,
450
492
  "model_capabilities": {model["value"]: model_capability(catalog.get("model_capabilities", {}).get(model["value"])) for model in models},
451
493
  "default_model": catalog.get("default_model", ""), "legacy_default_model": legacy_default}
452
494
  self._save_model_catalog(selected, self._catalogs[catalog_key(selected)])
@@ -457,6 +499,20 @@ class ProviderStore:
457
499
  if denials:
458
500
  self._cache_summary_capabilities(selected, denials)
459
501
 
502
+ def refresh_catalog(self, *, force: bool = False) -> None:
503
+ selected = self.registration(include_key=True)
504
+ if not selected:
505
+ return
506
+ with self.lock:
507
+ cached = self._catalogs.get(catalog_key(selected)) or self._saved_model_catalog(selected)
508
+ age = time.time() - cached.get("fetched_at", 0)
509
+ if not force and 0 <= age < MODEL_CATALOG_TTL_SECONDS:
510
+ return
511
+ result = endpoint_model_catalog(selected)
512
+ current = self.registration(include_key=True)
513
+ if current and current.get("credential_id") == selected.get("credential_id"):
514
+ self.cache_catalog(selected, result)
515
+
460
516
  def _save_model_catalog(self, selected: dict, catalog: dict) -> None:
461
517
  identifier = selected.get("credential_id")
462
518
  if not isinstance(identifier, str) or not re.fullmatch(r"[0-9a-f]{32}", identifier):
@@ -515,6 +571,8 @@ class ProviderStore:
515
571
  default_model = validate_model(default_model)
516
572
  legacy = catalog.get("legacy_default_model")
517
573
  result = {"models": models, "model_capabilities": capabilities, "default_model": default_model,
574
+ "fetched_at": catalog.get("fetched_at", 0) if isinstance(catalog.get("fetched_at", 0), (int, float)) else 0,
575
+ "discovery_status": catalog.get("discovery_status", "unavailable"),
518
576
  "legacy_default_model": validate_model(legacy) if legacy else None}
519
577
  self._saved_catalogs[identifier] = result
520
578
  return result