@agentsdock/server 1.0.12-beta.1 → 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.
@@ -400,8 +400,8 @@ class ExecutionTransportServer:
400
400
  _done, pending = await asyncio.wait(tuple(self._connections), timeout=max(0.0, timeout))
401
401
  for task in pending:
402
402
  task.cancel()
403
- # A peer that stopped reading can prevent close() from flushing its
404
- # buffered response indefinitely. Only explicit worker shutdown aborts
403
+ # A connected peer that stopped reading can prevent close() from
404
+ # flushing its buffered response. Explicit worker shutdown aborts
405
405
  # those remaining transports after the drain window.
406
406
  for writer in writers:
407
407
  connection = writer.get_extra_info("socket")
@@ -431,6 +431,16 @@ class ExecutionTransportServer:
431
431
  accepted = False
432
432
  disconnected = asyncio.Event()
433
433
  incoming: asyncio.Queue[dict[str, Any]] = asyncio.Queue(maxsize=4)
434
+
435
+ def disconnect_ingress() -> None:
436
+ disconnected.set()
437
+ # The accepted application keeps its task and queued input, but
438
+ # a departed ingress no longer needs an IPC descriptor or output.
439
+ # Abort also retires a socket with buffered, undeliverable output.
440
+ connection = writer.get_extra_info("socket")
441
+ if connection is not None and connection.fileno() >= 0:
442
+ writer.transport.abort()
443
+
434
444
  try:
435
445
  opening = await asyncio.wait_for(_read_frame(reader), HANDSHAKE_TIMEOUT)
436
446
  _fields(opening, {"v", "kind", "secret", "scope"})
@@ -453,14 +463,18 @@ class ExecutionTransportServer:
453
463
  if frame["kind"] != "event":
454
464
  raise ExecutionTransportError("Unexpected private protocol message")
455
465
  event = _event(frame["event"], encode=False, kind=kind, direction="request")
456
- await incoming.put(event)
457
466
  if event["type"].endswith(".disconnect"):
467
+ # Do not wait behind a full input queue to release
468
+ # the dead socket. receive() still drains every
469
+ # accepted body event before this disconnect.
470
+ disconnect.update(event)
458
471
  break
472
+ await incoming.put(event)
459
473
  except (ExecutionTransportError, asyncio.IncompleteReadError, ConnectionError, OSError):
460
474
  pass
461
475
  # Cancellation by our own completed app's cleanup is not peer
462
476
  # disconnection: leave its bounded input drain enabled.
463
- disconnected.set()
477
+ disconnect_ingress()
464
478
 
465
479
  async def receive() -> dict[str, Any]:
466
480
  if not incoming.empty():
@@ -486,7 +500,7 @@ class ExecutionTransportServer:
486
500
  try:
487
501
  await _write_frame(writer, {"kind": "event", "event": event})
488
502
  except (ConnectionError, OSError):
489
- disconnected.set()
503
+ disconnect_ingress()
490
504
  return
491
505
 
492
506
  pump = asyncio.create_task(read_events(), name="execution-request-reader")
@@ -516,8 +530,10 @@ class ExecutionTransportServer:
516
530
 
517
531
  with suppress(asyncio.TimeoutError, ConnectionError, OSError):
518
532
  await asyncio.wait_for(drain_ingress(), 1.0)
519
- self._writers.discard(writer)
520
- await _close_writer(writer)
533
+ try:
534
+ await _close_writer(writer)
535
+ finally:
536
+ self._writers.discard(writer)
521
537
 
522
538
 
523
539
  class ExecutionGateway:
@@ -544,6 +560,7 @@ class ExecutionGateway:
544
560
  pump: asyncio.Task[Any] | None = None
545
561
  response_started = False
546
562
  expects_trailers = False
563
+ client_disconnected = False
547
564
  try:
548
565
  secret = _read_secret(self.secret_path)
549
566
  identity = _socket_identity(self.socket_path)
@@ -558,11 +575,14 @@ class ExecutionGateway:
558
575
  raise ExecutionTransportError("Execution handshake failed")
559
576
 
560
577
  async def forward_requests() -> None:
578
+ nonlocal client_disconnected
561
579
  try:
562
580
  while True:
563
581
  message = await receive()
564
582
  for chunk in _chunks(message):
