@agentsdock/server 1.0.12-beta.6 → 1.0.12-beta.9

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.
@@ -151,8 +151,11 @@ def native_catalog_key(executable: str, env: dict[str, str]) -> str:
151
151
  """
152
152
  home = Path(env.get("HOME") or str(Path.home()))
153
153
  config = Path(env.get("CLAUDE_CONFIG_DIR") or home / ".claude")
154
+ # The runner adds this scheduling limit to real chat processes. It does
155
+ # not change account/model policy and is absent from catalog reads.
154
156
  relevant = {key: value for key, value in env.items()
155
- if key.startswith(("ANTHROPIC_", "CLAUDE_")) or key == "HOME"}
157
+ if (key.startswith(("ANTHROPIC_", "CLAUDE_")) or key == "HOME")
158
+ and key != "CLAUDE_CODE_MAX_CONCURRENT_SUBAGENTS"}
156
159
  resolved = shutil.which(executable, path=env.get("PATH")) or executable
157
160
  revisions = [_file_revision(Path(resolved)), *(
158
161
  _file_revision(path) for path in (
@@ -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 (
@@ -1255,8 +1265,8 @@ def _prove_native_source(thread: str, source: Path, root: Path, batches: dict, c
1255
1265
  raise _Unproven()
1256
1266
  if (item["kind"], key[2], key[3]) not in candidate_keys:
1257
1267
  continue
1258
- if item["kind"] == "user" and key[3] is not None:
1259
- # 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
1260
1270
  # checkpoint-verified record. Compare those bytes to the original
1261
1271
  # native input, never a shared preview or an unverified hash.
1262
1272
  full_text = None
@@ -1267,8 +1277,10 @@ def _prove_native_source(thread: str, source: Path, root: Path, batches: dict, c
1267
1277
  if (isinstance(blocks, list) and len(blocks) == 1 and isinstance(blocks[0], dict)
1268
1278
  and blocks[0].get("type") == "input_text"):
1269
1279
  full_text = blocks[0].get("text")
1270
- if (isinstance(full_text, str) and full_text
1271
- 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
+ )):
1272
1284
  full_user_keys[key] = _text_key(full_text)
1273
1285
  if item["kind"] == "user" and (body := _cross_chat_delivery_body(item["text"])):
1274
1286
  delivery_bodies[key] = body
@@ -1278,10 +1290,11 @@ def _prove_native_source(thread: str, source: Path, root: Path, batches: dict, c
1278
1290
  assistant_native_keys[key] = _text_key(cleaned)
1279
1291
  if origin:
1280
1292
  candidate_assistants.add((origin["event_id"], origin["turn_id"], origin["timestamp"]))
1281
- if origin:
1293
+ if origin or item["kind"] == "user":
1282
1294
  ids = canonical.setdefault(key, {})
1283
- retained += origin["event_id"] not in ids
1284
- ids[origin["event_id"]] = origin
1295
+ if origin:
1296
+ retained += origin["event_id"] not in ids
1297
+ ids[origin["event_id"]] = origin
1285
1298
  occurrences.setdefault((item["kind"], key[2], timestamp, key[3]), []).append((offset, key))
1286
1299
  retained += 1
1287
1300
  if retained > MAX_KEYS:
@@ -1289,6 +1302,28 @@ def _prove_native_source(thread: str, source: Path, root: Path, batches: dict, c
1289
1302
  if require_verified_checkpoint and any((offset, expected) not in verified
1290
1303
  for offset, expectations in wanted.items() for expected in expectations):
1291
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))
1292
1327
  proofs = {}
1293
1328
  for target in candidates:
1294
1329
  budget.check()
@@ -1348,9 +1383,17 @@ def _prove_native_source(thread: str, source: Path, root: Path, batches: dict, c
1348
1383
  if len(owned_runs) != 1:
1349
1384
  continue
1350
1385
  native_run = next(iter(owned_runs))
1351
- 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
1352
1387
  native_matches = [event for event in native.get((native_run, kind, native_body_key), [])
1353
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
1354
1397
  if not native_matches and kind == "user" and source_hash is None:
1355
1398
  delivery = deliveries.match(session_id, thread, native_run, source_origin,
1356
1399
  delivery_bodies.get(key), delivery_source_ids.get(key[0], set()), body_key)
@@ -1466,7 +1509,8 @@ class CodexNativeHistoryRepairCache(CodexGoalHistoryRepairCache):
1466
1509
  def _prove_pending_native_inputs(session_id: str, provider_id: str, items: list[dict],
1467
1510
  source: Path, root: Path, checkpoint: dict, parse_item: Callable,
1468
1511
  previous_seq: int, owners: dict, deliveries: _AsyncDeliveryIndex,
1469
- 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:
1470
1514
  """Reuse pinned-prefix proof before broadcast; the synthetic batch is never stored."""
1471
1515
  cursor = checkpoint.get("cursor")
1472
1516
  if (checkpoint.get("version") != 1 or not isinstance(cursor, dict) or cursor.get("version") != 1
@@ -1485,7 +1529,8 @@ def _prove_pending_native_inputs(session_id: str, provider_id: str, items: list[
1485
1529
  or origin.get("session_id", provider_id) != provider_id
1486
1530
  or not (item.get("source_text_sha256") is not None
1487
1531
  or _cross_chat_delivery_body(item["text"]) or _text_key(item["text"]) in deliveries.status_body_keys
1488
- 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()))):
1489
1534
  continue
1490
1535
  candidate = _replay_target({"seq": previous_seq + index + 2, "id": f"pending:{index}", "run_id": run,
1491
1536
  "type": "turn_started", "backend": "codex", "imported": True, "prompt": item["text"],
@@ -1544,6 +1589,7 @@ def filter_native_codex_history_items(session_id: str, provider_id: str, events:
1544
1589
  and isinstance(item.get("text"), str))
1545
1590
  owners, native, assistant_items, wake_keys, native_count = {}, {}, {}, set(), 0
1546
1591
  native_inputs, steered_inputs = {}, {}
1592
+ compacted_input_keys: set[str] = set()
1547
1593
  deliveries = _AsyncDeliveryIndex()
1548
1594
  goal_assistants = _NativeGoalAssistantReplays(provider_id)
1549
1595
  prove_deliveries = (source_path is not None and root is not None
@@ -1589,12 +1635,21 @@ def filter_native_codex_history_items(session_id: str, provider_id: str, events:
1589
1635
  body = event.get("prompt") if kind == "user" else event.get("result_text") if event.get("type") == "turn_finished" else event.get("text")
1590
1636
  wake_hash = _native_mailbox_wake_hash(event) if kind == "user" else None
1591
1637
  key = (kind, wake_hash or _text_key(body)) if kind and (isinstance(body, str) and body or wake_hash) else None
1592
- 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
1593
1644
  (kind, _text_key(" ".join(body.split()))) in source_keys):
1594
1645
  keys = steered_inputs.setdefault((run, steer_turn), {}) if steer_turn else native.setdefault(run, {})
1595
1646
  native_count += key not in keys
1596
1647
  if isinstance(event.get("id"), str) and 0 < len(event["id"]) <= 256:
1597
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)
1598
1653
  if prove_deliveries and kind == "user" and isinstance(body, str) and body:
1599
1654
  inputs = native_inputs.setdefault((run, kind, key[1]), [])
1600
1655
  if not any(prior.get("type") == event.get("type")
@@ -1630,16 +1685,16 @@ def filter_native_codex_history_items(session_id: str, provider_id: str, events:
1630
1685
  for item_key, turns in assistant_source_turns.items():
1631
1686
  if len(turns) == 1:
1632
1687
  owners.setdefault(next(iter(turns)), set()).update(assistant_item_owners[item_key])
1633
- if prove_deliveries and steered_inputs:
1688
+ if prove_deliveries and (steered_inputs or compacted_input_keys):
1634
1689
  # The unmatched import can contain only follow-ups: its assistant
1635
1690
  # messages were already reconciled. Preserve public item identities
1636
- # 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.
1637
1692
  for (run, _item_id, body_key), event in assistant_items.items():
1638
1693
  native_inputs.setdefault((run, "assistant", body_key), []).append(event)
1639
1694
  delivery_proofs = _prove_pending_native_inputs(
1640
1695
  session_id, provider_id, items, source_path, root, sync_checkpoint, parse_item,
1641
- previous_seq, owners, deliveries, budget, native_inputs,
1642
- ) 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(
1643
1698
  item.get("kind") == "user" and item.get("source_text_sha256") is not None for item in items)) else {}
1644
1699
  # A hidden wake has no public prompt body. Require a single exact source
1645
1700
  # item in this verified import range, in addition to native turn ownership.
@@ -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
@@ -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.
@@ -52,6 +52,13 @@ def parse_models(value):
52
52
  model = str(item.get("name") or "").removeprefix("models/")
53
53
  if not MODEL.fullmatch(model) or "generateContent" not in item.get("supportedGenerationMethods", []):
54
54
  continue
55
+ # generateContent also lists audio-only products. These cannot satisfy
56
+ # the text/tool contract of Gemini CLI. Unknown chat families stay in
57
+ # the inventory; do not use a version/deprecation blacklist.
58
+ modalities = item.get("outputModalities")
59
+ if (isinstance(modalities, list) and modalities and "TEXT" not in modalities
60
+ or re.search(r"(?:^|-)tts(?:-|$)", model) or model.startswith("lyria-")):
61
+ continue
55
62
  label = item.get("displayName") or model
56
63
  if not isinstance(label, str) or not label or len(label) > 256 or any(ord(c) < 32 or ord(c) == 127 for c in label):
57
64
  label = model
@@ -107,6 +114,7 @@ async def probe(selected):
107
114
  async with client.stream(method, target, headers=headers, **kwargs) as response:
108
115
  if response.status_code in {400, 401, 403}: return "authentication_failed" if not model or response.status_code != 400 else "unsupported"
109
116
  if response.status_code == 429: return "rate_limited"
117
+ if response.status_code == 404 and model: return "model_unavailable"
110
118
  if response.status_code != 200: return "connection_failed"
111
119
  raw = bytearray()
112
120
  async for chunk in response.aiter_bytes():
@@ -29,7 +29,7 @@ MAX_BODY_BYTES = 16 * 1024
29
29
  # Keep this explicit probe bounded and single-shot, including for such models.
30
30
  MODEL_CHECK_MAX_OUTPUT_TOKENS = 256
31
31
  PROTOCOLS = {"claude": {"anthropic"}, "opencode": {"anthropic", "chat_completions", "responses"}, "cursor": {"cursor"}, "gemini": {"gemini"}}
32
- RESULTS = {"verified", "authentication_failed", "rate_limited", "unsupported", "connection_failed", "invalid_response", "model_required", "cli_update_required"}
32
+ RESULTS = {"verified", "authentication_failed", "rate_limited", "unsupported", "model_unavailable", "connection_failed", "invalid_response", "model_required", "cli_update_required"}
33
33
 
34
34
 
35
35
  def backend_name(value: str) -> str:
@@ -75,6 +75,35 @@ class ConnectionStore:
75
75
  self.root = root
76
76
  self.lock = threading.RLock()
77
77
  self.catalog_cache = {}
78
+ self.catalog_status = {}
79
+ self.model_checks = {}
80
+
81
+ def remember_catalog(self, backend: str, value: dict, result: dict) -> list[dict]:
82
+ key = (backend, value["revision"])
83
+ with self.lock:
84
+ old = self.catalog_cache.get(key)
85
+ status = result.get("discovery_status", "unavailable")
86
+ # A transient failure is not an authoritative empty inventory.
87
+ models = result["models"] if status in {"ready", "empty", "partial"} else (old[1] if old else result["models"])
88
+ self.catalog_cache[key] = (time.monotonic(), models)
89
+ self.catalog_status[key] = status
90
+ while len(self.catalog_cache) > 32:
91
+ oldest = next(iter(self.catalog_cache))
92
+ self.catalog_cache.pop(oldest, None)
93
+ self.catalog_status.pop(oldest, None)
94
+ return self.checked_models(backend, value, models)
95
+
96
+ def checked_models(self, backend: str, value: dict, models: list[dict]) -> list[dict]:
97
+ result = []
98
+ for model in models:
99
+ evidence = self.model_checks.get((backend, value["revision"], model["value"]))
100
+ row = dict(model)
101
+ if evidence and time.monotonic() - evidence[0] < 300:
102
+ row["check_status"] = evidence[1]
103
+ if evidence[1] in {"unsupported", "model_unavailable"}:
104
+ row.update(locked=True, locked_reason="This model rejected a request for this API connection. Check again or choose another model.")
105
+ result.append(row)
106
+ return result
78
107
 
79
108
  def _directory(self, create=False):
80
109
  if self.root.is_symlink() or self.root.parent.is_symlink():
@@ -219,24 +248,29 @@ class ConnectionStore:
219
248
  return {"configured": configured, "available": configured and installed,
220
249
  "model": model, "base_url": value.get("base_url")}
221
250
  models = []
251
+ status = "unavailable"
222
252
  if configured:
223
253
  cache_key = (backend, value["revision"])
224
254
  cached = self.catalog_cache.get(cache_key)
225
255
  if cached and time.monotonic() - cached[0] < 300:
226
256
  models = cached[1]
257
+ status = self.catalog_status.get(cache_key, "ready")
227
258
  elif session is None and backend != "cursor": # Cursor discovery uses an async CLI probe.
228
- models = discover_models(value)
229
- self.catalog_cache[cache_key] = (time.monotonic(), models)
230
- if len(self.catalog_cache) > 32:
231
- self.catalog_cache.pop(next(iter(self.catalog_cache)))
259
+ result = discover_catalog(value)
260
+ models = self.remember_catalog(backend, value, result)
261
+ status = result.get("discovery_status", "unavailable")
262
+ elif cached:
263
+ models = cached[1] # stale, not revalidated for this binding
232
264
  if backend == "cursor" and not models:
233
265
  models = [{"value": "auto", "label": "Auto"}]
234
266
  if backend == "gemini":
235
267
  from gemini_api import model_options
236
268
  models = model_options(value, models)
237
- if model and not any(item["value"] == model for item in models):
238
- models = [{"value": model, "label": model}, *models]
269
+ models = self.checked_models(backend, value, models)
270
+ if session is None and self.read(backend)["revision"] != value["revision"]:
271
+ raise HTTPException(409, "Endpoint settings changed while reading models.")
239
272
  return {"configured": configured, "available": configured and installed,
273
+ "discovery_status": status,
240
274
  "models": models, "efforts": [], "default_model": model,
241
275
  "model": model, "default_effort": None, "base_url": value.get("base_url")}
242
276
  except HTTPException:
@@ -325,10 +359,14 @@ def require_model(value: dict) -> str:
325
359
 
326
360
 
327
361
  def discover_models(value: dict) -> list[dict]:
362
+ return discover_catalog(value)["models"]
363
+
364
+
365
+ def discover_catalog(value: dict) -> dict:
328
366
  if value["protocol"] == "gemini":
329
367
  from gemini_api import catalog
330
- return catalog(value)["models"]
331
- return endpoint_model_catalog(value, protocol=value["protocol"])["models"]
368
+ return catalog(value)
369
+ return endpoint_model_catalog(value, protocol=value["protocol"])
332
370
 
333
371
 
334
372
  def native_credentials_present(backend: str, diagnostic: dict) -> bool:
@@ -441,6 +479,8 @@ async def probe(selected: dict) -> str:
441
479
  return "authentication_failed"
442
480
  if response.status_code == 429:
443
481
  return "rate_limited"
482
+ if response.status_code == 404:
483
+ return "model_unavailable"
444
484
  if response.status_code != 200:
445
485
  return "unsupported" if response.status_code < 500 else "connection_failed"
446
486
  raw = bytearray()
@@ -599,16 +639,48 @@ def create_router(*, authorize, store: ConnectionStore, check=probe, account=nat
599
639
  if backend == "codex":
600
640
  codex_store.cache_catalog(selected, result)
601
641
  else:
602
- with store.lock:
603
- store.catalog_cache[(backend, selected["revision"])] = (time.monotonic(), result["models"])
604
- if len(store.catalog_cache) > 32: store.catalog_cache.pop(next(iter(store.catalog_cache)))
642
+ result["models"] = store.remember_catalog(backend, selected, result)
605
643
  model = selected.get("model")
606
644
  if backend == "gemini":
607
- from gemini_api import default_model
645
+ from gemini_api import default_model, model_options
608
646
  model = default_model(selected)
647
+ result["models"] = model_options(selected, result["models"])
609
648
  return reply({"backend": backend, "revision": selected.get("credential_id") if backend == "codex" else selected["revision"],
649
+ "check_available": backend in {"claude", "opencode", "gemini"},
610
650
  "models": result["models"], "default_model": model, "discovery_status": result["discovery_status"]})
611
651
 
652
+ @router.post("/api/admin/provider-models/{backend}/check")
653
+ async def check_model(backend: str, request: Request):
654
+ authorize(request)
655
+ if backend not in {"claude", "opencode", "gemini"}:
656
+ raise HTTPException(400, "Use this provider's native model check.")
657
+ payload = await body(request)
658
+ if set(payload) != {"model", "expected_revision"}:
659
+ raise HTTPException(400, "Provide model and saved revision only.")
660
+ model = validate_model(payload["model"])
661
+ if not model or model == "auto":
662
+ raise HTTPException(400, "Choose an explicit model for this check.")
663
+ selected = await model_selection(backend)
664
+ if selected["revision"] != revision(payload["expected_revision"]):
665
+ raise HTTPException(409, "Endpoint settings changed. Refresh and try again.")
666
+ if locks[backend].locked():
667
+ raise HTTPException(409, "An endpoint operation is already in progress.")
668
+ async with locks[backend]:
669
+ if (await model_selection(backend))["revision"] != selected["revision"]:
670
+ raise HTTPException(409, "Endpoint settings changed. Refresh and try again.")
671
+ # Explicit, single-shot text request. Never changes saved model,
672
+ # login readiness, credentials or a chat; no project/tool access.
673
+ result = await check({**selected, "model": model})
674
+ current = await model_selection(backend)
675
+ if current["revision"] != selected["revision"]:
676
+ raise HTTPException(409, "Endpoint settings changed. Refresh and try again.")
677
+ with store.lock:
678
+ store.model_checks[(backend, selected["revision"], model)] = (time.monotonic(), result)
679
+ while len(store.model_checks) > 512:
680
+ store.model_checks.pop(next(iter(store.model_checks)))
681
+ return reply({"backend": backend, "revision": selected["revision"], "model": model,
682
+ "status": result, "scope": "text_request"})
683
+
612
684
  @router.put("/api/admin/provider-models/{backend}")
613
685
  async def default_model(backend: str, request: Request):
614
686
  authorize(request)
@@ -635,7 +707,16 @@ def create_router(*, authorize, store: ConnectionStore, check=probe, account=nat
635
707
  value = {key: current[key] for key in ("base_url", "api_key", "protocol", "auth_header")}
636
708
  saved = store.write(backend, current["revision"], {**value, "model": model, "expected_revision": current["revision"]}, current["last_result"], checked_at=current["checked_at"])
637
709
  cached = store.catalog_cache.get((backend, current["revision"]))
638
- if cached: store.catalog_cache[(backend, saved["revision"])] = cached
710
+ if cached:
711
+ store.remember_catalog(backend, saved, {"models": cached[1],
712
+ "discovery_status": store.catalog_status.get((backend, current["revision"]), "unavailable")})
713
+ # This operation changes only the default, not credentials,
714
+ # endpoint or protocol. Preserve still-fresh observations.
715
+ for (source_backend, source_revision, source_model), evidence in list(store.model_checks.items()):
716
+ if source_backend == backend and source_revision == current["revision"]:
717
+ store.model_checks[(backend, saved["revision"], source_model)] = evidence
718
+ while len(store.model_checks) > 512:
719
+ store.model_checks.pop(next(iter(store.model_checks)))
639
720
  effective_model = saved["model"]
640
721
  if backend == "gemini":
641
722
  from gemini_api import default_model as gemini_default_model