agent7 0.1.2__tar.gz → 0.1.4__tar.gz

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.
@@ -1,14 +1,14 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: agent7
3
- Version: 0.1.2
4
- Summary: The simplest coding agent — four tools, one loop, ~1200 lines of Python
3
+ Version: 0.1.4
4
+ Summary: The simplest coding agent — four tools, one loop, ~1600 lines of Python
5
5
  Project-URL: Homepage, https://github.com/r1cardohj/agent7
6
6
  Project-URL: Repository, https://github.com/r1cardohj/agent7
7
7
  Project-URL: Issues, https://github.com/r1cardohj/agent7/issues
8
8
  Author-email: r1cardohj <2413302357@qq.com>
9
9
  License-Expression: MIT
10
10
  License-File: LICENSE
11
- Keywords: agent,cli,coding-agent,deepseek,kimi,llm,openai-compatible
11
+ Keywords: agent,cli,coding-agent,deepseek,grok,llm,openai-compatible,xai
12
12
  Classifier: Development Status :: 3 - Alpha
13
13
  Classifier: Environment :: Console
14
14
  Classifier: Intended Audience :: Developers
@@ -28,22 +28,23 @@ Description-Content-Type: text/markdown
28
28
 
29
29
  # agent7
30
30
 
31
- **The simplest coding agent. ~1500 lines of Python, four tools, one loop.**
31
+ **The simplest coding agent. ~1600 lines of Python, four tools, one loop.**
32
+
33
+ A deliberately minimal harness — all-in on modern, carefully chosen model providers.
34
+ Fast and precise. No seatbelt; hold on.
32
35
 
33
36
  No orchestration: no plan mode, no subagents, no parallel tasks, no background jobs.
34
37
  You give it one sentence; it reads files, edits files, runs commands, then stops.
35
38
  Built for people who work on one thing at a time — you hold one task in your head, and so does it.
36
39
 
37
- ```
38
- agent7/ 1482 lines
39
- __main__.py 434 CLI + REPL + @path completion + session wiring
40
- agent.py 398 tools + agent loop + compaction
41
- commands.py 236 slash commands + model switching
42
- providers.py 161 API key auth
43
- store.py 149 atomic JSON session snapshots
44
- session.py 101 session state
45
- __init__.py 3 version
46
- ```
40
+ ## Features
41
+
42
+ - **Deliberately minimal harness** — four tools, one loop, no orchestration
43
+ - **Complete CLI agent UX** — streaming thinking + answer, tool lines with ✓/✗, edit/write preview, vi-mode REPL, `@path` completion, session resume
44
+ - **Slash commands** — `/help` `/model` `/status` `/login` `/logout` `/compact`
45
+ - **Markdown rendering** — final replies rendered as Rich Markdown in the terminal, thanks rich.
46
+ - **Provider login** — paste an API key for DeepSeek or Grok (`/login` or env); switch models in-session
47
+
47
48
 
48
49
  ## Install
49
50
 
@@ -58,20 +59,19 @@ pip install agent7
58
59
  Paste an API key; there is no OAuth. Keys are stored in `~/.config/agent7/auth.json`.
59
60
 
60
61
  ```bash
61
- export DEEPSEEK_API_KEY=sk-...
62
- # export KIMI_API_KEY=...
63
- # export MOONSHOT_API_KEY=sk-...
64
- # export AGENT7_MODEL=deepseek-flash
62
+ export DEEPSEEK_API_KEY=sk-... # or /login deepseek
63
+ export XAI_API_KEY=xai-... # Grok, from console.x.ai (or /login grok)
64
+ # export AGENT7_MODEL=grok-4
65
65
  ```
66
66
 
67
67
  You can also log in from inside the REPL:
68
68
 
69
69
  ```text
70
70
  /login deepseek
71
- /login kimi # optional: /login kimi global
72
- /login moonshot
71
+ /login grok # xAI — Grok models
73
72
  /model # list models for every logged-in provider
74
73
  /model deepseek-flash
74
+ /model grok-4
75
75
  ```
76
76
 
77
77
  ## Usage
@@ -79,30 +79,39 @@ You can also log in from inside the REPL:
79
79
  ```bash
80
80
  uv run agent7 "create hello.py that prints hi" # one-shot
81
81
  uv run agent7 # new REPL session
82
- uv run agent7 -r # resume latest session in this cwd
83
- uv run agent7 -r <session-id> # resume a specific session
84
- uv run agent7 session -l # list this cwd's sessions
85
- uv run agent7 session "fix authentication" # new named REPL session
82
+ uv run agent7 -r # resume this cwd's session
83
+ uv run agent7 -r "continue" # resume + one-shot
86
84
  ```