565
583
  event = _event(chunk, encode=True, kind=scope["type"], direction="request")
584
+ if event["type"].endswith(".disconnect"):
585
+ client_disconnected = True
566
586
  await _write_frame(writer, {"kind": "event", "event": event})
567
587
  if message["type"].endswith(".disconnect"):
568
588
  writer.close()
@@ -603,6 +623,12 @@ class ExecutionGateway:
603
623
  return
604
624
  except (ExecutionTransportError, asyncio.IncompleteReadError, ConnectionError,
605
625
  OSError, asyncio.TimeoutError):
626
+ if client_disconnected:
627
+ # Closing ingress also closes IPC. Its resulting EOF is normal
628
+ # after an explicit client disconnect; the worker still owns
629
+ # accepted work. Do not report it as an execution failure or
630
+ # synthesize a response to a client that has already left.
631
+ return
606
632
  if not response_started:
607
633
  if scope["type"] == "http":
608
634
  await send({"type": "http.response.start", "status": 503,
@@ -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():
package/server/install.sh CHANGED
@@ -89,16 +89,16 @@ INSTANCE_EXPLICIT="false"
89
89
  LABEL="com.agentsdock.server"
90
90
  INSTANCE_LOG_DIR="$HOME/Library/Logs/AgentsServer"
91
91
  LEGACY_SERVICE_NAME="zenithbot-agent"
92
- # AgentsServer's cooperative shutdown has 18 independently bounded cleanup
92
+ # AgentsServer's cooperative shutdown has 19 independently bounded cleanup
93
93
  # phases in addition to uvicorn's graceful window. Five seconds was shorter
94
94
  # than even an ordinary slow shutdown: launchctl had already accepted bootout,
95
95
  # then the installer abandoned activation/rollback and could leave the service
96
96
  # unloaded. Keep this wait bounded, but long enough for the server's complete
97
97
  # worst-case graceful budget before declaring the exact launchd job wedged.
98
- # AgentsServer caps the configurable uvicorn window at 60 seconds; 185 seconds
99
- # covers that window, all 18 five-second teardown phases, the watchdog margin,
98
+ # AgentsServer caps the configurable uvicorn window at 60 seconds; 190 seconds
99
+ # covers that window, all 19 five-second teardown phases, the watchdog margin,
100
100
  # and another 30 seconds for launchd to reap the terminated process.
101
- LAUNCHCTL_STOP_ATTEMPTS=1850
101
+ LAUNCHCTL_STOP_ATTEMPTS=1900
102
102
  LAUNCHCTL_STOP_DELAY=0.1
103
103
  LAUNCHCTL_BOOTSTRAP_ATTEMPTS=3
104
104
  NON_INTERACTIVE="false"
@@ -1846,7 +1846,7 @@ if [[ "$TEAM_HUB_MODE" == "host" && "$TEAM_HUB_OPERATION_PENDING" != "true" \
1846
1846
  fi
1847
1847
  fi
1848
1848
 
1849
- RELEASE_FILES=(activation_transaction.py execution_activation.py execution_legacy_runner.py execution_preparation.py update_preparation.py update_handoff.py update_recovery.py execution_update_status.py execution_uninstall.py execution_recovery.py execution_recovery_status.py execution_http.py execution_durability.py execution_control.py execution_install.py execution_maintenance.py execution_manage.py execution_ownership.py execution_service.py execution_transport.py agent_server.py local_session_ownership.py cursor_history.py workspace_git.py team_hub_host.py secure_peer_runtime.py team_mail_runtime.py team_mail_websocket.py team_mail_grants.py secure_peer_delivery.py agentsdock_jobs.py agentsdock_chats.py chat_mailbox.py agentsdock_emergency.py agentsdock_notify.py agentsdock_publish.py agentsdock_mail.py agentsdock_team.py provider_commands.py provider_usage.py session_unread.py claude_sdk_client.py claude_model_catalog.py claude_goals.py claude_background_reconciliation.py codex_app_server.py codex_auth.py codex_provider.py codex_response_stream.py provider_connections.py cursor_api_key.py side_questions.py title_generation.py codex_side_question.py codex_side_chat_progress.py claude_side_question.py cursor_agent_client.py cursor_provider_mcp.py opencode_agent_client.py gemini_acp_client.py gemini_history.py gemini_content.py gemini_import.py gemini_runtime.py gemini_runner.py gemini_permissions.py gemini_api.py cursor_process_guard.py transcript_reader.py claude_history_repair.py claude_history_provenance.py codex_history_repair.py public_chat_shares.py public_chat_transcript.py public_chat_share_routes.py interactive_chat_shares.py interactive_chat_share_routes.py interactive_chat_share_web.py interactive_chat_projection.py interactive_chat_runtime.py interactive_chat_native.py shared_chat_videos.py shared_chat_analytics_web.py shared_chat_video_stream.py interactive_chat_controls.py install.sh uninstall.sh instances.sh server_instances.py npm/agentsdock/pair.cjs npm/agentsdock/qr-renderer.cjs npm/agentsdock/QR-NOTICES.txt update_runner.py pyproject.toml uv.lock VERSION release-public-key.pem LICENSE NOTICE)
1849
+ RELEASE_FILES=(activation_transaction.py execution_activation.py execution_legacy_runner.py execution_preparation.py update_preparation.py update_handoff.py update_recovery.py execution_update_status.py execution_uninstall.py execution_recovery.py execution_recovery_status.py execution_http.py execution_durability.py execution_control.py execution_install.py execution_maintenance.py execution_manage.py execution_ownership.py execution_service.py execution_transport.py agent_server.py local_session_ownership.py cursor_history.py workspace_git.py workspace_intelligence.py team_hub_host.py secure_peer_runtime.py team_mail_runtime.py team_mail_websocket.py team_mail_grants.py secure_peer_delivery.py agentsdock_jobs.py agentsdock_chats.py chat_mailbox.py agentsdock_emergency.py agentsdock_notify.py agentsdock_publish.py agentsdock_mail.py agentsdock_team.py provider_commands.py provider_usage.py session_unread.py claude_sdk_client.py claude_chat_routing.py claude_model_catalog.py claude_goals.py claude_background_reconciliation.py codex_app_server.py codex_auth.py codex_provider.py codex_response_stream.py provider_connections.py cursor_api_key.py side_questions.py title_generation.py codex_side_question.py codex_side_chat_progress.py claude_side_question.py cursor_agent_client.py cursor_provider_mcp.py opencode_agent_client.py gemini_acp_client.py gemini_history.py gemini_content.py gemini_import.py gemini_runtime.py gemini_runner.py gemini_permissions.py gemini_api.py cursor_process_guard.py transcript_reader.py claude_history_repair.py claude_history_provenance.py codex_history_repair.py public_chat_shares.py public_chat_transcript.py public_chat_share_routes.py interactive_chat_shares.py interactive_chat_share_routes.py interactive_chat_share_web.py interactive_chat_projection.py interactive_chat_runtime.py interactive_chat_native.py shared_chat_videos.py shared_chat_analytics_web.py shared_chat_video_stream.py interactive_chat_controls.py install.sh uninstall.sh instances.sh server_instances.py npm/agentsdock/pair.cjs npm/agentsdock/qr-renderer.cjs npm/agentsdock/QR-NOTICES.txt update_runner.py pyproject.toml uv.lock VERSION release-public-key.pem LICENSE NOTICE)
1850
1850
  RELEASE_DIRECTORIES=(agentsdock_team_hub)
1851
1851
  TEAM_HUB_RELEASE_FILES=(
1852
1852
  __init__.py
@@ -3761,6 +3761,7 @@ validate_staged_release_runtime() (
3761
3761
  "$STAGE_DIR/provider_usage.py" \
3762
3762
  "$STAGE_DIR/session_unread.py" \
3763
3763
  "$STAGE_DIR/claude_sdk_client.py" \
3764
+ "$STAGE_DIR/claude_chat_routing.py" \
3764
3765
  "$STAGE_DIR/claude_model_catalog.py" \
3765
3766
  "$STAGE_DIR/claude_goals.py" \
3766
3767
  "$STAGE_DIR/claude_background_reconciliation.py" \
@@ -3770,6 +3771,7 @@ validate_staged_release_runtime() (
3770
3771
  "$STAGE_DIR/provider_connections.py" "$STAGE_DIR/cursor_api_key.py" \
3771
3772
  "$STAGE_DIR/side_questions.py" \
3772
3773
  "$STAGE_DIR/workspace_git.py" \
3774
+ "$STAGE_DIR/workspace_intelligence.py" \
3773
3775
  "$STAGE_DIR/codex_side_question.py" \
3774
3776
  "$STAGE_DIR/codex_side_chat_progress.py" \
3775
3777
  "$STAGE_DIR/title_generation.py" \
@@ -3806,7 +3808,7 @@ validate_staged_release_runtime() (
3806
3808
  "$STAGE_DIR/update_runner.py"
3807
3809
  "$STAGE_DIR/.venv/bin/python" -m py_compile "$STAGE_DIR/server_instances.py"
3808
3810
  "$STAGE_DIR/.venv/bin/python" -m compileall -q "$STAGE_DIR/agentsdock_team_hub"
3809
- PYTHONPATH="$STAGE_DIR" "$STAGE_DIR/.venv/bin/python" -c 'import execution_activation, execution_preparation, update_preparation, update_handoff, update_recovery, execution_update_status, execution_uninstall, execution_recovery, execution_recovery_status, execution_http, execution_durability, execution_control, execution_install, execution_maintenance, execution_manage, execution_ownership, execution_service, execution_transport; import workspace_git, claude_model_catalog, server_instances, local_session_ownership, cursor_history; import codex_auth, codex_provider, codex_response_stream, provider_connections, cursor_api_key, side_questions, title_generation, codex_side_question, codex_side_chat_progress, claude_side_question, agentsdock_team_hub, cursor_agent_client, cursor_provider_mcp, opencode_agent_client, gemini_acp_client, gemini_history, gemini_content, gemini_import, gemini_runtime, gemini_runner, gemini_permissions, gemini_api, cursor_process_guard, secure_peer_delivery, secure_peer_runtime, team_mail_runtime, team_mail_websocket, team_mail_grants, team_hub_host, agentsdock_mail, agentsdock_team, transcript_reader, claude_history_repair, claude_history_provenance, claude_goals, claude_background_reconciliation, codex_history_repair, public_chat_shares, public_chat_transcript, public_chat_share_routes, interactive_chat_shares, interactive_chat_share_routes, interactive_chat_share_web, interactive_chat_projection, interactive_chat_runtime, interactive_chat_native, shared_chat_videos, shared_chat_analytics_web, shared_chat_video_stream, interactive_chat_controls, chat_mailbox, provider_commands, provider_usage; from agentsdock_team_hub import secure_peer, secure_peer_hub' >/dev/null
3811
+ PYTHONPATH="$STAGE_DIR" "$STAGE_DIR/.venv/bin/python" -c 'import execution_activation, execution_preparation, update_preparation, update_handoff, update_recovery, execution_update_status, execution_uninstall, execution_recovery, execution_recovery_status, execution_http, execution_durability, execution_control, execution_install, execution_maintenance, execution_manage, execution_ownership, execution_service, execution_transport; import workspace_git, workspace_intelligence, claude_model_catalog, claude_chat_routing, server_instances, local_session_ownership, cursor_history; import codex_auth, codex_provider, codex_response_stream, provider_connections, cursor_api_key, side_questions, title_generation, codex_side_question, codex_side_chat_progress, claude_side_question, agentsdock_team_hub, cursor_agent_client, cursor_provider_mcp, opencode_agent_client, gemini_acp_client, gemini_history, gemini_content, gemini_import, gemini_runtime, gemini_runner, gemini_permissions, gemini_api, cursor_process_guard, secure_peer_delivery, secure_peer_runtime, team_mail_runtime, team_mail_websocket, team_mail_grants, team_hub_host, agentsdock_mail, agentsdock_team, transcript_reader, claude_history_repair, claude_history_provenance, claude_goals, claude_background_reconciliation, codex_history_repair, public_chat_shares, public_chat_transcript, public_chat_share_routes, interactive_chat_shares, interactive_chat_share_routes, interactive_chat_share_web, interactive_chat_projection, interactive_chat_runtime, interactive_chat_native, shared_chat_videos, shared_chat_analytics_web, shared_chat_video_stream, interactive_chat_controls, chat_mailbox, provider_commands, provider_usage; from agentsdock_team_hub import secure_peer, secure_peer_hub' >/dev/null
3810
3812
  )
3811
3813
 
3812
3814
  abort_unclaimed_team_hub_reactivation() {
@@ -7017,15 +7019,31 @@ fi
7017
7019
  # links or configuration. Legacy runners can report a failed installer, so an
7018
7020
  # unfinished journal must never leave their old, unfenced API accepting work.
7019
7021
  if [[ "${EXECUTION_MODE:-legacy}" == "split" ]]; then
7020
- if ! execution_activation_command durability "$STAGE_DIR" \
7021
- || ! execution_recovery_arm "$STAGE_DIR" \
7022
- || ! record_activation_phase quiescing "$STAGE_DIR" \
7023
- || ! execution_stop_services "$STAGE_DIR" preflight \
7024
- || ! execution_activation_command suppress "$STAGE_DIR" \
7025
- || ! execution_stop_services "$STAGE_DIR" stop \
7026
- || ! record_activation_phase quiesced "$STAGE_DIR"; then
7022
+ # Name the quiesce boundary that actually failed. Arming the activation
7023
+ # recovery owner validates the recovery interpreter's ownership and
7024
+ # permission bits, which needs a different operator response than a native
7025
+ # service-stop failure; the single generic message below previously blamed
7026
+ # the service stop for every failure in this chain.
7027
+ ACTIVATION_QUIESCE_BOUNDARY=""
7028
+ if ! execution_activation_command durability "$STAGE_DIR"; then
7029
+ ACTIVATION_QUIESCE_BOUNDARY="recording activation durability evidence"
7030
+ elif ! execution_recovery_arm "$STAGE_DIR"; then
7031
+ ACTIVATION_QUIESCE_BOUNDARY="arming the activation recovery owner"
7032
+ elif ! record_activation_phase quiescing "$STAGE_DIR"; then
7033
+ ACTIVATION_QUIESCE_BOUNDARY="journaling the quiescing phase"
7034
+ elif ! execution_stop_services "$STAGE_DIR" preflight; then
7035
+ ACTIVATION_QUIESCE_BOUNDARY="preflighting the admitted execution service"
7036
+ elif ! execution_activation_command suppress "$STAGE_DIR"; then
7037
+ ACTIVATION_QUIESCE_BOUNDARY="suppressing the admitted execution service"
7038
+ elif ! execution_stop_services "$STAGE_DIR" stop; then
7039
+ ACTIVATION_QUIESCE_BOUNDARY="stopping the admitted execution service"
7040
+ elif ! record_activation_phase quiesced "$STAGE_DIR"; then
7041
+ ACTIVATION_QUIESCE_BOUNDARY="journaling the quiesced phase"
7042
+ fi
7043
+ if [[ -n "$ACTIVATION_QUIESCE_BOUNDARY" ]]; then
7027
7044
  [[ "$COLD_TEAM_HUB_HANDOFF" != "true" ]] || resume_install_signals
7028
7045
  echo "The admitted execution service could not be durably stopped before takeover." >&2
7046
+ echo " The failure occurred while $ACTIVATION_QUIESCE_BOUNDARY; the error above identifies the specific cause." >&2
7029
7047
  exit 1
7030
7048
  fi
7031
7049
  fi
@@ -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,30 +248,35 @@ 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:
243
277
  return {"configured": False, "available": False, "models": [], "efforts": [], "model": None, "base_url": None}
244
278
 
245
- def claude_overrides(self, session: dict) -> tuple[dict, str | None]:
279
+ def claude_overrides(self, session: dict, *, runtime_settings: dict | None = None) -> tuple[dict, str | None]:
246
280
  value = self.for_session(session)
247
281
  if not value:
248
282
  return {}, None
@@ -259,7 +293,7 @@ class ConnectionStore:
259
293
  env["CLAUDE_CODE_MAX_CONCURRENT_SUBAGENTS"] = str(session["subagent_limit"])
260
294
  # Flag settings outrank project/user settings. Pass a private file path,
261
295
  # never a key-bearing JSON argument visible in process listings.
262
- content = json.dumps({"env": env, "apiKeyHelper": ""}, sort_keys=True)
296
+ content = json.dumps({**(runtime_settings or {}), "env": env, "apiKeyHelper": ""}, sort_keys=True)
263
297
  digest = hashlib.sha256(content.encode()).hexdigest()
264
298
  path = self.root / f"claude-runtime-{digest}.json"
265
299
  with self.lock:
@@ -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