rigcode 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.
Files changed (64) hide show
  1. rigcode/__init__.py +4 -0
  2. rigcode/__main__.py +4 -0
  3. rigcode/agent/__init__.py +0 -0
  4. rigcode/agent/loop.py +627 -0
  5. rigcode/agent/mentions.py +70 -0
  6. rigcode/agent/prompts.py +195 -0
  7. rigcode/agent/runtime.py +535 -0
  8. rigcode/agent/session.py +165 -0
  9. rigcode/agent/state.py +161 -0
  10. rigcode/cli.py +283 -0
  11. rigcode/config.py +284 -0
  12. rigcode/doctor.py +158 -0
  13. rigcode/extensions.py +275 -0
  14. rigcode/hooks.py +142 -0
  15. rigcode/llm/__init__.py +0 -0
  16. rigcode/llm/client.py +259 -0
  17. rigcode/llm/probe.py +229 -0
  18. rigcode/llm/stream.py +240 -0
  19. rigcode/llm/textmode.py +161 -0
  20. rigcode/llm/types.py +92 -0
  21. rigcode/llm/wire.py +76 -0
  22. rigcode/mcp.py +329 -0
  23. rigcode/permissions.py +221 -0
  24. rigcode/prompts/agents/coder.md +13 -0
  25. rigcode/prompts/agents/debugger.md +14 -0
  26. rigcode/prompts/agents/explore.md +22 -0
  27. rigcode/prompts/agents/plan.md +21 -0
  28. rigcode/prompts/agents/researcher.md +14 -0
  29. rigcode/prompts/agents/reviewer.md +18 -0
  30. rigcode/prompts/agents/verifier.md +15 -0
  31. rigcode/prompts/commit.md +5 -0
  32. rigcode/prompts/compact.md +24 -0
  33. rigcode/prompts/init.md +10 -0
  34. rigcode/prompts/system.md +27 -0
  35. rigcode/tools/__init__.py +0 -0
  36. rigcode/tools/base.py +245 -0
  37. rigcode/tools/bashsafety.py +262 -0
  38. rigcode/tools/editmatch.py +367 -0
  39. rigcode/tools/files.py +534 -0
  40. rigcode/tools/interact.py +69 -0
  41. rigcode/tools/search.py +309 -0
  42. rigcode/tools/shell.py +424 -0
  43. rigcode/tools/skill.py +37 -0
  44. rigcode/tools/task.py +54 -0
  45. rigcode/tools/todo.py +62 -0
  46. rigcode/tools/web.py +346 -0
  47. rigcode/ui/__init__.py +0 -0
  48. rigcode/ui/base.py +69 -0
  49. rigcode/ui/commands.py +581 -0
  50. rigcode/ui/plain.py +321 -0
  51. rigcode/ui/render.py +207 -0
  52. rigcode/ui/terminal.py +1154 -0
  53. rigcode/utils/__init__.py +0 -0
  54. rigcode/utils/files.py +176 -0
  55. rigcode/utils/frontmatter.py +38 -0
  56. rigcode/utils/globmatch.py +91 -0
  57. rigcode/utils/jsonrepair.py +110 -0
  58. rigcode/utils/paths.py +83 -0
  59. rigcode/utils/text.py +105 -0
  60. rigcode-0.1.0.dist-info/METADATA +203 -0
  61. rigcode-0.1.0.dist-info/RECORD +64 -0
  62. rigcode-0.1.0.dist-info/WHEEL +4 -0
  63. rigcode-0.1.0.dist-info/entry_points.txt +2 -0
  64. rigcode-0.1.0.dist-info/licenses/LICENSE +21 -0
