saicode 0.3.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.
saicode/__init__.py ADDED
@@ -0,0 +1,3 @@
1
+ """saicode - a terminal coding agent."""
2
+
3
+ __version__ = "0.3.0"
saicode/__main__.py ADDED
@@ -0,0 +1,4 @@
1
+ from saicode.cli.main import main
2
+
3
+ if __name__ == "__main__":
4
+ main()
saicode/ai/__init__.py ADDED
@@ -0,0 +1,46 @@
1
+ """Model providers behind one interface, with an administrator allowlist."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from saicode.ai.base import Provider, ProviderError
6
+ from saicode.core.config import Config
7
+ from saicode.core.credentials import get_api_key
8
+
9
+ KNOWN_PROVIDERS = ("gemini",)
10
+
11
+
12
+ class ProviderNotAllowed(Exception):
13
+ pass
14
+
15
+
16
+ class MissingCredentials(Exception):
17
+ pass
18
+
19
+
20
+ def create_provider(config: Config) -> Provider:
21
+ name = config.get("model.provider", "gemini")
22
+ allowed = config.get("providers.allowed", [])
23
+ if name not in allowed:
24
+ raise ProviderNotAllowed(
25
+ f"Provider '{name}' is not allowed by your configuration "
26
+ f"(allowed: {', '.join(allowed) or 'none'})."
27
+ )
28
+ if name not in KNOWN_PROVIDERS:
29
+ raise ProviderNotAllowed(f"Provider '{name}' is not supported yet.")
30
+ key, _source = get_api_key(name)
31
+ if not key:
32
+ raise MissingCredentials(name)
33
+ if name == "gemini":
34
+ from saicode.ai.gemini import GeminiProvider
35
+
36
+ return GeminiProvider(key)
37
+ raise ProviderNotAllowed(name)
38
+
39
+
40
+ __all__ = [
41
+ "MissingCredentials",
42
+ "Provider",
43
+ "ProviderError",
44
+ "ProviderNotAllowed",
45
+ "create_provider",
46
+ ]
saicode/ai/base.py ADDED
@@ -0,0 +1,82 @@
1
+ """Provider interface. The core only talks to these types, never to a vendor SDK."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from dataclasses import dataclass, field
6
+ from typing import Any, Protocol
7
+
8
+
9
+ @dataclass
10
+ class ToolSpec:
11
+ name: str
12
+ description: str
13
+ parameters: dict[str, Any] # JSON Schema object
14
+
15
+
16
+ @dataclass
17
+ class ToolCall:
18
+ name: str
19
+ args: dict[str, Any]
20
+ id: str | None = None
21
+
22
+
23
+ @dataclass
24
+ class ToolResult:
25
+ call: ToolCall
26
+ output: str
27
+
28
+
29
+ @dataclass
30
+ class Usage:
31
+ input_tokens: int = 0
32
+ output_tokens: int = 0
33
+
34
+
35
+ @dataclass
36
+ class Reply:
37
+ text: str = ""
38
+ tool_calls: list[ToolCall] = field(default_factory=list)
39
+ usage: Usage = field(default_factory=Usage)
40
+
41
+
42
+ class ProviderError(Exception):
43
+ """A provider failure, translated into kinds the core understands.
44
+
45
+ kind: "quota" | "auth" | "permission" | "not_found" | "server" | "network" | "other"
46
+ """
47
+
48
+ def __init__(
49
+ self,
50
+ kind: str,
51
+ message: str,
52
+ *,
53
+ retry_after: int | None = None,
54
+ free_tier: bool = False,
55
+ no_quota: bool = False,
56
+ daily: bool = False,
57
+ code: int | None = None,
58
+ ):
59
+ super().__init__(message)
60
+ self.kind = kind
61
+ self.message = message
62
+ self.retry_after = retry_after
63
+ self.free_tier = free_tier
64
+ self.no_quota = no_quota
65
+ self.daily = daily
66
+ self.code = code
67
+
68
+
69
+ class ChatSession(Protocol):
70
+ def send(self, message: str) -> Reply: ...
71
+ def send_tool_results(self, results: list[ToolResult]) -> Reply: ...
72
+ def history(self) -> Any: ...
73
+
74
+
75
+ class Provider(Protocol):
76
+ name: str
77
+
78
+ def start_chat(
79
+ self, model: str, system: str, tools: list[ToolSpec], history: Any = None
80
+ ) -> ChatSession: ...
81
+ def list_models(self) -> list[str]: ...
82
+ def check_model(self, model: str) -> None: ...
saicode/ai/gemini.py ADDED
@@ -0,0 +1,144 @@
1
+ """Gemini provider (Google AI Studio API key)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import re
6
+ from typing import Any
7
+
8
+ from google import genai
9
+ from google.genai import errors, types
10
+
11
+ from saicode.ai.base import ProviderError, Reply, ToolCall, ToolResult, ToolSpec, Usage
12
+
13
+
14
+ def _retry_delay(e: errors.APIError) -> int | None:
15
+ try:
16
+ details = (e.details or {}).get("error", {}).get("details", [])
17
+ for d in details:
18
+ if "retryDelay" in d:
19
+ return int(float(str(d["retryDelay"]).rstrip("s")))
20
+ except Exception:
21
+ pass
22
+ m = re.search(r"retry in ([\d.]+)s", e.message or "")
23
+ return int(float(m.group(1))) if m else None
24
+
25
+
26
+ def translate(e: Exception) -> ProviderError:
27
+ if isinstance(e, errors.APIError):
28
+ msg = e.message or str(e)
29
+ code = e.code
30
+ if code == 429:
31
+ return ProviderError(
32
+ "quota",
33
+ msg,
34
+ code=code,
35
+ retry_after=_retry_delay(e),
36
+ free_tier="free_tier" in msg,
37
+ no_quota="limit: 0" in msg,
38
+ daily="per day" in msg.lower() or "PerDay" in str(e.details),
39
+ )
40
+ if code == 400 and "API key" in msg:
41
+ return ProviderError("auth", msg, code=code)
42
+ if code in (401,):
43
+ return ProviderError("auth", msg, code=code)
44
+ if code == 403:
45
+ return ProviderError("permission", msg, code=code)
46
+ if code == 404:
47
+ return ProviderError("not_found", msg, code=code)
48
+ if code and code >= 500:
49
+ return ProviderError("server", msg, code=code)
50
+ return ProviderError("other", msg, code=code)
51
+ return ProviderError("network", f"{type(e).__name__}: {e}")
52
+
53
+
54
+ def _reply(resp: Any) -> Reply:
55
+ text = ""
56
+ try:
57
+ parts = resp.candidates[0].content.parts or []
58
+ text = "".join(
59
+ p.text for p in parts if getattr(p, "text", None) and not getattr(p, "thought", False)
60
+ )
61
+ except (AttributeError, IndexError, TypeError):
62
+ pass
63
+ calls = [
64
+ ToolCall(name=c.name, args=dict(c.args or {}), id=getattr(c, "id", None))
65
+ for c in (resp.function_calls or [])
66
+ ]
67
+ usage = Usage()
68
+ if getattr(resp, "usage_metadata", None):
69
+ usage = Usage(
70
+ resp.usage_metadata.prompt_token_count or 0,
71
+ resp.usage_metadata.candidates_token_count or 0,
72
+ )
73
+ return Reply(text=text, tool_calls=calls, usage=usage)
74
+
75
+
76
+ class GeminiChat:
77
+ def __init__(self, chat: Any):
78
+ self._chat = chat
79
+
80
+ def send(self, message: str) -> Reply:
81
+ try:
82
+ return _reply(self._chat.send_message(message))
83
+ except Exception as e:
84
+ raise translate(e) from e
85
+
86
+ def send_tool_results(self, results: list[ToolResult]) -> Reply:
87
+ parts = [
88
+ types.Part.from_function_response(name=r.call.name, response={"result": r.output})
89
+ for r in results
90
+ ]
91
+ try:
92
+ return _reply(self._chat.send_message(parts))
93
+ except Exception as e:
94
+ raise translate(e) from e
95
+
96
+ def history(self) -> Any:
97
+ return self._chat.get_history()
98
+
99
+
100
+ class GeminiProvider:
101
+ name = "gemini"
102
+
103
+ def __init__(self, api_key: str):
104
+ # Preview models (e.g. gemini-3.1-pro-preview) are served on v1beta.
105
+ self.client = genai.Client(
106
+ api_key=api_key, http_options=types.HttpOptions(api_version="v1beta")
107
+ )
108
+
109
+ def start_chat(
110
+ self, model: str, system: str, tools: list[ToolSpec], history: Any = None
111
+ ) -> GeminiChat:
112
+ decls = [
113
+ types.FunctionDeclaration(
114
+ name=t.name, description=t.description, parameters_json_schema=t.parameters
115
+ )
116
+ for t in tools
117
+ ]
118
+ chat = self.client.chats.create(
119
+ model=model,
120
+ history=history or [],
121
+ config=types.GenerateContentConfig(
122
+ system_instruction=system,
123
+ tools=[types.Tool(function_declarations=decls)],
124
+ automatic_function_calling=types.AutomaticFunctionCallingConfig(disable=True),
125
+ ),
126
+ )
127
+ return GeminiChat(chat)
128
+
129
+ def list_models(self) -> list[str]:
130
+ try:
131
+ names = [
132
+ m.name.replace("models/", "")
133
+ for m in self.client.models.list()
134
+ if m.name and "generateContent" in (m.supported_actions or [])
135
+ ]
136
+ except Exception as e:
137
+ raise translate(e) from e
138
+ return sorted(names, reverse=True)
139
+
140
+ def check_model(self, model: str) -> None:
141
+ try:
142
+ self.client.models.get(model=model)
143
+ except Exception as e:
144
+ raise translate(e) from e
@@ -0,0 +1 @@
1
+ """Command line entry points."""
saicode/cli/main.py ADDED
@@ -0,0 +1,181 @@
1
+ """Command line entry point: `saicode`, `saicode login`, `saicode logout`, `saicode config`."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import argparse
6
+ import getpass
7
+ import sys
8
+ from pathlib import Path
9
+
10
+ from saicode import __version__
11
+
12
+
13
+ def _fail(title: str, body: str) -> None:
14
+ from rich.markup import escape
15
+
16
+ from saicode.tui.app import ERR, notice
17
+
18
+ # Bodies include error text and paths, so they are printed literally, not as markup.
19
+ notice(title, escape(body), ERR)
20
+ sys.exit(1)
21
+
22
+
23
+ def cmd_login(provider: str) -> None:
24
+ from saicode.core.credentials import store_api_key
25
+ from saicode.tui.app import OK, console
26
+
27
+ key = getpass.getpass(f"Paste your {provider} API key (input is hidden): ").strip()
28
+ if not key:
29
+ _fail("No key entered", "Nothing was saved.")
30
+ try:
31
+ store_api_key(provider, key)
32
+ except Exception as e:
33
+ _fail(
34
+ "Could not save the key",
35
+ f"{e}\n\nYou can set it as an environment variable instead, for example in ~/.zshrc:\n"
36
+ f' export GEMINI_API_KEY="..."',
37
+ )
38
+ console.print(f"[{OK}]Saved.[/] Your {provider} key is in the system keychain.")
39
+
40
+
41
+ def cmd_logout(provider: str) -> None:
42
+ from saicode.core.credentials import delete_api_key
43
+ from saicode.tui.app import console
44
+
45
+ removed = delete_api_key(provider)
46
+ console.print("Removed the key from the keychain." if removed else "No stored key was found.")
47
+
48
+
49
+ def cmd_config(workdir: Path) -> None:
50
+ from rich.markup import escape
51
+
52
+ from saicode.core.config import ConfigError, load_config
53
+ from saicode.tui.app import console
54
+
55
+ try:
56
+ config = load_config(workdir)
57
+ except ConfigError as e:
58
+ _fail("Configuration error", str(e))
59
+ for key, value, source in config.flat():
60
+ lock = " (locked)" if config.is_locked(key) else ""
61
+ console.print(f"{escape(key)} = {escape(repr(value))} [grey50]# {source}{lock}[/]")
62
+
63
+
64
+ def run_interactive(workdir: Path, model_override: str | None) -> None:
65
+ from saicode.ai import MissingCredentials, ProviderNotAllowed, create_provider
66
+ from saicode.core.agent import Agent
67
+ from saicode.core.config import ConfigError, load_config
68
+ from saicode.core.credentials import get_api_key
69
+ from saicode.core.events import EventBus, SessionLog, session_metadata
70
+ from saicode.core.policy import Policy
71
+ from saicode.sandbox import create_runner
72
+ from saicode.tools import ToolContext
73
+ from saicode.tui.app import App, Renderer, approver
74
+
75
+ try:
76
+ config = load_config(workdir)
77
+ except ConfigError as e:
78
+ _fail("Configuration error", str(e))
79
+
80
+ if model_override:
81
+ if config.is_locked("model.name"):
82
+ _fail(
83
+ "Model is set by your organization",
84
+ f"Your organization's policy fixes the model to {config.get('model.name')}.",
85
+ )
86
+ config.data["model"]["name"] = model_override
87
+
88
+ try:
89
+ provider = create_provider(config)
90
+ except MissingCredentials as e:
91
+ _fail(
92
+ "API key missing",
93
+ f"No {e} API key was found.\n\nStore one securely with:\n saicode login\n\n"
94
+ "or set an environment variable, for example GEMINI_API_KEY.",
95
+ )
96
+ except ProviderNotAllowed as e:
97
+ _fail("Provider not allowed", str(e))
98
+
99
+ try:
100
+ runner = create_runner(config.get("sandbox.mode", "off"))
101
+ except ValueError as e:
102
+ _fail("Sandbox not available", str(e))
103
+
104
+ _, key_source = get_api_key(provider.name)
105
+ email = config.get("identity.email", "")
106
+ bus = EventBus(user=email or getpass.getuser())
107
+ log = None
108
+ if config.get("logging.sessions", True):
109
+ log = SessionLog(
110
+ Path(config.get("logging.dir")),
111
+ bus.session_id,
112
+ bool(config.get("logging.include_content", False)),
113
+ )
114
+ bus.subscribe(log)
115
+ bus.subscribe(Renderer())
116
+
117
+ policy = Policy(config, workdir)
118
+ ctx = ToolContext(workdir=workdir, policy=policy, runner=runner, approver=approver)
119
+ model = config.get("model.name")
120
+ agent = Agent(
121
+ provider=provider,
122
+ model=model,
123
+ bus=bus,
124
+ ctx=ctx,
125
+ max_steps=int(config.get("ui.max_tool_steps", 40)),
126
+ )
127
+
128
+ bus.emit(
129
+ "session_start",
130
+ **session_metadata(
131
+ workdir,
132
+ model,
133
+ provider.name,
134
+ [f"{layer.name}:{layer.path}" if layer.path else layer.name for layer in config.layers],
135
+ email,
136
+ ),
137
+ )
138
+ app = App(
139
+ config=config,
140
+ provider=provider,
141
+ agent=agent,
142
+ bus=bus,
143
+ policy=policy,
144
+ log=log,
145
+ key_source=key_source,
146
+ workdir=workdir,
147
+ runner_name=runner.name,
148
+ )
149
+ try:
150
+ app.run()
151
+ finally:
152
+ bus.emit("session_end", tokens_in=agent.tokens_in, tokens_out=agent.tokens_out)
153
+ if log:
154
+ log.close()
155
+
156
+
157
+ def main(argv: list[str] | None = None) -> None:
158
+ parser = argparse.ArgumentParser(prog="saicode", description="saicode - terminal coding agent")
159
+ parser.add_argument("--version", action="version", version=f"saicode {__version__}")
160
+ parser.add_argument("--model", help="model to use for this session")
161
+ sub = parser.add_subparsers(dest="command")
162
+ p_login = sub.add_parser("login", help="store an API key in the system keychain")
163
+ p_login.add_argument("provider", nargs="?", default="gemini")
164
+ p_logout = sub.add_parser("logout", help="remove a stored API key")
165
+ p_logout.add_argument("provider", nargs="?", default="gemini")
166
+ sub.add_parser("config", help="show effective settings and where each comes from")
167
+ args = parser.parse_args(argv)
168
+
169
+ workdir = Path.cwd().resolve()
170
+ if args.command == "login":
171
+ cmd_login(args.provider)
172
+ elif args.command == "logout":
173
+ cmd_logout(args.provider)
174
+ elif args.command == "config":
175
+ cmd_config(workdir)
176
+ else:
177
+ run_interactive(workdir, args.model)
178
+
179
+
180
+ if __name__ == "__main__":
181
+ main()
@@ -0,0 +1,4 @@
1
+ """The saicode core: config, policy, events, credentials and the agent loop.
2
+
3
+ Rule: nothing in this package imports saicode.tui.
4
+ """
saicode/core/agent.py ADDED
@@ -0,0 +1,166 @@
1
+ """The agent loop. Knows nothing about the screen: it only emits events.
2
+
3
+ Event types emitted:
4
+ session_start, user_message, thinking, assistant_message, tool_call,
5
+ running, tool_result, waiting, error, cancelled, turn_end, model_switched,
6
+ conversation_reset, step_limit
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import functools
12
+ import time
13
+ from collections.abc import Callable
14
+ from dataclasses import dataclass, field
15
+ from pathlib import Path
16
+ from typing import Any
17
+
18
+ from saicode import tools
19
+ from saicode.ai.base import Provider, ProviderError, Reply, ToolResult
20
+ from saicode.core.events import EventBus, new_id
21
+
22
+ MAX_AUTO_WAIT = 90
23
+ SERVER_RETRIES = 3
24
+
25
+ ErrorHandler = Callable[[ProviderError], str | None] # return "retry" to try again
26
+
27
+
28
+ def system_prompt(workdir: Path) -> str:
29
+ return (
30
+ f"You are saicode, a coding agent working in the project folder: {workdir}\n"
31
+ "Use the tools to inspect files before changing them. Prefer edit_file for small "
32
+ "changes and write_file for new files. Run tests or commands to verify your work.\n"
33
+ "Some files and commands are blocked by policy; if a tool says 'Not allowed', do not "
34
+ "try to work around it, tell the user instead.\n"
35
+ "Be concise and professional. Use Markdown. Summarize what you changed at the end."
36
+ )
37
+
38
+
39
+ @dataclass
40
+ class Agent:
41
+ provider: Provider
42
+ model: str
43
+ bus: EventBus
44
+ ctx: tools.ToolContext
45
+ max_steps: int = 40
46
+ on_error: ErrorHandler = lambda e: None
47
+ sleep: Callable[[float], None] = time.sleep
48
+ tokens_in: int = 0
49
+ tokens_out: int = 0
50
+ chat: Any = field(default=None, init=False)
51
+
52
+ def __post_init__(self) -> None:
53
+ self.ctx.on_running = self._on_running
54
+ self.chat = self._new_chat()
55
+
56
+ def _on_running(self, command: str) -> None:
57
+ self.bus.emit("running", command=command)
58
+
59
+ def _send_tool_results(self, results: list[ToolResult]) -> Reply:
60
+ # self.chat is looked up on every call: after a quota error the retry
61
+ # may run on a switched (fallback) model with a new chat.
62
+ return self.chat.send_tool_results(results)
63
+
64
+ def _new_chat(self, history: Any = None):
65
+ return self.provider.start_chat(
66
+ self.model, system_prompt(self.ctx.workdir), tools.specs(), history
67
+ )
68
+
69
+ # ---- session control ----------------------------------------------------
70
+
71
+ def switch_model(self, name: str, keep_history: bool = True) -> None:
72
+ history = self.chat.history() if keep_history else None
73
+ old = self.model
74
+ self.model = name
75
+ self.chat = self._new_chat(history)
76
+ self.bus.emit("model_switched", old=old, new=name)
77
+
78
+ def reset(self) -> None:
79
+ self.chat = self._new_chat()
80
+ self.tokens_in = self.tokens_out = 0
81
+ self.bus.emit("conversation_reset")
82
+
83
+ # ---- the loop ------------------------------------------------------------
84
+
85
+ def _send(self, fn: Callable[[], Reply]) -> Reply | None:
86
+ server_tries = 0
87
+ while True:
88
+ self.bus.emit("thinking", model=self.model)
89
+ try:
90
+ return fn()
91
+ except KeyboardInterrupt:
92
+ self.bus.emit("cancelled")
93
+ return None
94
+ except ProviderError as e:
95
+ if (
96
+ e.kind == "quota"
97
+ and not e.no_quota
98
+ and not e.daily
99
+ and e.retry_after is not None
100
+ and e.retry_after <= MAX_AUTO_WAIT
101
+ ):
102
+ self.bus.emit("waiting", seconds=e.retry_after, reason="rate limit")
103
+ self.sleep(e.retry_after + 1)
104
+ continue
105
+ if e.kind == "server" and server_tries < SERVER_RETRIES:
106
+ server_tries += 1
107
+ wait = 2**server_tries
108
+ self.bus.emit("waiting", seconds=wait, reason="the model service is busy")
109
+ self.sleep(wait)
110
+ continue
111
+ self.bus.emit(
112
+ "error", kind=e.kind, code=e.code, message=e.message[:500], model=self.model
113
+ )
114
+ if self.on_error(e) == "retry":
115
+ continue
116
+ return None
117
+
118
+ def run_turn(self, message: str) -> None:
119
+ self.bus.turn_id = new_id("turn")
120
+ self.bus.emit("user_message", text=message)
121
+ reply = self._send(lambda: self.chat.send(message))
122
+ steps = 0
123
+ while reply is not None:
124
+ self.tokens_in += reply.usage.input_tokens
125
+ self.tokens_out += reply.usage.output_tokens
126
+ if reply.text.strip():
127
+ self.bus.emit("assistant_message", text=reply.text)
128
+ if not reply.tool_calls:
129
+ self.bus.emit("turn_end", tokens_in=self.tokens_in, tokens_out=self.tokens_out)
130
+ break
131
+ steps += 1
132
+ if steps > self.max_steps:
133
+ self.bus.emit("step_limit", limit=self.max_steps)
134
+ break
135
+ results = []
136
+ for call in reply.tool_calls:
137
+ action, target = tools.describe(call.name, call.args)
138
+ evt = self.bus.emit(
139
+ "tool_call",
140
+ tool=call.name,
141
+ action=action,
142
+ target=target,
143
+ args={
144
+ k: v
145
+ for k, v in call.args.items()
146
+ if k not in ("content", "old_text", "new_text")
147
+ },
148
+ )
149
+ try:
150
+ outcome = tools.execute(self.ctx, call.name, call.args)
151
+ except KeyboardInterrupt:
152
+ outcome = tools.ToolOutcome(
153
+ "The user cancelled this action.", "cancelled", "denied"
154
+ )
155
+ self.bus.emit(
156
+ "tool_result",
157
+ parent_id=evt.id,
158
+ tool=call.name,
159
+ status=outcome.status,
160
+ summary=outcome.summary,
161
+ output=outcome.output,
162
+ content=outcome.content,
163
+ )
164
+ results.append(ToolResult(call, outcome.output))
165
+ reply = self._send(functools.partial(self._send_tool_results, results))
166
+ self.bus.turn_id = None