acptui 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.
- acptui/__init__.py +21 -0
- acptui/__main__.py +8 -0
- acptui/cli.py +183 -0
- acptui/completion.py +127 -0
- acptui/config.py +335 -0
- acptui/demo.py +937 -0
- acptui/demo_scripts.py +413 -0
- acptui/headless.py +97 -0
- acptui/log.py +25 -0
- acptui/protocol/__init__.py +4 -0
- acptui/protocol/connection.py +691 -0
- acptui/protocol/content.py +144 -0
- acptui/protocol/diff.py +163 -0
- acptui/protocol/prompt.py +141 -0
- acptui/protocol/state.py +673 -0
- acptui/py.typed +0 -0
- acptui/setup.py +64 -0
- acptui/ui/__init__.py +1 -0
- acptui/ui/agent_log.py +57 -0
- acptui/ui/app.py +158 -0
- acptui/ui/render.py +87 -0
- acptui/ui/screens/__init__.py +1 -0
- acptui/ui/screens/dialogs.py +506 -0
- acptui/ui/screens/elicitation.py +317 -0
- acptui/ui/screens/log.py +88 -0
- acptui/ui/screens/permission.py +178 -0
- acptui/ui/screens/picker.py +123 -0
- acptui/ui/screens/providers.py +165 -0
- acptui/ui/screens/session.py +863 -0
- acptui/ui/widgets/__init__.py +1 -0
- acptui/ui/widgets/blocks.py +651 -0
- acptui/ui/widgets/conversation.py +134 -0
- acptui/ui/widgets/diff.py +259 -0
- acptui/ui/widgets/prompt.py +263 -0
- acptui/ui/widgets/status.py +116 -0
- acptui/ui/widgets/terminal.py +109 -0
- acptui-0.1.0.dist-info/METADATA +183 -0
- acptui-0.1.0.dist-info/RECORD +41 -0
- acptui-0.1.0.dist-info/WHEEL +4 -0
- acptui-0.1.0.dist-info/entry_points.txt +3 -0
- acptui-0.1.0.dist-info/licenses/LICENSE +661 -0
acptui/__init__.py
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
"""acptui: main package.
|
|
2
|
+
|
|
3
|
+
Terminal UI for AI coding agents, built on ACP v2.
|
|
4
|
+
"""
|
|
5
|
+
|
|
6
|
+
from __future__ import annotations
|
|
7
|
+
|
|
8
|
+
from importlib.metadata import version
|
|
9
|
+
|
|
10
|
+
__version__ = version("acptui")
|
|
11
|
+
__title__ = "acptui"
|
|
12
|
+
|
|
13
|
+
__author__ = "Philipp Temminghoff"
|
|
14
|
+
__author_email__ = "philipptemminghoff@googlemail.com"
|
|
15
|
+
__copyright__ = "Copyright (c) 2026 Philipp Temminghoff"
|
|
16
|
+
__license__ = "AGPL-3.0-or-later"
|
|
17
|
+
__url__ = "https://github.com/phil65/acptui"
|
|
18
|
+
|
|
19
|
+
__all__ = [
|
|
20
|
+
"__version__",
|
|
21
|
+
]
|
acptui/__main__.py
ADDED
acptui/cli.py
ADDED
|
@@ -0,0 +1,183 @@
|
|
|
1
|
+
"""Command line interface: ``acptui``, ``acptui run``, ``acptui connect``, ``acptui agents``."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import argparse
|
|
6
|
+
from pathlib import Path
|
|
7
|
+
import sys
|
|
8
|
+
from typing import TYPE_CHECKING
|
|
9
|
+
|
|
10
|
+
import acptui
|
|
11
|
+
from acptui.config import ConfigError, command_spec, config_path, load_settings, url_spec
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
if TYPE_CHECKING:
|
|
15
|
+
from collections.abc import Sequence
|
|
16
|
+
|
|
17
|
+
from acptui.config import AgentSpec, Settings
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def _parser() -> argparse.ArgumentParser:
|
|
21
|
+
parser = argparse.ArgumentParser(
|
|
22
|
+
prog="acptui",
|
|
23
|
+
description="Terminal UI for AI coding agents, built on ACP v2.",
|
|
24
|
+
epilog="Without a command, acptui shows the agent picker (or starts `default_agent`).",
|
|
25
|
+
)
|
|
26
|
+
parser.add_argument("--version", action="version", version=f"acptui {acptui.__version__}")
|
|
27
|
+
parser.add_argument("--cwd", type=Path, default=None, help="working directory of the session")
|
|
28
|
+
parser.add_argument(
|
|
29
|
+
"--config", type=Path, default=None, help="config file (default: platform config dir)"
|
|
30
|
+
)
|
|
31
|
+
parser.add_argument(
|
|
32
|
+
"-o",
|
|
33
|
+
"--option",
|
|
34
|
+
action="append",
|
|
35
|
+
default=[],
|
|
36
|
+
metavar="ID=VALUE",
|
|
37
|
+
help="initial session config option, e.g. model=opus or mode=auto (repeatable)",
|
|
38
|
+
)
|
|
39
|
+
parser.add_argument(
|
|
40
|
+
"--add-dir",
|
|
41
|
+
action="append",
|
|
42
|
+
default=[],
|
|
43
|
+
metavar="DIR",
|
|
44
|
+
help="additional workspace root for the session (repeatable)",
|
|
45
|
+
)
|
|
46
|
+
parser.add_argument("--system-prompt", metavar="TEXT", help="extra system instructions")
|
|
47
|
+
parser.add_argument(
|
|
48
|
+
"--system-prompt-mode",
|
|
49
|
+
choices=["append", "override"],
|
|
50
|
+
help="append to the agent's instructions (default) or replace them",
|
|
51
|
+
)
|
|
52
|
+
sub = parser.add_subparsers(dest="command", metavar="COMMAND")
|
|
53
|
+
|
|
54
|
+
run = sub.add_parser("run", help="start an agent: a registry id or a command line")
|
|
55
|
+
run.add_argument("agent", help="agent id (see `acptui agents`) or a program")
|
|
56
|
+
run.add_argument("args", nargs=argparse.REMAINDER, help="arguments for a program")
|
|
57
|
+
run.add_argument("--resume", metavar="SESSION_ID", help="resume this session")
|
|
58
|
+
|
|
59
|
+
connect = sub.add_parser("connect", help="connect to a remote agent (http(s):// or ws(s)://)")
|
|
60
|
+
connect.add_argument("url")
|
|
61
|
+
connect.add_argument(
|
|
62
|
+
"-H",
|
|
63
|
+
"--header",
|
|
64
|
+
action="append",
|
|
65
|
+
default=[],
|
|
66
|
+
metavar="'NAME: VALUE'",
|
|
67
|
+
help="HTTP header (repeatable; ${VAR} expands from the environment)",
|
|
68
|
+
)
|
|
69
|
+
connect.add_argument("--resume", metavar="SESSION_ID", help="resume this session")
|
|
70
|
+
|
|
71
|
+
sub.add_parser("agents", help="list known agents and whether they are installed")
|
|
72
|
+
options = sub.add_parser("options", help="print the session options an agent offers")
|
|
73
|
+
options.add_argument("agent", help="agent id or program")
|
|
74
|
+
options.add_argument("args", nargs=argparse.REMAINDER, help="arguments for a program")
|
|
75
|
+
sub.add_parser("config", help="print the config file path")
|
|
76
|
+
return parser
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
def _resolve_run(settings: Settings, agent: str, args: Sequence[str]) -> AgentSpec:
|
|
80
|
+
if not args and (spec := settings.find_agent(agent)) is not None:
|
|
81
|
+
return spec
|
|
82
|
+
return command_spec([agent, *args])
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
def _headers(values: Sequence[str]) -> dict[str, str]:
|
|
86
|
+
headers: dict[str, str] = {}
|
|
87
|
+
for value in values:
|
|
88
|
+
name, sep, content = value.partition(":")
|
|
89
|
+
if not sep:
|
|
90
|
+
msg = f"invalid header {value!r}, expected 'Name: value'"
|
|
91
|
+
raise SystemExit(msg)
|
|
92
|
+
headers[name.strip()] = content.strip()
|
|
93
|
+
return headers
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
def _list_agents(settings: Settings) -> None:
|
|
97
|
+
for spec in settings.all_agents():
|
|
98
|
+
installed = "installed" if spec.available else "not found"
|
|
99
|
+
print(f"{spec.id:<12} {spec.name:<14} {installed:<10} {spec.target}")
|
|
100
|
+
|
|
101
|
+
|
|
102
|
+
def main(argv: Sequence[str] | None = None) -> None:
|
|
103
|
+
"""Entry point."""
|
|
104
|
+
options = _parser().parse_args(argv)
|
|
105
|
+
try:
|
|
106
|
+
settings = load_settings(options.config)
|
|
107
|
+
except ConfigError as exc:
|
|
108
|
+
raise SystemExit(str(exc)) from exc
|
|
109
|
+
cwd: Path = (options.cwd or Path.cwd()).resolve()
|
|
110
|
+
if not cwd.is_dir():
|
|
111
|
+
raise SystemExit(f"not a directory: {cwd}")
|
|
112
|
+
|
|
113
|
+
spec: AgentSpec | None = None
|
|
114
|
+
resume: str | None = None
|
|
115
|
+
match options.command:
|
|
116
|
+
case "agents":
|
|
117
|
+
_list_agents(settings)
|
|
118
|
+
return
|
|
119
|
+
case "config":
|
|
120
|
+
print(options.config or config_path())
|
|
121
|
+
return
|
|
122
|
+
case "options":
|
|
123
|
+
spec = _resolve_run(settings, options.agent, options.args)
|
|
124
|
+
raise SystemExit(print_options(spec, cwd))
|
|
125
|
+
case "run":
|
|
126
|
+
args = list(options.args)
|
|
127
|
+
resume = options.resume
|
|
128
|
+
if settings.find_agent(options.agent) is not None and args[:1] == ["--resume"]:
|
|
129
|
+
if len(args) != 2: # noqa: PLR2004
|
|
130
|
+
raise SystemExit("usage: acptui run AGENT --resume SESSION_ID")
|
|
131
|
+
resume, args = args[1], []
|
|
132
|
+
if args and settings.find_agent(options.agent) is not None:
|
|
133
|
+
msg = (
|
|
134
|
+
f"{options.agent!r} is a registry agent; "
|
|
135
|
+
"run a program with: acptui run -- PROGRAM ARGS"
|
|
136
|
+
)
|
|
137
|
+
raise SystemExit(msg)
|
|
138
|
+
spec = _resolve_run(settings, options.agent, args)
|
|
139
|
+
case "connect":
|
|
140
|
+
spec = url_spec(options.url, _headers(options.header))
|
|
141
|
+
resume = options.resume
|
|
142
|
+
case _:
|
|
143
|
+
if settings.default_agent is not None:
|
|
144
|
+
spec = settings.find_agent(settings.default_agent)
|
|
145
|
+
if spec is None:
|
|
146
|
+
print(f"unknown default_agent {settings.default_agent!r}", file=sys.stderr)
|
|
147
|
+
|
|
148
|
+
from acptui.setup import build_setup, parse_option
|
|
149
|
+
from acptui.ui.app import AcpTui
|
|
150
|
+
|
|
151
|
+
setup = None
|
|
152
|
+
if spec is not None:
|
|
153
|
+
try:
|
|
154
|
+
overrides = dict(parse_option(item) for item in options.option)
|
|
155
|
+
except ValueError as exc:
|
|
156
|
+
raise SystemExit(str(exc)) from exc
|
|
157
|
+
setup = build_setup(
|
|
158
|
+
settings,
|
|
159
|
+
spec,
|
|
160
|
+
options=overrides,
|
|
161
|
+
additional_directories=options.add_dir,
|
|
162
|
+
system_prompt=options.system_prompt,
|
|
163
|
+
system_prompt_mode=options.system_prompt_mode,
|
|
164
|
+
)
|
|
165
|
+
AcpTui(settings, cwd, spec, resume_id=resume, setup=setup).run()
|
|
166
|
+
|
|
167
|
+
|
|
168
|
+
def print_options(spec: AgentSpec, cwd: Path) -> int:
|
|
169
|
+
"""Print the config options and commands a new session of the agent would have."""
|
|
170
|
+
import anyio
|
|
171
|
+
|
|
172
|
+
from acptui.headless import describe_options
|
|
173
|
+
|
|
174
|
+
try:
|
|
175
|
+
print(anyio.run(describe_options, spec, cwd))
|
|
176
|
+
except Exception as exc: # noqa: BLE001 - shown to the user as an error message
|
|
177
|
+
print(f"error: {exc}", file=sys.stderr)
|
|
178
|
+
return 1
|
|
179
|
+
return 0
|
|
180
|
+
|
|
181
|
+
|
|
182
|
+
if __name__ == "__main__":
|
|
183
|
+
main()
|
acptui/completion.py
ADDED
|
@@ -0,0 +1,127 @@
|
|
|
1
|
+
"""Completions for the prompt: ``/commands`` and ``@paths``."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from dataclasses import dataclass
|
|
6
|
+
import os
|
|
7
|
+
import re
|
|
8
|
+
from typing import TYPE_CHECKING, Literal
|
|
9
|
+
|
|
10
|
+
from aclientp.schema.v2 import Command, Skill, TextCommandInput
|
|
11
|
+
from aclientp.schema.v2.base import is_set
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
if TYPE_CHECKING:
|
|
15
|
+
from collections.abc import Sequence
|
|
16
|
+
from pathlib import Path
|
|
17
|
+
|
|
18
|
+
from aclientp.schema.v2 import AvailableCommand
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
IGNORED_DIRS = frozenset({
|
|
22
|
+
".git",
|
|
23
|
+
"node_modules",
|
|
24
|
+
"__pycache__",
|
|
25
|
+
".venv",
|
|
26
|
+
".mypy_cache",
|
|
27
|
+
".ruff_cache",
|
|
28
|
+
})
|
|
29
|
+
MAX_PATH_COMPLETIONS = 50
|
|
30
|
+
|
|
31
|
+
CompletionKind = Literal["command", "path"]
|
|
32
|
+
|
|
33
|
+
_PATH_TOKEN = re.compile(r"(?:^|(?<=\s))@((?:\\ |[^\s])*)$")
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
@dataclass(frozen=True)
|
|
37
|
+
class CompletionContext:
|
|
38
|
+
"""What is being completed: the token before the cursor and where it starts."""
|
|
39
|
+
|
|
40
|
+
kind: CompletionKind
|
|
41
|
+
token: str
|
|
42
|
+
"""The text typed so far (without the ``/`` or ``@``)."""
|
|
43
|
+
|
|
44
|
+
start: int
|
|
45
|
+
"""Column of the token start (after the ``/`` or ``@``) in the cursor line."""
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
@dataclass(frozen=True)
|
|
49
|
+
class Completion:
|
|
50
|
+
"""A completion candidate."""
|
|
51
|
+
|
|
52
|
+
label: str
|
|
53
|
+
"""Text shown in the list."""
|
|
54
|
+
|
|
55
|
+
insert: str
|
|
56
|
+
"""Text that replaces the token."""
|
|
57
|
+
|
|
58
|
+
detail: str = ""
|
|
59
|
+
"""Description shown next to the label."""
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
def completion_context(line: str, row: int) -> CompletionContext | None:
|
|
63
|
+
"""The completion context for the text before the cursor in line ``row``."""
|
|
64
|
+
if row == 0 and (match := re.fullmatch(r"/(\S*)", line)):
|
|
65
|
+
return CompletionContext("command", match.group(1), 1)
|
|
66
|
+
if match := _PATH_TOKEN.search(line):
|
|
67
|
+
return CompletionContext("path", match.group(1), match.start(1))
|
|
68
|
+
return None
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
def complete_command(prefix: str, commands: Sequence[AvailableCommand]) -> list[Completion]:
|
|
72
|
+
"""Commands matching a prefix (then a substring), with their descriptions."""
|
|
73
|
+
lowered = prefix.lower()
|
|
74
|
+
starts: list[Completion] = []
|
|
75
|
+
contains: list[Completion] = []
|
|
76
|
+
for command in commands:
|
|
77
|
+
name = command.name
|
|
78
|
+
hint = ""
|
|
79
|
+
if (
|
|
80
|
+
isinstance(command, Command)
|
|
81
|
+
and is_set(command.input)
|
|
82
|
+
and isinstance(command.input, TextCommandInput)
|
|
83
|
+
):
|
|
84
|
+
hint = f" <{command.input.hint}>"
|
|
85
|
+
kind = " (skill)" if isinstance(command, Skill) else ""
|
|
86
|
+
completion = Completion(f"/{name}{hint}", f"{name} ", f"{command.description}{kind}")
|
|
87
|
+
if name.lower().startswith(lowered):
|
|
88
|
+
starts.append(completion)
|
|
89
|
+
elif lowered in name.lower():
|
|
90
|
+
contains.append(completion)
|
|
91
|
+
return starts + contains
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
def _escape(path: str) -> str:
|
|
95
|
+
return path.replace(" ", "\\ ")
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
def complete_path(token: str, cwd: Path, limit: int = MAX_PATH_COMPLETIONS) -> list[Completion]:
|
|
99
|
+
"""Files and directories inside ``cwd`` matching a partial path."""
|
|
100
|
+
raw = token.replace("\\ ", " ")
|
|
101
|
+
directory, _, name = raw.rpartition("/")
|
|
102
|
+
base = (cwd / directory).resolve() if directory else cwd.resolve()
|
|
103
|
+
if not base.is_relative_to(cwd.resolve()) or not base.is_dir():
|
|
104
|
+
return []
|
|
105
|
+
lowered = name.lower()
|
|
106
|
+
starts: list[Completion] = []
|
|
107
|
+
contains: list[Completion] = []
|
|
108
|
+
try:
|
|
109
|
+
entries = sorted(os.scandir(base), key=lambda e: (not e.is_dir(), e.name.lower()))
|
|
110
|
+
except OSError:
|
|
111
|
+
return []
|
|
112
|
+
for entry in entries:
|
|
113
|
+
if entry.name in IGNORED_DIRS or (entry.name.startswith(".") and not name.startswith(".")):
|
|
114
|
+
continue
|
|
115
|
+
is_dir = entry.is_dir()
|
|
116
|
+
relative = f"{directory}/{entry.name}" if directory else entry.name
|
|
117
|
+
insert = _escape(relative) + ("/" if is_dir else "")
|
|
118
|
+
completion = Completion(
|
|
119
|
+
relative + ("/" if is_dir else ""), insert, "directory" if is_dir else ""
|
|
120
|
+
)
|
|
121
|
+
if entry.name.lower().startswith(lowered):
|
|
122
|
+
starts.append(completion)
|
|
123
|
+
elif lowered and lowered in entry.name.lower():
|
|
124
|
+
contains.append(completion)
|
|
125
|
+
if len(starts) >= limit:
|
|
126
|
+
break
|
|
127
|
+
return (starts + contains)[:limit]
|
acptui/config.py
ADDED
|
@@ -0,0 +1,335 @@
|
|
|
1
|
+
"""Agent registry and user configuration.
|
|
2
|
+
|
|
3
|
+
The built-in registry lists well-known ACP agents. Users add their own agents (or
|
|
4
|
+
override built-in ones) in ``config.toml`` in the platform config directory::
|
|
5
|
+
|
|
6
|
+
default_agent = "codex"
|
|
7
|
+
theme = "tokyo-night"
|
|
8
|
+
diff_view = "auto" # "unified", "split" or "auto"
|
|
9
|
+
|
|
10
|
+
[agents.my-agent]
|
|
11
|
+
name = "My agent"
|
|
12
|
+
command = ["my-agent", "--acp"]
|
|
13
|
+
env = { MY_FLAG = "1" }
|
|
14
|
+
|
|
15
|
+
[agents.remote]
|
|
16
|
+
name = "Remote agent"
|
|
17
|
+
url = "https://example.com/acp"
|
|
18
|
+
headers = { "X-API-Key" = "${MY_API_KEY}" } # ${VAR} expands from the environment
|
|
19
|
+
"""
|
|
20
|
+
|
|
21
|
+
from __future__ import annotations
|
|
22
|
+
|
|
23
|
+
from collections.abc import Mapping, Sequence
|
|
24
|
+
import os
|
|
25
|
+
from pathlib import Path
|
|
26
|
+
import re
|
|
27
|
+
import shutil
|
|
28
|
+
import sys
|
|
29
|
+
import tomllib
|
|
30
|
+
from typing import Literal
|
|
31
|
+
|
|
32
|
+
from aclientp.schema.v2 import EnvVariable, HttpHeader, McpServerHttp, McpServerStdio
|
|
33
|
+
import platformdirs
|
|
34
|
+
from pydantic import BaseModel, ConfigDict, Field, ValidationError, model_validator
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
DiffViewMode = Literal["unified", "split", "auto"]
|
|
38
|
+
"""How diffs are shown: one column, side by side, or side by side when wide enough."""
|
|
39
|
+
|
|
40
|
+
_ENV_REFERENCE = re.compile(r"\$\{([A-Za-z_][A-Za-z0-9_]*)\}")
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def expand_env(value: str, environ: Mapping[str, str] | None = None) -> str:
|
|
44
|
+
"""Replace ``${NAME}`` references with environment variables (unset ones become empty)."""
|
|
45
|
+
env = os.environ if environ is None else environ
|
|
46
|
+
return _ENV_REFERENCE.sub(lambda match: env.get(match.group(1), ""), value)
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
class AgentSpec(BaseModel):
|
|
50
|
+
"""How to reach an agent: a command to launch (stdio) or a URL (HTTP / WebSocket)."""
|
|
51
|
+
|
|
52
|
+
model_config = ConfigDict(frozen=True, extra="forbid")
|
|
53
|
+
|
|
54
|
+
id: str
|
|
55
|
+
"""Short identifier, used on the command line (``acptui run <id>``)."""
|
|
56
|
+
|
|
57
|
+
name: str
|
|
58
|
+
"""Display name."""
|
|
59
|
+
|
|
60
|
+
command: tuple[str, ...] = ()
|
|
61
|
+
"""Program and arguments of a local (stdio) agent."""
|
|
62
|
+
|
|
63
|
+
url: str | None = None
|
|
64
|
+
"""URL of a remote agent (``http(s)://`` or ``ws(s)://``)."""
|
|
65
|
+
|
|
66
|
+
env: Mapping[str, str] = Field(default_factory=dict)
|
|
67
|
+
"""Extra environment variables for a local agent (``${VAR}`` is expanded)."""
|
|
68
|
+
|
|
69
|
+
headers: Mapping[str, str] = Field(default_factory=dict)
|
|
70
|
+
"""HTTP headers for a remote agent (``${VAR}`` is expanded)."""
|
|
71
|
+
|
|
72
|
+
description: str = ""
|
|
73
|
+
"""One line about the agent."""
|
|
74
|
+
|
|
75
|
+
homepage: str = ""
|
|
76
|
+
"""Where to get it."""
|
|
77
|
+
|
|
78
|
+
install: str = ""
|
|
79
|
+
"""Command that installs the agent."""
|
|
80
|
+
|
|
81
|
+
builtin: bool = False
|
|
82
|
+
"""Whether the agent comes from the built-in registry."""
|
|
83
|
+
|
|
84
|
+
options: Mapping[str, str | bool] = Field(default_factory=dict)
|
|
85
|
+
"""Initial session config options (``config_id`` -> value), e.g. ``{"model": "opus"}``."""
|
|
86
|
+
|
|
87
|
+
@model_validator(mode="after")
|
|
88
|
+
def _check_target(self) -> AgentSpec:
|
|
89
|
+
if bool(self.command) == bool(self.url):
|
|
90
|
+
msg = f"agent {self.id!r} needs exactly one of `command` and `url`"
|
|
91
|
+
raise ValueError(msg)
|
|
92
|
+
return self
|
|
93
|
+
|
|
94
|
+
@property
|
|
95
|
+
def is_remote(self) -> bool:
|
|
96
|
+
"""Whether the agent is reached over the network."""
|
|
97
|
+
return self.url is not None
|
|
98
|
+
|
|
99
|
+
@property
|
|
100
|
+
def available(self) -> bool:
|
|
101
|
+
"""Whether the agent can be started: its program is on ``PATH`` (or it is remote)."""
|
|
102
|
+
if self.url is not None:
|
|
103
|
+
return True
|
|
104
|
+
program = self.command[0]
|
|
105
|
+
return Path(program).is_file() or shutil.which(program) is not None
|
|
106
|
+
|
|
107
|
+
@property
|
|
108
|
+
def target(self) -> str:
|
|
109
|
+
"""The command line or URL, for display."""
|
|
110
|
+
return self.url if self.url is not None else " ".join(self.command)
|
|
111
|
+
|
|
112
|
+
def resolved_env(self) -> dict[str, str]:
|
|
113
|
+
"""The extra environment, with ``${VAR}`` references expanded."""
|
|
114
|
+
return {key: expand_env(value) for key, value in self.env.items()}
|
|
115
|
+
|
|
116
|
+
def resolved_headers(self) -> dict[str, str]:
|
|
117
|
+
"""The headers, with ``${VAR}`` references expanded."""
|
|
118
|
+
return {key: expand_env(value) for key, value in self.headers.items()}
|
|
119
|
+
|
|
120
|
+
|
|
121
|
+
BUILTIN_AGENTS: tuple[AgentSpec, ...] = (
|
|
122
|
+
AgentSpec(
|
|
123
|
+
id="claude",
|
|
124
|
+
name="Claude Code",
|
|
125
|
+
command=("claude-agent-acp",),
|
|
126
|
+
description="Anthropic's Claude Code via the claude-agent-acp adapter",
|
|
127
|
+
homepage="https://github.com/agentclientprotocol/claude-agent-acp",
|
|
128
|
+
install="npm install -g @agentclientprotocol/claude-agent-acp",
|
|
129
|
+
builtin=True,
|
|
130
|
+
),
|
|
131
|
+
AgentSpec(
|
|
132
|
+
id="codex",
|
|
133
|
+
name="Codex",
|
|
134
|
+
command=("codex-acp",),
|
|
135
|
+
description="OpenAI Codex via the codex-acp adapter",
|
|
136
|
+
homepage="https://github.com/agentclientprotocol/codex-acp",
|
|
137
|
+
install="npm install -g @agentclientprotocol/codex-acp",
|
|
138
|
+
builtin=True,
|
|
139
|
+
),
|
|
140
|
+
AgentSpec(
|
|
141
|
+
id="gemini",
|
|
142
|
+
name="Gemini CLI",
|
|
143
|
+
command=("gemini", "--experimental-acp"),
|
|
144
|
+
description="Google's Gemini CLI in ACP mode",
|
|
145
|
+
homepage="https://github.com/google-gemini/gemini-cli",
|
|
146
|
+
install="npm install -g @google/gemini-cli",
|
|
147
|
+
builtin=True,
|
|
148
|
+
),
|
|
149
|
+
AgentSpec(
|
|
150
|
+
id="opencode",
|
|
151
|
+
name="OpenCode",
|
|
152
|
+
command=("opencode", "acp"),
|
|
153
|
+
description="SST's OpenCode in ACP mode",
|
|
154
|
+
homepage="https://opencode.ai",
|
|
155
|
+
install="curl -fsSL https://opencode.ai/install | bash",
|
|
156
|
+
builtin=True,
|
|
157
|
+
),
|
|
158
|
+
AgentSpec(
|
|
159
|
+
id="agentpool",
|
|
160
|
+
name="AgentPool",
|
|
161
|
+
command=("agentpool", "serve-acp"),
|
|
162
|
+
description="agentpool's configurable agents served over ACP",
|
|
163
|
+
homepage="https://github.com/phil65/agentpool",
|
|
164
|
+
install="uv tool install agentpool",
|
|
165
|
+
builtin=True,
|
|
166
|
+
),
|
|
167
|
+
AgentSpec(
|
|
168
|
+
id="demo",
|
|
169
|
+
name="Demo agent",
|
|
170
|
+
command=(sys.executable, "-m", "acptui.demo"),
|
|
171
|
+
description="Scripted v2 agent bundled with acptui (no LLM, no API key)",
|
|
172
|
+
homepage="https://github.com/phil65/acptui",
|
|
173
|
+
builtin=True,
|
|
174
|
+
),
|
|
175
|
+
)
|
|
176
|
+
"""Agents acptui knows out of the box."""
|
|
177
|
+
|
|
178
|
+
|
|
179
|
+
class UserAgent(BaseModel):
|
|
180
|
+
"""An agent entry of ``config.toml`` (the table key is its id)."""
|
|
181
|
+
|
|
182
|
+
model_config = ConfigDict(extra="forbid")
|
|
183
|
+
|
|
184
|
+
name: str | None = None
|
|
185
|
+
command: str | Sequence[str] | None = None
|
|
186
|
+
url: str | None = None
|
|
187
|
+
env: dict[str, str] = Field(default_factory=dict)
|
|
188
|
+
headers: dict[str, str] = Field(default_factory=dict)
|
|
189
|
+
description: str = ""
|
|
190
|
+
options: dict[str, str | bool] = Field(default_factory=dict)
|
|
191
|
+
|
|
192
|
+
def to_spec(self, agent_id: str) -> AgentSpec:
|
|
193
|
+
"""Build the agent spec."""
|
|
194
|
+
match self.command:
|
|
195
|
+
case None:
|
|
196
|
+
command: tuple[str, ...] = ()
|
|
197
|
+
case str():
|
|
198
|
+
command = tuple(self.command.split())
|
|
199
|
+
case _:
|
|
200
|
+
command = tuple(self.command)
|
|
201
|
+
return AgentSpec(
|
|
202
|
+
id=agent_id,
|
|
203
|
+
name=self.name or agent_id,
|
|
204
|
+
command=command,
|
|
205
|
+
url=self.url,
|
|
206
|
+
env=self.env,
|
|
207
|
+
headers=self.headers,
|
|
208
|
+
description=self.description,
|
|
209
|
+
options=self.options,
|
|
210
|
+
)
|
|
211
|
+
|
|
212
|
+
|
|
213
|
+
class McpServerConfig(BaseModel):
|
|
214
|
+
"""An MCP server passed to the agent on session setup (stdio or HTTP)."""
|
|
215
|
+
|
|
216
|
+
model_config = ConfigDict(extra="forbid")
|
|
217
|
+
|
|
218
|
+
name: str
|
|
219
|
+
command: str | None = None
|
|
220
|
+
"""Program of a stdio server (resolved on ``PATH``; ACP requires an absolute path)."""
|
|
221
|
+
args: list[str] = Field(default_factory=list)
|
|
222
|
+
env: dict[str, str] = Field(default_factory=dict)
|
|
223
|
+
url: str | None = None
|
|
224
|
+
"""URL of an HTTP server."""
|
|
225
|
+
headers: dict[str, str] = Field(default_factory=dict)
|
|
226
|
+
|
|
227
|
+
@model_validator(mode="after")
|
|
228
|
+
def _check_target(self) -> McpServerConfig:
|
|
229
|
+
if bool(self.command) == bool(self.url):
|
|
230
|
+
msg = f"MCP server {self.name!r} needs exactly one of `command` and `url`"
|
|
231
|
+
raise ValueError(msg)
|
|
232
|
+
return self
|
|
233
|
+
|
|
234
|
+
def to_schema(self) -> McpServerStdio | McpServerHttp:
|
|
235
|
+
"""The ACP model (``${VAR}`` is expanded in env and header values)."""
|
|
236
|
+
if self.url is not None:
|
|
237
|
+
headers = [HttpHeader(name=k, value=expand_env(v)) for k, v in self.headers.items()]
|
|
238
|
+
return McpServerHttp(name=self.name, url=self.url, headers=headers)
|
|
239
|
+
command = self.command or ""
|
|
240
|
+
resolved = shutil.which(command) or str(Path(command).expanduser().resolve())
|
|
241
|
+
env = [EnvVariable(name=k, value=expand_env(v)) for k, v in self.env.items()]
|
|
242
|
+
return McpServerStdio(name=self.name, command=resolved, args=self.args, env=env)
|
|
243
|
+
|
|
244
|
+
|
|
245
|
+
class Settings(BaseModel):
|
|
246
|
+
"""Contents of ``config.toml``."""
|
|
247
|
+
|
|
248
|
+
model_config = ConfigDict(extra="forbid")
|
|
249
|
+
|
|
250
|
+
default_agent: str | None = None
|
|
251
|
+
"""Agent to start when ``acptui`` is run without one (instead of the picker)."""
|
|
252
|
+
|
|
253
|
+
theme: str = "textual-dark"
|
|
254
|
+
"""Textual theme name."""
|
|
255
|
+
|
|
256
|
+
diff_view: DiffViewMode = "auto"
|
|
257
|
+
"""How diffs are shown."""
|
|
258
|
+
|
|
259
|
+
expand_thoughts: bool = False
|
|
260
|
+
"""Show agent thoughts expanded instead of collapsed."""
|
|
261
|
+
|
|
262
|
+
agents: dict[str, UserAgent] = Field(default_factory=dict)
|
|
263
|
+
"""User-defined agents; an id of a built-in agent replaces it."""
|
|
264
|
+
|
|
265
|
+
agent_options: dict[str, dict[str, str | bool]] = Field(default_factory=dict)
|
|
266
|
+
"""Initial session config options per agent id (also for built-in agents)."""
|
|
267
|
+
|
|
268
|
+
mcp_servers: list[McpServerConfig] = Field(default_factory=list)
|
|
269
|
+
"""MCP servers passed to every session (if the agent supports the transport)."""
|
|
270
|
+
|
|
271
|
+
system_prompt: str | None = None
|
|
272
|
+
"""Extra system instructions for every session (if the agent supports it)."""
|
|
273
|
+
|
|
274
|
+
system_prompt_mode: Literal["append", "override"] = "append"
|
|
275
|
+
"""Append to the agent's own instructions, or replace them (if supported)."""
|
|
276
|
+
|
|
277
|
+
additional_directories: list[str] = Field(default_factory=list)
|
|
278
|
+
"""More workspace roots for every session (if the agent supports it)."""
|
|
279
|
+
|
|
280
|
+
@model_validator(mode="after")
|
|
281
|
+
def _check_agents(self) -> Settings:
|
|
282
|
+
self.all_agents() # user agents must be valid specs
|
|
283
|
+
return self
|
|
284
|
+
|
|
285
|
+
def all_agents(self) -> list[AgentSpec]:
|
|
286
|
+
"""Built-in and user agents; user agents override built-in ones with the same id."""
|
|
287
|
+
merged = {spec.id: spec for spec in BUILTIN_AGENTS}
|
|
288
|
+
for agent_id, agent in self.agents.items():
|
|
289
|
+
merged[agent_id] = agent.to_spec(agent_id)
|
|
290
|
+
for agent_id, options in self.agent_options.items():
|
|
291
|
+
if (spec := merged.get(agent_id)) is not None:
|
|
292
|
+
merged[agent_id] = spec.model_copy(update={"options": {**spec.options, **options}})
|
|
293
|
+
return list(merged.values())
|
|
294
|
+
|
|
295
|
+
def find_agent(self, agent_id: str) -> AgentSpec | None:
|
|
296
|
+
"""The agent with this id, if any."""
|
|
297
|
+
return next((spec for spec in self.all_agents() if spec.id == agent_id), None)
|
|
298
|
+
|
|
299
|
+
|
|
300
|
+
class ConfigError(Exception):
|
|
301
|
+
"""The config file could not be read."""
|
|
302
|
+
|
|
303
|
+
|
|
304
|
+
def config_path() -> Path:
|
|
305
|
+
"""Path of ``config.toml`` (``$ACPTUI_CONFIG`` overrides the platform default)."""
|
|
306
|
+
if override := os.environ.get("ACPTUI_CONFIG"):
|
|
307
|
+
return Path(override)
|
|
308
|
+
return platformdirs.user_config_path("acptui") / "config.toml"
|
|
309
|
+
|
|
310
|
+
|
|
311
|
+
def load_settings(path: Path | None = None) -> Settings:
|
|
312
|
+
"""Read the settings; a missing file gives the defaults.
|
|
313
|
+
|
|
314
|
+
Raises:
|
|
315
|
+
ConfigError: The file is not valid TOML or has invalid values.
|
|
316
|
+
"""
|
|
317
|
+
path = path or config_path()
|
|
318
|
+
if not path.is_file():
|
|
319
|
+
return Settings()
|
|
320
|
+
try:
|
|
321
|
+
data = tomllib.loads(path.read_text(encoding="utf-8"))
|
|
322
|
+
return Settings.model_validate(data)
|
|
323
|
+
except (tomllib.TOMLDecodeError, ValidationError, OSError) as exc:
|
|
324
|
+
msg = f"invalid config file {path}: {exc}"
|
|
325
|
+
raise ConfigError(msg) from exc
|
|
326
|
+
|
|
327
|
+
|
|
328
|
+
def command_spec(command: Sequence[str]) -> AgentSpec:
|
|
329
|
+
"""An ad-hoc agent spec for a command line."""
|
|
330
|
+
return AgentSpec(id=Path(command[0]).name, name=Path(command[0]).name, command=tuple(command))
|
|
331
|
+
|
|
332
|
+
|
|
333
|
+
def url_spec(url: str, headers: Mapping[str, str] | None = None) -> AgentSpec:
|
|
334
|
+
"""An ad-hoc agent spec for a remote agent."""
|
|
335
|
+
return AgentSpec(id=url, name=url, url=url, headers=dict(headers or {}))
|