87
85
 
86
+ Each workspace keeps a single snapshot — starting without `-r` replaces it.
88
87
  Sessions are saved automatically after tasks, commands, interruptions, and exit.
89
- `agent7 session -l` prints tab-separated `ID`, `NAME`, and `PATH` columns and needs no login.
90
88
  Snapshots contain resumable model context, not a separate full transcript; compaction is reflected
91
89
  in the saved context. Files live in `${XDG_STATE_HOME:-~/.local/state}/agent7/sessions/` and do not
92
90
  store API keys. Hard process kills can lose the in-progress turn.
93
91
 
94
92
  REPL commands: `/help` `/model` `/status` `/login` `/logout` `/compact`.
95
- Exit with an empty line or Ctrl-D.
93
+ Exit with Ctrl-D (or Ctrl-Z on Windows).
94
+
95
+ Reasoning models (DeepSeek, Grok) stream their `reasoning_content` live: it shows up
96
+ dimmed under a `thinking` header, before the answer and above each tool line. It is
97
+ display only — reasoning is never replayed into the prompt or the saved session.
96
98
 
97
99
  Type `@` in the REPL to recursively complete files and directories from the cwd:
98
100
  `fix @agent7/agent.py`.
99
101
  Tab accepts, directories keep going (`@agent7/` → `@agent7/session.py`), and spaces
100
102
  are escaped (`@my\ file.txt`), so the path the model sees is the path it can read.
101
103
 
102
- `--cwd` sets the working directory, `--max-turns` caps the loop (default 30 turns;
103
- when it runs out you get `# (stopped after N turns)`). A run that ends with no visible
104
- text never ends silently: you get either `# (stopped after N turns)`,
105
- `# no text in the reply …` or `# … hit the output token limit …`.
104
+ `--cwd` sets the working directory. `--max-turns` caps the loop at **200 model rounds
105
+ per task** — high enough that ordinary work never hits it, low enough to stop a runaway.
106
+ When it runs out you get `# (stopped after N turns)`; the transcript is intact, so just
107
+ say `continue` (or rerun with `AGENT7_MAX_TURNS=500 agent7 -r "continue"`).
108
+
109
+ The cap is **per run**, not per session: `-r` never pins you to the `--max-turns` an
110
+ already-saved session was created with. Precedence is `--max-turns` > `$AGENT7_MAX_TURNS`
111
+ > 200.
112
+
113
+ A run that ends with no visible text never ends silently: you get either
114
+ `# (stopped after N turns)`, `# no text in the reply …` or `# … hit the output token limit …`.
106
115
 
107
116
  ## Tools
108
117
 
@@ -130,8 +139,25 @@ At 75% context usage, old tool/assistant text is compacted automatically: the la
130
139
  3 user turns are kept, or for one-shot tasks the last 4 tool results. `/compact`
131
140
  triggers the same compaction manually.
132
141
 
142
+ Providers that never report `usage` are measured by an estimate, so compaction still
143
+ kicks in; if the server rejects a request as too long anyway, it compacts harder and
144
+ retries that turn once.
145
+
133
146
  `AGENT7_CONTEXT_LIMIT` overrides the context limit.
134
147
 
148
+ ## When things go wrong
149
+
150
+ - **429 / 5xx / connection errors** are retried up to 3 times (0.5s, 1.5s, 3s) — but
151
+ only while nothing has been printed yet, so you never see a reply twice. After that
152
+ you get `# error: …` and, in the REPL, the prompt comes back instead of the process dying.
153
+ - **Ctrl-C in the middle of a tool batch** answers every remaining tool call with
154
+ `error: interrupted`, so the next request is still valid.
155
+ - **Writes are atomic** (temp file + rename): an interrupted `write`/`edit` leaves the
156
+ original file untouched, and symlinks keep pointing where they did.
157
+ - **Large outputs are bounded**: `read` streams the file and keeps only the window it
158
+ returns; `bash` captures to temp files and reads back ~12k chars. A 100 MB log costs
159
+ a few hundred KB of memory, not 300 MB.
160
+
135
161
  ## What it is not
