@agentsdock/server 1.0.11 → 1.0.12-beta.10

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -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
@@ -28,11 +28,19 @@ class PublicTranscriptError(ValueError):
28
28
  def _is_goal_followup(event: dict) -> bool:
29
29
  return bool(
30
30
  event.get("type") == "turn_steered"
31
- and event.get("native_goal_steer") is True
32
31
  and event.get("native_steer") is True
33
32
  and event.get("provider_user_authored") is True
34
- and event.get("backend") == "codex"
35
- and event.get("purpose") == "codex_goal_resume"
33
+ and (
34
+ (event.get("native_goal_steer") is True
35
+ and event.get("backend") == "codex"
36
+ and event.get("purpose") == "codex_goal_resume")
37
+ or (event.get("native_followup") is True
38
+ and event.get("backend") == "claude"
39
+ and event.get("purpose") is None
40
+ and event.get("provider_generated") is not True
41
+ and isinstance(event.get("provider_message_id"), str)
42
+ and event["provider_message_id"].strip())
43
+ )
36
44
  and isinstance(event.get("run_id"), str)
37
45
  and event["run_id"].strip()
38
46
  )
@@ -0,0 +1,184 @@
1
+ """Incremental unread provenance; journal recovery runs off the event loop."""
2
+ from __future__ import annotations
3
+
4
+ from pathlib import Path
5
+ from typing import Any, Callable, Iterable
6
+ from transcript_reader import jsonl_records
7
+
8
+
9
+ COUNTER = "latest_non_job_agent_event_seq"
10
+ CHECKPOINT = "_non_job_agent_event_checkpoint_seq"
11
+ PENDING_COUNTER = "_non_job_agent_event_pending_seq"
12
+ LAST_RUN = "_non_job_agent_last_run"
13
+ JOURNAL = "_non_job_agent_event_journal"
14
+
15
+
16
+ def imported_event(event: dict[str, Any]) -> bool:
17
+ return event.get("imported") is True or str(event.get("run_id") or "").startswith("import_")
18
+
19
+
20
+ def scheduled_event(event: dict[str, Any]) -> bool:
21
+ job = event.get("job")
22
+ return bool(
23
+ event.get("purpose") == "scheduled_job"
24
+ or str(event.get("job_id") or "").strip()
25
+ or isinstance(job, dict) and str(job.get("id") or "").strip()
26
+ or str(event.get("type") or "").startswith("job_")
27
+ )
28
+
29
+
30
+ def project_event(
31
+ session: dict[str, Any], event: dict[str, Any], *,
32
+ visible: bool, run_metadata: dict[str, Any],
33
+ ) -> None:
34
+ """Apply an appended event without I/O or changing the ordinary read cursor."""
35
+ seq = int(event.get("seq") or 0)
36
+ if seq <= 0:
37
+ return
38
+ # Only a new journal can establish an empty baseline without recovery.
39
+ if seq == 1 and not int(session.get("latest_event_seq") or 0):
40
+ session.setdefault(COUNTER, 0)
41
+ session.setdefault(CHECKPOINT, 0)
42
+ known = isinstance(session.get(COUNTER), int) and CHECKPOINT in session
43
+ run_id = str(event.get("run_id") or "")
44
+ contexts: list[dict[str, Any]] = []
45
+ if event.get("type") == "turn_started" and run_id:
46
+ context = {"run_id": run_id, "scheduled_job": scheduled_event(event) or scheduled_event(run_metadata)}
47
+ session[LAST_RUN] = context
48
+ contexts.append(context)
49
+ else:
50
+ for candidate in (session.get("active_run"), session.get(LAST_RUN)):
51
+ if isinstance(candidate, dict) and run_id and candidate.get("run_id") == run_id:
52
+ contexts.append(candidate)
53
+ scheduled = scheduled_event(event) or scheduled_event(run_metadata) or any(
54
+ scheduled_event(context) or context.get("scheduled_job") is True for context in contexts
55
+ )
56
+ if scheduled and run_id and (session.get(LAST_RUN) or {}).get("run_id") == run_id:
57
+ session[LAST_RUN] = {"run_id": run_id, "scheduled_job": True}
58
+ if visible and not scheduled and not imported_event(event):
59
+ field = COUNTER if known else PENDING_COUNTER
60
+ session[field] = max(int(session.get(field) or 0), seq)
61
+ if known:
62
+ session[CHECKPOINT] = max(int(session.get(CHECKPOINT) or 0), seq)
63
+
64
+
65
+ def recover_projection(
66
+ path: Path, snapshot: dict[str, Any], *,
67
+ visible: Callable[[str, dict[str, Any]], bool],
68
+ resume_offset: Callable[[Path, int], int],
69
+ prior_events: Callable[[], Iterable[dict[str, Any]]],
70
+ cancelled: Callable[[], bool],
71
+ ) -> dict[str, Any]:
72
+ """Project one fixed journal extent, then resolve missing run provenance once.
73
+
74
+ Legacy chats need one forward pass. A durable checkpoint resumes through the
75
+ existing sparse index; only an untagged tail run whose start precedes that
76
+ checkpoint requires a backwards provenance pass. No history is read by the
77
+ session-list endpoint or the live event projection.
78
+ """
79
+ known = isinstance(snapshot.get(COUNTER), int) and CHECKPOINT in snapshot
80
+ after = int(snapshot.get(CHECKPOINT) or 0) if known else 0
81
+ latest = int(snapshot.get(COUNTER) or 0) if known else 0
82
+ through = after
83
+ last_run = dict(snapshot.get(LAST_RUN) or {})
84
+ runs: dict[str, dict[str, Any]] = {}
85
+ unresolved: dict[str, list[dict[str, Any]]] = {}
86
+
87
+ def finish(run_id: str, run: dict[str, Any]) -> None:
88
+ nonlocal latest
89
+ if run["scheduled"] or not run["visible_seq"]:
90
+ return
91
+ if run["origin"]:
92
+ latest = max(latest, run["visible_seq"])
93
+ else:
94
+ unresolved.setdefault(run_id, []).append(run)
95
+
96
+ try:
97
+ source = path.open("rb")
98
+ except FileNotFoundError:
99
+ if after or int(snapshot.get("latest_event_seq") or 0):
100
+ raise
101
+ return {COUNTER: 0, CHECKPOINT: 0, LAST_RUN: {}}
102
+ with source:
103
+ extent = source.seek(0, 2)
104
+ inode = path.stat().st_ino
105
+ journal = snapshot.get(JOURNAL) or {}
106
+ if known and journal and (journal.get("inode") != inode or int(journal.get("offset") or 0) > extent):
107
+ after = latest = through = 0
108
+ last_run = {}
109
+ offset = int(journal.get("offset") or 0) if after and journal.get("inode") == inode else 0
110
+ source.seek(offset or (resume_offset(path, after) if after else 0))
111
+ complete_offset = source.tell()
112
+ for event, ending, raw in jsonl_records(
113
+ source, end=extent, project=False, require_newline=False, deadline=float("inf"), cancelled=cancelled,
114
+ max_records=float("inf"), max_nodes=None, max_depth=512,
115
+ retained_fields=frozenset({"seq", "type", "run_id", "purpose", "job_id", "job", "text", "result_text", "goal", "imported"}),
116
+ ):
117
+ if not raw.complete:
118
+ break # Leave a concurrently written/crash fragment unclaimed.
119
+ complete_offset = ending
120
+ if not isinstance(event, dict):
121
+ continue
122
+ seq = int(event.get("seq") or 0)
123
+ if seq <= after:
124
+ continue
125
+ through = max(through, seq)
126
+ event_type = str(event.get("type") or "")
127
+ is_visible = visible(event_type, event) and not imported_event(event)
128
+ run_id = str(event.get("run_id") or "")
129
+ scheduled = scheduled_event(event)
130
+ if not run_id:
131
+ if is_visible and not scheduled:
132
+ latest = max(latest, seq)
133
+ continue
134
+ if event_type == "turn_started" and run_id in runs:
135
+ finish(run_id, runs.pop(run_id))
136
+ run = runs.setdefault(run_id, {"first_seq": seq, "visible_seq": 0, "scheduled": False, "origin": False})
137
+ run["scheduled"] = run["scheduled"] or scheduled
138
+ if event_type == "turn_started":
139
+ run["origin"] = True
140
+ last_run = {"run_id": run_id, "scheduled_job": scheduled}
141
+ elif scheduled and last_run.get("run_id") == run_id:
142
+ last_run["scheduled_job"] = True
143
+ if is_visible:
144
+ run["visible_seq"] = max(run["visible_seq"], seq)
145
+ if event_type in {"turn_finished", "turn_stopped"} and (run["scheduled"] or not run["visible_seq"]):
146
+ # Completed cron runs do not accumulate with the schedule's
147
+ # history. A later untagged event is resolved by the single
148
+ # backwards provenance pass, just like a restart tail.
149
+ runs.pop(run_id, None)
150
+ for run_id, run in runs.items():
151
+ finish(run_id, run)
152
+ # One reverse pass resolves all tail runs together, including stripped raw
153
+ # provider events and a job_ran marker emitted after the provider's start.
154
+ if unresolved:
155
+ for event in prior_events():
156
+ if cancelled():
157
+ raise InterruptedError("unread projection cancelled")
158
+ run_id = str(event.get("run_id") or "")
159
+ candidates = unresolved.get(run_id)
160
+ if not candidates:
161
+ continue
162
+ seq = int(event.get("seq") or 0)
163
+ scheduled = scheduled_event(event)
164
+ if not scheduled and event.get("type") != "turn_started":
165
+ continue
166
+ remaining = []
167
+ for run in candidates:
168
+ if seq >= run["first_seq"]:
169
+ remaining.append(run)
170
+ elif not scheduled:
171
+ latest = max(latest, run["visible_seq"])
172
+ if remaining:
173
+ unresolved[run_id] = remaining
174
+ else:
175
+ unresolved.pop(run_id)
176
+ if not unresolved:
177
+ break
178
+ # Legacy output with no recorded job provenance remains ordinary;
179
+ # merely owning a schedule never suppresses a human conversation.
180
+ for candidates in unresolved.values():
181
+ for run in candidates:
182
+ latest = max(latest, run["visible_seq"])
183
+ return {COUNTER: latest, CHECKPOINT: through, LAST_RUN: last_run,
184
+ JOURNAL: {"inode": inode, "offset": complete_offset}}