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.
@@ -0,0 +1,288 @@
1
+ """Router helpers (T12a): request building + the compaction summarizer, extracted so
2
+ router.py stays within its 300-line budget. Sync or async git callables are both fine."""
3
+
4
+ from __future__ import annotations
5
+
6
+ import inspect
7
+ import re
8
+ import time
9
+ from collections.abc import Callable
10
+ from pathlib import Path
11
+ from typing import Any
12
+
13
+ from .config import RouterConfig
14
+ from .contracts import Capability, TurnRequest
15
+ from .handoff import api_messages, delta_brief, handoff_brief
16
+ from .scoring import detect_skills
17
+ from .selector import Need, order_candidates
18
+
19
+ TURN_TIMEOUT_S = 600
20
+ _STALE_MARKERS = ("not found", "no such", "does not exist")
21
+ _CODE_PROMPT_RE = re.compile(r"\b(?:review|code|implement|build|bug|test)\b", re.IGNORECASE)
22
+
23
+
24
+ def stale_session(error: str | None) -> bool:
25
+ """True when an ERROR text says the native session is gone (T12a: retry fresh)."""
26
+ if not error:
27
+ return False
28
+ lowered = error.lower()
29
+ return "session" in lowered and any(marker in lowered for marker in _STALE_MARKERS)
30
+
31
+
32
+ async def git_state_of(git: Callable[[Path], Any], workdir: Path) -> str:
33
+ result = git(workdir)
34
+ if inspect.isawaitable(result):
35
+ result = await result
36
+ return str(result or "")
37
+
38
+
39
+ def eligible_specs(need: Need, specs: list[Any], config: RouterConfig) -> list[Any]:
40
+ """Capability/family/cost-filtered specs (ignores availability) — retry_at hints."""
41
+ return [
42
+ s
43
+ for s in specs
44
+ if s.enabled
45
+ and need.capability in s.capabilities
46
+ and (need.avoid_family is None or s.family != need.avoid_family)
47
+ and s.id not in need.exclude
48
+ and (s.cost.value != "paid" or config.tier_policy.allow_paid)
49
+ ]
50
+
51
+
52
+ def bootstrap_prompt(prompt: str, workdir: Path) -> str:
53
+ """Turn 1 bootstrap: orient assistant to workspace and key guideline files."""
54
+ if not workdir.is_dir() or "<workspace-context>" in prompt:
55
+ return prompt
56
+ candidates = ("AGENTS.md", "CLAUDE.md", "SPEC.md", "README.md")
57
+ found = [name for name in candidates if (workdir / name).is_file()]
58
+ if not found:
59
+ return prompt
60
+ files_list = "\n".join(f"- {name}" for name in found)
61
+ header = (
62
+ f"<workspace-context>\n"
63
+ f"Workspace root: {workdir}\n"
64
+ f"Guideline files detected:\n{files_list}\n\n"
65
+ f"Review relevant guideline files (especially AGENTS.md if present) to adhere "
66
+ f"to repository rules and standards.\n"
67
+ f"</workspace-context>\n\n"
68
+ )
69
+ return header + prompt
70
+
71
+
72
+ def _should_bootstrap(need: Need, prompt: str) -> bool:
73
+ return (
74
+ need.capability == Capability.CODE
75
+ or need.role in ("builder", "reviewer", "auditor", "code", "code-review")
76
+ or bool(_CODE_PROMPT_RE.search(prompt))
77
+ )
78
+
79
+
80
+ def build_request(
81
+ session: dict[str, Any],
82
+ spec: Any,
83
+ need: Need,
84
+ prompt: str,
85
+ turns: list[dict[str, Any]],
86
+ git_text: str,
87
+ interrupted: bool,
88
+ config: RouterConfig,
89
+ native: dict[str, Any] | None,
90
+ ) -> TurnRequest:
91
+ """Route the turn: native resume (+delta) / full handoff / fresh prompt."""
92
+ wd = Path(session["workdir"])
93
+ t_s, i_s = need.timeout_s or config.turn_timeout_s, config.inactivity_timeout_s
94
+ boot = _should_bootstrap(need, prompt)
95
+ if spec.kind == "api":
96
+ act = prompt if turns or not boot else bootstrap_prompt(prompt, wd)
97
+ msgs = api_messages(session, turns, act, config.handoff)
98
+ return TurnRequest(
99
+ prompt=act, workdir=wd, messages=msgs, timeout_s=t_s, inactivity_timeout_s=i_s
100
+ )
101
+ if native is not None and native["native_id"]:
102
+ return _native_request(
103
+ session, spec, need, prompt, turns, git_text, interrupted, config, wd, native
104
+ )
105
+
106
+ brief = (
107
+ handoff_brief(session, turns, git_text, interrupted, config.handoff, prompt=prompt)
108
+ if (turns or interrupted)
109
+ else (bootstrap_prompt(prompt, wd) if boot else prompt)
110
+ )
111
+ return TurnRequest(prompt=brief, workdir=wd, timeout_s=t_s, inactivity_timeout_s=i_s)
112
+
113
+
114
+ def _native_request(
115
+ session: dict[str, Any],
116
+ spec: Any,
117
+ need: Need,
118
+ prompt: str,
119
+ turns: list[dict[str, Any]],
120
+ git_text: str,
121
+ interrupted: bool,
122
+ config: RouterConfig,
123
+ workdir: Path,
124
+ native: dict[str, Any],
125
+ ) -> TurnRequest:
126
+ missed = [t for t in turns if int(t["idx"]) > int(native["last_turn_idx"])]
127
+ timeout_s = need.timeout_s or config.turn_timeout_s
128
+ inactivity_s = config.inactivity_timeout_s
129
+ prefix = ""
130
+ if missed or interrupted:
131
+ prefix = delta_brief(missed, git_text, config.handoff)
132
+ if interrupted and need.capability == Capability.CODE:
133
+ prefix += "The previous assistant was interrupted mid-task. Inspect workspace.\n"
134
+ return TurnRequest(
135
+ prompt=f"{prefix}{prompt}",
136
+ workdir=workdir,
137
+ native_session_id=str(native["native_id"]),
138
+ timeout_s=timeout_s,
139
+ inactivity_timeout_s=inactivity_s,
140
+ )
141
+
142
+
143
+ async def _run_summarize_turn(
144
+ spec: Any, req: Any, executors: dict[str, Any], quota: Any, config: Any, sole: bool
145
+ ) -> tuple[str | None, Exception | None]:
146
+ try:
147
+ result = await executors[spec.id].run(req)
148
+ except Exception as exc:
149
+ return None, exc
150
+ quota.record(
151
+ spec,
152
+ result,
153
+ "",
154
+ None,
155
+ sole_usable=sole,
156
+ all_specs=list(config.executors),
157
+ profiles=config.profiles,
158
+ )
159
+ if result.stop.value != "done" or not result.text:
160
+ return None, RuntimeError(result.error or result.stop.value)
161
+ return result.text, None
162
+
163
+
164
+ def make_summarizer(
165
+ config: RouterConfig,
166
+ executors: dict[str, Any],
167
+ quota: Any,
168
+ usable: Callable[[Any], bool],
169
+ workdir: Path,
170
+ ) -> Callable[[str], Any]:
171
+ """CHAT-only summarizer (T12a): records usage, tries fallbacks, raises on all failures."""
172
+ from .contracts import Tier, TurnRequest
173
+ from .selector import Need, order_candidates
174
+
175
+ async def summarize(text: str) -> str:
176
+ specs = [e.spec for e in executors.values()]
177
+ cands = order_candidates(
178
+ Need(task_kind="summarize"), Tier.LOW, specs, usable, config.tier_policy
179
+ )
180
+ if not cands:
181
+ return text[: config.handoff.brief_max_chars]
182
+ last_error: Exception | None = None
183
+ req = TurnRequest(
184
+ prompt=f"Summarize this conversation in <=500 words:\n{text}",
185
+ workdir=workdir,
186
+ timeout_s=120,
187
+ )
188
+ for spec in cands[:2]:
189
+ text_out, err = await _run_summarize_turn(
190
+ spec, req, executors, quota, config, len(cands) <= 1
191
+ )
192
+ if text_out is not None:
193
+ return text_out
194
+ last_error = err
195
+ raise last_error or RuntimeError("summarizer failed")
196
+
197
+ return summarize
198
+
199
+
200
+ def _update_spec_override(s: Any, rec: dict[str, Any], now: float, ttl_s: float | None) -> Any:
201
+ checked_at = float(rec.get("checked_at") or 0.0)
202
+ if ttl_s is not None and (now - checked_at) > ttl_s:
203
+ return s
204
+ en = bool(rec["enabled_override"]) if rec.get("enabled_override") is not None else s.enabled
205
+ prio = rec["priority_override"] if rec.get("priority_override") is not None else s.priority
206
+ return s.model_copy(update={"enabled": en, "priority": prio})
207
+
208
+
209
+ def apply_executor_overrides(
210
+ specs: list[Any],
211
+ roles: dict[str, str],
212
+ overrides: dict[str, dict[str, Any]],
213
+ promote_roles: list[str],
214
+ benchmark_enabled: bool = True,
215
+ now_ts: float | None = None,
216
+ ttl_s: float | None = None,
217
+ usable: Callable[[Any], bool] | None = None,
218
+ ) -> tuple[list[Any], dict[str, str]]:
219
+ """Apply dynamic circuit overrides (enabled, priority) and promote top healthy executor."""
220
+ if not benchmark_enabled or not overrides:
221
+ return specs, roles
222
+ now = time.time() if now_ts is None else now_ts
223
+ updated_specs = [
224
+ _update_spec_override(s, overrides[s.id], now, ttl_s) if s.id in overrides else s
225
+ for s in specs
226
+ ]
227
+ effective_roles = dict(roles)
228
+ healthy = [
229
+ s
230
+ for s in updated_specs
231
+ if s.id in overrides
232
+ and overrides[s.id].get("status") == "healthy"
233
+ and s.enabled
234
+ and (usable is None or usable(s))
235
+ and (ttl_s is None or (now - float(overrides[s.id].get("checked_at") or 0.0)) <= ttl_s)
236
+ ]
237
+ if healthy:
238
+ healthy.sort(key=lambda s: s.priority)
239
+ for r in promote_roles:
240
+ effective_roles[r] = healthy[0].id
241
+ return updated_specs, effective_roles
242
+
243
+
244
+ def advance_native(
245
+ store: Any, session_id: str, spec: Any, result: Any, assistant_idx: int, resumed: bool
246
+ ) -> None:
247
+ if result.native_session_id:
248
+ store.set_native(session_id, spec.id, result.native_session_id, assistant_idx)
249
+ return
250
+ if resumed:
251
+ native = store.get_native(session_id, spec.id)
252
+ if native is not None and native["native_id"]:
253
+ store.set_native(session_id, spec.id, str(native["native_id"]), assistant_idx)
254
+
255
+
256
+ def select_candidates(
257
+ need: Need,
258
+ prompt: str,
259
+ tier: Any,
260
+ specs: list[Any],
261
+ roles: dict[str, str],
262
+ config: RouterConfig,
263
+ usable: Callable[[Any], bool],
264
+ workdir: Path | None = None,
265
+ ) -> tuple[list[Any], list[Any], dict[str, str]]:
266
+ """Select and order candidates with skill detection and circuit overrides."""
267
+ skills = need.skills
268
+ if not skills and config.skill_routing.auto_detect:
269
+ skills = detect_skills(
270
+ prompt=prompt, task_kind=need.task_kind, workdir=workdir, cfg=config.skill_routing
271
+ )
272
+ eff_need = need if eff_need_same(need, skills) else need.model_copy(update={"skills": skills})
273
+ cands = order_candidates(
274
+ eff_need,
275
+ tier,
276
+ specs,
277
+ usable,
278
+ config.tier_policy,
279
+ roles=roles,
280
+ skill_cfg=config.skill_routing,
281
+ model_scores=config.model_scores,
282
+ )
283
+ eligible = eligible_specs(eff_need, specs, config)
284
+ return cands, eligible, roles
285
+
286
+
287
+ def eff_need_same(need: Need, skills: tuple[str, ...]) -> bool:
288
+ return need.skills == skills
onechat/scoring.py ADDED
@@ -0,0 +1,241 @@
1
+ """Skill scoring, model resolution, and prompt skill detection."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import re
6
+ from pathlib import Path
7
+
8
+ from pydantic import BaseModel, Field
9
+
10
+ from .contracts import ExecutorSpec
11
+
12
+ CANONICAL_ALIASES: dict[str, str] = {
13
+ "javascript": "js",
14
+ "js": "js",
15
+ "jsx": "js",
16
+ "typescript": "ts",
17
+ "ts": "ts",
18
+ "tsx": "ts",
19
+ "python": "py",
20
+ "py": "py",
21
+ "rust": "rs",
22
+ "rs": "rs",
23
+ "golang": "golang",
24
+ "go": "golang",
25
+ "bash": "sh",
26
+ "sh": "sh",
27
+ "shell": "sh",
28
+ "zsh": "sh",
29
+ "css": "css",
30
+ "scss": "css",
31
+ "sass": "css",
32
+ "html": "frontend",
33
+ "frontend": "frontend",
34
+ "e2e": "e2e",
35
+ "playwright": "e2e",
36
+ "cypress": "e2e",
37
+ "review": "code-review",
38
+ "code-review": "code-review",
39
+ "architecture": "architecture",
40
+ "arch": "architecture",
41
+ }
42
+
43
+ DEFAULT_EXTENSIONS: dict[str, str] = {
44
+ ".spec.ts": "e2e",
45
+ ".test.ts": "ts",
46
+ ".ts": "ts",
47
+ ".tsx": "ts",
48
+ ".js": "js",
49
+ ".jsx": "js",
50
+ ".py": "py",
51
+ ".rs": "rs",
52
+ ".go": "golang",
53
+ ".sh": "sh",
54
+ ".css": "css",
55
+ ".scss": "css",
56
+ }
57
+
58
+ DEFAULT_MARKERS: dict[str, str] = {
59
+ "Cargo.toml": "rs",
60
+ "package.json": "js",
61
+ "tsconfig.json": "ts",
62
+ "pyproject.toml": "py",
63
+ "go.mod": "golang",
64
+ }
65
+
66
+ STRUCTURAL_TASKS: frozenset[str] = frozenset(
67
+ {"plan", "spec", "summarize", "digest", "research", "audit"}
68
+ )
69
+
70
+
71
+ class SkillRoutingConfig(BaseModel):
72
+ """Configuration for skill-based routing."""
73
+
74
+ enabled: bool = True
75
+ default_score: float = 50.0
76
+ weak_threshold: float = 40.0
77
+ role_bonus: float = 5.0
78
+ benchmark_bonus: float = 5.0
79
+ auto_detect: bool = True
80
+ aliases: dict[str, str] = Field(default_factory=dict)
81
+ extension_skills: dict[str, str] = Field(default_factory=dict)
82
+ marker_skills: dict[str, str] = Field(default_factory=dict)
83
+
84
+
85
+ class CandidateScore(BaseModel):
86
+ """Evaluated score for an executor candidate."""
87
+
88
+ spec: ExecutorSpec
89
+ final_score: float
90
+ is_weak: bool
91
+ is_rated: bool
92
+ min_explicit_score: float | None = None
93
+
94
+
95
+ def canonicalize_skill(skill: str, extra_aliases: dict[str, str] | None = None) -> str:
96
+ """Normalize a skill token to its canonical form."""
97
+ s = skill.strip().lower()
98
+ if extra_aliases:
99
+ low_extra = {k.strip().lower(): v.strip().lower() for k, v in extra_aliases.items()}
100
+ if s in low_extra:
101
+ return CANONICAL_ALIASES.get(low_extra[s], low_extra[s])
102
+ return CANONICAL_ALIASES.get(s, s)
103
+
104
+
105
+ def _canon_score_map(
106
+ raw: dict[str, float], aliases: dict[str, str] | None = None
107
+ ) -> dict[str, float]:
108
+ return {canonicalize_skill(k, aliases): float(v) for k, v in raw.items()}
109
+
110
+
111
+ def resolve_model_scores(
112
+ spec_model: str,
113
+ spec_model_key: str | None,
114
+ spec_scores: dict[str, float],
115
+ model_scores: dict[str, dict[str, float]],
116
+ extra_aliases: dict[str, str] | None = None,
117
+ ) -> dict[str, float]:
118
+ """Resolve scores: spec_scores > model_key > exact/base model > substr match."""
119
+ resolved: dict[str, float] = {}
120
+ m_clean = spec_model.removesuffix(":free").strip().lower()
121
+ m_base = m_clean.split("/")[-1]
122
+ norm_scores = {
123
+ k.removesuffix(":free").strip().lower(): _canon_score_map(sc, extra_aliases)
124
+ for k, sc in model_scores.items()
125
+ }
126
+
127
+ for k in sorted(norm_scores, key=len):
128
+ if k in m_clean or k in m_base:
129
+ resolved.update(norm_scores[k])
130
+ for k in (m_clean, m_base):
131
+ if k in norm_scores:
132
+ resolved.update(norm_scores[k])
133
+ if spec_model_key:
134
+ mk = spec_model_key.removesuffix(":free").strip().lower()
135
+ if mk in norm_scores:
136
+ resolved.update(norm_scores[mk])
137
+ resolved.update(_canon_score_map(spec_scores, extra_aliases))
138
+ return resolved
139
+
140
+
141
+ def detect_skills(
142
+ prompt: str = "",
143
+ task_kind: str | None = None,
144
+ workdir: Path | None = None,
145
+ cfg: SkillRoutingConfig | None = None,
146
+ ) -> tuple[str, ...]:
147
+ """Detect required skills from code blocks, extensions, keywords, and workdir markers."""
148
+ if task_kind and task_kind.lower() in STRUCTURAL_TASKS:
149
+ return ()
150
+ c = cfg or SkillRoutingConfig()
151
+ found: set[str] = set()
152
+ for lang in re.findall(r"```([a-zA-Z0-9_\-]+)", prompt):
153
+ found.add(canonicalize_skill(lang, c.aliases))
154
+ _scan_extensions(prompt, c, found)
155
+ _scan_keywords(prompt, c, found)
156
+ if not found and workdir and workdir.exists():
157
+ _scan_workdir(workdir, c, found)
158
+ return tuple(sorted(found))
159
+
160
+
161
+ def _scan_extensions(prompt: str, c: SkillRoutingConfig, found: set[str]) -> None:
162
+ ext_map = {**DEFAULT_EXTENSIONS, **c.extension_skills}
163
+ masked = prompt
164
+ for ext, sk in sorted(ext_map.items(), key=lambda x: -len(x[0])):
165
+ pat = re.compile(rf"(?<!\.){re.escape(ext)}(?![A-Za-z0-9_])", re.IGNORECASE)
166
+ if pat.search(masked):
167
+ found.add(canonicalize_skill(sk, c.aliases))
168
+ masked = pat.sub(" ", masked)
169
+
170
+
171
+ def _scan_keywords(prompt: str, c: SkillRoutingConfig, found: set[str]) -> None:
172
+ words = set(re.findall(r"\b[a-zA-Z0-9_\-]+\b", prompt.lower()))
173
+ alias_pool = {k: v for k, v in CANONICAL_ALIASES.items() if k != "review"}
174
+ for k, v in c.aliases.items():
175
+ alias_pool[k.strip().lower()] = v
176
+ for alias_key, canon in alias_pool.items():
177
+ if len(alias_key) > 2 and alias_key in words:
178
+ found.add(canonicalize_skill(canon, c.aliases))
179
+
180
+
181
+ def _scan_workdir(workdir: Path, cfg: SkillRoutingConfig, found: set[str]) -> None:
182
+ """Scan workdir/app then workdir markers without touching monitor/."""
183
+ markers = {**DEFAULT_MARKERS, **cfg.marker_skills}
184
+ for root in (workdir / "app", workdir):
185
+ if not root.is_dir():
186
+ continue
187
+ matched = False
188
+ for marker, sk in markers.items():
189
+ if (root / marker).exists():
190
+ found.add(canonicalize_skill(sk, cfg.aliases))
191
+ matched = True
192
+ if matched:
193
+ return
194
+
195
+
196
+ def _eval_skills(
197
+ skills: tuple[str, ...], scores: dict[str, float], c: SkillRoutingConfig
198
+ ) -> tuple[float, bool, bool, float | None]:
199
+ explicit: list[float] = []
200
+ vals: list[float] = []
201
+ for sk in skills:
202
+ canon = canonicalize_skill(sk, c.aliases)
203
+ if canon in scores:
204
+ v = scores[canon]
205
+ explicit.append(v)
206
+ vals.append(v)
207
+ else:
208
+ vals.append(c.default_score)
209
+ avg_score = sum(vals) / len(vals)
210
+ min_exp = min(explicit) if explicit else None
211
+ is_weak = min_exp is not None and min_exp < c.weak_threshold
212
+ return avg_score, is_weak, bool(explicit), min_exp
213
+
214
+
215
+ def score_candidate(
216
+ spec: ExecutorSpec,
217
+ skills: tuple[str, ...],
218
+ cfg: SkillRoutingConfig | None = None,
219
+ is_role_match: bool = False,
220
+ is_benchmarked: bool = False,
221
+ model_scores: dict[str, dict[str, float]] | None = None,
222
+ ) -> CandidateScore:
223
+ """Score candidate executor against requested skills."""
224
+ c = cfg or SkillRoutingConfig()
225
+ scores = resolve_model_scores(
226
+ spec.model, spec.model_key, spec.scores, model_scores or {}, c.aliases
227
+ )
228
+ if not skills:
229
+ return CandidateScore(
230
+ spec=spec, final_score=c.default_score, is_weak=False, is_rated=bool(scores)
231
+ )
232
+ avg, is_weak, is_rated, min_exp = _eval_skills(skills, scores, c)
233
+ final = avg + (c.role_bonus if is_role_match else 0.0)
234
+ final += c.benchmark_bonus if is_benchmarked else 0.0
235
+ return CandidateScore(
236
+ spec=spec,
237
+ final_score=final,
238
+ is_weak=is_weak,
239
+ is_rated=is_rated,
240
+ min_explicit_score=min_exp,
241
+ )