136
162
 
137
163
  - Not an orchestrator: no branching, no subagents
@@ -1,21 +1,22 @@
1
1
  # agent7
2
2
 
3
- **The simplest coding agent. ~1500 lines of Python, four tools, one loop.**
3
+ **The simplest coding agent. ~1600 lines of Python, four tools, one loop.**
4
+
5
+ A deliberately minimal harness — all-in on modern, carefully chosen model providers.
6
+ Fast and precise. No seatbelt; hold on.
4
7
 
5
8
  No orchestration: no plan mode, no subagents, no parallel tasks, no background jobs.
6
9
  You give it one sentence; it reads files, edits files, runs commands, then stops.
7
10
  Built for people who work on one thing at a time — you hold one task in your head, and so does it.
8
11
 
9
- ```
10
- agent7/ 1482 lines
11
- __main__.py 434 CLI + REPL + @path completion + session wiring
12
- agent.py 398 tools + agent loop + compaction
13
- commands.py 236 slash commands + model switching
14
- providers.py 161 API key auth
15
- store.py 149 atomic JSON session snapshots
16
- session.py 101 session state
17
- __init__.py 3 version
18
- ```
12
+ ## Features
13
+
14
+ - **Deliberately minimal harness** — four tools, one loop, no orchestration
15
+ - **Complete CLI agent UX** — streaming thinking + answer, tool lines with ✓/✗, edit/write preview, vi-mode REPL, `@path` completion, session resume
16
+ - **Slash commands** — `/help` `/model` `/status` `/login` `/logout` `/compact`
17
+ - **Markdown rendering** — final replies rendered as Rich Markdown in the terminal, thanks rich.
18
+ - **Provider login** — paste an API key for DeepSeek or Grok (`/login` or env); switch models in-session
19
+
19
20
 
20
21
  ## Install
21
22
 
@@ -30,20 +31,19 @@ pip install agent7
30
31
  Paste an API key; there is no OAuth. Keys are stored in `~/.config/agent7/auth.json`.
31
32
 
32
33
  ```bash
33
- export DEEPSEEK_API_KEY=sk-...
34
- # export KIMI_API_KEY=...
35
- # export MOONSHOT_API_KEY=sk-...
36
- # export AGENT7_MODEL=deepseek-flash
34
+ export DEEPSEEK_API_KEY=sk-... # or /login deepseek
35
+ export XAI_API_KEY=xai-... # Grok, from console.x.ai (or /login grok)
36
+ # export AGENT7_MODEL=grok-4
37
37
  ```
38
38
 
39
39
  You can also log in from inside the REPL:
40
40
 
41
41
  ```text
42
42
  /login deepseek
43
- /login kimi # optional: /login kimi global
44
- /login moonshot
43
+ /login grok # xAI — Grok models
45
44
  /model # list models for every logged-in provider
46
45
  /model deepseek-flash
46
+ /model grok-4
47
47
  ```
48
48
 
49
49
  ## Usage
@@ -51,30 +51,39 @@ You can also log in from inside the REPL:
51
51
  ```bash
52
52
  uv run agent7 "create hello.py that prints hi" # one-shot
53
53
  uv run agent7 # new REPL session
54
- uv run agent7 -r # resume latest session in this cwd
55
- uv run agent7 -r <session-id> # resume a specific session
56
- uv run agent7 session -l # list this cwd's sessions
57
- uv run agent7 session "fix authentication" # new named REPL session
54
+ uv run agent7 -r # resume this cwd's session
55
+ uv run agent7 -r "continue" # resume + one-shot
58
56
  ```
59
57
 
58
+ Each workspace keeps a single snapshot — starting without `-r` replaces it.
60
59
  Sessions are saved automatically after tasks, commands, interruptions, and exit.
61
- `agent7 session -l` prints tab-separated `ID`, `NAME`, and `PATH` columns and needs no login.
62
60
  Snapshots contain resumable model context, not a separate full transcript; compaction is reflected
63
61
  in the saved context. Files live in `${XDG_STATE_HOME:-~/.local/state}/agent7/sessions/` and do not
64
62
  store API keys. Hard process kills can lose the in-progress turn.
65
63
 
66
64
  REPL commands: `/help` `/model` `/status` `/login` `/logout` `/compact`.