@@ -0,0 +1,165 @@
1
+ """Session transcripts: append-only JSONL under ~/.rigcode/projects/<project>/<id>.jsonl.
2
+
3
+ Record types: meta, message, compact (replaces the message list), note.
4
+ Append-only writes mean a crash can lose at most the last line.
5
+ """
6
+ from __future__ import annotations
7
+
8
+ import json
9
+ import os
10
+ import re
11
+ import time
12
+ import uuid
13
+ from dataclasses import dataclass
14
+ from pathlib import Path
15
+
16
+ from rigcode.utils.paths import project_slug, rigcode_home
17
+
18
+
19
+ def new_session_id() -> str:
20
+ return time.strftime("%Y%m%d-%H%M%S") + "-" + uuid.uuid4().hex[:6]
21
+
22
+
23
+ def sessions_dir(project_root: Path) -> Path:
24
+ return rigcode_home() / "projects" / project_slug(project_root)
25
+
26
+
27
+ @dataclass
28
+ class SessionInfo:
29
+ id: str
30
+ path: Path
31
+ mtime: float
32
+ title: str
33
+ n_messages: int
34
+
35
+
36
+ class SessionStore:
37
+ def __init__(self, project_root: Path, session_id: str | None = None):
38
+ self.project_root = project_root
39
+ self.id = session_id or new_session_id()
40
+ self.dir = sessions_dir(project_root)
41
+ self.path = self.dir / f"{self.id}.jsonl"
42
+ self.enabled = True
43
+
44
+ def _write(self, record: dict) -> None:
45
+ if not self.enabled:
46
+ return
47
+ try:
48
+ self.dir.mkdir(parents=True, exist_ok=True)
49
+ line = json.dumps({"ts": time.time(), **record}, ensure_ascii=False, default=str) + "\n"
50
+ with open(self.path, "ab") as fh:
51
+ if fh.tell() > 0 and not self._ends_with_newline():
52
+ line = "\n" + line # a crash left a torn last line: don't glue onto it
53
+ fh.write(line.encode("utf-8"))
54
+ except OSError:
55
+ pass
56
+
57
+ def _ends_with_newline(self) -> bool:
58
+ with open(self.path, "rb") as fh:
59
+ fh.seek(-1, os.SEEK_END)
60
+ return fh.read(1) == b"\n"
61
+
62
+ def meta(self, **fields) -> None:
63
+ self._write({"type": "meta", **fields})
64
+
65
+ def message(self, msg: dict) -> None:
66
+ self._write({"type": "message", "message": msg})
67
+
68
+ def compact(self, messages: list[dict], summary_tokens: int | None = None) -> None:
69
+ self._write({"type": "compact", "messages": messages, "summary_tokens": summary_tokens})
70
+
71
+ def note(self, text: str) -> None:
72
+ self._write({"type": "note", "text": text})
73
+
74
+ # ------------------------------------------------------------------ loading
75
+ @staticmethod
76
+ def load(path: Path) -> tuple[dict, list[dict]]:
77
+ meta: dict = {}
78
+ messages: list[dict] = []
79
+ try:
80
+ with open(path, encoding="utf-8") as fh:
81
+ for line in fh:
82
+ line = line.strip()
83
+ if not line:
84
+ continue
85
+ try:
86
+ rec = json.loads(line)
87
+ except json.JSONDecodeError:
88
+ continue # torn last line
89
+ kind = rec.get("type")
90
+ if kind == "meta":
91
+ meta.update({k: v for k, v in rec.items() if k not in ("type", "ts")})
92
+ elif kind == "message" and isinstance(rec.get("message"), dict):
93
+ messages.append(rec["message"])
94
+ elif kind == "compact" and isinstance(rec.get("messages"), list):
95
+ messages = list(rec["messages"])
96
+ except OSError:
97
+ pass
98
+ return meta, _repair_tail(messages)
99
+
100
+ @staticmethod
101
+ def list(project_root: Path, limit: int = 30) -> list[SessionInfo]:
102
+ d = sessions_dir(project_root)
103
+ if not d.is_dir():
104
+ return []
105
+ infos = []
106
+ for p in sorted(d.glob("*.jsonl"), key=lambda p: p.stat().st_mtime, reverse=True)[:limit]:
107
+ title, count = "", 0
108
+ try:
109
+ with open(p, encoding="utf-8") as fh:
110
+ for line in fh:
111
+ try:
112
+ rec = json.loads(line)
113
+ except json.JSONDecodeError:
114
+ continue
115
+ if rec.get("type") == "message":
116
+ count += 1
117
+ m = rec["message"]
118
+ if not title and m.get("role") == "user" and not m.get("_meta"):
119
+ title = _first_text(m.get("content"))
120
+ elif rec.get("type") == "meta" and rec.get("title"):
121
+ title = rec["title"]
122
+ except OSError:
123
+ continue
124
+ infos.append(SessionInfo(p.stem, p, p.stat().st_mtime, " ".join(title.split())[:90], count))
125
+ return infos
126
+
127
+ @staticmethod
128
+ def resolve(project_root: Path, session_id: str | None) -> Path | None:
129
+ d = sessions_dir(project_root)
130
+ if session_id:
131
+ p = d / f"{session_id}.jsonl"
132
+ if p.exists():
133
+ return p
134
+ matches = sorted(d.glob(f"*{session_id}*.jsonl"), key=os.path.getmtime, reverse=True) if d.is_dir() else []
135
+ return matches[0] if matches else None
136
+ infos = SessionStore.list(project_root, limit=1)
137
+ return infos[0].path if infos else None
138
+
139
+
140
+ def _first_text(content) -> str:
141
+ if isinstance(content, str):
142
+ text = content
143
+ elif isinstance(content, list):
144
+ text = " ".join(p.get("text", "") for p in content if isinstance(p, dict))
145
+ else:
146
+ text = ""
147
+ # Strip injected reminders so titles show what the user typed.
148
+ text = re.sub(r"<system-reminder>.*?</system-reminder>", "", text, flags=re.S)
149
+ return text.strip()
150
+
151
+
152
+ def _repair_tail(messages: list[dict]) -> list[dict]:
153
+ """Ensure every assistant tool call has a tool result (e.g. after a crash)."""
154
+ out = list(messages)
155
+ pending: list[dict] = []
156
+ answered = {m.get("tool_call_id") for m in out if m.get("role") == "tool"}
157
+ for m in out:
158
+ if m.get("role") == "assistant":
159
+ for tc in m.get("tool_calls") or []:
160
+ if tc.get("id") not in answered:
161
+ pending.append({"role": "tool", "tool_call_id": tc.get("id"), "name": tc.get("function", {}).get("name"),
162
+ "content": "[No result: the session ended before this tool call completed.]"})
163
+ if pending:
164
+ out.extend(pending)
165
+ return out
rigcode/agent/state.py ADDED
@@ -0,0 +1,161 @@
1
+ """Mutable session state shared by tools: file read tracking, checkpoints, todos."""
2
+ from __future__ import annotations
3
+
4
+ import os
5
+ from dataclasses import dataclass, field
6
+ from pathlib import Path
7
+
8
+ MAX_SNAPSHOT_BYTES = 8 * 1024 * 1024
9
+
10
+
11
+ def _key(path: Path) -> str:
12
+ return os.path.normcase(os.path.abspath(str(path)))
13
+
14
+
15
+ class FileStateTracker:
16
+ """Remembers which files the model has read (and their mtime at that point)
17
+ so edits can require a prior read and detect external modifications."""
18
+
19
+ def __init__(self) -> None:
20
+ self._reads: dict[str, int] = {}
21
+ self._partial: set[str] = set() # seen only in part (Grep lines): enough for Edit, not Write
22
+ self._order: list[str] = []
23
+ self._paths: dict[str, Path] = {}
24
+
25
+ def record(self, path: Path, partial: bool = False) -> None:
26
+ k = _key(path)
27
+ try:
28
+ mtime = path.stat().st_mtime_ns
29
+ except OSError:
30
+ self._reads.pop(k, None)
31
+ return
32
+ if not partial:
33
+ self._partial.discard(k)
34
+ elif self._reads.get(k) != mtime or k in self._partial:
35
+ self._partial.add(k) # a partial view doesn't downgrade a full read of the same version
36
+ self._reads[k] = mtime
37
+ self._paths[k] = path
38
+ if k in self._order:
39
+ self._order.remove(k)
40
+ self._order.append(k)
41
+
42
+ def was_read(self, path: Path, partial_ok: bool = False) -> bool:
43
+ k = _key(path)
44
+ return k in self._reads and (partial_ok or k not in self._partial)
45
+
46
+ def changed_since_read(self, path: Path) -> bool:
47
+ k = _key(path)
48
+ if k not in self._reads:
49
+ return False
50
+ try:
51
+ return path.stat().st_mtime_ns != self._reads[k]
52
+ except OSError:
53
+ return True
54
+
55
+ def forget(self, path: Path) -> None:
56
+ """The model's copy of this file is stale (e.g. after /undo): require a fresh Read."""
57
+ k = _key(path)
58
+ self._reads.pop(k, None)
59
+ self._partial.discard(k)
60
+ self._paths.pop(k, None)
61
+ if k in self._order:
62
+ self._order.remove(k)
63
+
64
+ def recent(self, n: int = 10) -> list[Path]:
65
+ return [self._paths[k] for k in self._order[-n:] if k in self._paths]
66
+
67
+ def clear(self) -> None:
68
+ self._reads.clear()
69
+ self._partial.clear()
70
+ self._order.clear()
71
+ self._paths.clear()
72
+
73
+
74
+ @dataclass
75
+ class TurnCheckpoint:
76
+ label: str
77
+ files: dict[str, bytes | None] = field(default_factory=dict) # path -> original bytes (None = did not exist)
78
+
79
+
80
+ class Checkpoints:
81
+ """Per-turn snapshots of files before the agent modified them (for /undo)."""
82
+
83
+ def __init__(self) -> None:
84
+ self.turns: list[TurnCheckpoint] = []
85
+
86
+ def begin_turn(self, label: str) -> None:
87
+ if self.turns and not self.turns[-1].files:
88
+ self.turns[-1].label = label
89
+ return
90
+ self.turns.append(TurnCheckpoint(label))
91
+ del self.turns[:-50]
92
+
93
+ def snapshot(self, path: Path) -> None:
94
+ if not self.turns:
95
+ self.begin_turn("(start)")
96
+ cp = self.turns[-1]
97
+ k = str(path.resolve())
98
+ if k in cp.files:
99
+ return
100
+ if path.exists():
101
+ try:
102
+ if path.stat().st_size > MAX_SNAPSHOT_BYTES:
103
+ return
104
+ cp.files[k] = path.read_bytes()
105
+ except OSError:
106
+ return
107
+ else:
108
+ cp.files[k] = None
109
+
110
+ def last_with_changes(self) -> TurnCheckpoint | None:
111
+ for cp in reversed(self.turns):
112
+ if cp.files:
113
+ return cp
114
+ return None
115
+
116
+ def undo_last(self) -> list[tuple[str, str]]:
117
+ """Restore files changed in the most recent turn that changed files."""
118
+ while self.turns and not self.turns[-1].files:
119
+ self.turns.pop()
120
+ if not self.turns:
121
+ return []
122
+ cp = self.turns.pop()
123
+ results = []
124
+ for path_str, data in cp.files.items():
125
+ path = Path(path_str)
126
+ try:
127
+ if data is None:
128
+ if path.exists():
129
+ path.unlink()
130
+ results.append((path_str, "deleted (was created)"))
131
+ else:
132
+ path.parent.mkdir(parents=True, exist_ok=True)
133
+ path.write_bytes(data)
134
+ results.append((path_str, "restored"))
135
+ except OSError as e:
136
+ results.append((path_str, f"failed: {e}"))
137
+ return results
138
+
139
+
140
+ @dataclass
141
+ class TodoItem:
142
+ content: str
143
+ status: str = "pending" # pending | in_progress | completed
144
+ active_form: str | None = None
145
+
146
+
147
+ class TodoState:
148
+ def __init__(self) -> None:
149
+ self.items: list[TodoItem] = []
150
+
151
+ def set(self, items: list[TodoItem]) -> None:
152
+ self.items = items
153
+
154
+ def render_text(self) -> str:
155
+ if not self.items:
156
+ return "(no todos)"
157
+ marks = {"pending": "[ ]", "in_progress": "[~]", "completed": "[x]"}
158
+ return "\n".join(f"{i}. {marks.get(t.status, '[ ]')} {t.content}" for i, t in enumerate(self.items, 1))
159
+
160
+ def open_items(self) -> list[TodoItem]:
161
+ return [t for t in self.items if t.status != "completed"]
rigcode/cli.py ADDED
@@ -0,0 +1,283 @@
1
+ """rigcode command-line entry point."""
2
+ from __future__ import annotations
3
+
4
+ import argparse
5
+ import asyncio
6
+ import json
7
+ import os
8
+ import sys
9
+ import time
10
+ from pathlib import Path
11
+
12
+ from rigcode import __version__
13
+ from rigcode.agent.runtime import Runtime
14
+ from rigcode.agent.session import SessionStore
15
+ from rigcode.config import load_settings, settings_paths, update_settings_file
16
+ from rigcode.utils.paths import find_git_root, project_slug, rigcode_home
17
+
18
+ SUBCOMMANDS = ("doctor", "config", "sessions")
19
+
20
+
21
+ def build_parser() -> argparse.ArgumentParser:
22
+ p = argparse.ArgumentParser(
23
+ prog="rigcode",
24
+ description="A terminal coding agent for self-hosted models behind an OpenAI-compatible API.",
25
+ epilog="Subcommands: rigcode doctor [--quick] · rigcode config [get|set ...] · rigcode sessions")
26
+ p.add_argument("prompt", nargs="*", help="initial prompt (interactive) or the task to run (-p)")
27
+ p.add_argument("-p", "--print", action="store_true", dest="print_mode",
28
+ help="run one task non-interactively and print the result (stdin is appended to the prompt)")
29
+ p.add_argument("--output-format", choices=["text", "json", "stream-json"], default="text",
30
+ help="output for -p (default: text)")
31
+ p.add_argument("-c", "--continue", action="store_true", dest="cont",
32
+ help="continue the most recent session in this project")
33
+ p.add_argument("-r", "--resume", nargs="?", const="", default=None, metavar="ID",
34
+ help="resume a session by id (the most recent if no id is given)")
35
+ p.add_argument("-m", "--model", help="model name, or the name of a profile from settings")
36
+ p.add_argument("--base-url", help="OpenAI-compatible base URL, e.g. http://localhost:8080/v1 (default: find a local server)")
37
+ p.add_argument("--api-key", help="API key (most self-hosted servers accept anything)")
38
+ p.add_argument("-e", "--effort", help="reasoning effort: low, medium, high, max or none")
39
+ p.add_argument("--mode", "--permission-mode", dest="mode",
40
+ help="permission mode: default, acceptEdits, plan or bypass")
41
+ p.add_argument("--allow", action="append", default=[], metavar="RULE",
42
+ help="extra allow rule for this run, e.g. 'Bash(npm test:*)' (repeatable)")
43
+ p.add_argument("--deny", action="append", default=[], metavar="RULE", help="extra deny rule (repeatable)")
44
+ p.add_argument("-C", "--cwd", help="working directory (default: current directory)")
45
+ p.add_argument("--max-steps", type=int, help="maximum model calls per turn")
46
+ p.add_argument("--no-warmup", action="store_true", help="don't pre-process the prompt prefix at startup")
47
+ p.add_argument("--plain", action="store_true", help="use the simple line-based interface")
48
+ p.add_argument("-v", "--verbose", action="store_true", help="with -p: show progress on stderr")
49
+ p.add_argument("--debug", action="store_true", help="log requests to ~/.rigcode/logs and show tracebacks")
50
+ p.add_argument("--version", action="version", version=f"rigcode {__version__}")
51
+ return p
52
+
53
+
54
+ def _fix_stdio() -> None:
55
+ for s in (sys.stdout, sys.stderr):
56
+ if not s.isatty():
57
+ try:
58
+ s.reconfigure(encoding="utf-8", errors="replace")
59
+ except (AttributeError, ValueError):
60
+ pass
61
+
62
+
63
+ def _console_out():
64
+ from rich.console import Console
65
+ from rich.text import Text
66
+ console = Console(highlight=False, emoji=False)
67
+ styles = {"class:error": "red", "class:warn": "yellow", "class:dim": "dim", "class:faint": "dim",
68
+ "class:ok": "green", "bold": "bold"}
69
+
70
+ def out(text: str, style: str = "") -> None:
71
+ console.print(Text(text, style=styles.get(style, "")))
72
+ return out
73
+
74
+
75
+ def _project(cwd: Path) -> Path:
76
+ return find_git_root(cwd) or cwd
77
+
78
+
79
+ def _final_text(agent) -> str:
80
+ for m in reversed(agent.messages):
81
+ role = m.get("role")
82
+ if role == "assistant" and (m.get("content") or "").strip():
83
+ return m["content"].strip()
84
+ if role == "user" and not m.get("_meta"):
85
+ break
86
+ return ""
87
+
88
+
89
+ # ---------------------------------------------------------------- modes
90
+
91
+ async def _run_interactive(settings, project_root: Path, cwd: Path, prompt: str, args, resume: Path | None) -> int:
92
+ from rigcode.ui.plain import PlainUI
93
+ ui = None
94
+ if not args.plain and sys.stdin.isatty() and sys.stdout.isatty():
95
+ try:
96
+ from rigcode.ui.terminal import TerminalUI
97
+ ui = TerminalUI(settings, history_path=rigcode_home() / "projects" / project_slug(project_root) / "history")
98
+ except Exception as e: # noqa: BLE001 - e.g. no console screen buffer under mintty
99
+ print(f"(using the plain interface: {e})", file=sys.stderr)
100
+ if ui is None:
101
+ ui = PlainUI(settings, interactive=True)
102
+ base = settings.get("provider.base_url")
103
+ print(f"Connecting to {'a local model server' if base in (None, '', 'auto') else base} …", end="\r", flush=True)
104
+ rt = Runtime(settings, project_root, cwd, ui)
105
+ try:
106
+ await rt.start(resume=resume)
107
+ print(" " * 70, end="\r", flush=True)
108
+ await ui.run(rt, initial=prompt or None)
109
+ finally:
110
+ await rt.close()
111
+ return 0
112
+
113
+
114
+ async def _run_print(settings, project_root: Path, cwd: Path, prompt: str, args, resume: Path | None) -> int:
115
+ from rigcode.ui.plain import PlainUI
116
+ settings.set("provider.warmup", False) # we send the real request right away
117
+ ui = PlainUI(settings, interactive=False, output_format=args.output_format, verbose=args.verbose)
118
+ rt = Runtime(settings, project_root, cwd, ui)
119
+ started = time.monotonic()
120
+ try:
121
+ await rt.start(resume=resume)
122
+ ui.rt = rt
123
+ if not rt.server.reachable:
124
+ return 1
125
+ ui._event("system", subtype="init", session_id=rt.session.id, model=rt.client.model,
126
+ base_url=rt.client.base_url, cwd=str(cwd),
127
+ tools=rt.tools.names(), permission_mode=rt.permissions.mode)
128
+ stats = None
129
+ first = prompt.split()[0][1:] if prompt.startswith("/") and not prompt.startswith("//") else ""
130
+ if first and (ui.commands.find(first) or first in rt.commands):
131
+ await ui.handle(prompt)
132
+ else:
133
+ stats = await ui.run_turn(prompt)
134
+ text = _final_text(rt.main_agent)
135
+ reason = stats.stopped_reason if stats else "done"
136
+ u = rt.usage
137
+ summary = {"result": text, "stopped_reason": reason, "session_id": rt.session.id,
138
+ "steps": stats.steps if stats else 0, "tool_calls": stats.tool_calls if stats else 0,
139
+ "elapsed_s": round(time.monotonic() - started, 2),
140
+ "usage": {"prompt_tokens": u.prompt_tokens, "cached_tokens": u.cached_tokens,
141
+ "completion_tokens": u.completion_tokens}}
142
+ if args.output_format == "text":
143
+ if text:
144
+ print(text)
145
+ elif args.output_format == "json":
146
+ print(json.dumps(summary, ensure_ascii=False, indent=2))
147
+ else:
148
+ ui._event("result", **summary)
149
+ return 0 if reason in ("done", "denied") else 1
150
+ finally:
151
+ await rt.close()
152
+
153
+
154
+ # ---------------------------------------------------------------- subcommands
155
+
156
+ def _cmd_doctor(argv: list[str]) -> int:
157
+ from rigcode.doctor import run_doctor
158
+ cwd = Path.cwd()
159
+ root = _project(cwd)
160
+ settings = load_settings(root)
161
+ ok = asyncio.run(run_doctor(settings, root, _console_out(), chat_test="--quick" not in argv))
162
+ return 0 if ok else 1
163
+
164
+
165
+ def _parse_value(raw: str):
166
+ try:
167
+ return json.loads(raw)
168
+ except json.JSONDecodeError:
169
+ return raw
170
+
171
+
172
+ def _cmd_config(argv: list[str]) -> int:
173
+ root = _project(Path.cwd())
174
+ paths = settings_paths(root)
175
+ scope = "project"
176
+ for flag, sc in (("--user", "user"), ("--project", "project"), ("--local", "local")):
177
+ if flag in argv:
178
+ scope = sc
179
+ argv = [a for a in argv if a != flag]
180
+ if not argv or argv[0] == "show":
181
+ settings = load_settings(root)
182
+ for src in settings.sources:
183
+ state = "loaded" if src.loaded else (f"error: {src.error}" if src.error else "not present")
184
+ print(f"{src.scope:<8} {src.path} ({state})")
185
+ print(json.dumps(settings.data, indent=2, ensure_ascii=False))
186
+ return 0
187
+ if argv[0] == "get" and len(argv) >= 2:
188
+ print(json.dumps(load_settings(root).get(argv[1]), indent=2, ensure_ascii=False))
189
+ return 0
190
+ if argv[0] == "set" and len(argv) >= 3:
191
+ key, value = argv[1], _parse_value(" ".join(argv[2:]))
192
+
193
+ def mutate(d: dict) -> None:
194
+ cur = d
195
+ parts = key.split(".")
196
+ for part in parts[:-1]:
197
+ cur = cur.setdefault(part, {})
198
+ cur[parts[-1]] = value
199
+ update_settings_file(paths[scope], mutate)
200
+ print(f"Set {key} = {json.dumps(value, ensure_ascii=False)} in {paths[scope]}")
201
+ return 0
202
+ if argv[0] == "path":
203
+ for k, v in paths.items():
204
+ print(f"{k:<8} {v}")
205
+ return 0
206
+ print("usage: rigcode config [show | get KEY | set KEY VALUE [--user|--project|--local] | path]", file=sys.stderr)
207
+ return 2
208
+
209
+
210
+ def _cmd_sessions(argv: list[str]) -> int:
211
+ root = _project(Path.cwd())
212
+ infos = SessionStore.list(root, limit=30)
213
+ if not infos:
214
+ print("No sessions for this project yet.")
215
+ return 0
216
+ for i in infos:
217
+ when = time.strftime("%Y-%m-%d %H:%M", time.localtime(i.mtime))
218
+ print(f"{i.id} {when} {i.n_messages:>4} msgs {i.title[:70]}")
219
+ print("\nResume with: rigcode -r <id> (or rigcode -c for the latest)")
220
+ return 0
221
+
222
+
223
+ # ---------------------------------------------------------------- main
224
+
225
+ def main(argv: list[str] | None = None) -> int:
226
+ _fix_stdio()
227
+ argv = list(sys.argv[1:] if argv is None else argv)
228
+ if argv and argv[0] in SUBCOMMANDS:
229
+ return {"doctor": _cmd_doctor, "config": _cmd_config, "sessions": _cmd_sessions}[argv[0]](argv[1:])
230
+ args = build_parser().parse_args(argv)
231
+ cwd = Path(args.cwd).expanduser().resolve() if args.cwd else Path.cwd()
232
+ if not cwd.is_dir():
233
+ print(f"rigcode: not a directory: {cwd}", file=sys.stderr)
234
+ return 2
235
+ os.chdir(cwd)
236
+ project_root = _project(cwd)
237
+ overrides: dict = {}
238
+ if args.base_url:
239
+ overrides["provider.base_url"] = args.base_url
240
+ if args.api_key:
241
+ overrides["provider.api_key"] = args.api_key
242
+ if args.effort:
243
+ overrides["provider.reasoning_effort"] = args.effort
244
+ if args.mode:
245
+ overrides["permissions.mode"] = args.mode
246
+ if args.max_steps:
247
+ overrides["max_steps_per_turn"] = args.max_steps
248
+ if args.no_warmup:
249
+ overrides["provider.warmup"] = False
250
+ if args.debug:
251
+ overrides["debug"] = True
252
+ settings = load_settings(project_root, overrides)
253
+ if args.model:
254
+ if not settings.apply_profile(args.model):
255
+ settings.set("provider.model", args.model)
256
+ perms = settings.data.setdefault("permissions", {})
257
+ perms.setdefault("allow", []).extend(args.allow)
258
+ perms.setdefault("deny", []).extend(args.deny)
259
+
260
+ prompt = " ".join(args.prompt).strip()
261
+ if args.print_mode and not sys.stdin.isatty():
262
+ piped = sys.stdin.read()
263
+ if piped.strip():
264
+ prompt = f"{prompt}\n\n{piped}" if prompt else piped
265
+ resume = None
266
+ if args.cont or args.resume is not None:
267
+ resume = SessionStore.resolve(project_root, args.resume or None)
268
+ if resume is None:
269
+ print("rigcode: no session found to resume in this project.", file=sys.stderr)
270
+ return 1
271
+ try:
272
+ if args.print_mode:
273
+ if not prompt.strip():
274
+ print("rigcode: -p needs a prompt (argument or stdin).", file=sys.stderr)
275
+ return 2
276
+ return asyncio.run(_run_print(settings, project_root, cwd, prompt, args, resume))
277
+ return asyncio.run(_run_interactive(settings, project_root, cwd, prompt, args, resume))
278
+ except KeyboardInterrupt:
279
+ return 130
280
+
281
+
282
+ if __name__ == "__main__":
283
+ sys.exit(main())