@agentsdock/server 1.0.12-beta.1 → 1.0.12-beta.12

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.
@@ -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
@@ -308,6 +390,7 @@ def _target(event: dict) -> tuple[int, str, str] | None:
308
390
  class _Proof:
309
391
  provider_id: str
310
392
  targets: frozenset[tuple[int, str, str]] = frozenset()
393
+ complete: bool = True
311
394
  positions: frozenset[tuple[int, str]] = field(init=False, repr=False)
312
395
 
313
396
  def __post_init__(self) -> None:
@@ -378,6 +461,7 @@ def _prove(session_id: str, provider_id: str, events: Path, source: Path | None,
378
461
  selected = ([current_key] if current_key in groups else []) + prior_keys
379
462
  budget = _SourceBudget(MAX_AGGREGATE_SOURCE_BYTES, MAX_AGGREGATE_SOURCE_RECORDS)
380
463
  targets = set()
464
+ complete = True
381
465
  for source_provider, source_path in selected:
382
466
  selected_batches = groups[(source_provider, source_path)]
383
467
  selected_candidates = [target for target in candidates if target[1] in selected_batches]
@@ -389,8 +473,10 @@ def _prove(session_id: str, provider_id: str, events: Path, source: Path | None,
389
473
  except (OSError, ValueError, TypeError, KeyError, RuntimeError):
390
474
  # A missing, changed, oversized or ambiguous prior source cannot
391
475
  # invalidate a proof independently established from another source.
476
+ # Retry incomplete evidence at the next explicit history read.
477
+ complete = False
392
478
  continue
393
- return _Proof(provider_id, frozenset(targets))
479
+ return _Proof(provider_id, frozenset(targets), complete=complete)
394
480
 
395
481
 
396
482
  def _prove_source(provider_id: str, source: Path, root: Path,
@@ -493,7 +579,7 @@ class CodexGoalHistoryRepairCache:
493
579
  def is_prepared(self, session_id: str, provider_id: str) -> bool:
494
580
  with self._lock:
495
581
  proof = self._proofs.get(session_id)
496
- return proof is not None and proof.provider_id == provider_id
582
+ return proof is not None and proof.provider_id == provider_id and proof.complete
497
583
 
498
584
  def prepare(self, session_id: str, provider_id: str, events_path: Path,
499
585
  source_path: Path | None, root: Path,
@@ -502,7 +588,7 @@ class CodexGoalHistoryRepairCache:
502
588
  with self._prepare_lock:
503
589
  with self._lock:
504
590
  previous = self._proofs.get(session_id)
505
- if previous and previous.provider_id == provider_id:
591
+ if previous and previous.provider_id == provider_id and previous.complete:
506
592
  self._proofs.move_to_end(session_id)
507
593
  return False
508
594
  self._preparing, self._cancelled = session_id, False
@@ -510,18 +596,18 @@ class CodexGoalHistoryRepairCache:
510
596
  proof = _prove(session_id, provider_id, events_path, source_path, root,
511
597
  normalize_user, classify_user)
512
598
  except (OSError, ValueError, TypeError, KeyError, RuntimeError):
513
- proof = _Proof(provider_id)
599
+ proof = _Proof(provider_id, complete=False)
514
600
  with self._lock:
515
601
  self._preparing = None
516
602
  if self._cancelled:
517
603
  return bool(previous and previous.targets)
518
- if previous and previous.provider_id != provider_id:
604
+ if previous:
519
605
  # Proven immutable ledger positions stay proven when this
520
606
  # chat rotates provider threads. Fresh credentials/source
521
607
  # discovery must not resurrect old runtime-only bubbles.
522
608
  remaining = max(0, MAX_TARGETS - len(previous.targets))
523
609
  added = sorted(proof.targets - previous.targets)[:remaining]
524
- proof = _Proof(provider_id, previous.targets.union(added))
610
+ proof = _Proof(provider_id, previous.targets.union(added), complete=proof.complete)
525
611
  self._proofs[session_id] = proof
526
612
  self._proofs.move_to_end(session_id)
527
613
  while len(self._proofs) > MAX_SESSIONS:
@@ -640,12 +726,19 @@ def _native_mailbox_wake_hash(event: dict) -> str | None:
640
726
  """A server-authored hidden input, not a text-based provider classification."""
641
727
  digest = event.get("provider_input_sha256")
642
728
  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)
729
+ if (event.get("type") != "turn_started" or event.get("imported") is True
730
+ or event.get("prompt") != "" or event.get("provider_generated") is not True
731
+ or _runtime_human_provenance(event) or not isinstance(digest, str)
732
+ or not _DIGEST.fullmatch(digest)):
733
+ return None
734
+ if (event.get("purpose") == "chat_mailbox_wake"
646
735
  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)):
736
+ and type(event.get("mailbox_wake_through_seq")) is int
737
+ and 0 < event["mailbox_wake_through_seq"] < 2**63):
738
+ return digest
739
+ queued_id = event.get("queued_id")
740
+ if (event.get("purpose") == "server_update_continuation"
741
+ and isinstance(queued_id, str) and re.fullmatch(r"queued_[a-f0-9]{16}", queued_id)):
649
742
  return digest
650
743
  return None
651
744
 
@@ -974,6 +1067,7 @@ def _prove_native_replays(session_id: str, provider_id: str, events: Path, sourc
974
1067
  stamp = _native_stamp(events)
975
1068
  batches, terminals, candidates, native, owners = {}, {}, [], {}, {}
976
1069
  deliveries = _AsyncDeliveryIndex()
1070
+ goal_assistants = _NativeGoalAssistantReplays(provider_id)
977
1071
  previous_seq, retained = 0, 0
978
1072
  for event, _offset, _line in _native_records(events, stamp, budget):
979
1073
  seq = event.get("seq")
@@ -983,7 +1077,8 @@ def _prove_native_replays(session_id: str, provider_id: str, events: Path, sourc
983
1077
  if event.get("session_id") not in (None, "", session_id):
984
1078
  continue
985
1079
  deliveries.observe(event)
986
- if len(candidates) + len(batches) + len(terminals) + retained + deliveries.count > MAX_KEYS:
1080
+ goal_assistants.event(event)
1081
+ if len(candidates) + len(batches) + len(terminals) + retained + deliveries.count + goal_assistants.count > MAX_KEYS:
987
1082
  raise CodexNativeHistoryProofCapacityExceeded("native history proof key budget exceeded")
988
1083
  run = event.get("run_id")
989
1084
  if not isinstance(run, str) or not 0 < len(run) <= 256:
@@ -1009,6 +1104,10 @@ def _prove_native_replays(session_id: str, provider_id: str, events: Path, sourc
1009
1104
  owned = owners.setdefault((thread, turn), set())
1010
1105
  retained += run not in owned
1011
1106
  owned.add(run)
1107
+ if event.get("purpose") == "codex_goal_resume" and not _native_goal_steer_turn(event):
1108
+ # Goal replies use exact item/turn proof, never run-wide text
1109
+ # credit. Accepted user steers still need source-occurrence proof.
1110
+ continue
1012
1111
  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
1112
  body = event.get("prompt") if kind == "user" else event.get("result_text") if event.get("type") == "turn_finished" else event.get("text")
1014
1113
  if kind and isinstance(body, str) and body and len(body) <= 4 * 1024 * 1024:
@@ -1017,7 +1116,7 @@ def _prove_native_replays(session_id: str, provider_id: str, events: Path, sourc
1017
1116
  elif kind == "user" and (wake_hash := _native_mailbox_wake_hash(event)):
1018
1117
  native.setdefault((run, kind, wake_hash), []).append(_native_event_identity(event))
1019
1118
  retained += 1
1020
- if len(candidates) + len(batches) + len(terminals) + retained + deliveries.count > MAX_KEYS:
1119
+ if len(candidates) + len(batches) + len(terminals) + retained + deliveries.count + goal_assistants.count > MAX_KEYS:
1021
1120
  raise CodexNativeHistoryProofCapacityExceeded("native history proof key budget exceeded")
1022
1121
  if not candidates:
1023
1122
  return _NativeProof(provider_id)
@@ -1043,7 +1142,7 @@ def _prove_native_replays(session_id: str, provider_id: str, events: Path, sourc
1043
1142
  proofs = {}
1044
1143
  for thread, path in selected:
1045
1144
  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))
1145
+ session_id=session_id, deliveries=deliveries, goal_assistants=goal_assistants))
1047
1146
  budget.check()
1048
1147
  return _NativeProof(provider_id, proofs)
1049
1148
 
@@ -1051,7 +1150,8 @@ def _prove_native_replays(session_id: str, provider_id: str, events: Path, sourc
1051
1150
  def _prove_native_source(thread: str, source: Path, root: Path, batches: dict, candidates: list,
1052
1151
  native: dict, owners: dict, parse_item: Callable, budget: _NativeReadBudget,
1053
1152
  *, session_id: str, deliveries: _AsyncDeliveryIndex,
1054
- require_verified_checkpoint: bool = False) -> dict:
1153
+ require_verified_checkpoint: bool = False,
1154
+ goal_assistants: _NativeGoalAssistantReplays | None = None) -> dict:
1055
1155
  if (not source.is_absolute() or source.is_symlink() or source.suffix != ".jsonl"
1056
1156
  or not (source.stem == thread or source.stem.endswith("-" + thread))):
1057
1157
  raise _Unproven()
@@ -1169,8 +1269,8 @@ def _prove_native_source(thread: str, source: Path, root: Path, batches: dict, c
1169
1269
  raise _Unproven()
1170
1270
  if (item["kind"], key[2], key[3]) not in candidate_keys:
1171
1271
  continue
1172
- if item["kind"] == "user" and key[3] is not None:
1173
- # A display-trimmed input still has its complete source in this
1272
+ if item["kind"] == "user":
1273
+ # A display-compacted input still has its complete source in this
1174
1274
  # checkpoint-verified record. Compare those bytes to the original
1175
1275
  # native input, never a shared preview or an unverified hash.
1176
1276
  full_text = None
@@ -1181,8 +1281,10 @@ def _prove_native_source(thread: str, source: Path, root: Path, batches: dict, c
1181
1281
  if (isinstance(blocks, list) and len(blocks) == 1 and isinstance(blocks[0], dict)
1182
1282
  and blocks[0].get("type") == "input_text"):
1183
1283
  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]):
1284
+ if (isinstance(full_text, str) and full_text and (
1285
+ key[3] is not None and _text_key(" ".join(full_text.split())) == key[3]
1286
+ or key[3] is None and _native_user_import_text(full_text) == item["text"]
1287
+ )):
1186
1288
  full_user_keys[key] = _text_key(full_text)
1187
1289
  if item["kind"] == "user" and (body := _cross_chat_delivery_body(item["text"])):
1188
1290
  delivery_bodies[key] = body
@@ -1192,10 +1294,11 @@ def _prove_native_source(thread: str, source: Path, root: Path, batches: dict, c
1192
1294
  assistant_native_keys[key] = _text_key(cleaned)
1193
1295
  if origin:
1194
1296
  candidate_assistants.add((origin["event_id"], origin["turn_id"], origin["timestamp"]))
1195
- if origin:
1297
+ if origin or item["kind"] == "user":
1196
1298
  ids = canonical.setdefault(key, {})
1197
- retained += origin["event_id"] not in ids
1198
- ids[origin["event_id"]] = origin
1299
+ if origin:
1300
+ retained += origin["event_id"] not in ids
1301
+ ids[origin["event_id"]] = origin
1199
1302
  occurrences.setdefault((item["kind"], key[2], timestamp, key[3]), []).append((offset, key))
1200
1303
  retained += 1
1201
1304
  if retained > MAX_KEYS:
@@ -1203,6 +1306,28 @@ def _prove_native_source(thread: str, source: Path, root: Path, batches: dict, c
1203
1306
  if require_verified_checkpoint and any((offset, expected) not in verified
1204
1307
  for offset, expectations in wanted.items() for expected in expectations):
1205
1308
  raise _Unproven()
1309
+ # One logical run may own its initial turn and later continuations. Display
1310
+ # compaction must not let its original input consume a genuine repeat in
1311
+ # another owned turn. Keep at most two source identities per display key;
1312
+ # unknown or ambiguous ownership cannot establish this additional proof.
1313
+ compacted_user_sources: dict = {}
1314
+ uncertain_user_sources: set[str] = set()
1315
+ for source_key, source_ids in canonical.items():
1316
+ budget.check()
1317
+ if source_key[1] != "user" or source_key[3] is not None:
1318
+ continue
1319
+ source_owners = set(owners.get((thread, source_key[0]), set()))
1320
+ for _offset, item_key in assistant_owner_evidence.get(source_key[0], ()):
1321
+ if len(assistant_source_turns[item_key]) == 1:
1322
+ source_owners.update(assistant_item_owners[item_key])
1323
+ if len(source_owners) != 1 or not source_ids:
1324
+ uncertain_user_sources.add(source_key[2])
1325
+ continue
1326
+ identities = compacted_user_sources.setdefault((next(iter(source_owners)), source_key[2]), set())
1327
+ for source_id in source_ids:
1328
+ if len(identities) >= 2:
1329
+ break
1330
+ identities.add((source_key[0], source_id))
1206
1331
  proofs = {}
1207
1332
  for target in candidates:
1208
1333
  budget.check()
@@ -1241,6 +1366,15 @@ def _prove_native_source(thread: str, source: Path, root: Path, batches: dict, c
1241
1366
  if len(proofs) > MAX_TARGETS:
1242
1367
  raise _Unproven()
1243
1368
  continue
1369
+ goal_origin = timestamp_origins[0] if len(timestamp_origins) == 1 else None
1370
+ goal_match = goal_assistants.match(goal_origin, assistant_native_keys.get(key, ""),
1371
+ before_seq=first, provider_id=thread) if (
1372
+ goal_assistants and goal_origin and kind == "assistant" and source_hash is None) else None
1373
+ if goal_match is not None:
1374
+ proofs[target] = {**goal_origin, "native_event_id": goal_match["id"], "source_text_sha256": body_key}
1375
+ if len(proofs) > MAX_TARGETS:
1376
+ raise _Unproven()
1377
+ continue
1244
1378
  if len(source_ids) != 1 or source_hash is not None and key not in full_user_keys:
1245
1379
  continue
1246
1380
  source_origin = next(iter(source_ids.values()))
@@ -1253,9 +1387,17 @@ def _prove_native_source(thread: str, source: Path, root: Path, batches: dict, c
1253
1387
  if len(owned_runs) != 1:
1254
1388
  continue
1255
1389
  native_run = next(iter(owned_runs))
1256
- native_body_key = full_user_keys.get(key, body_key)
1390
+ native_body_key = full_user_keys.get(key, body_key) if source_hash is not None else body_key
1257
1391
  native_matches = [event for event in native.get((native_run, kind, native_body_key), [])
1258
1392
  if event.get("type") != "turn_steered" or event.get("provider_turn_id") == key[0]]
1393
+ if (not native_matches and kind == "user" and source_hash is None and key in full_user_keys
1394
+ and body_key not in uncertain_user_sources
1395
+ and len(compacted_user_sources.get((native_run, body_key), ())) == 1):
1396
+ original_key = full_user_keys[key]
1397
+ original_matches = [event for event in native.get((native_run, kind, original_key), [])
1398
+ if event.get("type") != "turn_steered" or event.get("provider_turn_id") == key[0]]
1399
+ if original_matches:
1400
+ native_body_key, native_matches = original_key, original_matches
1259
1401
  if not native_matches and kind == "user" and source_hash is None:
1260
1402
  delivery = deliveries.match(session_id, thread, native_run, source_origin,
1261
1403
  delivery_bodies.get(key), delivery_source_ids.get(key[0], set()), body_key)
@@ -1371,7 +1513,8 @@ class CodexNativeHistoryRepairCache(CodexGoalHistoryRepairCache):
1371
1513
  def _prove_pending_native_inputs(session_id: str, provider_id: str, items: list[dict],
1372
1514
  source: Path, root: Path, checkpoint: dict, parse_item: Callable,
1373
1515
  previous_seq: int, owners: dict, deliveries: _AsyncDeliveryIndex,
1374
- budget: _NativeReadBudget, native_inputs: dict | None = None) -> dict:
1516
+ budget: _NativeReadBudget, native_inputs: dict | None = None,
1517
+ compacted_input_keys: set[str] | None = None) -> dict:
1375
1518
  """Reuse pinned-prefix proof before broadcast; the synthetic batch is never stored."""
1376
1519
  cursor = checkpoint.get("cursor")
1377
1520
  if (checkpoint.get("version") != 1 or not isinstance(cursor, dict) or cursor.get("version") != 1
@@ -1390,7 +1533,8 @@ def _prove_pending_native_inputs(session_id: str, provider_id: str, items: list[
1390
1533
  or origin.get("session_id", provider_id) != provider_id
1391
1534
  or not (item.get("source_text_sha256") is not None
1392
1535
  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)):
1536
+ or _text_key(item["text"]) in steer_keys
1537
+ or _text_key(item["text"]) in (compacted_input_keys or set()))):
1394
1538
  continue
1395
1539
  candidate = _replay_target({"seq": previous_seq + index + 2, "id": f"pending:{index}", "run_id": run,
1396
1540
  "type": "turn_started", "backend": "codex", "imported": True, "prompt": item["text"],
@@ -1449,7 +1593,9 @@ def filter_native_codex_history_items(session_id: str, provider_id: str, events:
1449
1593
  and isinstance(item.get("text"), str))
1450
1594
  owners, native, assistant_items, wake_keys, native_count = {}, {}, {}, set(), 0
1451
1595
  native_inputs, steered_inputs = {}, {}
1596
+ compacted_input_keys: set[str] = set()
1452
1597
  deliveries = _AsyncDeliveryIndex()
1598
+ goal_assistants = _NativeGoalAssistantReplays(provider_id)
1453
1599
  prove_deliveries = (source_path is not None and root is not None
1454
1600
  and isinstance(sync_checkpoint, dict) and callable(parse_item)
1455
1601
  and any(item.get("kind") == "user" and isinstance(item.get("text"), str) for item in items))
@@ -1460,6 +1606,10 @@ def filter_native_codex_history_items(session_id: str, provider_id: str, events:
1460
1606
  raise _Unproven()
1461
1607
  previous_seq = seq
1462
1608
  run = event.get("run_id")
1609
+ if event.get("session_id") in (None, "", session_id):
1610
+ goal_assistants.event(event)
1611
+ if native_count + owner_count + len(assistant_items) + deliveries.count + goal_assistants.count > MAX_KEYS:
1612
+ raise _Unproven()
1463
1613
  if prove_deliveries and event.get("session_id") in (None, "", session_id):
1464
1614
  deliveries.observe(event)
1465
1615
  if native_count + owner_count + len(assistant_items) + deliveries.count > MAX_KEYS:
@@ -1475,16 +1625,35 @@ def filter_native_codex_history_items(session_id: str, provider_id: str, events:
1475
1625
  owner_count += run not in owned
1476
1626
  owned.add(run)
1477
1627
  steer_turn = _native_goal_steer_turn(event)
1628
+ if event.get("purpose") == "codex_goal_resume" and not steer_turn:
1629
+ # Keep exact public reply identity for source-prefix ownership,
1630
+ # without granting equal-text credit to every reply in the goal.
1631
+ item_id = _public_assistant_item_id(event)
1632
+ body = event.get("text")
1633
+ if item_id is not None and isinstance(body, str) and body:
1634
+ assistant_items[(run, item_id, _text_key(body))] = _native_event_identity(event)
1635
+ if native_count + owner_count + len(assistant_items) + deliveries.count + goal_assistants.count > MAX_KEYS:
1636
+ raise _Unproven()
1637
+ continue
1478
1638
  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
1639
  body = event.get("prompt") if kind == "user" else event.get("result_text") if event.get("type") == "turn_finished" else event.get("text")
1480
1640
  wake_hash = _native_mailbox_wake_hash(event) if kind == "user" else None
1481
1641
  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
1642
+ compacted_key = (_text_key(_native_user_import_text(body))
1643
+ if prove_deliveries and kind == "user" and event.get("type") == "turn_started"
1644
+ and isinstance(body, str) and body and wake_hash is None else None)
1645
+ compacted_candidate = (compacted_key is not None and key != ("user", compacted_key)
1646
+ and ("user", compacted_key) in candidate_keys)
1647
+ if key in candidate_keys or compacted_candidate or (isinstance(body, str) and
1483
1648
  (kind, _text_key(" ".join(body.split()))) in source_keys):
1484
1649
  keys = steered_inputs.setdefault((run, steer_turn), {}) if steer_turn else native.setdefault(run, {})
1485
1650
  native_count += key not in keys
1486
1651
  if isinstance(event.get("id"), str) and 0 < len(event["id"]) <= 256:
1487
1652
  keys.setdefault(key, event["id"])
1653
+ if compacted_candidate:
1654
+ # Only select a source-proof candidate. The native maps
1655
+ # retain the original bytes, never a display-text alias.
1656
+ compacted_input_keys.add(compacted_key)
1488
1657
  if prove_deliveries and kind == "user" and isinstance(body, str) and body:
1489
1658
  inputs = native_inputs.setdefault((run, kind, key[1]), [])
1490
1659
  if not any(prior.get("type") == event.get("type")
@@ -1499,7 +1668,7 @@ def filter_native_codex_history_items(session_id: str, provider_id: str, events:
1499
1668
  item_id = _public_assistant_item_id(event)
1500
1669
  if item_id is not None and key is not None:
1501
1670
  assistant_items[(run, item_id, key[1])] = _native_event_identity(event)
1502
- if native_count + owner_count + len(assistant_items) + deliveries.count > MAX_KEYS:
1671
+ if native_count + owner_count + len(assistant_items) + deliveries.count + goal_assistants.count > MAX_KEYS:
1503
1672
  raise _Unproven()
1504
1673
  assistant_item_owners = _native_assistant_item_owners(
1505
1674
  assistant_items, {run for runs in owners.values() for run in runs}, provider_id,
@@ -1520,16 +1689,16 @@ def filter_native_codex_history_items(session_id: str, provider_id: str, events:
1520
1689
  for item_key, turns in assistant_source_turns.items():
1521
1690
  if len(turns) == 1:
1522
1691
  owners.setdefault(next(iter(turns)), set()).update(assistant_item_owners[item_key])
1523
- if prove_deliveries and steered_inputs:
1692
+ if prove_deliveries and (steered_inputs or compacted_input_keys):
1524
1693
  # The unmatched import can contain only follow-ups: its assistant
1525
1694
  # messages were already reconciled. Preserve public item identities
1526
- # for the source scan to recover earlier turns of a long goal run.
1695
+ # for the source scan to recover earlier turns of a long native run.
1527
1696
  for (run, _item_id, body_key), event in assistant_items.items():
1528
1697
  native_inputs.setdefault((run, "assistant", body_key), []).append(event)
1529
1698
  delivery_proofs = _prove_pending_native_inputs(
1530
1699
  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(
1700
+ previous_seq, owners, deliveries, budget, native_inputs, compacted_input_keys,
1701
+ ) if prove_deliveries and (deliveries.starts or steered_inputs or compacted_input_keys or any(
1533
1702
  item.get("kind") == "user" and item.get("source_text_sha256") is not None for item in items)) else {}
1534
1703
  # A hidden wake has no public prompt body. Require a single exact source
1535
1704
  # item in this verified import range, in addition to native turn ownership.
@@ -1545,6 +1714,10 @@ def filter_native_codex_history_items(session_id: str, provider_id: str, events:
1545
1714
  for index, item in enumerate(items):
1546
1715
  budget.check()
1547
1716
  origin = item.get("provider_origin")
1717
+ if (item.get("kind") == "assistant" and isinstance(origin, dict)
1718
+ and isinstance(item.get("text"), str) and item.get("source_text_sha256") is None
1719
+ and goal_assistants.match(origin, _text_key(_native_assistant_text(item["text"]))) is not None):
1720
+ continue
1548
1721
  runs = owners.get(origin.get("turn_id"), set()) if isinstance(origin, dict) else set()
1549
1722
  owned = (isinstance(origin, dict) and origin.get("provider") == "codex"
1550
1723
  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
@@ -19,7 +19,7 @@ from side_questions import (
19
19
  )
20
20
 
21
21
 
22
- SIDE_INSTRUCTIONS = """Answer questions and explore in this separate side chat without disrupting the main conversation.
22
+ SIDE_INSTRUCTIONS = """You are a separate side chat of the parent conversation, not the main chat. Answer questions and explore here without disrupting the main conversation.
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
 
@@ -287,6 +287,8 @@ class NativeCodexSideChat:
287
287
  raise SideQuestionError(409, "Side chat was closed; open a new side chat")
288
288
  config = side_chat_config(self.fork_overrides.get("config"))
289
289
  config.update(self.provider_config)
290
+ inherited_instructions = self.fork_overrides.get("developerInstructions") or ""
291
+ side_instructions = "\n\n".join(value for value in (inherited_instructions, SIDE_INSTRUCTIONS) if value)
290
292
  # Preserve Codex's auth/runtime location. Overriding sqlite_home while
291
293
  # retaining the user's history root can trigger a complete reindex.
292
294
  config.update({"log_dir": str(Path(temporary) / "log"), "history.persistence": "none"})
@@ -322,11 +324,10 @@ class NativeCodexSideChat:
322
324
  await self._client.start()
323
325
  if self._closed:
324
326
  raise SideQuestionError(409, "Side chat was closed; open a new side chat")
325
- inherited_instructions = self.fork_overrides.get("developerInstructions") or ""
326
327
  params = {
327
328
  **self.fork_overrides,
328
329
  "ephemeral": not self.durable, "excludeTurns": True,
329
- "developerInstructions": "\n\n".join(value for value in (inherited_instructions, SIDE_INSTRUCTIONS) if value),
330
+ "developerInstructions": side_instructions,
330
331
  "config": config,
331
332
  }
332
333
  if self.cwd:
@@ -369,6 +370,15 @@ class NativeCodexSideChat:
369
370
  elif metadata.get("ephemeral") is not True or metadata.get("path") is not None:
370
371
  raise SideQuestionError(503, "Codex did not confirm an ephemeral side chat")
371
372
 
373
+ # Native forks/resumes can inherit the parent's effective developer
374
+ # context even when developerInstructions is supplied in their config.
375
+ # Append the side identity to the actual child context, including on
376
+ # resume. This is provider context, never a user message in the UI.
377
+ await self._client.inject_items(self.thread_id, [{
378
+ "type": "message", "role": "developer",
379
+ "content": [{"type": "input_text", "text": SIDE_INSTRUCTIONS}],
380
+ }])
381
+
372
382
  async def ask(self, question: str, *, runtime_settings: dict | None = None, on_progress=None) -> str:
373
383
  if self._closed:
374
384
  raise SideQuestionError(409, "Side chat was closed; open a new side chat")
@@ -57,7 +57,9 @@ async def catalog(selected: dict, *, executable: str | None, env: dict) -> dict:
57
57
  and selected["api_key"] not in item["id"] + item["label"]]
58
58
  if not models:
59
59
  return {"models": [], "discovery_status": "unavailable"}
60
- return {"models": models[:256], "discovery_status": "ready"}
60
+ # Match the shared catalog boundary. A truncated list is not complete
61
+ # evidence that a saved model disappeared from this account.
62
+ return {"models": models[:512], "discovery_status": "partial" if len(models) > 512 else "ready"}
61
63
  except SideQuestionError:
62
64
  # Offline and invalid keys can look identical in CLI output. Do not
63
65
  # misclassify an outage as a logout or return key-bearing stderr.