67
- Exit with an empty line or Ctrl-D.
65
+ Exit with Ctrl-D (or Ctrl-Z on Windows).
66
+
67
+ Reasoning models (DeepSeek, Grok) stream their `reasoning_content` live: it shows up
68
+ dimmed under a `thinking` header, before the answer and above each tool line. It is
69
+ display only — reasoning is never replayed into the prompt or the saved session.
68
70
 
69
71
  Type `@` in the REPL to recursively complete files and directories from the cwd:
70
72
  `fix @agent7/agent.py`.
71
73
  Tab accepts, directories keep going (`@agent7/` → `@agent7/session.py`), and spaces
72
74
  are escaped (`@my\ file.txt`), so the path the model sees is the path it can read.
73
75
 
74
- `--cwd` sets the working directory, `--max-turns` caps the loop (default 30 turns;
75
- when it runs out you get `# (stopped after N turns)`). A run that ends with no visible
76
- text never ends silently: you get either `# (stopped after N turns)`,
77
- `# no text in the reply …` or `# … hit the output token limit …`.
76
+ `--cwd` sets the working directory. `--max-turns` caps the loop at **200 model rounds
77
+ per task** — high enough that ordinary work never hits it, low enough to stop a runaway.
78
+ When it runs out you get `# (stopped after N turns)`; the transcript is intact, so just
79
+ say `continue` (or rerun with `AGENT7_MAX_TURNS=500 agent7 -r "continue"`).
80
+
81
+ The cap is **per run**, not per session: `-r` never pins you to the `--max-turns` an
82
+ already-saved session was created with. Precedence is `--max-turns` > `$AGENT7_MAX_TURNS`
83
+ > 200.
84
+
85
+ A run that ends with no visible text never ends silently: you get either
86
+ `# (stopped after N turns)`, `# no text in the reply …` or `# … hit the output token limit …`.
78
87
 
79
88
  ## Tools
80
89
 
@@ -102,8 +111,25 @@ At 75% context usage, old tool/assistant text is compacted automatically: the la
102
111
  3 user turns are kept, or for one-shot tasks the last 4 tool results. `/compact`
103
112
  triggers the same compaction manually.
104
113
 
114
+ Providers that never report `usage` are measured by an estimate, so compaction still
115
+ kicks in; if the server rejects a request as too long anyway, it compacts harder and
116
+ retries that turn once.
117
+
105
118
  `AGENT7_CONTEXT_LIMIT` overrides the context limit.
106
119
 
120
+ ## When things go wrong
121
+
122
+ - **429 / 5xx / connection errors** are retried up to 3 times (0.5s, 1.5s, 3s) — but
123
+ only while nothing has been printed yet, so you never see a reply twice. After that
124
+ you get `# error: …` and, in the REPL, the prompt comes back instead of the process dying.
125
+ - **Ctrl-C in the middle of a tool batch** answers every remaining tool call with
126
+ `error: interrupted`, so the next request is still valid.
127
+ - **Writes are atomic** (temp file + rename): an interrupted `write`/`edit` leaves the
128
+ original file untouched, and symlinks keep pointing where they did.
129
+ - **Large outputs are bounded**: `read` streams the file and keeps only the window it
130
+ returns; `bash` captures to temp files and reads back ~12k chars. A 100 MB log costs
131
+ a few hundred KB of memory, not 300 MB.
132
+
107
133
  ## What it is not
108
134
 
109
135
  - Not an orchestrator: no branching, no subagents
@@ -1,3 +1,3 @@
1
1
  """agent7 — minimal coding agent."""
2
2
 
3
- __version__ = "0.1.2"
3
+ __version__ = "0.1.4"
@@ -7,7 +7,6 @@ import asyncio
7
7
  import os
8
8
  import re
9
9
  import sys
10
- import time
11
10
  from collections.abc import Callable
12
11
  from pathlib import Path
13
12
 
@@ -24,14 +23,23 @@ from rich.console import Console
24
23
  from rich.markdown import Markdown
25
24
  from rich.text import Text
26
25
 
27
- from .agent import SHELL, SYSTEM, Interrupted, run_agent, tool_summary
26
+ from .agent import DEFAULT_MAX_TURNS, SHELL, SYSTEM, Interrupted, run_agent, tool_summary
28
27
  from .commands import dispatch, fetch_models, known_names, switch_model
