sagixs 0.2.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.
- sagixs/__init__.py +3 -0
- sagixs/__main__.py +4 -0
- sagixs/agent.py +271 -0
- sagixs/cli.py +373 -0
- sagixs/config.py +91 -0
- sagixs/prompts.py +79 -0
- sagixs/providers/__init__.py +1 -0
- sagixs/providers/anthropic.py +180 -0
- sagixs/providers/base.py +119 -0
- sagixs/providers/http.py +88 -0
- sagixs/providers/local_gguf.py +112 -0
- sagixs/providers/local_transformers.py +192 -0
- sagixs/providers/openai_compat.py +178 -0
- sagixs/providers/registry.py +273 -0
- sagixs/repl.py +110 -0
- sagixs/sessions.py +37 -0
- sagixs/toolprompt.py +186 -0
- sagixs/tools/__init__.py +15 -0
- sagixs/tools/base.py +107 -0
- sagixs/tools/files.py +228 -0
- sagixs/tools/search.py +136 -0
- sagixs/tools/shell.py +95 -0
- sagixs/ui.py +121 -0
- sagixs-0.2.0.dist-info/METADATA +248 -0
- sagixs-0.2.0.dist-info/RECORD +28 -0
- sagixs-0.2.0.dist-info/WHEEL +4 -0
- sagixs-0.2.0.dist-info/entry_points.txt +2 -0
- sagixs-0.2.0.dist-info/licenses/LICENSE +17 -0
sagixs/__init__.py
ADDED
sagixs/__main__.py
ADDED
sagixs/agent.py
ADDED
|
@@ -0,0 +1,271 @@
|
|
|
1
|
+
"""The agent loop: model -> tool calls -> results -> model, until done."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import itertools
|
|
6
|
+
from pathlib import Path
|
|
7
|
+
from typing import Any, Callable
|
|
8
|
+
|
|
9
|
+
from sagixs.prompts import build_system_prompt
|
|
10
|
+
from sagixs.providers.base import Provider, ProviderError, ToolCall
|
|
11
|
+
from sagixs.toolprompt import (
|
|
12
|
+
CLOSE,
|
|
13
|
+
ToolTagFilter,
|
|
14
|
+
format_call,
|
|
15
|
+
format_result,
|
|
16
|
+
parse_tool_call,
|
|
17
|
+
render_instructions,
|
|
18
|
+
to_prompt_history,
|
|
19
|
+
)
|
|
20
|
+
from sagixs.tools.base import Tool, ToolContext, ToolError
|
|
21
|
+
|
|
22
|
+
MODES = ("readonly", "ask", "auto-edit", "yolo")
|
|
23
|
+
MAX_TOOL_RESULT_CHARS = 30_000
|
|
24
|
+
STUB = "[older tool output removed to save context]"
|
|
25
|
+
|
|
26
|
+
DECLINED = (
|
|
27
|
+
"The user declined this action. Do not retry it; ask the user how they would like to proceed."
|
|
28
|
+
)
|
|
29
|
+
READONLY = (
|
|
30
|
+
"Blocked: Sagixs is in read-only mode, so changes and commands are not allowed. "
|
|
31
|
+
"Tell the user what you would change instead."
|
|
32
|
+
)
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
class Agent:
|
|
36
|
+
def __init__(
|
|
37
|
+
self,
|
|
38
|
+
provider: Provider,
|
|
39
|
+
tools: list[Tool],
|
|
40
|
+
ui: Any,
|
|
41
|
+
*,
|
|
42
|
+
root: Path,
|
|
43
|
+
mode: str = "ask",
|
|
44
|
+
tool_mode: str = "auto",
|
|
45
|
+
max_steps: int = 25,
|
|
46
|
+
notes: str = "",
|
|
47
|
+
extra_system: str = "",
|
|
48
|
+
approve: Callable[[Tool, str], str] | None = None,
|
|
49
|
+
context_chars: int | None = None,
|
|
50
|
+
) -> None:
|
|
51
|
+
if mode not in MODES:
|
|
52
|
+
raise ValueError(f"mode must be one of {', '.join(MODES)}")
|
|
53
|
+
self.provider = provider
|
|
54
|
+
self.tools = list(tools)
|
|
55
|
+
self.by_name = {t.name: t for t in self.tools}
|
|
56
|
+
self.ui = ui
|
|
57
|
+
self.ctx = ToolContext(root=Path(root).resolve())
|
|
58
|
+
self.mode = mode
|
|
59
|
+
self.tool_mode = tool_mode
|
|
60
|
+
self.max_steps = max_steps
|
|
61
|
+
self.notes = notes
|
|
62
|
+
self.extra_system = extra_system
|
|
63
|
+
self.approve = approve or ui.confirm
|
|
64
|
+
self.context_budget = context_chars
|
|
65
|
+
self.always: set[str] = set()
|
|
66
|
+
self._ids = itertools.count(1)
|
|
67
|
+
self.native = self._wants_native()
|
|
68
|
+
self.messages: list[dict[str, Any]] = [{"role": "system", "content": self._system()}]
|
|
69
|
+
self._warned_context = False
|
|
70
|
+
|
|
71
|
+
# -- setup -------------------------------------------------------------
|
|
72
|
+
def _wants_native(self) -> bool:
|
|
73
|
+
return bool(self.tools) and self.provider.native_tools and self.tool_mode in {"auto", "native"}
|
|
74
|
+
|
|
75
|
+
def _system(self) -> str:
|
|
76
|
+
text = build_system_prompt(
|
|
77
|
+
self.ctx.root, with_tools=bool(self.tools), notes=self.notes, extra=self.extra_system
|
|
78
|
+
)
|
|
79
|
+
if self.tools and not self.native:
|
|
80
|
+
text += "\n" + render_instructions(self.tools)
|
|
81
|
+
return text
|
|
82
|
+
|
|
83
|
+
def _refresh_system(self) -> None:
|
|
84
|
+
self.messages[0] = {"role": "system", "content": self._system()}
|
|
85
|
+
|
|
86
|
+
def reset(self) -> None:
|
|
87
|
+
self.messages = [{"role": "system", "content": self._system()}]
|
|
88
|
+
|
|
89
|
+
def set_provider(self, provider: Provider, tool_mode: str) -> None:
|
|
90
|
+
was_native = self.native
|
|
91
|
+
self.provider = provider
|
|
92
|
+
self.tool_mode = tool_mode
|
|
93
|
+
self.native = self._wants_native()
|
|
94
|
+
if was_native and not self.native:
|
|
95
|
+
self.messages = to_prompt_history(self.messages)
|
|
96
|
+
self._refresh_system()
|
|
97
|
+
|
|
98
|
+
def load_history(self, messages: list[dict[str, Any]]) -> None:
|
|
99
|
+
body = [m for m in messages if m.get("role") != "system"]
|
|
100
|
+
if not self.native:
|
|
101
|
+
body = to_prompt_history(body)
|
|
102
|
+
self.messages = [self.messages[0], *body]
|
|
103
|
+
|
|
104
|
+
# -- one user turn -----------------------------------------------------
|
|
105
|
+
def run_turn(self, user_text: str) -> str:
|
|
106
|
+
"""Run the loop for one user message. Returns the final assistant text."""
|
|
107
|
+
self.messages.append({"role": "user", "content": user_text})
|
|
108
|
+
safe = len(self.messages) # history is valid up to here if we are interrupted
|
|
109
|
+
final = ""
|
|
110
|
+
try:
|
|
111
|
+
for _step in range(self.max_steps):
|
|
112
|
+
text, calls, problem = self._complete()
|
|
113
|
+
if problem:
|
|
114
|
+
self.messages.append({"role": "assistant", "content": text})
|
|
115
|
+
self.messages.append({"role": "user", "content": problem})
|
|
116
|
+
self.ui.warn("The model wrote a malformed tool call; asking it to retry.")
|
|
117
|
+
elif not calls:
|
|
118
|
+
self.messages.append({"role": "assistant", "content": text})
|
|
119
|
+
final = text
|
|
120
|
+
safe = len(self.messages)
|
|
121
|
+
break
|
|
122
|
+
elif self.native:
|
|
123
|
+
self.messages.append(
|
|
124
|
+
{
|
|
125
|
+
"role": "assistant",
|
|
126
|
+
"content": text,
|
|
127
|
+
"tool_calls": [
|
|
128
|
+
{
|
|
129
|
+
"id": c.id,
|
|
130
|
+
"type": "function",
|
|
131
|
+
"function": {"name": c.name, "arguments": c.arguments or "{}"},
|
|
132
|
+
}
|
|
133
|
+
for c in calls
|
|
134
|
+
],
|
|
135
|
+
}
|
|
136
|
+
)
|
|
137
|
+
results = [(c, self._run_tool(c)) for c in calls]
|
|
138
|
+
for call, result in results:
|
|
139
|
+
self.messages.append(
|
|
140
|
+
{"role": "tool", "tool_call_id": call.id, "content": result}
|
|
141
|
+
)
|
|
142
|
+
else:
|
|
143
|
+
call = calls[0]
|
|
144
|
+
shown = (text + "\n" if text else "") + format_call(call.name, call.parsed())
|
|
145
|
+
self.messages.append({"role": "assistant", "content": shown})
|
|
146
|
+
result = self._run_tool(call)
|
|
147
|
+
self.messages.append(
|
|
148
|
+
{"role": "user", "content": format_result(call.name, result)}
|
|
149
|
+
)
|
|
150
|
+
safe = len(self.messages)
|
|
151
|
+
else:
|
|
152
|
+
self.ui.warn(
|
|
153
|
+
f"Stopped after {self.max_steps} steps. Say 'continue' to keep going."
|
|
154
|
+
)
|
|
155
|
+
except KeyboardInterrupt:
|
|
156
|
+
del self.messages[safe:]
|
|
157
|
+
self.ui.end_text()
|
|
158
|
+
self.ui.warn("Interrupted. Any changes already made to files are kept.")
|
|
159
|
+
return ""
|
|
160
|
+
return final
|
|
161
|
+
|
|
162
|
+
# -- model call --------------------------------------------------------
|
|
163
|
+
def _complete(self) -> tuple[str, list[ToolCall], str | None]:
|
|
164
|
+
self._trim()
|
|
165
|
+
try:
|
|
166
|
+
return self._complete_once()
|
|
167
|
+
except ProviderError as exc:
|
|
168
|
+
lowered = str(exc).lower()
|
|
169
|
+
if (
|
|
170
|
+
self.native
|
|
171
|
+
and self.tool_mode == "auto"
|
|
172
|
+
and exc.status in (400, 404, 422)
|
|
173
|
+
and ("tool" in lowered or "function" in lowered)
|
|
174
|
+
):
|
|
175
|
+
self.ui.info("This model/API rejected native tool calling; switching to text tool calls.")
|
|
176
|
+
self.tool_mode = "prompt"
|
|
177
|
+
self.native = False
|
|
178
|
+
self.messages = to_prompt_history(self.messages)
|
|
179
|
+
self._refresh_system()
|
|
180
|
+
return self._complete_once()
|
|
181
|
+
raise
|
|
182
|
+
|
|
183
|
+
def _complete_once(self) -> tuple[str, list[ToolCall], str | None]:
|
|
184
|
+
if self.native:
|
|
185
|
+
schema = [t.schema() for t in self.tools]
|
|
186
|
+
turn = self.provider.complete(self.messages, schema, on_text=self.ui.text)
|
|
187
|
+
self.ui.end_text()
|
|
188
|
+
return turn.text, turn.tool_calls, None
|
|
189
|
+
if not self.tools:
|
|
190
|
+
turn = self.provider.complete(self.messages, None, on_text=self.ui.text)
|
|
191
|
+
self.ui.end_text()
|
|
192
|
+
return turn.text, [], None
|
|
193
|
+
shield = ToolTagFilter(self.ui.text)
|
|
194
|
+
turn = self.provider.complete(self.messages, None, on_text=shield.feed, stop=[CLOSE])
|
|
195
|
+
shield.flush()
|
|
196
|
+
self.ui.end_text()
|
|
197
|
+
visible, call, problem = parse_tool_call(turn.text, lambda: f"call_{next(self._ids)}")
|
|
198
|
+
if call is None and problem is None:
|
|
199
|
+
return turn.text, [], None
|
|
200
|
+
if problem is not None:
|
|
201
|
+
return turn.text.split("<tool_result")[0], [], problem
|
|
202
|
+
return visible, [call], None
|
|
203
|
+
|
|
204
|
+
# -- tools -------------------------------------------------------------
|
|
205
|
+
def _run_tool(self, call: ToolCall) -> str:
|
|
206
|
+
tool = self.by_name.get(call.name)
|
|
207
|
+
if tool is None:
|
|
208
|
+
return f"Error: there is no tool named '{call.name}'. Available: {', '.join(self.by_name)}."
|
|
209
|
+
try:
|
|
210
|
+
args = call.parsed()
|
|
211
|
+
except ValueError as exc:
|
|
212
|
+
return f"Error: could not read the arguments for {call.name}: {exc}."
|
|
213
|
+
required = [r for r in tool.parameters.get("required", []) if r not in args]
|
|
214
|
+
if required:
|
|
215
|
+
return f"Error: {call.name} is missing required argument(s): {', '.join(required)}."
|
|
216
|
+
self.ui.tool_start(tool, args)
|
|
217
|
+
decision = self._permission(tool, args)
|
|
218
|
+
if decision == "readonly":
|
|
219
|
+
result = READONLY
|
|
220
|
+
elif decision == "no":
|
|
221
|
+
result = DECLINED
|
|
222
|
+
else:
|
|
223
|
+
try:
|
|
224
|
+
result = tool.run(args, self.ctx)
|
|
225
|
+
except ToolError as exc:
|
|
226
|
+
result = f"Error: {exc}"
|
|
227
|
+
except (KeyboardInterrupt, SystemExit):
|
|
228
|
+
raise
|
|
229
|
+
except Exception as exc: # a tool bug must not kill the session
|
|
230
|
+
result = f"Error: {type(exc).__name__}: {exc}"
|
|
231
|
+
if len(result) > MAX_TOOL_RESULT_CHARS:
|
|
232
|
+
result = result[: MAX_TOOL_RESULT_CHARS // 2] + "\n... [truncated] ...\n" + result[-MAX_TOOL_RESULT_CHARS // 2 :]
|
|
233
|
+
self.ui.tool_result(result)
|
|
234
|
+
return result
|
|
235
|
+
|
|
236
|
+
def _permission(self, tool: Tool, args: dict[str, Any]) -> str:
|
|
237
|
+
if tool.permission == "read" or self.mode == "yolo":
|
|
238
|
+
return "yes"
|
|
239
|
+
if self.mode == "readonly":
|
|
240
|
+
return "readonly"
|
|
241
|
+
if self.mode == "auto-edit" and tool.permission == "edit":
|
|
242
|
+
return "yes"
|
|
243
|
+
if tool.name in self.always:
|
|
244
|
+
return "yes"
|
|
245
|
+
answer = self.approve(tool, tool.preview(args, self.ctx))
|
|
246
|
+
if answer == "always":
|
|
247
|
+
self.always.add(tool.name)
|
|
248
|
+
return "yes"
|
|
249
|
+
return "yes" if answer == "yes" else "no"
|
|
250
|
+
|
|
251
|
+
# -- context budget ----------------------------------------------------
|
|
252
|
+
def _size(self) -> int:
|
|
253
|
+
return sum(len(m.get("content") or "") for m in self.messages)
|
|
254
|
+
|
|
255
|
+
def _trim(self) -> None:
|
|
256
|
+
budget = self.context_budget or self.provider.context_chars
|
|
257
|
+
if self._size() <= budget:
|
|
258
|
+
return
|
|
259
|
+
protected = len(self.messages) - 4
|
|
260
|
+
for i, m in enumerate(self.messages):
|
|
261
|
+
if i >= protected or self._size() <= budget:
|
|
262
|
+
break
|
|
263
|
+
content = m.get("content") or ""
|
|
264
|
+
is_result = m.get("role") == "tool" or (
|
|
265
|
+
m.get("role") == "user" and content.startswith("<tool_result")
|
|
266
|
+
)
|
|
267
|
+
if is_result and len(content) > 300:
|
|
268
|
+
self.messages[i] = {**m, "content": STUB}
|
|
269
|
+
if self._size() > budget and not self._warned_context:
|
|
270
|
+
self._warned_context = True
|
|
271
|
+
self.ui.warn("The conversation is getting long for this model; use /clear if answers degrade.")
|
sagixs/cli.py
ADDED
|
@@ -0,0 +1,373 @@
|
|
|
1
|
+
"""Command-line interface."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import argparse
|
|
6
|
+
import getpass
|
|
7
|
+
import importlib.util
|
|
8
|
+
import json
|
|
9
|
+
import os
|
|
10
|
+
import shutil
|
|
11
|
+
import sys
|
|
12
|
+
from pathlib import Path
|
|
13
|
+
from typing import Any
|
|
14
|
+
|
|
15
|
+
from sagixs import __version__
|
|
16
|
+
from sagixs.agent import MODES, Agent
|
|
17
|
+
from sagixs.config import (
|
|
18
|
+
DEFAULTS,
|
|
19
|
+
config_path,
|
|
20
|
+
credentials_path,
|
|
21
|
+
load_config,
|
|
22
|
+
load_credentials,
|
|
23
|
+
save_config,
|
|
24
|
+
save_credentials,
|
|
25
|
+
)
|
|
26
|
+
from sagixs.prompts import load_project_notes
|
|
27
|
+
from sagixs.providers.base import ProviderError
|
|
28
|
+
from sagixs.providers.registry import (
|
|
29
|
+
PRESETS,
|
|
30
|
+
build_provider,
|
|
31
|
+
canonical,
|
|
32
|
+
find_key,
|
|
33
|
+
resolve_spec,
|
|
34
|
+
)
|
|
35
|
+
from sagixs.repl import run_repl
|
|
36
|
+
from sagixs.sessions import load_session
|
|
37
|
+
from sagixs.tools import default_tools
|
|
38
|
+
from sagixs.ui import UI
|
|
39
|
+
|
|
40
|
+
COMMANDS = {"providers", "models", "config", "auth", "doctor"}
|
|
41
|
+
|
|
42
|
+
INT_KEYS = {"max_tokens", "max_steps", "n_ctx", "n_gpu_layers"}
|
|
43
|
+
FLOAT_KEYS = {"temperature", "timeout"}
|
|
44
|
+
CONFIG_KEYS = [
|
|
45
|
+
"provider", "model", "base_url", "mode", "tool_mode", "max_steps", "temperature",
|
|
46
|
+
"max_tokens", "timeout", "system_prompt", "device", "dtype", "n_ctx", "n_gpu_layers",
|
|
47
|
+
] # fmt: skip
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
# ---------------------------------------------------------------- parsers
|
|
51
|
+
def build_agent_parser() -> argparse.ArgumentParser:
|
|
52
|
+
p = argparse.ArgumentParser(
|
|
53
|
+
prog="sagixs",
|
|
54
|
+
description="Sagixs In Terminal - an AI agent for your terminal that works with any "
|
|
55
|
+
"model API or a local Hugging Face model.",
|
|
56
|
+
epilog="Other commands: sagixs providers | models | config | auth | doctor",
|
|
57
|
+
)
|
|
58
|
+
p.add_argument("prompt", nargs="*", help="Optional first message.")
|
|
59
|
+
p.add_argument("--version", action="version", version=f"Sagixs {__version__}")
|
|
60
|
+
p.add_argument("-p", "--print", action="store_true", help="Run once, print the answer, and exit (piped stdin is appended to the prompt).")
|
|
61
|
+
p.add_argument("--provider", help="Provider name (see `sagixs providers`).")
|
|
62
|
+
p.add_argument("-m", "--model", help="Model name, or provider:model.")
|
|
63
|
+
p.add_argument("--base-url", help="Override the API base URL (OpenAI-compatible).")
|
|
64
|
+
p.add_argument("--api-key", help="API key. Visible in shell history; prefer env vars or `sagixs auth set`.")
|
|
65
|
+
p.add_argument("--mode", choices=MODES, help="Permission mode (default: ask).")
|
|
66
|
+
p.add_argument("-y", "--yes", action="store_true", help="Allow every tool call without asking (same as --mode yolo).")
|
|
67
|
+
p.add_argument("--no-tools", action="store_true", help="Plain chat with no file or shell access.")
|
|
68
|
+
p.add_argument("--tool-mode", choices=["auto", "native", "prompt"], help="How tool calls are made: native API field, or text protocol (default: auto).")
|
|
69
|
+
p.add_argument("-c", "--continue", dest="continue_session", action="store_true", help="Continue the last conversation in this directory.")
|
|
70
|
+
p.add_argument("--cwd", help="Working directory (default: current).")
|
|
71
|
+
p.add_argument("--max-steps", type=int, help="Tool-use steps per message (default 25).")
|
|
72
|
+
p.add_argument("--temperature", type=float)
|
|
73
|
+
p.add_argument("--max-tokens", type=int)
|
|
74
|
+
p.add_argument("--system-prompt", help="Extra instructions appended to the system prompt.")
|
|
75
|
+
p.add_argument("--device", help="Local transformers: cpu, cuda, mps or auto.")
|
|
76
|
+
p.add_argument("--dtype", help="Local transformers: auto, float16, bfloat16, float32.")
|
|
77
|
+
p.add_argument("--n-ctx", type=int, help="GGUF: context window in tokens.")
|
|
78
|
+
p.add_argument("--n-gpu-layers", type=int, help="GGUF: layers to offload to the GPU.")
|
|
79
|
+
p.add_argument("--trust-remote-code", action="store_true", help="Local transformers: allow the model repo to run its own code.")
|
|
80
|
+
return p
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
def build_command_parser() -> argparse.ArgumentParser:
|
|
84
|
+
parser = argparse.ArgumentParser(prog="sagixs")
|
|
85
|
+
sub = parser.add_subparsers(dest="command", required=True)
|
|
86
|
+
|
|
87
|
+
sub.add_parser("providers", help="List providers and whether a key is set.")
|
|
88
|
+
|
|
89
|
+
models = sub.add_parser("models", help="List the models a provider offers.")
|
|
90
|
+
models.add_argument("--provider")
|
|
91
|
+
models.add_argument("--base-url")
|
|
92
|
+
models.add_argument("--filter", help="Only show ids containing this text.")
|
|
93
|
+
|
|
94
|
+
config = sub.add_parser("config", help="View or change configuration.")
|
|
95
|
+
csub = config.add_subparsers(dest="config_command", required=True)
|
|
96
|
+
csub.add_parser("show", help="Show configuration (no secrets).")
|
|
97
|
+
csub.add_parser("path", help="Print the config file path.")
|
|
98
|
+
cset = csub.add_parser("set", help="Set a value.")
|
|
99
|
+
cset.add_argument("key", choices=CONFIG_KEYS)
|
|
100
|
+
cset.add_argument("value")
|
|
101
|
+
add = csub.add_parser("add-provider", help="Register your own OpenAI-compatible endpoint.")
|
|
102
|
+
add.add_argument("name")
|
|
103
|
+
add.add_argument("--base-url", required=True)
|
|
104
|
+
add.add_argument("--api-key-env", help="Environment variable holding the key.")
|
|
105
|
+
add.add_argument("--model", help="Default model.")
|
|
106
|
+
add.add_argument("--tool-mode", choices=["auto", "native", "prompt"])
|
|
107
|
+
rm = csub.add_parser("remove-provider", help="Remove a registered provider.")
|
|
108
|
+
rm.add_argument("name")
|
|
109
|
+
|
|
110
|
+
auth = sub.add_parser("auth", help="Store API keys (in a private file) so you don't have to export them.")
|
|
111
|
+
asub = auth.add_subparsers(dest="auth_command", required=True)
|
|
112
|
+
aset = asub.add_parser("set", help="Save a key (prompts without echo).")
|
|
113
|
+
aset.add_argument("provider")
|
|
114
|
+
asub.add_parser("list", help="Show which providers have keys.")
|
|
115
|
+
arm = asub.add_parser("remove", help="Delete a saved key.")
|
|
116
|
+
arm.add_argument("provider")
|
|
117
|
+
|
|
118
|
+
sub.add_parser("doctor", help="Check the environment.")
|
|
119
|
+
return parser
|
|
120
|
+
|
|
121
|
+
|
|
122
|
+
# ---------------------------------------------------------------- settings
|
|
123
|
+
def settings_from(config: dict[str, Any], args: argparse.Namespace) -> dict[str, Any]:
|
|
124
|
+
s = dict(config)
|
|
125
|
+
for key in ("provider", "model", "temperature", "max_tokens", "tool_mode", "mode",
|
|
126
|
+
"max_steps", "device", "dtype", "n_ctx", "n_gpu_layers"): # fmt: skip
|
|
127
|
+
value = getattr(args, key, None)
|
|
128
|
+
if value is not None:
|
|
129
|
+
s[key] = value
|
|
130
|
+
s["base_url_override"] = getattr(args, "base_url", None) or ""
|
|
131
|
+
if getattr(args, "trust_remote_code", False):
|
|
132
|
+
s["trust_remote_code"] = True
|
|
133
|
+
return s
|
|
134
|
+
|
|
135
|
+
|
|
136
|
+
# ---------------------------------------------------------------- run the agent
|
|
137
|
+
def run_agent(args: argparse.Namespace) -> int:
|
|
138
|
+
ui = UI(print_mode=args.print)
|
|
139
|
+
try:
|
|
140
|
+
config = load_config()
|
|
141
|
+
except RuntimeError as exc:
|
|
142
|
+
ui.error(str(exc))
|
|
143
|
+
return 2
|
|
144
|
+
settings = settings_from(config, args)
|
|
145
|
+
root = Path(args.cwd).expanduser().resolve() if args.cwd else Path.cwd()
|
|
146
|
+
if not root.is_dir():
|
|
147
|
+
ui.error(f"Working directory not found: {root}")
|
|
148
|
+
return 2
|
|
149
|
+
|
|
150
|
+
def rebuild(provider: str | None, model: str | None):
|
|
151
|
+
s = dict(settings)
|
|
152
|
+
if provider:
|
|
153
|
+
s["provider"] = provider
|
|
154
|
+
if not model:
|
|
155
|
+
s["model"] = ""
|
|
156
|
+
if model:
|
|
157
|
+
s["model"] = model
|
|
158
|
+
prov, tool_mode = build_provider(s, args.api_key)
|
|
159
|
+
name, resolved_model, _spec = resolve_spec(s)
|
|
160
|
+
settings.update(s)
|
|
161
|
+
return prov, tool_mode, name, resolved_model
|
|
162
|
+
|
|
163
|
+
try:
|
|
164
|
+
provider, default_tool_mode, pname, pmodel = rebuild(None, None)
|
|
165
|
+
except (ProviderError, RuntimeError) as exc:
|
|
166
|
+
ui.error(f"{exc}")
|
|
167
|
+
return 2
|
|
168
|
+
|
|
169
|
+
mode = "yolo" if args.yes else str(settings.get("mode") or "ask")
|
|
170
|
+
if mode not in MODES:
|
|
171
|
+
ui.error(f"Invalid mode '{mode}'. Use one of: {', '.join(MODES)}.")
|
|
172
|
+
return 2
|
|
173
|
+
tools = [] if args.no_tools else default_tools()
|
|
174
|
+
agent = Agent(
|
|
175
|
+
provider,
|
|
176
|
+
tools,
|
|
177
|
+
ui,
|
|
178
|
+
root=root,
|
|
179
|
+
mode=mode,
|
|
180
|
+
tool_mode=default_tool_mode,
|
|
181
|
+
max_steps=int(settings.get("max_steps") or 25),
|
|
182
|
+
notes=load_project_notes(root),
|
|
183
|
+
extra_system=args.system_prompt or str(settings.get("system_prompt") or ""),
|
|
184
|
+
)
|
|
185
|
+
if args.continue_session:
|
|
186
|
+
history = load_session(root)
|
|
187
|
+
if history:
|
|
188
|
+
agent.load_history(history)
|
|
189
|
+
ui.info(f"Continuing previous conversation ({len(history)} messages).")
|
|
190
|
+
|
|
191
|
+
prompt = " ".join(args.prompt).strip()
|
|
192
|
+
if args.print:
|
|
193
|
+
if not sys.stdin.isatty(): # piped input is appended to the prompt, if there is one
|
|
194
|
+
try:
|
|
195
|
+
piped = sys.stdin.read().strip()
|
|
196
|
+
except (OSError, ValueError): # stdin closed or unreadable
|
|
197
|
+
piped = ""
|
|
198
|
+
if piped:
|
|
199
|
+
prompt = f"{prompt}\n\n{piped}" if prompt else piped
|
|
200
|
+
if not prompt:
|
|
201
|
+
ui.error("Nothing to do: give a prompt, or pipe one in on stdin.")
|
|
202
|
+
return 2
|
|
203
|
+
try:
|
|
204
|
+
agent.run_turn(prompt)
|
|
205
|
+
except ProviderError as exc:
|
|
206
|
+
ui.end_text()
|
|
207
|
+
ui.error(f"Model error: {exc}")
|
|
208
|
+
return 1
|
|
209
|
+
return 0
|
|
210
|
+
|
|
211
|
+
return run_repl(agent, ui, rebuild, provider_name=pname, model=pmodel, initial=prompt)
|
|
212
|
+
|
|
213
|
+
|
|
214
|
+
# ---------------------------------------------------------------- management commands
|
|
215
|
+
def cmd_providers() -> int:
|
|
216
|
+
print(f"{'PROVIDER':<13}{'KEY':<32}ABOUT")
|
|
217
|
+
config = load_config()
|
|
218
|
+
names = dict(PRESETS)
|
|
219
|
+
for name, spec in (config.get("providers") or {}).items():
|
|
220
|
+
names[canonical(name)] = {**spec, "about": "user-defined"}
|
|
221
|
+
for name in sorted(names):
|
|
222
|
+
spec = names[name]
|
|
223
|
+
envs = spec.get("key_env") or ([spec["api_key_env"]] if spec.get("api_key_env") else [])
|
|
224
|
+
if spec.get("type") in {"transformers", "gguf"} or (not envs and spec.get("base_url")):
|
|
225
|
+
status = "not needed"
|
|
226
|
+
else:
|
|
227
|
+
key, source = find_key(name, list(envs))
|
|
228
|
+
status = f"set ({source})" if key else f"missing ({envs[0] if envs else 'n/a'})"
|
|
229
|
+
print(f"{name:<13}{status:<32}{spec.get('about', '')}")
|
|
230
|
+
print("\nUse with: sagixs --provider NAME --model MODEL (or --model NAME:MODEL)")
|
|
231
|
+
return 0
|
|
232
|
+
|
|
233
|
+
|
|
234
|
+
def cmd_models(args: argparse.Namespace) -> int:
|
|
235
|
+
ns = argparse.Namespace(provider=args.provider, base_url=args.base_url, model=None)
|
|
236
|
+
settings = settings_from(load_config(), ns)
|
|
237
|
+
settings.setdefault("model", "")
|
|
238
|
+
try:
|
|
239
|
+
name, _model, spec = resolve_spec(settings)
|
|
240
|
+
if spec.get("type") in {"transformers", "gguf"}:
|
|
241
|
+
print("Local providers take any Hugging Face repo id or a local path; there is no list.")
|
|
242
|
+
return 0
|
|
243
|
+
settings["model"] = settings.get("model") or "list" # model not needed to list
|
|
244
|
+
provider, _ = build_provider(settings)
|
|
245
|
+
ids = provider.list_models()
|
|
246
|
+
except (ProviderError, RuntimeError) as exc:
|
|
247
|
+
print(f"Error: {exc}", file=sys.stderr)
|
|
248
|
+
return 1
|
|
249
|
+
if args.filter:
|
|
250
|
+
ids = [i for i in ids if args.filter.lower() in i.lower()]
|
|
251
|
+
print("\n".join(ids) if ids else "No models found.")
|
|
252
|
+
return 0
|
|
253
|
+
|
|
254
|
+
|
|
255
|
+
def _coerce(key: str, value: str) -> Any:
|
|
256
|
+
if key in INT_KEYS:
|
|
257
|
+
return None if value.lower() in {"none", "default", ""} else int(value)
|
|
258
|
+
if key in FLOAT_KEYS:
|
|
259
|
+
return None if value.lower() in {"none", "default", ""} else float(value)
|
|
260
|
+
return value
|
|
261
|
+
|
|
262
|
+
|
|
263
|
+
def cmd_config(args: argparse.Namespace) -> int:
|
|
264
|
+
if args.config_command == "path":
|
|
265
|
+
print(config_path())
|
|
266
|
+
return 0
|
|
267
|
+
config = load_config()
|
|
268
|
+
if args.config_command == "show":
|
|
269
|
+
shown = {k: v for k, v in config.items() if v not in ("", None, {}) or k in {"provider"}}
|
|
270
|
+
print(json.dumps(shown or DEFAULTS, indent=2))
|
|
271
|
+
return 0
|
|
272
|
+
if args.config_command == "set":
|
|
273
|
+
try:
|
|
274
|
+
config[args.key] = _coerce(args.key, args.value)
|
|
275
|
+
except ValueError:
|
|
276
|
+
print(f"Error: {args.key} needs a number.", file=sys.stderr)
|
|
277
|
+
return 2
|
|
278
|
+
if args.key == "mode" and args.value not in MODES:
|
|
279
|
+
print(f"Error: mode must be one of {', '.join(MODES)}.", file=sys.stderr)
|
|
280
|
+
return 2
|
|
281
|
+
elif args.config_command == "add-provider":
|
|
282
|
+
entry = {"base_url": args.base_url}
|
|
283
|
+
if args.api_key_env:
|
|
284
|
+
entry["api_key_env"] = args.api_key_env
|
|
285
|
+
if args.model:
|
|
286
|
+
entry["model"] = args.model
|
|
287
|
+
if args.tool_mode:
|
|
288
|
+
entry["tool_mode"] = args.tool_mode
|
|
289
|
+
config.setdefault("providers", {})[args.name.lower()] = entry
|
|
290
|
+
print(f"Added provider '{args.name.lower()}'. Use: sagixs --provider {args.name.lower()}")
|
|
291
|
+
elif args.config_command == "remove-provider":
|
|
292
|
+
if (config.get("providers") or {}).pop(args.name.lower(), None) is None:
|
|
293
|
+
print(f"No user-defined provider named '{args.name}'.", file=sys.stderr)
|
|
294
|
+
return 1
|
|
295
|
+
print(f"Saved {save_config(config)}")
|
|
296
|
+
return 0
|
|
297
|
+
|
|
298
|
+
|
|
299
|
+
def cmd_auth(args: argparse.Namespace) -> int:
|
|
300
|
+
creds = load_credentials()
|
|
301
|
+
if args.auth_command == "list":
|
|
302
|
+
for name in sorted(PRESETS):
|
|
303
|
+
envs = PRESETS[name].get("key_env") or []
|
|
304
|
+
if not envs:
|
|
305
|
+
continue
|
|
306
|
+
key, source = find_key(name, list(envs))
|
|
307
|
+
print(f"{name:<13}{'set (' + source + ')' if key else 'not set'}")
|
|
308
|
+
return 0
|
|
309
|
+
name = canonical(args.provider)
|
|
310
|
+
if args.auth_command == "remove":
|
|
311
|
+
if creds.pop(name, None) is None:
|
|
312
|
+
print(f"No saved key for '{name}'.", file=sys.stderr)
|
|
313
|
+
return 1
|
|
314
|
+
else:
|
|
315
|
+
key = getpass.getpass(f"API key for {name} (input hidden): ").strip()
|
|
316
|
+
if not key:
|
|
317
|
+
print("No key entered.", file=sys.stderr)
|
|
318
|
+
return 1
|
|
319
|
+
creds[name] = key
|
|
320
|
+
save_credentials(creds)
|
|
321
|
+
print(f"Updated {credentials_path()} (owner-only permissions).")
|
|
322
|
+
return 0
|
|
323
|
+
|
|
324
|
+
|
|
325
|
+
def cmd_doctor() -> int:
|
|
326
|
+
print(f"Sagixs {__version__} Python {sys.version.split()[0]} {sys.platform}")
|
|
327
|
+
print(f"Config: {config_path()} ({'found' if config_path().exists() else 'not created yet'})")
|
|
328
|
+
print(f"Credentials: {credentials_path()} ({'found' if credentials_path().exists() else 'none'})")
|
|
329
|
+
for tool in ("git", "rg"):
|
|
330
|
+
print(f"{tool:<12} {'found' if shutil.which(tool) else 'not found'}")
|
|
331
|
+
print("Optional packages for local models:")
|
|
332
|
+
for module, label in (("torch", "torch"), ("transformers", "transformers"),
|
|
333
|
+
("accelerate", "accelerate"), ("llama_cpp", "llama-cpp-python")): # fmt: skip
|
|
334
|
+
found = importlib.util.find_spec(module) is not None
|
|
335
|
+
print(f" {label:<18}{'installed' if found else 'not installed'}")
|
|
336
|
+
notes = [n for n in ("SAGIXS.md", "AGENTS.md", "CLAUDE.md") if (Path.cwd() / n).is_file()]
|
|
337
|
+
print(f"Project notes in this folder: {', '.join(notes) or 'none'}")
|
|
338
|
+
print("Run `sagixs providers` to see which API keys are set.")
|
|
339
|
+
return 0
|
|
340
|
+
|
|
341
|
+
|
|
342
|
+
def main(argv: list[str] | None = None) -> None:
|
|
343
|
+
argv = sys.argv[1:] if argv is None else list(argv)
|
|
344
|
+
if argv and argv[0] in COMMANDS:
|
|
345
|
+
args = build_command_parser().parse_args(argv)
|
|
346
|
+
try:
|
|
347
|
+
code = _run_command(args)
|
|
348
|
+
except BrokenPipeError: # e.g. `sagixs models | head`
|
|
349
|
+
os.dup2(os.open(os.devnull, os.O_WRONLY), sys.stdout.fileno())
|
|
350
|
+
code = 0
|
|
351
|
+
sys.exit(code)
|
|
352
|
+
if argv and argv[0] == "chat": # kept for 0.1.x compatibility
|
|
353
|
+
argv = argv[1:]
|
|
354
|
+
args = build_agent_parser().parse_args(argv)
|
|
355
|
+
try:
|
|
356
|
+
sys.exit(run_agent(args))
|
|
357
|
+
except KeyboardInterrupt:
|
|
358
|
+
print()
|
|
359
|
+
sys.exit(130)
|
|
360
|
+
|
|
361
|
+
|
|
362
|
+
def _run_command(args: argparse.Namespace) -> int:
|
|
363
|
+
return {
|
|
364
|
+
"providers": lambda: cmd_providers(),
|
|
365
|
+
"models": lambda: cmd_models(args),
|
|
366
|
+
"config": lambda: cmd_config(args),
|
|
367
|
+
"auth": lambda: cmd_auth(args),
|
|
368
|
+
"doctor": lambda: cmd_doctor(),
|
|
369
|
+
}[args.command]()
|
|
370
|
+
|
|
371
|
+
|
|
372
|
+
if __name__ == "__main__":
|
|
373
|
+
main()
|