onechat-cli 0.1.1__py3-none-any.whl

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.
onechat/quota.py ADDED
@@ -0,0 +1,287 @@
1
+ """Quota bookkeeping (Plan 02 §8 / T10): retry-after parsing, rolling windows, cooldowns.
2
+
3
+ The K1 statistical window is SQLite-backed (survives restarts); only QUOTA and TIMEOUT
4
+ count as backend failures — ERROR is our own fault and never blacklists a backend.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import math
10
+ import re
11
+ from collections.abc import Callable
12
+ from datetime import UTC, datetime
13
+
14
+ from .config import CliProfile, CooldownPolicy
15
+ from .contracts import ExecutorSpec, Stop, TurnResult
16
+ from .store import Store
17
+
18
+ BACKOFF_STRIKES = [60, 300, 1800, 7200]
19
+ AUTH_COOLDOWN_S = 24 * 3600
20
+ _RPM_WINDOW_S = 60
21
+ _RPD_WINDOW_S = 86400
22
+ _FAILURE_STOPS = ("quota", "timeout")
23
+
24
+ _ABSOLUTE_RE = re.compile(r"resets? at (\d{4}-\d{2}-\d{2}T[0-9:.]+(?:Z|[+-]\d{2}:\d{2}))", re.I)
25
+ _RELATIVE_RE = re.compile(
26
+ r"(?:try again|retry|wait|resets?)\s*(?:in|after)?\s*"
27
+ r"((?:\d+(?:\.\d+)?\s*(?:h|ms|m|s)\b[\s,]*)+)",
28
+ re.I,
29
+ )
30
+ _UNIT_SECONDS = {"h": 3600.0, "ms": 0.001, "m": 60.0, "s": 1.0}
31
+ _KEYWORDS = ("try again", "retry", "resets", "usage limit", "rate limit", "quota", "wait")
32
+
33
+
34
+ def parse_retry_after(text: str, now: datetime) -> int | None:
35
+ """Extract a retry delay from quota error text. Returns seconds, or None (T10:
36
+ durations are anchored to a retry/wait phrase, so window specs like '1000/1h'
37
+ are never mistaken for delays; invalid absolute stamps never raise)."""
38
+ lowered = text.lower()
39
+ if not any(marker in lowered for marker in _KEYWORDS):
40
+ return None
41
+ absolute = _ABSOLUTE_RE.search(text)
42
+ if absolute:
43
+ reset = _parse_iso(absolute.group(1))
44
+ if reset is not None:
45
+ return max(int((reset - now).total_seconds()), 0)
46
+ return _relative_from_phrase(text)
47
+
48
+
49
+ def _parse_iso(stamp: str) -> datetime | None:
50
+ try:
51
+ reset = datetime.fromisoformat(stamp.replace("Z", "+00:00"))
52
+ except ValueError:
53
+ return None
54
+ if reset.tzinfo is None:
55
+ reset = reset.replace(tzinfo=UTC)
56
+ return reset
57
+
58
+
59
+ def _relative_from_phrase(text: str) -> int | None:
60
+ phrase = _RELATIVE_RE.search(text)
61
+ if not phrase:
62
+ return None
63
+ total = 0.0
64
+ for number, unit in re.findall(r"(\d+(?:\.\d+)?)\s*(h|ms|m|s)\b", phrase.group(1), re.I):
65
+ total += float(number) * _UNIT_SECONDS[unit.lower()]
66
+ return math.ceil(total) if total > 0 else None
67
+
68
+
69
+ def _utc_now_ts() -> float:
70
+ return datetime.now(UTC).timestamp()
71
+
72
+
73
+ class QuotaBook:
74
+ """Rolling-window usage limits + cooldowns, backed by the Store."""
75
+
76
+ def __init__(
77
+ self,
78
+ store: Store,
79
+ clock: Callable[[], float] = _utc_now_ts,
80
+ policy: CooldownPolicy | None = None,
81
+ ) -> None:
82
+ self._store = store
83
+ self._clock = clock
84
+ self._policy = policy or CooldownPolicy()
85
+
86
+ def _statistically_failing(self, executor_id: str) -> bool:
87
+ """SQLite-backed K1 window (T10): failure rate over recent stops."""
88
+ now = self._clock()
89
+ stops = self._store.recent_stops(executor_id, now - self._policy.window_s)
90
+ if len(stops) < self._policy.min_requests:
91
+ return False
92
+ failures = sum(1 for stop in stops if stop.lower() in _FAILURE_STOPS)
93
+ return failures / len(stops) >= self._policy.failure_rate
94
+
95
+ def available(self, spec: ExecutorSpec) -> bool:
96
+ cooldown = self._store.get_cooldown(spec.id)
97
+ if cooldown and cooldown["until_ts"] > self._clock():
98
+ return False
99
+ now = self._clock()
100
+ within_rpm = (
101
+ spec.limits.rpm is not None
102
+ and self._store.usage_count(spec.id, now - _RPM_WINDOW_S) >= spec.limits.rpm
103
+ )
104
+ within_rpd = (
105
+ spec.limits.rpd is not None
106
+ and self._store.usage_count(spec.id, now - _RPD_WINDOW_S) >= spec.limits.rpd
107
+ )
108
+ return not (within_rpm or within_rpd)
109
+
110
+ def earliest_available(
111
+ self, specs: list[ExecutorSpec], now: float | None = None
112
+ ) -> float | None:
113
+ """Min future expiry across specs, where each spec needs ALL blockers cleared."""
114
+ now = self._clock() if now is None else now
115
+ ready = [t for spec in specs if (t := self._spec_ready_at(spec, now)) is not None]
116
+ return min(ready) if ready else None
117
+
118
+ def _spec_ready_at(self, spec: ExecutorSpec, now: float) -> float | None:
119
+ blockers: list[float] = []
120
+ cooldown = self._store.get_cooldown(spec.id)
121
+ if cooldown and cooldown["until_ts"] > now:
122
+ blockers.append(float(cooldown["until_ts"]))
123
+ for window_s, limit in (
124
+ (_RPM_WINDOW_S, spec.limits.rpm),
125
+ (_RPD_WINDOW_S, spec.limits.rpd),
126
+ ):
127
+ if limit is None:
128
+ continue
129
+ count = self._store.usage_count(spec.id, now - window_s)
130
+ if count < limit:
131
+ continue
132
+ release_ts = self._store.nth_oldest_usage_ts(
133
+ spec.id, now - window_s, offset=count - limit
134
+ )
135
+ if release_ts is not None:
136
+ blockers.append(release_ts + window_s)
137
+ return max(blockers) if blockers else None
138
+
139
+ def record(
140
+ self,
141
+ spec: ExecutorSpec,
142
+ result: TurnResult,
143
+ session_id: str,
144
+ run_id: str | None,
145
+ sole_usable: bool = False,
146
+ all_specs: list[ExecutorSpec] | None = None,
147
+ profiles: dict[str, CliProfile] | None = None,
148
+ ) -> None:
149
+ now = self._clock()
150
+ self._store.record_usage(
151
+ ts=now,
152
+ executor_id=spec.id,
153
+ session_id=session_id,
154
+ run_id=run_id,
155
+ input_tokens=result.usage.input_tokens,
156
+ output_tokens=result.usage.output_tokens,
157
+ cost_usd=result.usage.cost_usd,
158
+ stop=result.stop.value,
159
+ )
160
+ if result.stop == Stop.DONE:
161
+ self._store.clear_cooldown(spec.id)
162
+ self._clear_sibling_cooldown(spec, all_specs, profiles)
163
+ return
164
+ if result.stop == Stop.AUTH:
165
+ until_ts = now + self._policy.auth_cooldown_s
166
+ self._store.set_cooldown(spec.id, until_ts, 1, "auth")
167
+ self._propagate_sibling_cooldown(spec, until_ts, "auth", all_specs, profiles)
168
+ return
169
+ if result.stop in (Stop.QUOTA, Stop.TIMEOUT, Stop.ERROR):
170
+ self._backend_failure(spec, result, now, sole_usable, all_specs, profiles)
171
+
172
+ def _clear_sibling_cooldown(
173
+ self,
174
+ spec: ExecutorSpec,
175
+ all_specs: list[ExecutorSpec] | None,
176
+ profiles: dict[str, CliProfile] | None,
177
+ ) -> None:
178
+ if not self._policy.share_profile_cooldown or not all_specs or not spec.profile:
179
+ return
180
+ prof = (profiles or {}).get(spec.profile)
181
+ if not prof or not prof.share_cooldown:
182
+ return
183
+ for s in all_specs:
184
+ if s.id != spec.id and s.profile == spec.profile and s.env == spec.env:
185
+ self._store.clear_cooldown(s.id)
186
+
187
+ def _is_structural_error(
188
+ self,
189
+ spec: ExecutorSpec,
190
+ result: TurnResult,
191
+ profiles: dict[str, CliProfile] | None,
192
+ ) -> bool:
193
+ if spec.kind != "cli" or result.stop != Stop.ERROR:
194
+ return False
195
+ err = (result.error or "").strip().lower()
196
+ if not err:
197
+ return True
198
+ prof = (profiles or {}).get(spec.profile) if spec.profile else None
199
+ if prof and any(p.lower() in err for p in prof.unavailable_patterns):
200
+ return True
201
+ markers = (
202
+ "connection refused",
203
+ "not running",
204
+ "cannot connect",
205
+ "no output",
206
+ "remote debugging",
207
+ "cdp",
208
+ )
209
+ return any(m in err for m in markers)
210
+
211
+ def _failure_delay(
212
+ self, spec: ExecutorSpec, result: TurnResult, strikes: int, is_structural: bool
213
+ ) -> int | None:
214
+ if result.stop == Stop.ERROR:
215
+ if is_structural:
216
+ base = self._policy.error_cooldown_s
217
+ elif self._policy.error_cooldown_s > 0:
218
+ return 60
219
+ else:
220
+ return None
221
+ elif result.stop == Stop.TIMEOUT:
222
+ base = self._policy.timeout_cooldown_s
223
+ else:
224
+ base = self._policy.quota_cooldown_s
225
+ ladder = self._policy.backoff_strikes
226
+ ladder_delay = ladder[min(strikes - 1, len(ladder) - 1)] if ladder else base
227
+ return max(base, ladder_delay) if base > 0 else ladder_delay
228
+
229
+ def _propagate_sibling_cooldown(
230
+ self,
231
+ spec: ExecutorSpec,
232
+ until_ts: float,
233
+ reason: str,
234
+ all_specs: list[ExecutorSpec] | None,
235
+ profiles: dict[str, CliProfile] | None,
236
+ ) -> None:
237
+ if not self._policy.share_profile_cooldown or not all_specs or not spec.profile:
238
+ return
239
+ prof = (profiles or {}).get(spec.profile)
240
+ if not prof or not prof.share_cooldown:
241
+ return
242
+ siblings = [
243
+ s
244
+ for s in all_specs
245
+ if s.id != spec.id and s.profile == spec.profile and s.env == spec.env
246
+ ]
247
+ if not siblings:
248
+ return
249
+ usable_now = [s for s in all_specs if s.enabled and self.available(s)]
250
+ if len(usable_now) <= len(siblings) + 1 and all(
251
+ s.id == spec.id or s in siblings for s in usable_now
252
+ ):
253
+ return
254
+ for sib in siblings:
255
+ self._store.set_cooldown(sib.id, until_ts, 1, reason)
256
+
257
+ def _backend_failure(
258
+ self,
259
+ spec: ExecutorSpec,
260
+ result: TurnResult,
261
+ now: float,
262
+ sole_usable: bool,
263
+ all_specs: list[ExecutorSpec] | None = None,
264
+ profiles: dict[str, CliProfile] | None = None,
265
+ ) -> None:
266
+ existing = self._store.get_cooldown(spec.id) or {}
267
+ if result.stop == Stop.QUOTA and result.retry_after_s is not None:
268
+ delay_s = max(1, result.retry_after_s)
269
+ self._store.set_cooldown(
270
+ spec.id, now + delay_s, existing.get("strikes", 0) + 1, "quota"
271
+ )
272
+ return
273
+ is_structural = self._is_structural_error(spec, result, profiles)
274
+ if sole_usable and not is_structural:
275
+ return
276
+ demonstrated = existing.get("strikes", 0) >= 1
277
+ needs_gate = self._policy.min_requests > 1 and not is_structural
278
+ if needs_gate and not demonstrated and not self._statistically_failing(spec.id):
279
+ return
280
+ strikes = existing.get("strikes", 0) + 1
281
+ delay = self._failure_delay(spec, result, strikes, is_structural)
282
+ if delay is None or delay <= 0:
283
+ return
284
+ reason = "error" if result.stop == Stop.ERROR else result.stop.value
285
+ until_ts = now + delay
286
+ self._store.set_cooldown(spec.id, until_ts, strikes, reason)
287
+ self._propagate_sibling_cooldown(spec, until_ts, reason, all_specs, profiles)
onechat/redact.py ADDED
@@ -0,0 +1,58 @@
1
+ """Secret redaction (Plan 02 §9 / T04): mask known provider token shapes and configured
2
+ env var values. Boundary-anchored patterns: snake_case identifiers that merely start
3
+ with sk/ask never match; real provider prefixes, Bearer headers and URL userinfos do."""
4
+
5
+ from __future__ import annotations
6
+
7
+ import os
8
+ import re
9
+ from collections.abc import Callable, Iterable
10
+
11
+ SECRET_RE = re.compile(
12
+ r"\b(?:"
13
+ r"sk-(?:proj-|ant-|live-|test-)?[A-Za-z0-9_-]{16,}" # openai / anthropic style
14
+ r"|gsk_[A-Za-z0-9]{16,}" # groq
15
+ r"|AIza[0-9A-Za-z_-]{35}" # google api key
16
+ r"|(?:ghp|gho|ghu|ghs|ghr)_[A-Za-z0-9]{20,}" # github classic
17
+ r"|github_pat_[A-Za-z0-9_]{20,}" # github fine-grained
18
+ r"|xox[baprs]-[A-Za-z0-9-]{10,}" # slack
19
+ r"|nvapi-[A-Za-z0-9_-]{16,}" # nvidia nim
20
+ r"|ya29\.[A-Za-z0-9._-]{20,}" # google oauth access token
21
+ r"|csk-[A-Za-z0-9_-]{16,}" # cerebras style
22
+ r"|hf_[A-Za-z0-9]{16,}" # huggingface
23
+ r"|AKIA[0-9A-Z]{16}" # aws access key id
24
+ r"|eyJ[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}" # JWT
25
+ r")"
26
+ )
27
+ BEARER_RE = re.compile(r"Bearer\s+[A-Za-z0-9._~+/=-]{16,}", re.IGNORECASE)
28
+ URL_USERINFO_RE = re.compile(r"(?<=://)[^/\s:@]+:[^/\s@]+(?=@)")
29
+ MASK = "[REDACTED]"
30
+
31
+ _MIN_ENV_VALUE_LEN = 8
32
+
33
+
34
+ def redact(text: str) -> str:
35
+ """Mask secret-shaped tokens (T04: provider-prefix exact shapes, no sk/ask false hits)."""
36
+ out = SECRET_RE.sub(MASK, text)
37
+ out = BEARER_RE.sub("Bearer " + MASK, out)
38
+ return URL_USERINFO_RE.sub(MASK, out)
39
+
40
+
41
+ def make_redactor(
42
+ api_key_envs: list[str], extra_values: Iterable[str] = ()
43
+ ) -> Callable[[str], str]:
44
+ """Build a redactor that also masks the *values* of the named env vars (if set)
45
+ and any inline literal secret values. Values shorter than 8 chars are skipped."""
46
+ literals = [v for v in extra_values if len(v) >= _MIN_ENV_VALUE_LEN]
47
+
48
+ def _redact(text: str) -> str:
49
+ out = redact(text)
50
+ for name in api_key_envs:
51
+ value = os.environ.get(name, "")
52
+ if len(value) >= _MIN_ENV_VALUE_LEN:
53
+ out = out.replace(value, MASK)
54
+ for value in literals:
55
+ out = out.replace(value, MASK)
56
+ return out
57
+
58
+ return _redact
onechat/router.py ADDED
@@ -0,0 +1,299 @@
1
+ """Router: one turn across many backends with invisible failover."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import asyncio
6
+ import contextlib
7
+ import os
8
+ import time
9
+ import uuid
10
+ from collections.abc import Callable
11
+ from pathlib import Path
12
+ from typing import Any
13
+
14
+ from .config import RouterConfig
15
+ from .contracts import (
16
+ Capability,
17
+ CostClass,
18
+ Event,
19
+ Executor,
20
+ NoExecutorAvailable,
21
+ OnEvent,
22
+ Reply,
23
+ SessionBusy,
24
+ Stop,
25
+ Tier,
26
+ TurnRequest,
27
+ TurnResult,
28
+ )
29
+ from .handoff import maybe_compact
30
+ from .quota import QuotaBook
31
+ from .router_helpers import (
32
+ advance_native,
33
+ apply_executor_overrides,
34
+ build_request,
35
+ git_state_of,
36
+ make_summarizer,
37
+ select_candidates,
38
+ stale_session,
39
+ )
40
+ from .selector import Need, clamp_tier, coerce_tier, resolve_tier
41
+ from .store import Store
42
+
43
+ LEASE_TTL_S = 300.0
44
+
45
+
46
+ class Router:
47
+ """Owns tier selection, failover, session context and turn recording."""
48
+
49
+ def __init__(
50
+ self,
51
+ config: RouterConfig,
52
+ store: Store,
53
+ executors: dict[str, Executor],
54
+ quota: QuotaBook,
55
+ git: Callable[[Path], Any] = lambda _p: "",
56
+ max_attempts: int = 4,
57
+ clock: Callable[[], float] = time.time,
58
+ lease_renew_s: float = 60.0,
59
+ ) -> None:
60
+ self.config, self.store, self.executors = config, store, executors
61
+ self.quota, self._git, self.max_attempts = quota, git, max_attempts
62
+ self._clock, self.lease_renew_s = clock, lease_renew_s
63
+ self._session_locks: dict[str, asyncio.Lock] = {}
64
+
65
+ async def turn(
66
+ self,
67
+ session_id: str,
68
+ prompt: str,
69
+ need: Need,
70
+ on_event: OnEvent | None = None,
71
+ run_id: str | None = None,
72
+ ) -> Reply:
73
+ lock = self._session_locks.setdefault(session_id, asyncio.Lock())
74
+ try:
75
+ async with lock:
76
+ if self.store.get_session(session_id) is None:
77
+ raise ValueError(f"unknown session {session_id!r}")
78
+ return await self._turn_locked(session_id, prompt, need, on_event, run_id)
79
+ finally:
80
+ if not lock.locked() and self._session_locks.get(session_id) is lock:
81
+ self._session_locks.pop(session_id, None)
82
+
83
+ async def _turn_locked(
84
+ self, session_id: str, prompt: str, need: Need, on_event: OnEvent | None, run_id: str | None
85
+ ) -> Reply:
86
+ session = self.store.get_session(session_id) or {}
87
+ owner = f"{os.getpid()}:{uuid.uuid4().hex[:8]}"
88
+ self._acquire_lease(session_id, session, owner)
89
+ renewal = asyncio.create_task(self._renew_lease(session_id, owner))
90
+ try:
91
+ return await self._turn_leased(session_id, prompt, need, on_event, run_id)
92
+ finally:
93
+ renewal.cancel()
94
+ with contextlib.suppress(asyncio.CancelledError, Exception):
95
+ await renewal
96
+ self.store.release_lease(session_id, owner)
97
+
98
+ def _acquire_lease(self, session_id: str, session: dict[str, Any], owner: str) -> None:
99
+ now, until = self._clock(), session.get("lock_until")
100
+ if session.get("lock_owner") and until and float(until) > now:
101
+ raise SessionBusy(f"session {session_id} busy until {until}")
102
+ if not self.store.acquire_lease(session_id, owner, now + LEASE_TTL_S, now):
103
+ raise SessionBusy(f"session {session_id} busy")
104
+
105
+ async def _renew_lease(self, session_id: str, owner: str) -> None:
106
+ """Keep the cross-process lease alive while a long turn runs (T12a: CAS + safe)."""
107
+ while True:
108
+ await asyncio.sleep(self.lease_renew_s)
109
+ with contextlib.suppress(Exception):
110
+ self.store.acquire_lease(
111
+ session_id, owner, self._clock() + LEASE_TTL_S, self._clock()
112
+ )
113
+
114
+ def _prepare_cands(
115
+ self, session_id: str, prompt: str, need: Need, tier: Tier
116
+ ) -> tuple[list[Any], list[Any], list[Any]]:
117
+ bench = getattr(self.config, "benchmark", None)
118
+ ttl = max(2 * getattr(bench, "interval_s", 1800.0), 3600.0) if bench else 3600.0
119
+ p_roles = getattr(bench, "promote_roles", []) if bench else []
120
+ en = getattr(bench, "enabled", True) if bench else False
121
+ specs, roles = apply_executor_overrides(
122
+ [e.spec for e in self.executors.values()],
123
+ self.config.roles,
124
+ self.store.get_executor_overrides(),
125
+ p_roles,
126
+ en,
127
+ self._clock(),
128
+ ttl,
129
+ self._usable,
130
+ )
131
+ sess = self.store.get_session(session_id) or {}
132
+ wd = Path(str(sess["workdir"])) if sess.get("workdir") else None
133
+ cands, eligible, _ = select_candidates(
134
+ need, prompt, tier, specs, roles, self.config, self._usable, workdir=wd
135
+ )
136
+ return cands, eligible, specs
137
+
138
+ async def _turn_leased(
139
+ self, session_id: str, prompt: str, need: Need, on_event: OnEvent | None, run_id: str | None
140
+ ) -> Reply:
141
+ tier = self._resolve_tier(need, prompt)
142
+ cands, eligible, specs = self._prepare_cands(session_id, prompt, need, tier)
143
+ if not cands:
144
+ raise NoExecutorAvailable(retry_at=self.quota.earliest_available(eligible))
145
+ assistant_idx = self._append_user(session_id, prompt)
146
+ failed: list[str] = []
147
+ attempts = cands[: self.max_attempts]
148
+ for idx, spec in enumerate(attempts, 1):
149
+ if not self.quota.available(spec):
150
+ continue
151
+ self._emit(
152
+ on_event,
153
+ Event(
154
+ kind="status",
155
+ text=f"attempt {idx}/{len(attempts)}: {spec.id} ({spec.model})",
156
+ ),
157
+ )
158
+ result, resumed = await self._attempt(session_id, spec, need, prompt, failed, on_event)
159
+
160
+ sole = self._sole_usable(spec, need, tier, specs=specs)
161
+ self.quota.record(
162
+ spec,
163
+ result,
164
+ session_id,
165
+ run_id,
166
+ sole_usable=sole,
167
+ all_specs=specs,
168
+ profiles=self.config.profiles,
169
+ )
170
+ if result.stop == Stop.DONE:
171
+ return await self._finish(
172
+ session_id, spec, result, failed, assistant_idx, resumed, on_event, need
173
+ )
174
+ failed.append(spec.id)
175
+ self._emit(on_event, Event(kind="status", text=f"{spec.id}: {result.stop} → next"))
176
+ raise NoExecutorAvailable(retry_at=self.quota.earliest_available(eligible))
177
+
178
+ def _resolve_tier(self, need: Need, prompt: str) -> Tier:
179
+ policy = self.config.tier_policy
180
+ exp = coerce_tier(need.tier)
181
+ if exp is not None:
182
+ return clamp_tier(exp, prompt, policy)
183
+ return resolve_tier(need, prompt, policy)
184
+
185
+ def _append_user(self, session_id: str, prompt: str) -> int:
186
+ """Store the user turn once (T12a): a retry of the SAME prompt reuses the row."""
187
+ turns = self.store.turns(session_id)
188
+ if turns and turns[-1]["role"] == "user" and turns[-1]["text"] == prompt:
189
+ return int(turns[-1]["idx"]) + 1
190
+ idx = self.store.next_turn_idx(session_id)
191
+ self.store.append_turn(session_id, idx, "user", prompt, executor_id="", stop="done")
192
+ return idx + 1
193
+
194
+ async def _attempt(
195
+ self,
196
+ session_id: str,
197
+ spec: Any,
198
+ need: Need,
199
+ prompt: str,
200
+ failed: list[str],
201
+ on_event: OnEvent | None,
202
+ ) -> tuple[TurnResult, bool]:
203
+ executor = self.executors[spec.id]
204
+ req = await self._build_request(session_id, spec, need, prompt, failed)
205
+ result = await executor.run(req, on_event)
206
+ if result.stop == Stop.ERROR and req.native_session_id and stale_session(result.error):
207
+ self.store.set_native(session_id, spec.id, "", -1) # invalidate (T12a)
208
+ fresh = await self._build_request(session_id, spec, need, prompt, failed)
209
+ return await executor.run(fresh, on_event), False
210
+ return result, bool(req.native_session_id)
211
+
212
+ async def _build_request(
213
+ self, session_id: str, spec: Any, need: Need, prompt: str, failed: list[str]
214
+ ) -> TurnRequest:
215
+ session = self.store.get_session(session_id) or {}
216
+ turns = self.store.turns(session_id, since_idx=0)[:-1] # exclude current user turn
217
+ interrupted = bool(failed) and need.capability == Capability.CODE
218
+ git_text = (
219
+ await git_state_of(self._git, Path(session.get("workdir", ".")))
220
+ if need.capability == Capability.CODE or interrupted
221
+ else ""
222
+ )
223
+ native = self.store.get_native(session_id, spec.id)
224
+ return build_request(
225
+ session, spec, need, prompt, turns, git_text, interrupted, self.config, native
226
+ )
227
+
228
+ def _sole_usable(
229
+ self, executing: Any, need: Need, tier: Tier | None = None, specs: list[Any] | None = None
230
+ ) -> bool:
231
+ """Only ONE usable executor for THIS need's capability/filters (T12a)."""
232
+ target = specs if specs is not None else [e.spec for e in self.executors.values()]
233
+ usable = [s for s in target if self._usable(s, need, tier)]
234
+ return len(usable) == 1 and usable[0].id == executing.id
235
+
236
+ def _usable(self, spec: Any, need: Need | None = None, tier: Tier | None = None) -> bool:
237
+ if not getattr(spec, "enabled", True):
238
+ return False
239
+ executor = self.executors.get(spec.id)
240
+ if executor is None or not executor.available() or not self.quota.available(spec):
241
+ return False
242
+ if need is None:
243
+ return True
244
+ paid_blocked = spec.cost == CostClass.PAID and not self.config.tier_policy.allow_paid
245
+ tier_blocked = tier is not None and need.executor_id is None and spec.tier < tier
246
+ if paid_blocked or tier_blocked:
247
+ return False
248
+ return (
249
+ need.capability in spec.capabilities
250
+ and (need.avoid_family is None or spec.family != need.avoid_family)
251
+ and spec.id not in need.exclude
252
+ )
253
+
254
+ async def _finish(
255
+ self,
256
+ session_id: str,
257
+ spec: Any,
258
+ result: TurnResult,
259
+ switched_from: list[str],
260
+ assistant_idx: int,
261
+ resumed: bool,
262
+ on_event: OnEvent | None,
263
+ need: Need | None = None,
264
+ ) -> Reply:
265
+ self.store.append_turn(
266
+ session_id,
267
+ assistant_idx,
268
+ "assistant",
269
+ result.text,
270
+ executor_id=spec.id,
271
+ stop=result.stop.value,
272
+ subagent_role=need.role if need else None,
273
+ )
274
+ advance_native(self.store, session_id, spec, result, assistant_idx, resumed)
275
+ session = self.store.get_session(session_id) or {}
276
+ turns = self.store.turns(session_id, since_idx=0) # full history (T12a off-by-one)
277
+ await self._safe_compact(session, turns)
278
+ self._emit(on_event, Event(kind="status", text=f"{spec.id}: done"))
279
+ return Reply(
280
+ text=result.text,
281
+ executor_id=spec.id,
282
+ stop=Stop.DONE,
283
+ switched_from=switched_from,
284
+ turn_idx=assistant_idx,
285
+ )
286
+
287
+ async def _safe_compact(self, session: dict[str, Any], turns: list[dict[str, Any]]) -> None:
288
+ """Compaction is best-effort: a summarizer failure keeps the reply intact (T12a)."""
289
+ with contextlib.suppress(Exception):
290
+ wd = Path(str(session.get("workdir", ".")))
291
+ summarizer = make_summarizer(self.config, self.executors, self.quota, self._usable, wd)
292
+ compacted = await maybe_compact(session, turns, self.config.handoff, summarizer)
293
+ if compacted is not None:
294
+ self.store.set_summary(str(session["id"]), *compacted)
295
+
296
+ def _emit(self, on_event: OnEvent | None, event: Event) -> None:
297
+ with contextlib.suppress(Exception):
298
+ if on_event is not None:
299
+ on_event(event)