29
- from .providers import get_provider, resolve_all, resolve_default
28
+ from .providers import (
29
+ default_model_for,
30
+ get_provider,
31
+ list_providers,
32
+ login_hints,
33
+ resolve_all,
34
+ resolve_default,
35
+ )
30
36
  from .session import Session, format_context_prompt
31
- from .store import list_sessions, new_id, resume, resume_messages, save, timestamp
37
+ from .store import resume, resume_messages, save, timestamp
32
38
 
33
39
  console, err = Console(stderr=False), Console(stderr=True)
34
- _THINK_FRAMES = ("thinking ", "thinking. ", "thinking.. ", "thinking...")
40
+ _THINK_HEADER = " thinking"
41
+ _THINK_PREFIX = " │ "
42
+ _THINK_ON, _THINK_OFF = "\033[36;2m", "\033[0m"
35
43
 
36
44
  def _load_dotenv(path: Path = Path(".env")) -> None:
37
45
  if not path.is_file():
@@ -56,7 +64,7 @@ class ReplyPrinter:
56
64
  self.buf: list[str] = []
57
65
  self._chars = 0
58
66
  self._thinking_open = False
59
- self._thinking_t0 = 0.0
67
+ self._thinking_bol = True
60
68
  self._counting = False
61
69
 
62
70
  def __enter__(self) -> ReplyPrinter:
@@ -73,15 +81,24 @@ class ReplyPrinter:
73
81
  console.print(Markdown(text))
74
82
  console.print()
75
83
 
84
+ def _write(self, text: str) -> None:
85
+ out = getattr(err, "file", None) or sys.stderr
86
+ out.write(text)
87
+ out.flush()
88
+
89
+ def _paint(self, text: str) -> str:
90
+ return f"{_THINK_ON}{text}{_THINK_OFF}" if err.is_terminal else text
91
+
76
92
  def _clear_status_line(self) -> None:
77
93
  if err.is_terminal:
78
- sys.stderr.write("\r\033[K")
79
- sys.stderr.flush()
94
+ self._write("\r\033[K")
80
95
 
81
96
  def _close_thinking(self) -> None:
82
- if self._thinking_open:
83
- self._clear_status_line()
84
- self._thinking_open = False
97
+ if not self._thinking_open:
98
+ return
99
+ if not self._thinking_bol:
100
+ self._write("\n")
101
+ self._thinking_open, self._thinking_bol = False, True
85
102
 
86
103
  def _clear_counter(self) -> None:
87
104
  if self._counting:
@@ -93,27 +110,41 @@ class ReplyPrinter:
93
110
  return
94
111
  self._close_thinking()
95
112
  self._counting = True
96
- sys.stderr.write(f"\r\033[K … {self._chars} chars")
97
- sys.stderr.flush()
113
+ self._write(f"\r\033[K … {self._chars} chars")
114
+
115
+ def _open_thinking(self) -> None:
116
+ self._thinking_open, self._thinking_bol = True, True
117
+ self._write("\n" + self._paint(_THINK_HEADER) + "\n")
98
118
 
99
119
  def on_thinking(self, text: str) -> None:
120
+ """Stream the model's reasoning as dim text under a `thinking` header."""
100
121
  if not text:
101
122
  return
102
123
  self._clear_counter()
103
124
  if not self._thinking_open:
104
- self._thinking_open, self._thinking_t0 = True, time.monotonic()
105
- if err.is_terminal:
106
- frame = int((time.monotonic() - self._thinking_t0) / 0.4) % len(_THINK_FRAMES)
107
- sys.stderr.write(f"\r\033[K {_THINK_FRAMES[frame]}")
108
- sys.stderr.flush()
125
+ self._open_thinking()
126
+ lines = text.split("\n")
127
+ chunks: list[str] = []
128
+ for i, line in enumerate(lines):
129
+ if line:
130
+ if self._thinking_bol:
131
+ chunks.append(self._paint(_THINK_PREFIX))
132
+ self._thinking_bol = False
133
+ chunks.append(self._paint(line))
134
+ if i < len(lines) - 1: # the stream continues on a new line
135
+ chunks.append("\n")
136
+ self._thinking_bol = True
137
+ self._write("".join(chunks))
109
138
 
110
139
  def on_answer_to_thinking(self) -> None:
140
+ # Content streamed before a tool call is not the final answer: drop it,
141
+ # and end the thinking block so later reasoning opens a fresh one.
142
+ self._close_thinking()
111
143
  if not self.buf:
112
144
  return
113
145
  self.buf.clear()
