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/cli_doctor.py ADDED
@@ -0,0 +1,272 @@
1
+ """onechat doctor implementation: extracted so cli.py stays lean."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import shutil
6
+ import subprocess
7
+ import time
8
+ from collections.abc import Callable
9
+ from pathlib import Path
10
+ from typing import Any
11
+
12
+ from .scoring import detect_skills, score_candidate
13
+ from .sdk import AsfClient
14
+ from .selector import Need, order_candidates
15
+
16
+
17
+ def run_doctor(client: AsfClient, echo: Callable[[str], None]) -> None:
18
+ """CLIs + versions vs docs/compat.md, key envs present, DB writable."""
19
+ _print_cli_versions(client, echo)
20
+ _print_api_keys(client, echo)
21
+ _print_executors(client, echo)
22
+ _print_benchmark_overrides(client, echo)
23
+ echo(f"db: {client.config.db_path} (writable: {_probe_writable(client.config.db_path)})")
24
+ echo(f"compat.md: {_compat_md_path() or 'NOT FOUND'}")
25
+
26
+
27
+ def _print_benchmark_overrides(client: AsfClient, echo: Callable[[str], None]) -> None:
28
+ overrides = client.store.get_executor_overrides()
29
+ if not overrides:
30
+ return
31
+ echo("benchmark circuit overrides")
32
+ for eid, rec in sorted(overrides.items()):
33
+ status = rec.get("status", "unknown")
34
+ latency = f"{rec.get('latency_s'):.2f}s" if rec.get("latency_s") is not None else "?"
35
+ prio = rec.get("priority_override")
36
+ enabled = "enabled" if rec.get("enabled_override") == 1 else "circuited-out"
37
+ echo(f"{eid}: status={status} latency={latency} priority={prio} ({enabled})")
38
+
39
+
40
+ def _print_cli_versions(client: AsfClient, echo: Callable[[str], None]) -> None:
41
+ echo("CLI binaries")
42
+ for profile in client.config.profiles.values():
43
+ path = shutil.which(profile.binary)
44
+ version = ""
45
+ if path:
46
+ try:
47
+ out = subprocess.run(
48
+ [profile.binary, "--version"], capture_output=True, text=True, timeout=15
49
+ )
50
+ version = (out.stdout or out.stderr).strip().splitlines()[0][:40]
51
+ except Exception: # noqa: BLE001 - doctor must not crash on one CLI
52
+ version = "?"
53
+ echo(f"{profile.binary}: {'present' if path else 'MISSING'} {version}")
54
+
55
+
56
+ def _print_api_keys(client: AsfClient, echo: Callable[[str], None]) -> None:
57
+ import os
58
+
59
+ echo("api key envs")
60
+ for spec in client.config.executors:
61
+ if spec.kind == "api" and spec.api_key_env:
62
+ state = "set" if os.environ.get(spec.api_key_env) else "MISSING"
63
+ echo(f"{spec.api_key_env}: {state}")
64
+
65
+
66
+ def _print_executors(client: AsfClient, echo: Callable[[str], None]) -> None:
67
+ echo("executors")
68
+ for spec in client.config.executors:
69
+ executor = client.executors.get(spec.id)
70
+ cooldown = "yes" if _cooldown_active(client, spec.id) else "no"
71
+ echo(
72
+ f"{spec.id}: kind={spec.kind} tier={int(spec.tier)} "
73
+ f"available={executor.available() if executor else False} cooldown={cooldown}"
74
+ )
75
+
76
+
77
+ def _cooldown_active(client: AsfClient, executor_id: str) -> bool:
78
+ cd = client.store.get_cooldown(executor_id)
79
+ return cd is not None and cd["until_ts"] > time.time()
80
+
81
+
82
+ def _probe_writable(db_path: Path) -> bool:
83
+ try:
84
+ db_path.parent.mkdir(parents=True, exist_ok=True)
85
+ probe = db_path.with_suffix(".doctor-probe")
86
+ probe.write_text("", encoding="utf-8")
87
+ probe.unlink()
88
+ return True
89
+ except OSError:
90
+ return False
91
+
92
+
93
+ def _compat_md_path() -> Path | None:
94
+ for candidate in (Path.cwd() / "docs" / "compat.md", Path.cwd() / "compat.md"):
95
+ if candidate.exists():
96
+ return candidate
97
+ return None
98
+
99
+
100
+ def _score_cand(
101
+ s: Any, skills: tuple[str, ...], cfg: Any, roles: dict[str, str], role: str | None, scores: Any
102
+ ) -> Any:
103
+ target = roles.get(role) if role else None
104
+ is_role = target is not None and (
105
+ s.id == target or s.profile == target or s.model == target or s.family == target
106
+ )
107
+ return score_candidate(
108
+ s, skills, cfg, is_role_match=is_role, is_benchmarked=s.priority == 0, model_scores=scores
109
+ )
110
+
111
+
112
+ def _render_explain_text(
113
+ prompt: str,
114
+ skills: tuple[str, ...],
115
+ tier: Any,
116
+ cands: list[Any],
117
+ roles: dict[str, str],
118
+ role: str | None,
119
+ cfg: Any,
120
+ model_scores: dict[str, dict[str, float]],
121
+ echo: Callable[[str], None],
122
+ ) -> None:
123
+ echo(f"prompt: {prompt[:60]}...")
124
+ echo(f"detected skills: {', '.join(skills) if skills else '(none)'}")
125
+ echo(f"resolved tier: {tier.name} ({int(tier)})")
126
+ echo("candidate decision table:")
127
+ for idx, s in enumerate(cands, 1):
128
+ cs = _score_cand(s, skills, cfg, roles, role, model_scores)
129
+ st = "WEAK" if cs.is_weak else ("RATED" if cs.is_rated else "UNRATED")
130
+ echo(f" {idx}. {s.id} [{st}] score={cs.final_score:.1f} model={s.model} prio={s.priority}")
131
+
132
+
133
+ def print_executors_table(client: AsfClient, echo: Callable[[str], None]) -> None:
134
+ echo("id\tkind\ttier\tcost\tavailable\tcooldown\trequests today")
135
+ for spec in client.config.executors:
136
+ executor = client.executors.get(spec.id)
137
+ available = executor.available() if executor else False
138
+ cd = client.store.get_cooldown(spec.id)
139
+ active = cd is not None and cd["until_ts"] > time.time()
140
+ expiry = time.strftime("%H:%M:%S", time.localtime(cd["until_ts"])) if active else ""
141
+ cooldown = f"{expiry} ({cd.get('reason', 'quota')})" if active else "-"
142
+ echo(
143
+ f"{spec.id}\t{spec.kind}\t{int(spec.tier)}\t{spec.cost.value}\t"
144
+ f"{available}\t{cooldown}\t{client.store.usage_count(spec.id, time.time() - 86400)}"
145
+ )
146
+
147
+
148
+ def _explain_skills(
149
+ client: AsfClient, prompt: str, workdir: Path | None, explicit: list[str] | None
150
+ ) -> tuple[tuple[str, ...], Any]:
151
+ from .scoring import canonicalize_skill
152
+
153
+ cfg = client.config.skill_routing
154
+ if explicit:
155
+ sk = tuple(sorted({canonicalize_skill(s, cfg.aliases) for s in explicit if s.strip()}))
156
+ return sk, cfg
157
+ return (detect_skills(prompt=prompt, workdir=workdir, cfg=cfg) if cfg.auto_detect else ()), cfg
158
+
159
+
160
+ def export_session(
161
+ client: AsfClient, session_id: str, fmt: str, echo: Callable[[str], None]
162
+ ) -> None:
163
+ import json
164
+
165
+ turns = client.store.turns(session_id)
166
+ if fmt == "jsonl":
167
+ for turn in turns:
168
+ echo(json.dumps(turn, ensure_ascii=False))
169
+ return
170
+ for turn in turns:
171
+ echo(f"## [{turn['role']}] {turn['executor_id']}\n\n{turn['text']}\n")
172
+
173
+
174
+ def _explain_specs(client: AsfClient) -> tuple[list[Any], dict[str, str]]:
175
+ from .router_helpers import apply_executor_overrides
176
+
177
+ bench = getattr(client.config, "benchmark", None)
178
+ ttl = max(2 * getattr(bench, "interval_s", 1800.0), 3600.0) if bench else 3600.0
179
+ return apply_executor_overrides(
180
+ [e.spec for e in client.executors.values()],
181
+ client.config.roles,
182
+ client.store.get_executor_overrides(),
183
+ getattr(bench, "promote_roles", []) if bench else [],
184
+ benchmark_enabled=getattr(bench, "enabled", True) if bench else False,
185
+ ttl_s=ttl,
186
+ usable=client.router._usable,
187
+ )
188
+
189
+
190
+ def _resolve_explain_cands(
191
+ client: AsfClient,
192
+ prompt: str,
193
+ role: str | None,
194
+ tier_name: str,
195
+ workdir: Path | None,
196
+ explicit_skills: list[str] | None = None,
197
+ capability: str = "auto",
198
+ ) -> tuple[tuple[str, ...], Any, list[Any], dict[str, str], Any]:
199
+ from .contracts import Capability
200
+
201
+ skills, cfg = _explain_skills(client, prompt, workdir, explicit_skills)
202
+ auto_cap = "code" if role in ("builder", "code") else "chat"
203
+ cap = Capability((auto_cap if capability == "auto" else capability).lower())
204
+ need = Need(capability=cap, tier=tier_name, role=role, skills=skills)
205
+ tier = client.router._resolve_tier(need, prompt)
206
+ specs, roles = _explain_specs(client)
207
+ cands = order_candidates(
208
+ need,
209
+ tier,
210
+ specs,
211
+ client.router._usable,
212
+ client.config.tier_policy,
213
+ roles=roles,
214
+ skill_cfg=cfg,
215
+ model_scores=client.config.model_scores,
216
+ )
217
+ return skills, tier, cands, roles, cfg
218
+
219
+
220
+ def _render_explain_json(
221
+ prompt: str,
222
+ skills: tuple[str, ...],
223
+ tier: Any,
224
+ cands: list[Any],
225
+ roles: dict[str, str],
226
+ role: str | None,
227
+ cfg: Any,
228
+ scores: Any,
229
+ echo: Callable[[str], None],
230
+ ) -> None:
231
+ import json
232
+
233
+ cand_list = []
234
+ for s in cands:
235
+ cs = _score_cand(s, skills, cfg, roles, role, scores)
236
+ cand_list.append(
237
+ {
238
+ "id": s.id,
239
+ "model": s.model,
240
+ "model_key": s.model_key,
241
+ "tier": int(s.tier),
242
+ "priority": s.priority,
243
+ "score": cs.final_score,
244
+ "weak": cs.is_weak,
245
+ "rated": cs.is_rated,
246
+ }
247
+ )
248
+ echo(
249
+ json.dumps(
250
+ {"prompt": prompt, "skills": list(skills), "tier": int(tier), "candidates": cand_list},
251
+ indent=2,
252
+ )
253
+ )
254
+
255
+
256
+ def explain_routing(
257
+ client: AsfClient,
258
+ prompt: str,
259
+ role: str | None,
260
+ tier_name: str,
261
+ workdir: Path | None,
262
+ json_output: bool,
263
+ echo: Callable[[str], None],
264
+ explicit_skills: list[str] | None = None,
265
+ capability: str = "auto",
266
+ ) -> None:
267
+ skills, tier, cands, roles, cfg = _resolve_explain_cands(
268
+ client, prompt, role, tier_name, workdir, explicit_skills, capability
269
+ )
270
+ scores = client.config.model_scores
271
+ render = _render_explain_json if json_output else _render_explain_text
272
+ render(prompt, skills, tier, cands, roles, role, cfg, scores, echo)
onechat/cli_repl.py ADDED
@@ -0,0 +1,116 @@
1
+ """onechat CLI REPL helpers: extracted from cli.py to maintain LOC budget."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from pathlib import Path
6
+ from typing import Any
7
+
8
+ import typer
9
+
10
+ from .contracts import Tier
11
+ from .router import NoExecutorAvailable, SessionBusy
12
+ from .sdk import _UNSET, AsfClient
13
+ from .selector import coerce_tier
14
+
15
+ SLASH_COMMANDS = ("/tier", "/use", "/auto", "/status", "/new", "/sessions", "/help", "/exit")
16
+
17
+
18
+ def slash_command(
19
+ client: AsfClient,
20
+ sess: Any,
21
+ prompt: str,
22
+ current_tier: str | Tier,
23
+ current_executor: str | None,
24
+ last_executor: str | None,
25
+ workdir: Path,
26
+ ) -> tuple[str, str | Tier, str | None, Any, str | None, bool]:
27
+ """Handle one REPL slash command. Returns (command, tier, executor, session, last, done)."""
28
+ command, _, argument = prompt.partition(" ")
29
+ if command == "/exit":
30
+ return command, current_tier, current_executor, sess, last_executor, True
31
+ if command == "/tier":
32
+ current_tier = argument or "auto"
33
+ typer.echo(f"tier: {current_tier}")
34
+ elif command == "/use":
35
+ current_executor = argument or None
36
+ typer.echo(f"executor: {current_executor or '(auto)'}")
37
+ elif command == "/auto":
38
+ current_tier, current_executor = "auto", None
39
+ typer.echo("mode: auto")
40
+ if command == "/new":
41
+ sess = client.session(workdir=str(workdir))
42
+ typer.echo(f"new session: {sess.id}")
43
+ elif command == "/sessions":
44
+ for row in client.store.list_sessions()[:10]:
45
+ typer.echo(f" {row['id']} {row.get('title') or ''}")
46
+ elif command == "/help":
47
+ typer.echo(" ".join(SLASH_COMMANDS))
48
+ elif command == "/status":
49
+ typer.echo(
50
+ f"session: {sess.id} tier: {current_tier} "
51
+ f"executor: {current_executor or '(auto)'} last: {last_executor or '(none)'}"
52
+ )
53
+ return command, current_tier, current_executor, sess, last_executor, False
54
+
55
+
56
+ def handle_slash(
57
+ client: AsfClient,
58
+ sess: Any,
59
+ prompt: str,
60
+ tier: str | Tier,
61
+ exec_id: str | None,
62
+ last: str | None,
63
+ workdir: Path,
64
+ ) -> tuple[str | Tier, str | None, Any, str | None, bool]:
65
+ cmd, tier, exec_id, sess, last, done = slash_command(
66
+ client, sess, prompt, tier, exec_id, last, workdir
67
+ )
68
+ if cmd in ("/tier", "/use", "/auto"):
69
+ try:
70
+ tier_val = coerce_tier(tier) if isinstance(tier, str) else tier
71
+ sess.pin(
72
+ executor=exec_id if cmd != "/tier" else _UNSET,
73
+ tier=tier_val if cmd != "/use" else _UNSET,
74
+ )
75
+ except ValueError as exc:
76
+ typer.echo(f"[error] {exc}")
77
+ return tier, exec_id, sess, last, done
78
+
79
+
80
+ def run_chat_turn(
81
+ sess: Any,
82
+ prompt: str,
83
+ current_tier: str | Tier,
84
+ current_executor: str | None,
85
+ capability: str,
86
+ last_executor: str | None,
87
+ ) -> str | None:
88
+ streamed = False
89
+
90
+ def on_event(event: Any) -> None:
91
+ nonlocal streamed
92
+ if event.kind == "text":
93
+ streamed = True
94
+ typer.echo(event.text, nl=False)
95
+ else:
96
+ typer.echo(f"\n{event.text}")
97
+
98
+ try:
99
+ reply: Any = sess.ask_sync(
100
+ prompt,
101
+ tier=current_tier,
102
+ executor=current_executor,
103
+ capability=capability,
104
+ on_event=on_event,
105
+ )
106
+ except (NoExecutorAvailable, SessionBusy, ValueError) as exc:
107
+ typer.echo(f"[error] {exc}")
108
+ return last_executor
109
+ if streamed:
110
+ typer.echo()
111
+ typer.echo(f"{reply.executor_id} {reply.stop.value}")
112
+ else:
113
+ switched = f" (switched: {', '.join(reply.switched_from)})" if reply.switched_from else ""
114
+ typer.echo(f"{reply.executor_id} {reply.stop.value}{switched}")
115
+ typer.echo(reply.text)
116
+ return str(reply.executor_id)
onechat/config.py ADDED
@@ -0,0 +1,311 @@
1
+ """Config loading (Plan 02 §3-4): defaults.yaml + user overrides, CLI profile registry.
2
+
3
+ User config resolution (T03): explicit user_path wins; else $ASF_CONFIG; else
4
+ ~/.asf/config.yaml when present. Nested sections (tier_policy/handoff/cooldown) deep-merge;
5
+ scalar keys: user wins; executors merge by id.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import os
11
+ from pathlib import Path
12
+ from typing import Literal
13
+
14
+ import yaml
15
+ from pydantic import BaseModel, Field, model_validator
16
+
17
+ from .contracts import Capability, CostClass, ExecutorSpec, Tier
18
+ from .scoring import SkillRoutingConfig
19
+
20
+ _PACKAGE_DIR = Path(__file__).resolve().parent
21
+
22
+
23
+ class CliProfile(BaseModel):
24
+ """How to drive one CLI family headlessly (template rules in Plan 02 §4)."""
25
+
26
+ name: str
27
+ binary: str
28
+ new: list[str]
29
+ resume: list[str]
30
+ auto: list[str] = Field(default_factory=list)
31
+ prompt_via: Literal["argv", "stdin"] = "argv"
32
+ parser: str
33
+ quota_patterns: list[str] = Field(default_factory=list)
34
+ auth_patterns: list[str] = Field(default_factory=list)
35
+ unavailable_patterns: list[str] = Field(default_factory=list)
36
+ share_cooldown: bool = False
37
+
38
+
39
+ class HandoffConfig(BaseModel):
40
+ recent_turns: int = 6
41
+ turn_max_chars: int = 4000
42
+ brief_max_chars: int = 24000
43
+ compact_threshold_chars: int = 30000
44
+
45
+
46
+ class TierPolicy(BaseModel):
47
+ by_task_kind: dict[str, Tier] = Field(
48
+ default_factory=lambda: {
49
+ "summarize": Tier.LOW,
50
+ "research": Tier.LOW,
51
+ "digest": Tier.MEDIUM,
52
+ "fix": Tier.MEDIUM,
53
+ "test": Tier.MEDIUM,
54
+ "code": Tier.MEDIUM,
55
+ "plan": Tier.HIGH,
56
+ "spec": Tier.HIGH,
57
+ "review": Tier.HIGH,
58
+ }
59
+ )
60
+ chat_default: Tier = Tier.MEDIUM
61
+ high_keywords: list[str] = Field(
62
+ default_factory=lambda: [
63
+ "architecture",
64
+ "design",
65
+ "security",
66
+ "race condition",
67
+ "migration",
68
+ "root cause",
69
+ ]
70
+ )
71
+ escalate_every: int = 2
72
+ cost_order: list[CostClass] = Field(
73
+ default_factory=lambda: [CostClass.FREE, CostClass.SUBSCRIPTION, CostClass.PAID]
74
+ )
75
+ allow_paid: bool = False
76
+ min_tier: Tier = Tier.LOW
77
+ max_tier: Tier = Tier.MAX
78
+
79
+
80
+ class CooldownPolicy(BaseModel):
81
+ """Cooldown policy: immediate multi-hour failure caching + optional K1 rate gate."""
82
+
83
+ min_requests: int = Field(default=1, ge=1)
84
+ failure_rate: float = Field(default=0.5, ge=0.0, le=1.0)
85
+ window_s: int = Field(default=60, ge=1)
86
+ quota_cooldown_s: int = Field(default=7200, ge=0)
87
+ timeout_cooldown_s: int = Field(default=7200, ge=0)
88
+ error_cooldown_s: int = Field(default=14400, ge=0)
89
+ auth_cooldown_s: int = Field(default=86400, ge=0)
90
+ backoff_strikes: list[int] = Field(default_factory=lambda: [7200, 14400, 28800, 86400])
91
+ share_profile_cooldown: bool = True
92
+
93
+
94
+ class BenchmarkTarget(BaseModel):
95
+ executor_id: str
96
+ model: str
97
+ promoted_priority: int = 0
98
+
99
+
100
+ class BenchmarkConfig(BaseModel):
101
+ enabled: bool = True
102
+ endpoint: str = "http://127.0.0.1:8789"
103
+ interval_s: int = 1800
104
+ max_latency_s: float = 15.0
105
+ timeout_s: float = 20.0
106
+ promote_roles: list[str] = Field(default_factory=lambda: ["builder", "code"])
107
+ selection_mode: Literal["order", "fastest"] = "order"
108
+ targets: list[BenchmarkTarget] = Field(default_factory=list)
109
+
110
+
111
+ class RouterConfig(BaseModel):
112
+ db_path: Path
113
+ executors: list[ExecutorSpec] = Field(default_factory=list)
114
+ profiles: dict[str, CliProfile] = Field(default_factory=dict)
115
+ handoff: HandoffConfig = Field(default_factory=HandoffConfig)
116
+ tier_policy: TierPolicy = Field(default_factory=TierPolicy)
117
+ cooldown: CooldownPolicy = Field(default_factory=CooldownPolicy)
118
+ benchmark: BenchmarkConfig = Field(default_factory=BenchmarkConfig)
119
+ skill_routing: SkillRoutingConfig = Field(default_factory=SkillRoutingConfig)
120
+ model_scores: dict[str, dict[str, float]] = Field(default_factory=dict)
121
+ roles: dict[str, str] = Field(
122
+ default_factory=lambda: {
123
+ "builder": "codex",
124
+ "reviewer": "agy",
125
+ "auditor": "workbuddy",
126
+ }
127
+ )
128
+ turn_timeout_s: int = Field(default=600, ge=1)
129
+ inactivity_timeout_s: int = Field(default=180, ge=0)
130
+
131
+ @model_validator(mode="after")
132
+ def _profiles_must_exist(self) -> RouterConfig:
133
+ for spec in self.executors:
134
+ if spec.kind == "cli" and spec.profile not in self.profiles:
135
+ raise ValueError(
136
+ f"executor {spec.id!r} references unknown profile {spec.profile!r}"
137
+ )
138
+ return self
139
+
140
+
141
+ def _read_yaml(path: Path) -> dict:
142
+ with path.open(encoding="utf-8") as fh:
143
+ data = yaml.safe_load(fh) or {}
144
+ if not isinstance(data, dict):
145
+ raise ValueError(f"{path} must contain a mapping")
146
+ return data
147
+
148
+
149
+ def _deep_merge(base: dict, override: dict) -> dict:
150
+ """Nested dicts merge recursively; scalars and lists: override wins (T03)."""
151
+ out = dict(base)
152
+ for key, value in override.items():
153
+ if isinstance(value, dict) and isinstance(out.get(key), dict):
154
+ out[key] = _deep_merge(out[key], value)
155
+ else:
156
+ out[key] = value
157
+ return out
158
+
159
+
160
+ def _load_package_profiles() -> dict[str, CliProfile]:
161
+ profiles: dict[str, CliProfile] = {}
162
+ for path in sorted((_PACKAGE_DIR / "profiles").glob("*.yaml")):
163
+ profile = CliProfile(**_read_yaml(path))
164
+ profiles[profile.name] = profile
165
+ return profiles
166
+
167
+
168
+ def _validate_parsers(profiles: dict[str, CliProfile]) -> None:
169
+ from .executors.parsers import PARSERS # deferred: executors import config back
170
+
171
+ for profile in profiles.values():
172
+ if profile.parser not in PARSERS:
173
+ raise ValueError(
174
+ f"profile {profile.name!r}: unknown parser {profile.parser!r} "
175
+ f"(known: {sorted(PARSERS)})"
176
+ )
177
+
178
+
179
+ def _merge_executors(defaults: list[ExecutorSpec], user: list[ExecutorSpec]) -> list[ExecutorSpec]:
180
+ user_by_id = {spec.id: spec for spec in user}
181
+ merged = [user_by_id.get(spec.id, spec) for spec in defaults]
182
+ seen = {spec.id for spec in defaults}
183
+ merged += [spec for spec in user if spec.id not in seen]
184
+ return merged
185
+
186
+
187
+ def _reject_duplicate_ids(specs: list[ExecutorSpec], source: Path) -> None:
188
+ seen: set[str] = set()
189
+ for spec in specs:
190
+ if spec.id in seen:
191
+ raise ValueError(f"duplicate executor id {spec.id!r} in {source}")
192
+ seen.add(spec.id)
193
+
194
+
195
+ def _expand_tilde(value: str, home: Path) -> str:
196
+ """Expand only a LEADING ~ (T03): 'HEAD~1' is data, '~/acc' is a home path."""
197
+ if value == "~":
198
+ return str(home)
199
+ if value.startswith("~/"):
200
+ return str(home) + value[1:]
201
+ return value
202
+
203
+
204
+ def _expand_env(spec: ExecutorSpec, home: Path) -> ExecutorSpec:
205
+ data = spec.model_dump()
206
+ data["env"] = {k: _expand_tilde(v, home) for k, v in spec.env.items()}
207
+ data["capabilities"] = sorted(c.value for c in spec.capabilities)
208
+ return ExecutorSpec(**data)
209
+
210
+
211
+ def _build_specs(raw: list[dict], home: Path) -> list[ExecutorSpec]:
212
+ specs = [
213
+ ExecutorSpec(
214
+ **{
215
+ **spec,
216
+ "tier": Tier(spec["tier"]),
217
+ "cost": CostClass(spec["cost"]),
218
+ "capabilities": frozenset(Capability(c) for c in spec.get("capabilities", [])),
219
+ }
220
+ )
221
+ for spec in raw
222
+ ]
223
+ return [_expand_env(spec, home) for spec in specs]
224
+
225
+
226
+ def _user_config_path(user_path: Path | None, home: Path) -> Path | None:
227
+ """Explicit path wins; else $ONECHAT_CONFIG; else $ASF_CONFIG; else config.yaml."""
228
+ if user_path is not None:
229
+ return user_path
230
+ for env_var in ("ONECHAT_CONFIG", "ASF_CONFIG"):
231
+ env = os.environ.get(env_var)
232
+ if env:
233
+ return Path(env)
234
+ for folder in (".onechat", ".asf"):
235
+ default = home / folder / "config.yaml"
236
+ if default.exists():
237
+ return default
238
+ return None
239
+
240
+
241
+ def _load_env_file(path: Path) -> None:
242
+ if not path.is_file():
243
+ return
244
+ import re
245
+
246
+ for line in path.read_text(encoding="utf-8").splitlines():
247
+ line = line.strip()
248
+ if not line or line.startswith("#"):
249
+ continue
250
+ if line.startswith("export "):
251
+ line = line[7:].strip()
252
+ match = re.match(r"^([A-Za-z_0-9]+)=(.*)$", line)
253
+ if match:
254
+ k, v = match.group(1), match.group(2).strip("\"'")
255
+ if k not in os.environ:
256
+ os.environ[k] = v
257
+
258
+
259
+ def _load_all_profiles(home: Path) -> dict[str, CliProfile]:
260
+ profiles = _load_package_profiles()
261
+ for folder in (".asf", ".onechat"):
262
+ for path in sorted((home / folder / "profiles").glob("*.yaml")):
263
+ profile = CliProfile(**_read_yaml(path))
264
+ profiles[profile.name] = profile
265
+ _validate_parsers(profiles)
266
+ return profiles
267
+
268
+
269
+ def load_config(
270
+ user_path: Path | None = None, home: Path | None = None, defaults_path: Path | None = None
271
+ ) -> RouterConfig:
272
+ """Merge package defaults.yaml with user config; user executors win by id."""
273
+ home = home or Path.home()
274
+ for folder in (".onechat", ".asf"):
275
+ _load_env_file(home / folder / "env")
276
+ defaults_file = defaults_path or (_PACKAGE_DIR / "defaults.yaml")
277
+ defaults_data = _read_yaml(defaults_file)
278
+ user_file = _user_config_path(user_path, home)
279
+ user_data: dict = _read_yaml(user_file) if user_file is not None else {}
280
+ data = _deep_merge(defaults_data, user_data)
281
+ if (
282
+ "db_path" not in user_data
283
+ and (home / ".asf" / "asf.db").exists()
284
+ and not (home / ".onechat" / "onechat.db").exists()
285
+ ):
286
+ data["db_path"] = "~/.asf/asf.db"
287
+ data["db_path"] = _expand_tilde(str(data.get("db_path", "~/.onechat/onechat.db")), home)
288
+ default_specs = _build_specs(defaults_data.get("executors", []), home)
289
+ _reject_duplicate_ids(default_specs, defaults_file)
290
+ if "executors" in user_data: # Plan 02 §3: executors merge by id, not replace
291
+ user_specs = _build_specs(user_data["executors"], home)
292
+ _reject_duplicate_ids(user_specs, user_file or Path("<auto>"))
293
+ executors = _merge_executors(default_specs, user_specs)
294
+ else:
295
+ executors = default_specs
296
+ return RouterConfig(
297
+ db_path=Path(data["db_path"]),
298
+ executors=executors,
299
+ profiles=_load_all_profiles(home),
300
+ handoff=HandoffConfig(**(data.get("handoff") or {})),
301
+ tier_policy=TierPolicy(**(data.get("tier_policy") or {})),
302
+ cooldown=CooldownPolicy(**(data.get("cooldown") or {})),
303
+ benchmark=BenchmarkConfig(**(data.get("benchmark") or {})),
304
+ skill_routing=SkillRoutingConfig(**(data.get("skill_routing") or {})),
305
+ model_scores=dict(data.get("model_scores") or {}),
306
+ roles=dict(
307
+ data.get("roles") or {"builder": "codex", "reviewer": "agy", "auditor": "workbuddy"}
308
+ ),
309
+ turn_timeout_s=int(data.get("turn_timeout_s", 600)),
310
+ inactivity_timeout_s=int(data.get("inactivity_timeout_s", 180)),
311
+ )