agent7 0.1.0__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.
agent7/agent.py ADDED
@@ -0,0 +1,398 @@
1
+ """Async agent loop and tools: read, write, bash, grep (+ compact)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import asyncio
6
+ import difflib
7
+ import json
8
+ import os
9
+ import shutil
10
+ import subprocess
11
+ import sys
12
+ from collections.abc import Callable
13
+ from contextlib import suppress
14
+ from pathlib import Path
15
+ from typing import Any
16
+
17
+ from openai import AsyncOpenAI
18
+
19
+ MAX_READ_CHARS, MAX_BASH_CHARS, MAX_GREP_CHARS = 50_000, 12_000, 12_000
20
+ DEFAULT_READ_LINES, MAX_GREP_LINES, MAX_TURNS = 200, 100, 30
21
+ COMPACT_THRESHOLD, KEEP_USER_TURNS, KEEP_TOOL_RESULTS = 0.75, 3, 4
22
+ TOOL_MAX_CHARS, ASSISTANT_MAX_CHARS = 2_000, 4_000
23
+ class Interrupted(Exception):
24
+ def __init__(self, partial: str = "") -> None:
25
+ self.partial = partial
26
+ super().__init__(partial)
27
+
28
+ SYSTEM = (
29
+ "You are a coding agent. Tools: read, write, bash, grep. "
30
+ "Explore before editing; read pages ~200 lines (offset/limit). "
31
+ "Prefer write(old_string=...) for small edits. Finish with a short summary."
32
+ )
33
+
34
+ def _fn(name: str, desc: str, props: dict, required: list[str]) -> dict:
35
+ return {
36
+ "type": "function",
37
+ "function": {
38
+ "name": name,
39
+ "description": desc,
40
+ "parameters": {"type": "object", "properties": props, "required": required},
41
+ },
42
+ }
43
+
44
+ TOOLS: list[dict[str, Any]] = [
45
+ _fn("read", "Read text file (numbered). Default 200 lines; page with offset/limit.",
46
+ {"path": {"type": "string"}, "offset": {"type": "integer"}, "limit": {"type": "integer"}},
47
+ ["path"]),
48
+ _fn("write", "Write file, or replace one unique span via old_string.",
49
+ {"path": {"type": "string"}, "content": {"type": "string"},
50
+ "old_string": {"type": "string"}}, ["path", "content"]),
51
+ _fn("bash", "Shell in cwd. Output capped ~12k chars.",
52
+ {"command": {"type": "string"}, "timeout": {"type": "integer"}}, ["command"]),
53
+ _fn("grep", "rg/grep search. Capped at 100 lines.",
54
+ {"pattern": {"type": "string"}, "path": {"type": "string"}, "glob": {"type": "string"}},
55
+ ["pattern"]),
56
+ ]
57
+
58
+ def _truncate(s: str, limit: int, *, tag: str = "truncated") -> str:
59
+ return s if len(s) <= limit else s[:limit] + f"\n...[{tag} {len(s) - limit} chars]"
60
+
61
+ def _resolve(cwd: Path, path: str) -> Path:
62
+ p = Path(path.removeprefix("@").replace("\\ ", " ")) # tolerate `@path` typed in the REPL
63
+ return p if p.is_absolute() else cwd / p
64
+
65
+ def tool_read(cwd: Path, path: str, offset: int | None = None, limit: int | None = None) -> str:
66
+ fp = _resolve(cwd, path)
67
+ if not fp.is_file():
68
+ return f"error: not a file: {fp}"
69
+ try:
70
+ lines = fp.read_text(encoding="utf-8").splitlines()
71
+ except UnicodeDecodeError:
72
+ return f"error: binary or non-utf8: {fp}"
73
+ total = len(lines)
74
+ start = min(max(0, (offset or 1) - 1), total) if offset is not None else 0
75
+ want = limit if limit is not None and limit > 0 else DEFAULT_READ_LINES
76
+ end = min(total, start + want)
77
+ body = "\n".join(f"{i + start + 1}|{line}" for i, line in enumerate(lines[start:end])) or "(empty)"
78
+ body = _truncate(body, MAX_READ_CHARS)
79
+ if start > 0 or end < total:
80
+ hint = f"...[lines {start + 1}-{end} of {total}"
81
+ if end < total:
82
+ hint += f"; continue with offset={end + 1}"
83
+ body = f"{body}\n{hint}]"
84
+ return body
85
+
86
+ def _write_stats(fp: Path, before: str, after: str) -> str:
87
+ a, b = before.splitlines(), after.splitlines()
88
+ add = delete = 0
89
+ for tag, i1, i2, j1, j2 in difflib.SequenceMatcher(a=a, b=b).get_opcodes():
90
+ if tag == "insert":
91
+ add += j2 - j1
92
+ elif tag == "delete":
93
+ delete += i2 - i1
94
+ elif tag == "replace":
95
+ delete += i2 - i1
96
+ add += j2 - j1
97
+ return f"{fp} +{add} -{delete}"
98
+
99
+ def tool_write(
100
+ cwd: Path,
101
+ path: str,
102
+ content: str,
103
+ old_string: str | None = None,
104
+ on_preview: Callable[[str], None] | None = None,
105
+ ) -> str:
106
+ fp = _resolve(cwd, path)
107
+ try:
108
+ before = fp.read_text(encoding="utf-8") if fp.exists() else ""
109
+ except UnicodeDecodeError:
110
+ return f"error: binary or non-utf8: {fp}"
111
+ if old_string is not None:
112
+ if not fp.is_file():
113
+ return f"error: not a file: {fp}"
114
+ if not old_string:
115
+ return "error: old_string must not be empty"
116
+ n = before.count(old_string)
117
+ if n != 1:
118
+ return f"error: old_string occurs {n} times in {fp}; expected exactly 1"
119
+ after = before.replace(old_string, content, 1)
120
+ else:
121
+ after = content
122
+ if before == after and fp.is_file():
123
+ return f"no changes: {fp}"
124
+ if on_preview:
125
+ on_preview(_write_stats(fp, before, after))
126
+ fp.parent.mkdir(parents=True, exist_ok=True)
127
+ fp.write_text(after, encoding="utf-8")
128
+ return f"wrote {len(after.encode('utf-8'))} bytes to {fp}"
129
+
130
+ def tool_bash(cwd: Path, command: str, timeout: int | None = None) -> str:
131
+ env = os.environ.copy()
132
+ env.setdefault("PYTHONIOENCODING", "utf-8")
133
+ env.setdefault("LANG", "C.UTF-8")
134
+ env.setdefault("LC_ALL", "C.UTF-8")
135
+ try:
136
+ proc = subprocess.run(
137
+ command, shell=True, cwd=cwd, capture_output=True,
138
+ encoding="utf-8", errors="replace", timeout=timeout or 60, env=env,
139
+ )
140
+ except subprocess.TimeoutExpired as e:
141
+ return _truncate(
142
+ f"timeout after {timeout or 60}s\n{(e.stdout or '')}{(e.stderr or '')}", MAX_BASH_CHARS
143
+ )
144
+ parts = [f"exit={proc.returncode}"]
145
+ if proc.stdout:
146
+ parts.append("stdout:\n" + proc.stdout)
147
+ if proc.stderr:
148
+ parts.append("stderr:\n" + proc.stderr)
149
+ return _truncate("\n".join(parts), MAX_BASH_CHARS)
150
+
151
+ def tool_grep(cwd: Path, pattern: str, path: str | None = None, glob: str | None = None) -> str:
152
+ target = str(_resolve(cwd, path) if path else cwd)
153
+ if shutil.which("rg"):
154
+ cmd = ["rg", "--line-number", "--no-heading", "--color", "never", pattern, target]
155
+ if glob:
156
+ cmd[1:1] = ["--glob", glob]
157
+ else:
158
+ cmd = ["grep", "-RIn", f"--include={glob}", "--", pattern, target] if glob else [
159
+ "grep", "-RIn", "--", pattern, target
160
+ ]
161
+ try:
162
+ proc = subprocess.run(cmd, capture_output=True, encoding="utf-8", errors="replace", timeout=30)
163
+ except subprocess.TimeoutExpired:
164
+ return "error: grep timed out"
165
+ except FileNotFoundError:
166
+ return "error: neither rg nor grep available"
167
+ out = proc.stdout or ""
168
+ if proc.returncode not in (0, 1) and not out:
169
+ return _truncate(proc.stderr or f"grep failed exit={proc.returncode}", MAX_GREP_CHARS)
170
+ lines = out.splitlines()
171
+ if len(lines) > MAX_GREP_LINES:
172
+ out = "\n".join(lines[:MAX_GREP_LINES]) + f"\n...[{len(lines) - MAX_GREP_LINES} more]"
173
+ return _truncate(out or "(no matches)", MAX_GREP_CHARS)
174
+
175
+ HANDLERS = {"read": tool_read, "write": tool_write, "bash": tool_bash, "grep": tool_grep}
176
+
177
+ def dispatch_tool(
178
+ cwd: Path, name: str, args: dict[str, Any], *, on_preview: Callable[[str], None] | None = None
179
+ ) -> str:
180
+ fn = HANDLERS.get(name)
181
+ if not fn:
182
+ return f"error: unknown tool {name}"
183
+ try:
184
+ return tool_write(cwd, **args, on_preview=on_preview) if name == "write" else fn(cwd, **args)
185
+ except TypeError as e:
186
+ return f"error: bad args for {name}: {e}"
187
+ except Exception as e: # noqa: BLE001
188
+ return f"error: {type(e).__name__}: {e}"
189
+
190
+ def _trunc(s: str, n: int = 88) -> str:
191
+ s = " ".join(s.split())
192
+ return s if len(s) <= n else s[: n - 1] + "…"
193
+
194
+ def tool_summary(name: str, args: dict[str, Any]) -> str:
195
+ if name == "bash":
196
+ return _trunc(str(args.get("command") or ""))
197
+ if name == "read":
198
+ path = str(args.get("path") or "")
199
+ off, lim = args.get("offset"), args.get("limit")
200
+ return f"{path} (offset={off} limit={lim})" if off is not None or lim is not None else path
201
+ if name == "write":
202
+ action = "replace" if args.get("old_string") is not None else "write"
203
+ return f"{args.get('path', '')} ({action}, {len(str(args.get('content') or ''))} chars)"
204
+ if name == "grep":
205
+ bits = [repr(args.get("pattern") or ""), "in", str(args.get("path") or ".")]
206
+ if args.get("glob"):
207
+ bits.append(str(args["glob"]))
208
+ return _trunc(" ".join(bits))
209
+ return _trunc(json.dumps(args, ensure_ascii=False))
210
+
211
+ def should_compact(
212
+ prompt_tokens: int | None, context_limit: int | None, *, threshold: float = COMPACT_THRESHOLD
213
+ ) -> bool:
214
+ if prompt_tokens is None or context_limit is None or context_limit <= 0:
215
+ return False
216
+ return prompt_tokens >= int(context_limit * threshold)
217
+
218
+ def compact_messages(
219
+ messages: list[dict[str, Any]],
220
+ *,
221
+ keep_user_turns: int = KEEP_USER_TURNS,
222
+ keep_tool_results: int = KEEP_TOOL_RESULTS,
223
+ tool_max_chars: int = TOOL_MAX_CHARS,
224
+ assistant_max_chars: int = ASSISTANT_MAX_CHARS,
225
+ ) -> tuple[list[dict[str, Any]], int]:
226
+ if not messages:
227
+ return messages, 0
228
+ head, rest = ([], messages)
229
+ if messages[0].get("role") == "system":
230
+ head, rest = [messages[0]], messages[1:]
231
+ user_idxs = [i for i, m in enumerate(rest) if m.get("role") == "user"]
232
+ keep_from = user_idxs[-keep_user_turns] if len(user_idxs) >= keep_user_turns else 0
233
+ tool_idxs = [i for i, m in enumerate(rest) if m.get("role") == "tool"]
234
+ old_tool_before = keep_from or len(rest)
235
+ if keep_from == 0 and tool_idxs:
236
+ old_tool_before = (
237
+ len(rest) if keep_tool_results <= 0
238
+ else tool_idxs[max(0, len(tool_idxs) - keep_tool_results)]
239
+ )
240
+ out, changed = list(head), 0
241
+ for i, m in enumerate(rest):
242
+ role, content = m.get("role"), m.get("content")
243
+ if role == "tool" and i < old_tool_before and isinstance(content, str) and len(content) > tool_max_chars:
244
+ out.append({**m, "content": _truncate(content, tool_max_chars, tag="compacted")})
245
+ changed += 1
246
+ elif (
247
+ role == "assistant" and i < keep_from and isinstance(content, str)
248
+ and len(content) > assistant_max_chars and not m.get("tool_calls")
249
+ ):
250
+ out.append({**m, "content": _truncate(content, assistant_max_chars, tag="compacted")})
251
+ changed += 1
252
+ else:
253
+ out.append(m)
254
+ return out, changed
255
+
256
+ async def _emit(cb: Callable[..., Any] | None, *args: Any) -> None:
257
+ if cb and asyncio.iscoroutine(maybe := cb(*args)):
258
+ await maybe
259
+
260
+ def _delta_reasoning(delta: Any) -> str | None:
261
+ if text := getattr(delta, "reasoning_content", None):
262
+ return text
263
+ extra = getattr(delta, "model_extra", None) or {}
264
+ return str(extra["reasoning_content"]) if isinstance(extra, dict) and extra.get("reasoning_content") else None
265
+
266
+ def _usage_from_chunk(chunk: Any) -> dict[str, int] | None:
267
+ usage = getattr(chunk, "usage", None)
268
+ if not usage:
269
+ return None
270
+ out = {k: int(v) for k in ("prompt_tokens", "completion_tokens", "total_tokens")
271
+ if (v := getattr(usage, k, None)) is not None}
272
+ return out or None
273
+
274
+ async def _stream_completion(
275
+ client: AsyncOpenAI, *, model: str, messages: list[dict[str, Any]],
276
+ on_delta, on_thinking, on_answer_to_thinking, on_finish=None,
277
+ ) -> tuple[str, list[dict[str, Any]], dict[str, int] | None]:
278
+ kwargs: dict[str, Any] = {
279
+ "model": model, "messages": messages, "tools": TOOLS, "stream": True,
280
+ "stream_options": {"include_usage": True},
281
+ }
282
+ try:
283
+ stream = await client.chat.completions.create(**kwargs)
284
+ except Interrupted:
285
+ raise
286
+ except (asyncio.CancelledError, KeyboardInterrupt) as e:
287
+ raise Interrupted() from e
288
+ except Exception:
289
+ kwargs.pop("stream_options", None)
290
+ try:
291
+ stream = await client.chat.completions.create(**kwargs)
292
+ except (asyncio.CancelledError, KeyboardInterrupt) as e:
293
+ raise Interrupted() from e
294
+ parts: list[str] = []
295
+ tool_acc: dict[int, dict[str, str]] = {}
296
+ saw_tools, usage = False, None
297
+ try:
298
+ async for chunk in stream:
299
+ if u := _usage_from_chunk(chunk):
300
+ usage = u
301
+ if not chunk.choices:
302
+ continue
303
+ if finish := getattr(chunk.choices[0], "finish_reason", None):
304
+ await _emit(on_finish, finish) # "stop" | "length" | "tool_calls" | ...
305
+ delta = chunk.choices[0].delta
306
+ if r := _delta_reasoning(delta):
307
+ await _emit(on_thinking, r)
308
+ if delta.tool_calls:
309
+ if not saw_tools:
310
+ saw_tools = True
311
+ await _emit(on_answer_to_thinking)
312
+ for tc in delta.tool_calls:
313
+ slot = tool_acc.setdefault(tc.index, {"id": "", "name": "", "arguments": ""})
314
+ if tc.id:
315
+ slot["id"] = tc.id
316
+ if tc.function:
317
+ if tc.function.name:
318
+ slot["name"] = tc.function.name
319
+ if tc.function.arguments:
320
+ slot["arguments"] += tc.function.arguments
321
+ if delta.content:
322
+ parts.append(delta.content)
323
+ await _emit(on_thinking if saw_tools else on_delta, delta.content)
324
+ except (asyncio.CancelledError, KeyboardInterrupt) as e:
325
+ raise Interrupted("".join(parts)) from e
326
+ finally:
327
+ if close := getattr(stream, "close", None):
328
+ with suppress(Exception):
329
+ result = close()
330
+ if asyncio.iscoroutine(result):
331
+ await result
332
+ return "".join(parts), [
333
+ {"id": tool_acc[i]["id"], "type": "function",
334
+ "function": {"name": tool_acc[i]["name"], "arguments": tool_acc[i]["arguments"] or "{}"}}
335
+ for i in sorted(tool_acc)
336
+ ], usage
337
+
338
+ async def run_agent(
339
+ task: str, *, cwd: Path, client: AsyncOpenAI, model: str, max_turns: int = MAX_TURNS,
340
+ messages: list[dict[str, Any]], on_delta=None, on_thinking=None, on_answer_to_thinking=None,
341
+ on_tool=None, on_preview=None, on_usage=None, context_limit: int | None = None,
342
+ prompt_tokens: int | None = None, on_compact=None, on_finish=None,
343
+ ) -> str:
344
+ cwd = cwd.resolve()
345
+ messages.append({"role": "user", "content": task})
346
+ last_prompt = prompt_tokens
347
+ try:
348
+ for turn in range(1, max_turns + 1):
349
+ if should_compact(last_prompt, context_limit):
350
+ new_msgs, n = compact_messages(messages)
351
+ if n:
352
+ messages[:] = new_msgs
353
+ await _emit(on_compact, n)
354
+ try:
355
+ content, tool_calls, usage = await _stream_completion(
356
+ client, model=model, messages=messages, on_delta=on_delta,
357
+ on_thinking=on_thinking, on_answer_to_thinking=on_answer_to_thinking,
358
+ on_finish=on_finish,
359
+ )
360
+ except Interrupted as e:
361
+ if e.partial:
362
+ messages.append({"role": "assistant", "content": e.partial})
363
+ raise
364
+ if usage:
365
+ await _emit(on_usage, usage)
366
+ last_prompt = usage.get("prompt_tokens", last_prompt)
367
+ assistant: dict[str, Any] = {"role": "assistant", "content": content}
368
+ if tool_calls:
369
+ assistant["tool_calls"] = tool_calls
370
+ messages.append(assistant)
371
+ if not tool_calls:
372
+ return content
373
+ for tc in tool_calls:
374
+ name, raw_args = tc["function"]["name"], tc["function"]["arguments"]
375
+ try:
376
+ args = json.loads(raw_args or "{}")
377
+ except json.JSONDecodeError:
378
+ args, result = {}, f"error: invalid JSON arguments: {raw_args!r}"
379
+ else:
380
+ try:
381
+ result = await asyncio.to_thread(
382
+ dispatch_tool, cwd, name, args, on_preview=on_preview
383
+ )
384
+ except (asyncio.CancelledError, KeyboardInterrupt) as e:
385
+ messages.append(
386
+ {"role": "tool", "tool_call_id": tc["id"], "content": "error: interrupted"}
387
+ )
388
+ raise Interrupted() from e
389
+ if on_tool:
390
+ await _emit(on_tool, turn, name, args, result)
391
+ else:
392
+ print(f" [{turn}] {name} {tool_summary(name, args)}", file=sys.stderr, flush=True)
393
+ messages.append({"role": "tool", "tool_call_id": tc["id"], "content": result})
394
+ return f"(stopped after {max_turns} turns)"
395
+ except Interrupted:
396
+ raise
397
+ except (asyncio.CancelledError, KeyboardInterrupt) as e:
398
+ raise Interrupted() from e
agent7/commands.py ADDED
@@ -0,0 +1,236 @@
1
+ """Slash-command interface for the REPL."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import asyncio
6
+ from collections.abc import Awaitable, Callable
7
+ from dataclasses import dataclass
8
+ from getpass import getpass
9
+
10
+ from .agent import compact_messages
11
+ from .providers import (
12
+ agent7_auth_path,
13
+ describe_found,
14
+ get_provider,
15
+ list_providers,
16
+ load_auth,
17
+ resolve_all,
18
+ )
19
+ from .session import Session, fmt_tokens, format_usage
20
+
21
+ @dataclass
22
+ class CommandResult:
23
+ message: str = ""
24
+
25
+ SlashHandler = Callable[[Session, list[str]], CommandResult | Awaitable[CommandResult]]
26
+ _COMMANDS: dict[str, tuple[str, SlashHandler]] = {}
27
+
28
+ def command(name: str, *, help: str) -> Callable[[SlashHandler], SlashHandler]:
29
+ def deco(fn: SlashHandler) -> SlashHandler:
30
+ _COMMANDS[name.lower().lstrip("/")] = (help, fn)
31
+ return fn
32
+ return deco
33
+
34
+ def list_commands() -> list[tuple[str, str]]:
35
+ return sorted((n, h) for n, (h, _) in _COMMANDS.items())
36
+
37
+ def known_names() -> list[str]:
38
+ return sorted(_COMMANDS)
39
+
40
+ async def fetch_models(session: Session, *, refresh: bool = False) -> list[str]:
41
+ if session.models_cache is not None and not refresh:
42
+ return session.models_cache
43
+ if session.credential and session.provider_id:
44
+ session.remember(session.provider_id, session.credential)
45
+ for pid, cred in resolve_all().items():
46
+ session.credentials.setdefault(pid, cred)
47
+ if not session.credentials:
48
+ session.models_cache = []
49
+ return []
50
+ order = {p.id: i for i, p in enumerate(list_providers())}
51
+ errors, refs = [], []
52
+
53
+ async def _one(pid: str):
54
+ p = get_provider(pid)
55
+ if not p:
56
+ return pid, [], "unknown"
57
+ try:
58
+ return pid, await p.list_models(session.credentials[pid]), None
59
+ except Exception as e: # noqa: BLE001
60
+ return pid, [], str(e)
61
+
62
+ for pid, ids, err in await asyncio.gather(*[_one(p) for p in session.credentials]):
63
+ if err:
64
+ errors.append(f"{pid}: {err}")
65
+ else:
66
+ refs.extend(f"{pid}/{m}" for m in ids)
67
+ refs = sorted(set(refs), key=lambda r: (order.get(r.partition("/")[0], 99), r))
68
+ session.models_cache = refs
69
+ if errors and not refs:
70
+ raise RuntimeError("; ".join(errors))
71
+ return refs
72
+
73
+ def resolve_model_ref(session: Session, name: str) -> tuple[str, str, str] | str:
74
+ available, raw = session.models_cache or [], name.strip()
75
+ lower = {m.lower(): m for m in available}
76
+ if "/" in raw:
77
+ ref = lower.get(raw.lower())
78
+ if ref is None:
79
+ prov, _, mid = raw.partition("/")
80
+ return (prov, mid, f"{prov}/{mid}") if mid else f"bad model ref: {name!r}"
81
+ prov, _, mid = ref.partition("/")
82
+ return prov, mid, ref
83
+ matches = [m for m in available if m.partition("/")[2].lower() == raw.lower()]
84
+ if len(matches) == 1:
85
+ ref = matches[0]
86
+ return ref.partition("/")[0], ref.partition("/")[2], ref
87
+ if len(matches) > 1:
88
+ return f"ambiguous model {raw!r} — pick one of: {', '.join(matches)}"
89
+ if raw.lower().startswith("deepseek"):
90
+ return "deepseek", raw, f"deepseek/{raw}"
91
+ if session.provider_id:
92
+ return session.provider_id, raw, f"{session.provider_id}/{raw}"
93
+ return f"unknown model {raw!r} — try /model"
94
+
95
+ async def switch_model(session: Session, name: str) -> CommandResult:
96
+ resolved = resolve_model_ref(session, name)
97
+ if isinstance(resolved, str):
98
+ return CommandResult(message=resolved)
99
+ provider_id, model_id, ref = resolved
100
+ p = get_provider(provider_id)
101
+ if p is None:
102
+ return CommandResult(message=f"unknown provider {provider_id!r}")
103
+ cred = session.credentials.get(provider_id) or p.resolve()
104
+ if cred is None:
105
+ alias = p.aliases[0] if p.aliases else p.id
106
+ return CommandResult(message=f"no credentials for {provider_id} — /login {alias}")
107
+ session.remember(provider_id, cred)
108
+ if session.provider_id != provider_id or session.credential is not cred:
109
+ await session.apply(p, cred)
110
+ old = session.model_ref or session.model
111
+ session.set_model(model_id, ref=ref)
112
+ limit = f" context={fmt_tokens(session.context_limit)}" if session.context_limit else ""
113
+ return CommandResult(message=f"model: {old} → {ref}{limit}")
114
+
115
+ async def dispatch(session: Session, line: str) -> CommandResult | None:
116
+ raw = line.strip()
117
+ if not raw.startswith("/"):
118
+ return None
119
+ body = raw[1:].strip()
120
+ if not body:
121
+ return CommandResult(message="empty command — try /help")
122
+ name, _, rest = body.partition(" ")
123
+ entry = _COMMANDS.get(name.lower())
124
+ if not entry:
125
+ return CommandResult(message=f"unknown command /{name.lower()} (see /help)")
126
+ result = entry[1](session, rest.split() if rest.strip() else [])
127
+ return await result if asyncio.iscoroutine(result) else result
128
+
129
+ async def _activate(session: Session, prefer: str | None = None) -> CommandResult:
130
+ session.credentials.update(resolve_all())
131
+ target = get_provider(prefer) if prefer else None
132
+ cred = (session.credentials.get(target.id) or target.resolve()) if target else None
133
+ if target and cred:
134
+ session.remember(target.id, cred)
135
+ if not target or not cred:
136
+ if session.credential and session.provider_id:
137
+ target, cred = get_provider(session.provider_id), session.credential
138
+ elif session.credentials:
139
+ pid = next(iter(session.credentials))
140
+ target, cred = get_provider(pid), session.credentials[pid]
141
+ if not target or not cred:
142
+ return CommandResult(message="no credentials — try /login deepseek | /login kimi")
143
+ await session.apply(target, cred)
144
+ try:
145
+ ids, note = await fetch_models(session, refresh=True), ""
146
+ except Exception as e: # noqa: BLE001
147
+ ids, note = [], f"\nmodels fetch failed: {e}"
148
+ cur = session.model_ref or session.model
149
+ if ids and (not session.model or session.model == "pending" or cur not in ids):
150
+ pick = next((r for r in ids if r.startswith(f"{target.id}/")), ids[0])
151
+ await switch_model(session, pick)
152
+ return CommandResult(
153
+ message=(
154
+ f"active: {target.id} source={cred.source}\n"
155
+ f"providers: [{', '.join(session.credentials)}]\n"
156
+ f"base_url={cred.base_url}\nmodel={session.model_ref or session.model}{note}"
157
+ )
158
+ )
159
+
160
+ @command("help", help="list slash commands")
161
+ def cmd_help(session: Session, args: list[str]) -> CommandResult:
162
+ lines = ["commands:"] + [f" /{n:<12} {h}" for n, h in list_commands()]
163
+ lines.append(f"current: model={session.model_ref or session.model} cwd={session.cwd}")
164
+ lines.append("tip: type @ in the prompt to complete a file path")
165
+ return CommandResult(message="\n".join(lines))
166
+
167
+ @command("model", help="list/switch models (/model | /model <ref> | /model refresh)")
168
+ async def cmd_model(session: Session, args: list[str]) -> CommandResult:
169
+ refresh = bool(args and args[0].lower() in ("refresh", "-r"))
170
+ try:
171
+ available = await fetch_models(session, refresh=refresh)
172
+ except Exception as e: # noqa: BLE001
173
+ return CommandResult(message=f"failed to fetch models: {e}")
174
+ cur = session.model_ref or session.model
175
+ if not args or (refresh and len(args) == 1):
176
+ providers = ", ".join(session.credentials) or (session.provider_id or "?")
177
+ lines = [f"model={cur} providers=[{providers}]", "available:"]
178
+ lines += [f" {'*' if m == cur else ' '} {m}" for m in available]
179
+ lines.append("usage: /model <id|provider/id> | /model refresh")
180
+ return CommandResult(message="\n".join(lines))
181
+ return await switch_model(session, args[1] if refresh else args[0])
182
+
183
+ @command("status", help="show session status")
184
+ def cmd_status(session: Session, args: list[str]) -> CommandResult:
185
+ n = max(0, len(session.messages) - 1)
186
+ return CommandResult(message=(
187
+ f"model={session.model_ref or session.model}\n"
188
+ f"provider={session.provider_id} source={session.cred_source}\n"
189
+ f"providers=[{', '.join(session.credentials) or '?'}]\n"
190
+ f"cwd={session.cwd}\nmessages={n} max_turns={session.max_turns}\n"
191
+ f"{format_usage(session)}\nbase_url={session.client.base_url}"
192
+ ))
193
+
194
+ @command("login", help="paste API key (/login deepseek | /login kimi [global])")
195
+ async def cmd_login(session: Session, args: list[str]) -> CommandResult:
196
+ if not args:
197
+ rows = describe_found()
198
+ names = " | ".join(p.id for p in list_providers())
199
+ lines = [f"usage: /login <provider> ({names})", f"auth file: {agent7_auth_path()}"]
200
+ lines += (["found:"] + [f" {a} {b}" for a, b in rows]) if rows else ["found: (none)"]
201
+ if session.provider_id:
202
+ lines.append(f"active: {session.provider_id} source={session.cred_source}")
203
+ return CommandResult(message="\n".join(lines))
204
+ target = get_provider(args[0])
205
+ if not target:
206
+ return CommandResult(message=f"unknown provider {args[0]!r}")
207
+ try:
208
+ cred = await target.login(args=args[1:], prompt_secret=lambda s: getpass(f"{s}: ").strip())
209
+ except Exception as e: # noqa: BLE001
210
+ return CommandResult(message=f"{target.id} login failed: {e}")
211
+ session.remember(target.id, cred)
212
+ result = await _activate(session, target.id)
213
+ return CommandResult(message=f"logged in {target.id}\n{result.message}")
214
+
215
+ @command("compact", help="shrink old tool/assistant text in history")
216
+ def cmd_compact(session: Session, args: list[str]) -> CommandResult:
217
+ new_msgs, n = compact_messages(session.messages)
218
+ session.messages[:] = new_msgs
219
+ if not n:
220
+ return CommandResult(message="compact: nothing to shrink (history short or already small)")
221
+ return CommandResult(message=f"compact: shrunk {n} message(s); recent turns kept intact")
222
+
223
+ @command("logout", help="clear saved key (/logout deepseek|kimi|moonshot)")
224
+ def cmd_logout(session: Session, args: list[str]) -> CommandResult:
225
+ if not args:
226
+ keys = [p.id for p in list_providers() if p.id in load_auth()]
227
+ return CommandResult(
228
+ message="nothing stored" if not keys else "usage: /logout <provider>\nstored: " + ", ".join(keys)
229
+ )
230
+ p = get_provider(args[0])
231
+ if not p:
232
+ return CommandResult(message=f"unknown provider {args[0]!r}")
233
+ if p.logout():
234
+ session.credentials.pop(p.id, None)
235
+ return CommandResult(message=f"cleared {p.id}")
236
+ return CommandResult(message=f"no stored key for {p.id}")