114
146
  self._chars = 0
115
147
  self._clear_counter()
116
- self.on_thinking(".")
117
148
 
118
149
  def on_delta(self, text: str) -> None:
119
150
  self.buf.append(text)
@@ -154,6 +185,12 @@ class ReplyPrinter:
154
185
  err.print(head)
155
186
 
156
187
  _AT_PATH = re.compile(r"(?<![A-Za-z0-9_.\-/@])@((?:\\ |[^\s@])*)$")
188
+ SKIP_DIRS = frozenset({
189
+ ".git", ".hg", ".svn", ".venv", "venv", "node_modules", "__pycache__",
190
+ ".mypy_cache", ".ruff_cache", ".pytest_cache", ".tox", ".next",
191
+ ".gradle", ".idea", ".cache",
192
+ })
193
+ MAX_COMPLETIONS, MAX_DEPTH = 300, 8
157
194
 
158
195
  def at_path_prefix(text: str) -> str | None:
159
196
  """The path fragment after an '@' that starts the current word ('@' -> '')."""
@@ -167,19 +204,30 @@ def path_completions(cwd: Path, text: str) -> list[Completion]:
167
204
  return []
168
205
  raw = os.path.expanduser(fragment.replace("\\ ", " "))
169
206
  head, _, prefix = raw.rpartition("/")
170
- target = Path(head) if head else Path()
207
+ target = Path(head).expanduser() if head else Path()
171
208
  if not target.is_absolute():
172
209
  target = cwd / target
210
+ if not target.is_dir():
211
+ return []
173
212
  entries: list[tuple[Path, str]] = []
174
213
  show_hidden = prefix.startswith(".")
175
214
  for root, dirs, files in os.walk(target):
176
- if not show_hidden:
177
- dirs[:] = [name for name in dirs if not name.startswith(".")]
215
+ # A bare '@' must not walk node_modules / .git / $HOME: prune, cap depth, cap results.
216
+ dirs[:] = [
217
+ name for name in dirs
218
+ if name not in SKIP_DIRS and (show_hidden or not name.startswith("."))
219
+ ]
220
+ if len(Path(root).relative_to(target).parts) >= MAX_DEPTH:
221
+ dirs[:] = []
178
222
  for name in dirs + files:
179
- if (name.startswith(".") and not show_hidden) or not name.startswith(prefix):
223
+ if not name.startswith(prefix) or (name.startswith(".") and not show_hidden):
180
224
  continue
181
225
  p = Path(root) / name
182
226
  entries.append((p, p.relative_to(target).as_posix()))
227
+ if len(entries) >= MAX_COMPLETIONS:
228
+ break
229
+ if len(entries) >= MAX_COMPLETIONS:
230
+ break
183
231
  entries.sort(key=lambda entry: (not entry[0].is_dir(), entry[1].lower()))
184
232
  out = []
185
233
  for p, path in entries:
@@ -218,7 +266,8 @@ class ReplCompleter(Completer):
218
266
  if mid.startswith(prefix) or bare.startswith(prefix) or prefix.lower() in mid.lower():
219
267
  yield Completion(mid, start_position=-len(prefix), display=mid)
220
268
  elif cmd in ("login", "logout"):
221
- for mid in ("deepseek", "kimi", "moonshot", "global"):
269
+ names = [n for p in list_providers() for n in (p.id, *p.aliases)]
270
+ for mid in names:
222
271
  if mid.startswith(prefix.lower()):
223
272
  yield Completion(mid, start_position=-len(prefix), display=mid)
224
273
 
@@ -259,44 +308,37 @@ async def _run_agent_once(session: Session, task: str) -> str:
259
308
  err.print(f"[dim]# {notice}[/dim]")
260
309
  return answer
261
310
 
262
- def _print_sessions(cwd: Path) -> None:
263
- print("ID\tNAME\tPATH")
264
- for snapshot in list_sessions(cwd):
265
- print(f"{snapshot['id']}\t{snapshot['name'] or '-'}\t{snapshot['path']}")
311
+ def _positive_int(raw: str) -> int:
312
+ value = int(raw)
313
+ if value < 1:
314
+ raise argparse.ArgumentTypeError(f"must be at least 1, got {value}")
315
+ return value
266
316
 
267
317
  def _parse_args(argv: list[str] | None) -> argparse.Namespace:
268
318
  p = argparse.ArgumentParser(description="agent7 — minimal coding agent")
