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/sdk.py ADDED
@@ -0,0 +1,210 @@
1
+ """Public SDK (Plan 03 §6 / T12b): AsfClient + Session. The factory talks to AI only here."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import asyncio
6
+ import secrets
7
+ import time
8
+ from collections.abc import Callable
9
+ from pathlib import Path
10
+ from typing import Any
11
+
12
+ from .config import RouterConfig, load_config
13
+ from .contracts import Capability, Executor, OnEvent, Tier
14
+ from .executors import build_executor
15
+ from .quota import QuotaBook
16
+ from .router import Reply, Router
17
+ from .selector import Need
18
+ from .store import Store
19
+
20
+ _UNSET = object() # pin sentinel: leave that field untouched (T12b)
21
+
22
+
23
+ class Session:
24
+ """One conversation. All asks go through the Router (failover + context included)."""
25
+
26
+ def __init__(self, client: OneChatClient, session_id: str) -> None:
27
+ self._client = client
28
+ self.id = session_id
29
+
30
+ async def ask(
31
+ self,
32
+ prompt: str,
33
+ *,
34
+ tier: Tier | str = "auto",
35
+ executor: str | None = None,
36
+ capability: str = "chat",
37
+ task_kind: str | None = None,
38
+ role: str | None = None,
39
+ model: str | None = None,
40
+ skills: tuple[str, ...] | list[str] | None = None,
41
+ failures: int = 0,
42
+ avoid_family: str | None = None,
43
+ allow_fallback: bool = True,
44
+ exclude: frozenset[str] | None = None,
45
+ on_event: OnEvent | None = None,
46
+ run_id: str | None = None,
47
+ timeout_s: int | None = None,
48
+ ) -> Reply:
49
+ pinned_executor, pinned_tier = self._pins()
50
+ return await self._client.router.turn(
51
+ self.id,
52
+ prompt,
53
+ Need(
54
+ capability=Capability(capability),
55
+ tier=pinned_tier if pinned_tier is not None and tier == "auto" else tier,
56
+ executor_id=executor or pinned_executor,
57
+ role=role,
58
+ model=model,
59
+ skills=skills or (),
60
+ task_kind=task_kind,
61
+ failures=failures,
62
+ avoid_family=avoid_family,
63
+ allow_fallback=allow_fallback,
64
+ exclude=exclude if exclude is not None else frozenset(),
65
+ timeout_s=timeout_s,
66
+ ),
67
+ on_event=on_event,
68
+ run_id=run_id,
69
+ )
70
+
71
+ def _pins(self) -> tuple[str | None, Tier | None]:
72
+ row = self._client.store.get_session(self.id) or {}
73
+ tier_value = row.get("tier")
74
+ return row.get("pinned_executor"), Tier(tier_value) if tier_value else None
75
+
76
+ def ask_sync(self, prompt: str, **kw: Any) -> Reply:
77
+ return asyncio.run(self.ask(prompt, **kw))
78
+
79
+ def pin(self, executor: Any = _UNSET, tier: Any = _UNSET) -> None:
80
+ """Pin executor/tier (T12b: _UNSET fields keep their current pinned value)."""
81
+ row = self._client.store.get_session(self.id) or {}
82
+ executor_id = row.get("pinned_executor") if executor is _UNSET else executor
83
+ tier_value = row.get("tier") if tier is _UNSET else (int(tier) if tier else None)
84
+ self._client.store.pin(self.id, executor_id=executor_id, tier=tier_value)
85
+
86
+ def history(self) -> list[dict[str, Any]]:
87
+ return self._client.store.turns(self.id)
88
+
89
+
90
+ class OneChatClient:
91
+ """Wires config, store, executors, quota and the router. Entry point for everything."""
92
+
93
+ def __init__(self, config_path: Path | None = None, home: Path | None = None) -> None:
94
+ self.config: RouterConfig = load_config(config_path, home=home)
95
+ self.config.db_path.parent.mkdir(parents=True, exist_ok=True)
96
+ self.store = Store(
97
+ self.config.db_path,
98
+ api_key_envs=sorted(
99
+ {spec.api_key_env for spec in self.config.executors if spec.api_key_env}
100
+ ),
101
+ )
102
+ target_ids = (
103
+ {t.executor_id for t in getattr(self.config.benchmark, "targets", [])}
104
+ if getattr(self.config, "benchmark", None)
105
+ else set()
106
+ )
107
+ self.executors: dict[str, Executor] = {
108
+ spec.id: build_executor(spec, self.config.profiles)
109
+ for spec in self.config.executors
110
+ if spec.enabled or spec.id in target_ids
111
+ }
112
+ self.quota = QuotaBook(self.store, policy=self.config.cooldown)
113
+ self.router = Router(
114
+ config=self.config,
115
+ store=self.store,
116
+ executors=self.executors,
117
+ quota=self.quota,
118
+ git=_default_git(),
119
+ )
120
+
121
+ def session(
122
+ self, workdir: Path | str = ".", session_id: str | None = None, title: str | None = None
123
+ ) -> Session:
124
+ sid = session_id or f"s-{time.time_ns():x}-{secrets.token_hex(4)}"
125
+ if self.store.get_session(sid) is None:
126
+ self.store.create_session(sid, title=title or sid, workdir=str(workdir))
127
+ return Session(self, sid)
128
+
129
+ async def ask_once(self, prompt: str, **need: Any) -> Reply:
130
+ """Ephemeral one-shot ask: the session (and its rows) never outlive the call."""
131
+ sid = f"s-{time.time_ns():x}-{secrets.token_hex(4)}"
132
+ self.store.create_session(sid, title=sid, workdir=".")
133
+ try:
134
+ return await Session(self, sid).ask(prompt, **need)
135
+ finally:
136
+ self._drop_session(sid) # ephemeral: no rows kept (T12b)
137
+
138
+ def _drop_session(self, sid: str) -> None:
139
+ """Ephemeral-session teardown: turns first (FK), then native rows, then the row."""
140
+ self.store.delete_session(sid)
141
+
142
+ def close(self) -> None:
143
+ """Release the store (T12b). Any later store use fails closed."""
144
+ self.store.close()
145
+
146
+ async def aclose(self) -> None:
147
+ for executor in self.executors.values():
148
+ aclose = getattr(executor, "aclose", None)
149
+ if callable(aclose):
150
+ await aclose()
151
+ self.close()
152
+
153
+ @classmethod
154
+ def _for_tests(
155
+ cls,
156
+ tmp_path: Path,
157
+ executor_factory: Callable[[RouterConfig], dict[str, Executor]],
158
+ ) -> OneChatClient:
159
+ """Test constructor: tmp store + injected executors, no CLIs needed."""
160
+ client = cls.__new__(cls)
161
+ client.config = _test_config(tmp_path)
162
+ client.store = Store(tmp_path / "asf.db")
163
+ client.executors = executor_factory(client.config)
164
+ client.quota = QuotaBook(client.store, policy=client.config.cooldown)
165
+ client.router = Router(
166
+ config=client.config,
167
+ store=client.store,
168
+ executors=client.executors,
169
+ quota=client.quota,
170
+ git=lambda _p: "",
171
+ )
172
+ return client
173
+
174
+
175
+ # Backwards compatibility alias
176
+ AsfClient = OneChatClient
177
+
178
+
179
+ def _test_config(tmp_path: Path) -> RouterConfig:
180
+ """Two free CODE-capable cli executors for fake-driven SDK tests."""
181
+ from .config import CliProfile
182
+ from .contracts import Capability, CostClass, ExecutorSpec, Tier
183
+
184
+ def spec(eid: str) -> ExecutorSpec:
185
+ return ExecutorSpec(
186
+ id=eid,
187
+ kind="cli",
188
+ profile=eid,
189
+ model="m",
190
+ tier=Tier.MEDIUM,
191
+ capabilities=frozenset({Capability.CHAT, Capability.CODE}),
192
+ cost=CostClass.FREE,
193
+ family=f"family-{eid}",
194
+ )
195
+
196
+ profiles = {
197
+ eid: CliProfile(
198
+ name=eid, binary="true", new=["{prompt}"], resume=["{prompt}"], parser="codex_jsonl"
199
+ )
200
+ for eid in ("exec-a", "exec-b")
201
+ }
202
+ return RouterConfig(
203
+ db_path=tmp_path / "asf.db", executors=[spec("exec-a"), spec("exec-b")], profiles=profiles
204
+ )
205
+
206
+
207
+ def _default_git() -> Callable[[Path], Any]:
208
+ from .gitstate import async_git_state
209
+
210
+ return async_git_state
onechat/selector.py ADDED
@@ -0,0 +1,294 @@
1
+ """Selector (Plan 03 §2 / T10): tier resolution + candidate ordering. Pure functions."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import re
6
+ from collections.abc import Callable
7
+
8
+ from pydantic import BaseModel, Field, field_validator
9
+
10
+ from .config import TierPolicy
11
+ from .contracts import Capability, CostClass, ExecutorSpec, Tier
12
+ from .scoring import SkillRoutingConfig, score_candidate
13
+
14
+ _BENCHMARK_RE = re.compile(r"\b(?:deepswe|automationbench)\b", re.IGNORECASE)
15
+
16
+
17
+ def is_high_effort_benchmark(prompt: str) -> bool:
18
+ """Return True if prompt contains benchmark tokens requiring high thinking effort."""
19
+ return bool(_BENCHMARK_RE.search(prompt))
20
+
21
+
22
+ def clamp_tier(tier: Tier, prompt: str, policy: TierPolicy) -> Tier:
23
+ """Enforce TierPolicy min_tier and max_tier bounds, with benchmark HIGH exception."""
24
+ if is_high_effort_benchmark(prompt):
25
+ return Tier.HIGH
26
+ return Tier(max(policy.min_tier, min(tier, policy.max_tier)))
27
+
28
+
29
+ class Need(BaseModel):
30
+ capability: Capability = Capability.CHAT
31
+ tier: Tier | str = "auto" # Tier or "auto"
32
+ executor_id: str | None = None
33
+ role: str | None = None
34
+ model: str | None = None
35
+ allow_fallback: bool = True
36
+ avoid_family: str | None = None
37
+ exclude: frozenset[str] = frozenset()
38
+ task_kind: str | None = None
39
+ skills: tuple[str, ...] = ()
40
+ failures: int = Field(default=0, ge=0) # negative escalation makes no sense (T10)
41
+ timeout_s: int | None = Field(default=None, ge=1)
42
+
43
+ @field_validator("skills", mode="before")
44
+ @classmethod
45
+ def _coerce_skills(cls, v: object) -> tuple[str, ...]:
46
+ if isinstance(v, (list, tuple, set)):
47
+ return tuple(str(x).strip().lower() for x in v if str(x).strip())
48
+ if isinstance(v, str):
49
+ return tuple(str(x).strip().lower() for x in v.split(",") if str(x).strip())
50
+ return ()
51
+
52
+
53
+ __all__ = [
54
+ "Need",
55
+ "TierPolicy",
56
+ "resolve_tier",
57
+ "order_candidates",
58
+ "is_high_effort_benchmark",
59
+ "clamp_tier",
60
+ ]
61
+
62
+
63
+ def resolve_tier(need: Need, prompt: str, policy: TierPolicy) -> Tier:
64
+ """Auto tier: task_kind map -> keywords -> short prompt -> chat_default; escalate, cap MAX."""
65
+ tier: Tier
66
+ lowered = prompt.lower()
67
+ if need.task_kind and need.task_kind in policy.by_task_kind:
68
+ tier = policy.by_task_kind[need.task_kind]
69
+ elif any(k in lowered for k in policy.high_keywords):
70
+ tier = Tier.HIGH
71
+ elif len(prompt) < 200 and "```" not in prompt:
72
+ tier = Tier.LOW
73
+ else:
74
+ tier = policy.chat_default
75
+ if need.failures and policy.escalate_every > 0:
76
+ tier = Tier(min(tier + need.failures // policy.escalate_every, int(Tier.MAX)))
77
+ return clamp_tier(tier, prompt, policy)
78
+
79
+
80
+ def order_candidates(
81
+ need: Need,
82
+ tier: Tier,
83
+ specs: list[ExecutorSpec],
84
+ usable: Callable[[ExecutorSpec], bool],
85
+ policy: TierPolicy,
86
+ roles: dict[str, str] | None = None,
87
+ skill_cfg: SkillRoutingConfig | None = None,
88
+ model_scores: dict[str, dict[str, float]] | None = None,
89
+ ) -> list[ExecutorSpec]:
90
+ """Keep usable+capable+family/cost/exclude filters, tier-sufficient; cheapest-smart wins.
91
+
92
+ A pinned executor_id bypasses the tier/family/exclude filters (explicit user override)
93
+ but must still be enabled, usable, capable and cost-allowed. With allow_fallback=False
94
+ a pinned executor that is NOT usable yields [] — never other backends (T10).
95
+ """
96
+ wanted_capability = need.capability
97
+
98
+ def cost_allowed(s: ExecutorSpec) -> bool:
99
+ return s.cost != CostClass.PAID or policy.allow_paid
100
+
101
+ if need.executor_id:
102
+ pinned = [
103
+ s
104
+ for s in specs
105
+ if s.id == need.executor_id
106
+ and s.enabled
107
+ and usable(s)
108
+ and wanted_capability in s.capabilities
109
+ and cost_allowed(s)
110
+ ]
111
+ if not need.allow_fallback:
112
+ return pinned
113
+ if pinned:
114
+ rest = [s for s in _filtered(need, tier, specs, usable, policy) if s.id != pinned[0].id]
115
+ sorted_r = _sort_candidates(rest, need, tier, policy, roles, skill_cfg, model_scores)
116
+ return [pinned[0], *[s for s in sorted_r if s.id != pinned[0].id]]
117
+ filtered = _filtered(need, tier, specs, usable, policy)
118
+ return _sort_candidates(filtered, need, tier, policy, roles, skill_cfg, model_scores)
119
+
120
+
121
+ def _sort_candidates(
122
+ cands: list[ExecutorSpec],
123
+ need: Need,
124
+ tier: Tier,
125
+ policy: TierPolicy,
126
+ roles: dict[str, str] | None,
127
+ skill_cfg: SkillRoutingConfig | None,
128
+ model_scores: dict[str, dict[str, float]] | None,
129
+ ) -> list[ExecutorSpec]:
130
+ if not skill_cfg or not skill_cfg.enabled or not need.skills:
131
+ by_role = _filter_role(_sort_rest(cands, tier, policy), need, roles)
132
+ return _filter_model(by_role, need.model)
133
+
134
+ if not need.allow_fallback and need.role and roles and need.role in roles:
135
+ cands = _filter_role(cands, need, roles)
136
+
137
+ strong, weak = _split_by_skills(cands, need, tier, policy, roles, skill_cfg, model_scores)
138
+ return _filter_model(strong, need.model, strict=not need.allow_fallback) + _filter_model(
139
+ weak, need.model, strict=not need.allow_fallback
140
+ )
141
+
142
+
143
+ def _score_one(
144
+ s: ExecutorSpec,
145
+ need: Need,
146
+ roles: dict[str, str] | None,
147
+ cfg: SkillRoutingConfig,
148
+ scores: dict[str, dict[str, float]] | None,
149
+ ):
150
+ target = roles.get(need.role) if roles and need.role else None
151
+ is_role = target is not None and (
152
+ s.id == target or s.profile == target or s.model == target or s.family == target
153
+ )
154
+ return score_candidate(
155
+ s,
156
+ need.skills,
157
+ cfg,
158
+ is_role_match=is_role,
159
+ is_benchmarked=s.priority == 0,
160
+ model_scores=scores,
161
+ )
162
+
163
+
164
+ def _split_by_skills(
165
+ cands: list[ExecutorSpec],
166
+ need: Need,
167
+ tier: Tier,
168
+ policy: TierPolicy,
169
+ roles: dict[str, str] | None,
170
+ skill_cfg: SkillRoutingConfig,
171
+ model_scores: dict[str, dict[str, float]] | None,
172
+ ) -> tuple[list[ExecutorSpec], list[ExecutorSpec]]:
173
+ scored = [(s, _score_one(s, need, roles, skill_cfg, model_scores)) for s in cands]
174
+ strong = [item for item in scored if not item[1].is_weak]
175
+ weak = [item for item in scored if item[1].is_weak]
176
+
177
+ def cost_rank(s: ExecutorSpec) -> int:
178
+ return (
179
+ policy.cost_order.index(s.cost)
180
+ if s.cost in policy.cost_order
181
+ else len(policy.cost_order)
182
+ )
183
+
184
+ def sort_key(item: tuple[ExecutorSpec, any]):
185
+ s, cs = item
186
+ return (
187
+ -cs.final_score,
188
+ s.priority if s.priority <= 1 else 999,
189
+ s.tier - tier,
190
+ cost_rank(s),
191
+ s.priority,
192
+ s.id,
193
+ )
194
+
195
+ strong_sorted = [s for s, _ in sorted(strong, key=sort_key)]
196
+ weak_sorted = [s for s, _ in sorted(weak, key=sort_key)]
197
+ return strong_sorted, weak_sorted
198
+
199
+
200
+ def _filter_model(
201
+ cands: list[ExecutorSpec], model: str | None, *, strict: bool = False
202
+ ) -> list[ExecutorSpec]:
203
+ if not model:
204
+ return cands
205
+ m_lower = model.removesuffix(":free").lower()
206
+
207
+ def keys(s: ExecutorSpec) -> list[str]:
208
+ out = [s.model.lower(), s.model.removesuffix(":free").lower()]
209
+ if s.model_key:
210
+ out.append(s.model_key.removesuffix(":free").lower())
211
+ return out
212
+
213
+ exact = [s for s in cands if m_lower in keys(s)]
214
+ sub = [s for s in cands if s not in exact and any(m_lower in k for k in keys(s))]
215
+ matching = exact + sub
216
+ if strict:
217
+ return matching
218
+ return matching + [s for s in cands if s not in matching] if matching else cands
219
+
220
+
221
+ def _filter_role(
222
+ cands: list[ExecutorSpec], need: Need, roles: dict[str, str] | None
223
+ ) -> list[ExecutorSpec]:
224
+ if not roles or not need.role or need.role not in roles or need.executor_id:
225
+ return cands
226
+ target = roles[need.role]
227
+ matching = [
228
+ s
229
+ for s in cands
230
+ if s.id == target or s.profile == target or s.model == target or s.family == target
231
+ ]
232
+ if not need.allow_fallback:
233
+ return matching
234
+ return matching + [s for s in cands if s not in matching]
235
+
236
+
237
+ def _filtered(
238
+ need: Need,
239
+ tier: Tier,
240
+ specs: list[ExecutorSpec],
241
+ usable: Callable[[ExecutorSpec], bool],
242
+ policy: TierPolicy,
243
+ ) -> list[ExecutorSpec]:
244
+ wanted_capability = need.capability
245
+ base = [
246
+ s
247
+ for s in specs
248
+ if s.enabled
249
+ and usable(s)
250
+ and wanted_capability in s.capabilities
251
+ and s.id not in need.exclude
252
+ and (s.cost != CostClass.PAID or policy.allow_paid)
253
+ and s.tier >= tier
254
+ ]
255
+ if need.avoid_family is not None:
256
+ avoided = [s for s in base if s.family != need.avoid_family]
257
+ if avoided:
258
+ return avoided
259
+ return base
260
+
261
+
262
+ def _sort_rest(rest: list[ExecutorSpec], tier: Tier, policy: TierPolicy) -> list[ExecutorSpec]:
263
+ def cost_rank(s: ExecutorSpec) -> int:
264
+ return (
265
+ policy.cost_order.index(s.cost)
266
+ if s.cost in policy.cost_order
267
+ else len(policy.cost_order)
268
+ )
269
+
270
+ return sorted(
271
+ rest,
272
+ key=lambda s: (
273
+ s.priority if s.priority <= 1 else 999,
274
+ s.tier - tier,
275
+ cost_rank(s),
276
+ s.priority,
277
+ s.id,
278
+ ),
279
+ )
280
+
281
+
282
+ def coerce_tier(value: Tier | str | None) -> Tier | None:
283
+ """Explicit tier values from CLIs/SDK: Tier passes through, strings parse, 'auto' -> None."""
284
+ if value is None or value == "auto":
285
+ return None
286
+ if isinstance(value, Tier):
287
+ return value
288
+ text = str(value).strip().lower()
289
+ names = {"low": Tier.LOW, "medium": Tier.MEDIUM, "high": Tier.HIGH, "max": Tier.MAX}
290
+ if text in names:
291
+ return names[text]
292
+ if text.isdigit():
293
+ return Tier(int(text))
294
+ raise ValueError(f"unknown tier: {value!r} (use low|medium|high|max|auto or 1-4)")