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/core/config.py ADDED
@@ -0,0 +1,253 @@
1
+ """Layered configuration.
2
+
3
+ Layers are merged in this order (later wins):
4
+
5
+ 1. built-in defaults
6
+ 2. user config ~/.saicode/config.toml
7
+ 3. project config <project>/.saicode/config.toml
8
+ 4. system policy set by an administrator, always wins (locked)
9
+
10
+ Security lists (``permissions.deny`` and ``permissions.deny_read``) are
11
+ *unioned* across every layer, so no layer can remove a rule another added.
12
+
13
+ A project config comes from the repository, so it is untrusted: its
14
+ ``permissions.allow`` rules are ignored unless the user config sets
15
+ ``trust_project_permissions = true`` and the system policy does not forbid it.
16
+ It can never change logging, identity or the provider allowlist (PROJECT_NEVER).
17
+ """
18
+
19
+ from __future__ import annotations
20
+
21
+ import copy
22
+ import os
23
+ import sys
24
+ import tomllib
25
+ from dataclasses import dataclass, field
26
+ from pathlib import Path
27
+ from typing import Any
28
+
29
+ UNION_KEYS = {("permissions", "deny"), ("permissions", "deny_read")}
30
+
31
+ # Settings a project config (which comes from the repository) can never change.
32
+ PROJECT_NEVER: dict[str, tuple[str, ...]] = {
33
+ "logging": ("sessions", "dir", "include_content"),
34
+ "identity": ("email",),
35
+ "providers": ("allowed",),
36
+ }
37
+
38
+ DEFAULTS: dict[str, Any] = {
39
+ "model": {
40
+ "provider": "gemini",
41
+ "name": "gemini-3.1-pro-preview",
42
+ "fallbacks": ["gemini-3-flash-preview", "gemini-3.1-flash-lite", "gemini-2.5-flash"],
43
+ },
44
+ "providers": {
45
+ # Providers saicode may talk to. An administrator can narrow this list.
46
+ "allowed": ["gemini"],
47
+ },
48
+ "permissions": {
49
+ # "ask" - ask before file changes and commands (default)
50
+ # "read-only" - deny every file change and command
51
+ "mode": "ask",
52
+ # Rules: "run:<command glob>", "write:<path glob>", "read:<path glob>"
53
+ "allow": [],
54
+ "deny": [
55
+ "run:rm -rf /*",
56
+ "run:rm -rf ~*",
57
+ "run:sudo *",
58
+ "run:* | sh",
59
+ "run:* | bash",
60
+ ],
61
+ # Files the agent may never read, write or touch in a command.
62
+ "deny_read": [
63
+ ".env",
64
+ ".env.*",
65
+ "**/.env",
66
+ "**/.env.*",
67
+ "**/*.pem",
68
+ "**/*.key",
69
+ "**/id_rsa*",
70
+ "**/id_ed25519*",
71
+ "**/.ssh/**",
72
+ "**/secrets/**",
73
+ "**/credentials*",
74
+ "**/.aws/**",
75
+ "**/.npmrc",
76
+ "**/.pypirc",
77
+ ],
78
+ "allow_always": True, # may the user choose "always allow" for a session?
79
+ "trust_project_permissions": False,
80
+ },
81
+ "sandbox": {
82
+ # "off" until the sandbox ships in phase A2.
83
+ "mode": "off",
84
+ # If true, commands are refused whenever no sandbox is available.
85
+ "required": False,
86
+ },
87
+ "logging": {
88
+ "sessions": True,
89
+ "dir": "~/.saicode/sessions",
90
+ # Full file contents and command output in the log. Off by default for privacy.
91
+ "include_content": False,
92
+ },
93
+ "identity": {
94
+ # Optional: who is using saicode, recorded in every event.
95
+ "email": "",
96
+ },
97
+ "ui": {
98
+ "max_tool_steps": 40,
99
+ },
100
+ }
101
+
102
+
103
+ def system_policy_path() -> Path:
104
+ override = os.environ.get("SAICODE_SYSTEM_POLICY")
105
+ if override:
106
+ return Path(override)
107
+ platform: str = sys.platform
108
+ if platform == "darwin":
109
+ return Path("/Library/Application Support/saicode/policy.toml")
110
+ if platform.startswith("win"):
111
+ base = os.environ.get("PROGRAMDATA", r"C:\ProgramData")
112
+ return Path(base) / "saicode" / "policy.toml"
113
+ return Path("/etc/saicode/policy.toml")
114
+
115
+
116
+ def user_config_path() -> Path:
117
+ override = os.environ.get("SAICODE_USER_CONFIG")
118
+ if override:
119
+ return Path(override)
120
+ return Path.home() / ".saicode" / "config.toml"
121
+
122
+
123
+ def project_config_path(workdir: Path) -> Path:
124
+ return workdir / ".saicode" / "config.toml"
125
+
126
+
127
+ class ConfigError(Exception):
128
+ pass
129
+
130
+
131
+ @dataclass
132
+ class Layer:
133
+ name: str
134
+ path: Path | None
135
+ data: dict[str, Any]
136
+
137
+
138
+ @dataclass
139
+ class Config:
140
+ data: dict[str, Any]
141
+ layers: list[Layer] = field(default_factory=list)
142
+ sources: dict[str, str] = field(default_factory=dict) # "a.b" -> layer name
143
+ locked: set[str] = field(default_factory=set) # keys set by system policy
144
+
145
+ def get(self, dotted: str, default: Any = None) -> Any:
146
+ node: Any = self.data
147
+ for part in dotted.split("."):
148
+ if not isinstance(node, dict) or part not in node:
149
+ return default
150
+ node = node[part]
151
+ return node
152
+
153
+ def is_locked(self, dotted: str) -> bool:
154
+ return any(dotted == k or dotted.startswith(k + ".") for k in self.locked)
155
+
156
+ def flat(self) -> list[tuple[str, Any, str]]:
157
+ rows: list[tuple[str, Any, str]] = []
158
+
159
+ def walk(prefix: str, node: Any) -> None:
160
+ if isinstance(node, dict):
161
+ for k, v in node.items():
162
+ walk(f"{prefix}.{k}" if prefix else k, v)
163
+ else:
164
+ rows.append((prefix, node, self.sources.get(prefix, "default")))
165
+
166
+ walk("", self.data)
167
+ return rows
168
+
169
+
170
+ def _read_toml(path: Path) -> dict[str, Any]:
171
+ if not path.is_file():
172
+ return {}
173
+ try:
174
+ with path.open("rb") as f:
175
+ return tomllib.load(f)
176
+ except (tomllib.TOMLDecodeError, OSError) as e:
177
+ raise ConfigError(f"Could not read {path}: {e}") from e
178
+
179
+
180
+ def _merge(base: dict, over: dict, layer: str, sources: dict, prefix: tuple = ()) -> None:
181
+ for key, value in over.items():
182
+ path = (*prefix, key)
183
+ dotted = ".".join(path)
184
+ if isinstance(value, dict) and isinstance(base.get(key), dict):
185
+ _merge(base[key], value, layer, sources, path)
186
+ continue
187
+ if path in UNION_KEYS and isinstance(value, list):
188
+ existing = base.get(key) or []
189
+ base[key] = existing + [v for v in value if v not in existing]
190
+ else:
191
+ base[key] = copy.deepcopy(value)
192
+ sources[dotted] = layer
193
+
194
+
195
+ def _keys(node: dict, prefix: str = "") -> set[str]:
196
+ out: set[str] = set()
197
+ for k, v in node.items():
198
+ dotted = f"{prefix}.{k}" if prefix else k
199
+ if isinstance(v, dict):
200
+ out |= _keys(v, dotted)
201
+ else:
202
+ out.add(dotted)
203
+ return out
204
+
205
+
206
+ def load_config(workdir: Path) -> Config:
207
+ data = copy.deepcopy(DEFAULTS)
208
+ sources: dict[str, str] = {}
209
+ layers: list[Layer] = [Layer("default", None, copy.deepcopy(DEFAULTS))]
210
+
211
+ user_path = user_config_path()
212
+ user = _read_toml(user_path)
213
+ project_path = project_config_path(workdir)
214
+ project = _read_toml(project_path)
215
+ system_path = system_policy_path()
216
+ system = _read_toml(system_path)
217
+
218
+ trust_project = bool(
219
+ system.get("permissions", {}).get(
220
+ "trust_project_permissions",
221
+ user.get("permissions", {}).get("trust_project_permissions", False),
222
+ )
223
+ )
224
+ if project:
225
+ # A repository may never redirect or switch off the audit log, change who the
226
+ # user is, or widen the provider list.
227
+ for section, keys in PROJECT_NEVER.items():
228
+ node = project.get(section)
229
+ if isinstance(node, dict):
230
+ for key in keys:
231
+ node.pop(key, None)
232
+ perms = project.get("permissions")
233
+ if isinstance(perms, dict):
234
+ perms.pop("trust_project_permissions", None) # a repo cannot trust itself
235
+ if not trust_project:
236
+ perms.pop("allow", None)
237
+ perms.pop("mode", None) # a repo cannot loosen the permission mode
238
+ perms.pop("allow_always", None)
239
+
240
+ for name, path, layer in (
241
+ ("user", user_path, user),
242
+ ("project", project_path, project),
243
+ ("system", system_path, system),
244
+ ):
245
+ if layer:
246
+ _merge(data, layer, name, sources)
247
+ layers.append(Layer(name, path, layer))
248
+
249
+ # System policy can replace the user's allow list outright.
250
+ if system.get("permissions", {}).get("allow") is not None:
251
+ data["permissions"]["allow"] = list(system["permissions"]["allow"])
252
+
253
+ return Config(data=data, layers=layers, sources=sources, locked=_keys(system))
@@ -0,0 +1,60 @@
1
+ """API keys: environment variable first, then the OS keychain.
2
+
3
+ On macOS the keychain is the login Keychain, on Windows the Credential
4
+ Manager, on Linux the Secret Service (if available). Keys are never written
5
+ to saicode's own config files.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import os
11
+
12
+ SERVICE = "saicode"
13
+
14
+ ENV_VARS = {
15
+ "gemini": ["GEMINI_API_KEY", "GOOGLE_API_KEY"],
16
+ }
17
+
18
+
19
+ def _keyring():
20
+ try:
21
+ import keyring
22
+
23
+ return keyring
24
+ except Exception:
25
+ return None
26
+
27
+
28
+ def get_api_key(provider: str) -> tuple[str | None, str]:
29
+ """Return (key, where it came from)."""
30
+ for var in ENV_VARS.get(provider, [f"{provider.upper()}_API_KEY"]):
31
+ value = os.environ.get(var)
32
+ if value:
33
+ return value, f"environment variable {var}"
34
+ kr = _keyring()
35
+ if kr is not None:
36
+ try:
37
+ value = kr.get_password(SERVICE, provider)
38
+ except Exception:
39
+ value = None
40
+ if value:
41
+ return value, "system keychain"
42
+ return None, ""
43
+
44
+
45
+ def store_api_key(provider: str, key: str) -> None:
46
+ kr = _keyring()
47
+ if kr is None:
48
+ raise RuntimeError("No system keychain is available on this computer.")
49
+ kr.set_password(SERVICE, provider, key)
50
+
51
+
52
+ def delete_api_key(provider: str) -> bool:
53
+ kr = _keyring()
54
+ if kr is None:
55
+ return False
56
+ try:
57
+ kr.delete_password(SERVICE, provider)
58
+ return True
59
+ except Exception:
60
+ return False
saicode/core/events.py ADDED
@@ -0,0 +1,117 @@
1
+ """Events: everything the agent does is an event with stable IDs.
2
+
3
+ The UI subscribes to events to draw the screen. The session log writes them
4
+ to disk. Later, saicode Server can receive the same events for central audit.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import getpass
10
+ import json
11
+ import socket
12
+ import uuid
13
+ from collections.abc import Callable
14
+ from dataclasses import asdict, dataclass, field
15
+ from datetime import UTC, datetime
16
+ from pathlib import Path
17
+ from typing import Any
18
+
19
+ from saicode import __version__
20
+
21
+ # Fields that may hold file contents or command output. Dropped from the
22
+ # session log unless logging.include_content is true.
23
+ CONTENT_FIELDS = {"content", "output", "text", "diff", "old_text", "new_text", "result"}
24
+
25
+
26
+ def _now() -> str:
27
+ return datetime.now(UTC).isoformat(timespec="milliseconds")
28
+
29
+
30
+ def new_id(prefix: str) -> str:
31
+ return f"{prefix}_{uuid.uuid4().hex[:16]}"
32
+
33
+
34
+ @dataclass
35
+ class Event:
36
+ type: str
37
+ data: dict[str, Any]
38
+ id: str
39
+ session_id: str
40
+ user: str
41
+ seq: int
42
+ ts: str
43
+ turn_id: str | None = None
44
+ parent_id: str | None = None
45
+
46
+ def to_record(self, include_content: bool) -> dict[str, Any]:
47
+ record = asdict(self)
48
+ if not include_content:
49
+ record["data"] = {
50
+ k: (f"<{len(str(v))} chars omitted>" if k in CONTENT_FIELDS and v else v)
51
+ for k, v in self.data.items()
52
+ }
53
+ return record
54
+
55
+
56
+ Listener = Callable[[Event], None]
57
+
58
+
59
+ @dataclass
60
+ class EventBus:
61
+ session_id: str = field(default_factory=lambda: new_id("ses"))
62
+ user: str = field(default_factory=lambda: getpass.getuser())
63
+ listeners: list[Listener] = field(default_factory=list)
64
+ seq: int = 0
65
+ turn_id: str | None = None
66
+
67
+ def subscribe(self, listener: Listener) -> None:
68
+ self.listeners.append(listener)
69
+
70
+ def emit(self, type: str, parent_id: str | None = None, **data: Any) -> Event:
71
+ self.seq += 1
72
+ event = Event(
73
+ type=type,
74
+ data=data,
75
+ id=new_id("evt"),
76
+ session_id=self.session_id,
77
+ user=self.user,
78
+ seq=self.seq,
79
+ ts=_now(),
80
+ turn_id=self.turn_id,
81
+ parent_id=parent_id,
82
+ )
83
+ for listener in list(self.listeners):
84
+ listener(event)
85
+ return event
86
+
87
+
88
+ class SessionLog:
89
+ """Append-only JSONL file: one event per line."""
90
+
91
+ def __init__(self, directory: Path, session_id: str, include_content: bool):
92
+ day = datetime.now(UTC).strftime("%Y-%m-%d")
93
+ self.path = directory.expanduser() / day / f"{session_id}.jsonl"
94
+ self.path.parent.mkdir(parents=True, exist_ok=True)
95
+ self.include_content = include_content
96
+ self._file = self.path.open("a", encoding="utf-8")
97
+
98
+ def __call__(self, event: Event) -> None:
99
+ self._file.write(json.dumps(event.to_record(self.include_content), default=str) + "\n")
100
+ self._file.flush()
101
+
102
+ def close(self) -> None:
103
+ self._file.close()
104
+
105
+
106
+ def session_metadata(
107
+ workdir: Path, model: str, provider: str, config_sources: list[str], identity_email: str
108
+ ) -> dict[str, Any]:
109
+ return {
110
+ "saicode_version": __version__,
111
+ "host": socket.gethostname(),
112
+ "workdir": str(workdir),
113
+ "provider": provider,
114
+ "model": model,
115
+ "config_layers": config_sources,
116
+ "identity_email": identity_email or None,
117
+ }
saicode/core/policy.py ADDED
@@ -0,0 +1,168 @@
1
+ """Permission decisions for every tool action.
2
+
3
+ Order of evaluation (first match wins):
4
+
5
+ 1. outside the workspace -> deny
6
+ 2. protected file (deny_read) -> deny
7
+ 3. deny rule -> deny
8
+ 4. read-only mode -> deny changes and commands
9
+ 5. allow rule -> allow
10
+ 6. reads and listings -> allow
11
+ 7. everything else -> ask
12
+ """
13
+
14
+ from __future__ import annotations
15
+
16
+ import fnmatch
17
+ import re
18
+ from dataclasses import dataclass
19
+ from enum import StrEnum
20
+ from pathlib import Path, PurePosixPath
21
+
22
+ from saicode.core.config import Config
23
+
24
+
25
+ class Decision(StrEnum):
26
+ ALLOW = "allow"
27
+ ASK = "ask"
28
+ DENY = "deny"
29
+
30
+
31
+ @dataclass(frozen=True)
32
+ class Verdict:
33
+ decision: Decision
34
+ reason: str = ""
35
+
36
+
37
+ # Action kinds, also used as the "always allow" bucket names.
38
+ READ, LIST, WRITE, RUN = "read", "list", "write", "run"
39
+
40
+
41
+ def _glob(pattern: str, value: str) -> bool:
42
+ # fnmatch "*" already crosses "/", so "**/" also needs to match "no directory".
43
+ if fnmatch.fnmatchcase(value, pattern):
44
+ return True
45
+ return bool(pattern.startswith("**/") and fnmatch.fnmatchcase(value, pattern[3:]))
46
+
47
+
48
+ _WORD = "A-Za-z0-9_"
49
+
50
+
51
+ def _literal_tokens(pattern: str) -> list[re.Pattern[str]]:
52
+ """Plain words of a glob as regexes, e.g. '**/id_rsa*' -> id_rsa, '**/*.pem' -> .pem.
53
+
54
+ A word must stand on its own unless the glob has a wildcard right next to it,
55
+ so '**/*.key' matches 'cat server.key' but not 'python -c "d.keys()"', and
56
+ '**/id_rsa*' still matches 'id_rsa.pub'.
57
+ """
58
+ tokens: list[re.Pattern[str]] = []
59
+ for m in re.finditer(r"[^*?/\[\]]+", pattern):
60
+ word = m.group(0)
61
+ if len(word) < 3:
62
+ continue
63
+ before = pattern[m.start() - 1] if m.start() > 0 else ""
64
+ after = pattern[m.end()] if m.end() < len(pattern) else ""
65
+ left = "" if before in ("*", "?") else f"(?<![{_WORD}])"
66
+ right = "" if after in ("*", "?") else f"(?![{_WORD}])"
67
+ tokens.append(re.compile(left + re.escape(word) + right))
68
+ return tokens
69
+
70
+
71
+ class Policy:
72
+ def __init__(self, config: Config, workdir: Path):
73
+ self.config = config
74
+ self.workdir = workdir.resolve()
75
+ perms = config.get("permissions", {})
76
+ self.mode: str = perms.get("mode", "ask")
77
+ self.allow_rules: list[str] = list(perms.get("allow", []))
78
+ self.deny_rules: list[str] = list(perms.get("deny", []))
79
+ self.deny_read: list[str] = list(perms.get("deny_read", []))
80
+ self.allow_always: bool = bool(perms.get("allow_always", True))
81
+ self.sandbox_required: bool = bool(config.get("sandbox.required", False))
82
+ self.session_always: set[str] = set()
83
+
84
+ # ---- paths -------------------------------------------------------------
85
+
86
+ def resolve(self, path: str) -> Path | None:
87
+ target = (self.workdir / path).resolve()
88
+ if target == self.workdir or self.workdir in target.parents:
89
+ return target
90
+ return None
91
+
92
+ def relative(self, target: Path) -> str:
93
+ try:
94
+ rel = target.relative_to(self.workdir)
95
+ except ValueError:
96
+ return str(target)
97
+ return str(PurePosixPath(*rel.parts)) or "."
98
+
99
+ def is_protected(self, target: Path) -> str | None:
100
+ rel = self.relative(target)
101
+ name = target.name
102
+ for pattern in self.deny_read:
103
+ if _glob(pattern, rel) or _glob(pattern, name):
104
+ return pattern
105
+ return None
106
+
107
+ # ---- rules -------------------------------------------------------------
108
+
109
+ @staticmethod
110
+ def _rule_matches(rules: list[str], kind: str, value: str) -> str | None:
111
+ for rule in rules:
112
+ rkind, _, pattern = rule.partition(":")
113
+ if rkind == kind and _glob(pattern, value):
114
+ return rule
115
+ return None
116
+
117
+ # ---- checks ------------------------------------------------------------
118
+
119
+ def check_path(self, kind: str, path: str) -> Verdict:
120
+ target = self.resolve(path)
121
+ if target is None:
122
+ return Verdict(Decision.DENY, "path is outside the project folder")
123
+ protected = self.is_protected(target)
124
+ if protected:
125
+ return Verdict(Decision.DENY, f"protected file (matches {protected})")
126
+ rel = self.relative(target)
127
+ rule = self._rule_matches(self.deny_rules, kind, rel)
128
+ if rule:
129
+ return Verdict(Decision.DENY, f"blocked by rule {rule}")
130
+ if kind == WRITE and self.mode == "read-only":
131
+ return Verdict(Decision.DENY, "saicode is in read-only mode")
132
+ rule = self._rule_matches(self.allow_rules, kind, rel)
133
+ if rule:
134
+ return Verdict(Decision.ALLOW, f"allowed by rule {rule}")
135
+ if kind in (READ, LIST):
136
+ return Verdict(Decision.ALLOW)
137
+ if kind in self.session_always:
138
+ return Verdict(Decision.ALLOW, "allowed for this session")
139
+ return Verdict(Decision.ASK)
140
+
141
+ def check_command(self, command: str) -> Verdict:
142
+ cmd = " ".join(command.split())
143
+ for pattern in self.deny_read:
144
+ for token in _literal_tokens(pattern):
145
+ found = token.search(cmd)
146
+ if found:
147
+ return Verdict(
148
+ Decision.DENY, f"command touches a protected file ({found.group(0)})"
149
+ )
150
+ rule = self._rule_matches(self.deny_rules, RUN, cmd)
151
+ if rule:
152
+ return Verdict(Decision.DENY, f"blocked by rule {rule}")
153
+ if self.mode == "read-only":
154
+ return Verdict(Decision.DENY, "saicode is in read-only mode")
155
+ if self.sandbox_required and self.config.get("sandbox.mode", "off") == "off":
156
+ return Verdict(Decision.DENY, "policy requires a sandbox and none is available")
157
+ rule = self._rule_matches(self.allow_rules, RUN, cmd)
158
+ if rule:
159
+ return Verdict(Decision.ALLOW, f"allowed by rule {rule}")
160
+ if RUN in self.session_always:
161
+ return Verdict(Decision.ALLOW, "allowed for this session")
162
+ return Verdict(Decision.ASK)
163
+
164
+ def remember_always(self, kind: str) -> bool:
165
+ if not self.allow_always:
166
+ return False
167
+ self.session_always.add(kind)
168
+ return True
@@ -0,0 +1,57 @@
1
+ """Command execution behind one interface.
2
+
3
+ Phase A1 ships the interface and an unsandboxed local runner. Phase A2 adds
4
+ an OS-level sandbox (andbox-runtime) behind the same interface,
5
+ so no other code changes when it arrives.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import subprocess
11
+ from dataclasses import dataclass
12
+ from pathlib import Path
13
+ from typing import Protocol
14
+
15
+
16
+ @dataclass
17
+ class RunResult:
18
+ exit_code: int
19
+ output: str
20
+ timed_out: bool = False
21
+
22
+
23
+ class Runner(Protocol):
24
+ name: str
25
+ isolated: bool
26
+
27
+ def run(self, command: str, cwd: Path, timeout: int = 300) -> RunResult: ...
28
+
29
+
30
+ class LocalRunner:
31
+ """Runs commands directly on this computer. No isolation."""
32
+
33
+ name = "local"
34
+ isolated = False
35
+
36
+ def run(self, command: str, cwd: Path, timeout: int = 300) -> RunResult:
37
+ try:
38
+ # Shell is intentional: this runner executes the agent's shell tool commands.
39
+ r = subprocess.run(
40
+ command,
41
+ shell=True,
42
+ cwd=cwd,
43
+ capture_output=True, # nosec B602
44
+ text=True,
45
+ timeout=timeout,
46
+ )
47
+ except subprocess.TimeoutExpired:
48
+ return RunResult(exit_code=-1, output=f"timed out after {timeout}s", timed_out=True)
49
+ return RunResult(exit_code=r.returncode, output=(r.stdout + r.stderr).strip())
50
+
51
+
52
+ def create_runner(mode: str) -> Runner:
53
+ if mode in ("off", "", None):
54
+ return LocalRunner()
55
+ raise ValueError(
56
+ f"Sandbox mode '{mode}' is not available in this version (coming in phase A2)."
57
+ )