269
319
  p.add_argument("task", nargs="*", help="task; omit for REPL")
270
320
  p.add_argument("--cwd", type=Path, default=None)
271
- p.add_argument("--max-turns", type=int, default=None)
272
- p.add_argument("-r", "--resume", nargs="?", const="latest", metavar="ID",
273
- help="resume the latest workspace session, or the given ID")
274
- p.add_argument("--session-list", action="store_true", help=argparse.SUPPRESS)
275
- p.add_argument("--session-name", help=argparse.SUPPRESS)
276
- raw = sys.argv[1:] if argv is None else argv
277
- # `session` is a reserved command; all other positional text remains a task.
278
- # Only the first positional token is a command; options may have any values.
279
- i = 0
280
- while i < len(raw) and raw[i] != "--":
281
- if raw[i] in ("--cwd", "--max-turns"):
282
- i += 2
283
- elif raw[i] in ("-r", "--resume"):
284
- i += 2 if i + 1 < len(raw) and raw[i + 1] != "session" else 1
285
- elif raw[i].startswith("-"):
286
- i += 1
287
- else:
288
- break
289
- if i < len(raw) and raw[i] == "session":
290
- tail = raw[i + 1:]
291
- name = " ".join(tail).strip()
292
- if tail in (["-l"], ["--list"]):
293
- command = ["--session-list"]
294
- elif not name or any(c in name for c in "\t\r\n"):
295
- p.error("session name must be non-empty and on one line")
296
- else:
297
- command = ["--session-name", name]
298
- raw = [*raw[:i], *command]
299
- return p.parse_args(raw)
321
+ p.add_argument("--max-turns", type=_positive_int, default=None,
322
+ help=f"model rounds per task (default {DEFAULT_MAX_TURNS}, or $AGENT7_MAX_TURNS)")
323
+ p.add_argument("-r", "--resume", action="store_true",
324
+ help="resume the last session in this workspace")
325
+ return p.parse_args(sys.argv[1:] if argv is None else argv)
326
+
327
+ def resolve_max_turns(args: argparse.Namespace) -> int:
328
+ """CLI > $AGENT7_MAX_TURNS > default.
329
+
330
+ A saved session keeps its transcript, not its turn budget: resuming must not
331
+ pin you to whatever `--max-turns` the snapshot was created with.
332
+ """
333
+ if args.max_turns is not None:
334
+ return args.max_turns
335
+ raw = os.environ.get("AGENT7_MAX_TURNS", "").strip()
336
+ if raw:
337
+ try:
338
+ return _positive_int(raw)
339
+ except (ValueError, argparse.ArgumentTypeError):
340
+ err.print(f"[dim]# ignoring bad AGENT7_MAX_TURNS={raw!r}[/dim]")
341
+ return DEFAULT_MAX_TURNS
300
342
 
301
343
  async def async_main(argv: list[str] | None = None) -> None:
302
344
  _force_utf8_stdio()
@@ -305,27 +347,13 @@ async def async_main(argv: list[str] | None = None) -> None:
305
347
  task = " ".join(args.task).strip() or None
306
348
  cwd = (args.cwd or Path.cwd()).resolve()
307
349
  snapshot = None
308
- if args.session_list:
309
- if args.resume or args.task:
310
- raise SystemExit("session -l cannot be combined with a task or --resume")
311
- _print_sessions(cwd)
312
- return
313
- if args.session_name is not None:
314
- if args.resume:
315
- raise SystemExit("session and --resume cannot be combined")
316
- task = None # A named session opens the REPL; a bare task remains one-shot.
317
350
  if args.resume:
318
351
  try:
319
- snapshot = resume(cwd, args.resume)
352
+ snapshot = resume(cwd)
320
353
  except ValueError as e:
321
354
  raise SystemExit(str(e)) from None
322
- session_id = snapshot["id"] if snapshot else new_id()
323
- session_name = snapshot["name"] if snapshot else args.session_name or ""
324
355
  created_at = snapshot["created_at"] if snapshot else timestamp()
325
- max_turns = (
326
- args.max_turns if args.max_turns is not None
327
- else snapshot["max_turns"] if snapshot else 30
328
- )
356
+ max_turns = resolve_max_turns(args)
329
357
  model = os.environ.get("AGENT7_MODEL") or (
330
358
  snapshot.get("model_ref", "") if snapshot else ""
331
359
  )
