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.
- {agent7-0.1.2 → agent7-0.1.4}/PKG-INFO +56 -30
- {agent7-0.1.2 → agent7-0.1.4}/README.md +53 -27
- {agent7-0.1.2 → agent7-0.1.4}/agent7/__init__.py +1 -1
- {agent7-0.1.2 → agent7-0.1.4}/agent7/__main__.py +115 -83
- {agent7-0.1.2 → agent7-0.1.4}/agent7/agent.py +217 -50
- {agent7-0.1.2 → agent7-0.1.4}/agent7/commands.py +9 -8
- {agent7-0.1.2 → agent7-0.1.4}/agent7/providers.py +19 -19
- {agent7-0.1.2 → agent7-0.1.4}/agent7/session.py +4 -5
- {agent7-0.1.2 → agent7-0.1.4}/agent7/store.py +45 -67
- {agent7-0.1.2 → agent7-0.1.4}/pyproject.toml +4 -3
- {agent7-0.1.2 → agent7-0.1.4}/.gitignore +0 -0
- {agent7-0.1.2 → agent7-0.1.4}/LICENSE +0 -0
|
@@ -1,14 +1,14 @@
|
|
|
1
1
|
Metadata-Version: 2.5
|
|
2
2
|
Name: agent7
|
|
3
|
-
Version: 0.1.
|
|
4
|
-
Summary: The simplest coding agent — four tools, one loop, ~
|
|
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,
|
|
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. ~
|
|
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
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
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
|
-
#
|
|
63
|
-
# export
|
|
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
|
|
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
|
|
83
|
-
uv run agent7 -r
|
|
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
|
|
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
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
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. ~
|
|
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
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
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
|
-
#
|
|
35
|
-
# export
|
|
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
|
|
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
|
|
55
|
-
uv run agent7 -r
|
|
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
|
|
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
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
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
|
|
@@ -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
|
|
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
|
|
37
|
+
from .store import resume, resume_messages, save, timestamp
|
|
32
38
|
|
|
33
39
|
console, err = Console(stderr=False), Console(stderr=True)
|
|
34
|
-
|
|
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.
|
|
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
|
-
|
|
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
|
-
|
|
84
|
-
|
|
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
|
-
|
|
97
|
-
|
|
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.
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
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
|
-
|
|
177
|
-
|
|
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)
|
|
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
|
|
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
|
|
263
|
-
|
|
264
|
-
|
|
265
|
-
|
|
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=
|
|
272
|
-
|
|
273
|
-
|
|
274
|
-
|
|
275
|
-
p.
|
|
276
|
-
|
|
277
|
-
|
|
278
|
-
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
|
|
287
|
-
|
|
288
|
-
|
|
289
|
-
|
|
290
|
-
|
|
291
|
-
|
|
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
|
|
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=
|
|
371
|
+
client = AsyncOpenAI(api_key="missing", base_url=list_providers()[0].default_base)
|
|
344
372
|
if task:
|
|
345
|
-
|
|
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(
|
|
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(
|
|
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
|
|
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 = "
|
|
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 —
|
|
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
|
-
|
|
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:
|
|
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()
|