@@ -340,9 +368,10 @@ async def async_main(argv: list[str] | None = None) -> None:
340
368
  prov, cred = picked
341
369
  client = prov.make_client(cred)
342
370
  else:
343
- client = AsyncOpenAI(api_key="missing", base_url="https://api.deepseek.com")
371
+ client = AsyncOpenAI(api_key="missing", base_url=list_providers()[0].default_base)
344
372
  if task:
345
- print("No credentials. Set DEEPSEEK_API_KEY / KIMI_API_KEY / MOONSHOT_API_KEY,\n"
373
+ keys = ", ".join(k for p in list_providers() for k in p.env_keys)
374
+ print(f"No credentials. Set {keys},\n"
346
375
  "or run `uv run agent7` and `/login`.", file=sys.stderr)
347
376
  sys.exit(1)
348
377
  prov, cred = None, None
@@ -353,7 +382,7 @@ async def async_main(argv: list[str] | None = None) -> None:
353
382
  credential=cred, credentials=dict(all_creds),
354
383
  )
355
384
  def persist() -> None:
356
- save(session_id, state, name=session_name, created_at=created_at)
385
+ save(state, created_at=created_at)
357
386
  try:
358
387
  ids: list[str] = []
359
388
  if all_creds:
@@ -373,23 +402,24 @@ async def async_main(argv: list[str] | None = None) -> None:
373
402
  if ids:
374
403
  await switch_model(state, ids[0])
375
404
  else:
376
- state.set_model("deepseek-chat")
405
+ state.set_model(default_model_for(state.provider_id))
377
406
  err.print(f"[dim]# agent7 model={state.model_ref or state.model} "
378
407
  f"providers=[{','.join(state.credentials) or 'none'}] "
379
408
  f"shell={SHELL.name} cwd={state.cwd}[/dim]")
380
- label = f" name={session_name}" if session_name else ""
381
409
  action = "resumed" if snapshot else "new"
382
- err.print(f"[dim]# {action} session {session_id}{label}[/dim]")
410
+ err.print(f"[dim]# {action} session[/dim]")
383
411
  if task:
384
412
  try:
385
413
  await _run_once(state, task, on_saved=persist)
386
414
  except Interrupted:
387
415
  err.print("\n[dim]# interrupted[/dim]")
416
+ except Exception as e: # noqa: BLE001
417
+ err.print(f"[red]# error: {type(e).__name__}: {e}[/red]")
388
418
  return
389
- quit_hint = "empty line / Ctrl-Z to quit" if sys.platform == "win32" else "empty line / Ctrl-D to quit"
419
+ quit_hint = "Ctrl-Z to quit" if sys.platform == "win32" else "Ctrl-D to quit"
390
420
  err.print(f"[dim]# REPL /help · /login · /model · @file · {quit_hint}[/dim]")
391
421
  if not all_creds:
392
- err.print("[dim]# no credentials — /login deepseek | /login kimi[/dim]")
422
+ err.print(f"[dim]# no credentials — {login_hints()}[/dim]")
393
423
 
394
424
  def _vi_rprompt() -> HTML:
395
425
  mode = get_app().vi_state.input_mode
@@ -412,7 +442,7 @@ async def async_main(argv: list[str] | None = None) -> None:
412
442
  print(file=sys.stderr)
413
443
  break
414
444
  if not line:
415
- break
445
+ continue
416
446
  result = await dispatch(state, line)
417
447
  persist()
418
448
  if result is not None:
@@ -420,12 +450,14 @@ async def async_main(argv: list[str] | None = None) -> None:
420
450
  err.print(f"[dim]{row}[/dim]")
421
451
  continue
422
452
  if state.credential is None:
423
- err.print("[yellow]# login first: /login deepseek | /login kimi[/yellow]")
453
+ err.print(f"[yellow]# login first: {login_hints()}[/yellow]")
424
454
  continue
425
455
  try:
426
456
  await _run_once(state, line, on_saved=persist)
427
457
  except (Interrupted, asyncio.CancelledError, KeyboardInterrupt):
428
458
  err.print("\n[dim]# interrupted[/dim]")
459
+ except Exception as e: # noqa: BLE001 a failed turn must not kill the REPL
460
+ err.print(f"[red]# error: {type(e).__name__}: {e}[/red]")
429
461
  finally:
430
462
  try:
431
463
  persist()