ireri-code 2.0.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.
- agent/__init__.py +27 -0
- agent/cli.py +2573 -0
- agent/config.py +304 -0
- agent/context.py +215 -0
- agent/controller.py +633 -0
- agent/model.py +285 -0
- agent/prompts.py +90 -0
- agent/session.py +223 -0
- agent/tools/__init__.py +95 -0
- agent/tools/files.py +322 -0
- agent/tools/search.py +223 -0
- agent/tools/terminal.py +542 -0
- ireri_code-2.0.0.dist-info/METADATA +219 -0
- ireri_code-2.0.0.dist-info/RECORD +17 -0
- ireri_code-2.0.0.dist-info/WHEEL +5 -0
- ireri_code-2.0.0.dist-info/entry_points.txt +2 -0
- ireri_code-2.0.0.dist-info/top_level.txt +1 -0
agent/cli.py
ADDED
|
@@ -0,0 +1,2573 @@
|
|
|
1
|
+
"""Command-line interface for ireri."""
|
|
2
|
+
|
|
3
|
+
import asyncio
|
|
4
|
+
import os
|
|
5
|
+
import sys
|
|
6
|
+
from pathlib import Path
|
|
7
|
+
from typing import Optional, List
|
|
8
|
+
|
|
9
|
+
import typer
|
|
10
|
+
from rich.console import Console, Group
|
|
11
|
+
from rich.panel import Panel
|
|
12
|
+
from rich.prompt import Prompt, Confirm
|
|
13
|
+
from rich.markdown import Markdown
|
|
14
|
+
from rich.syntax import Syntax
|
|
15
|
+
from rich.table import Table
|
|
16
|
+
from rich.align import Align
|
|
17
|
+
from rich.columns import Columns
|
|
18
|
+
from rich.text import Text
|
|
19
|
+
from rich.box import ROUNDED
|
|
20
|
+
|
|
21
|
+
from agent.config import get_config, AgentConfig, reset_config
|
|
22
|
+
from agent.controller import AgentController, run_agent_task
|
|
23
|
+
from agent.context import ContextManager
|
|
24
|
+
from agent.model import get_model_client, reset_model_client
|
|
25
|
+
from agent.tools import get_registry
|
|
26
|
+
from typing import Dict, Any
|
|
27
|
+
|
|
28
|
+
console = Console()
|
|
29
|
+
app = typer.Typer(
|
|
30
|
+
name="ireri",
|
|
31
|
+
help="IRERI CODE - Terminal AI Coding Agent",
|
|
32
|
+
add_completion=False,
|
|
33
|
+
)
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def render_user_message(content: str) -> Panel:
|
|
37
|
+
"""Render a user message on the right side."""
|
|
38
|
+
panel = Panel(
|
|
39
|
+
Markdown(content),
|
|
40
|
+
title="[bold cyan]You[/bold cyan]",
|
|
41
|
+
border_style="cyan",
|
|
42
|
+
box=ROUNDED,
|
|
43
|
+
padding=(0, 1),
|
|
44
|
+
width=min(console.width - 4, 100),
|
|
45
|
+
)
|
|
46
|
+
return Align.right(panel)
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def render_agent_message(content: str) -> Panel:
|
|
50
|
+
"""Render an agent message on the left side."""
|
|
51
|
+
panel = Panel(
|
|
52
|
+
Markdown(content),
|
|
53
|
+
title="[bold bright_green]ireri[/bold bright_green]",
|
|
54
|
+
border_style="bright_green",
|
|
55
|
+
box=ROUNDED,
|
|
56
|
+
padding=(0, 1),
|
|
57
|
+
width=min(console.width - 4, 100),
|
|
58
|
+
)
|
|
59
|
+
return Align.left(panel)
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
def render_system_message(content: str) -> Panel:
|
|
63
|
+
"""Render a system/info message centered."""
|
|
64
|
+
if isinstance(content, str):
|
|
65
|
+
try:
|
|
66
|
+
text = Text.from_markup(content, justify="center")
|
|
67
|
+
except Exception:
|
|
68
|
+
text = Text(content, justify="center")
|
|
69
|
+
else:
|
|
70
|
+
text = content
|
|
71
|
+
return Panel(
|
|
72
|
+
text,
|
|
73
|
+
border_style="dim",
|
|
74
|
+
box=ROUNDED,
|
|
75
|
+
padding=(0, 1),
|
|
76
|
+
width=console.width - 4,
|
|
77
|
+
)
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
def _progress_callback(event: str, data: Dict[str, Any], thinking: Optional["ThinkingIndicator"] = None) -> None:
|
|
81
|
+
"""Display progress updates from the agent."""
|
|
82
|
+
if event == "iteration_start":
|
|
83
|
+
if thinking:
|
|
84
|
+
thinking.stop()
|
|
85
|
+
thinking.start("[bold bright_cyan]Thinking...[/bold bright_cyan]")
|
|
86
|
+
elif event == "model_response":
|
|
87
|
+
if thinking:
|
|
88
|
+
thinking.stop()
|
|
89
|
+
up = data.get("tokens_up", 0)
|
|
90
|
+
down = data.get("tokens_down", 0)
|
|
91
|
+
tok_str = ""
|
|
92
|
+
if up or down:
|
|
93
|
+
tok_str = f" [dim cyan](↑ {up:,} tokens sent, ↓ {down:,} tokens received)[/dim cyan]"
|
|
94
|
+
|
|
95
|
+
if data.get("tool_calls_count", 0) > 0:
|
|
96
|
+
console.print(f"\n [cyan]Model: Planning {data['tool_calls_count']} tool call(s)[/cyan]{tok_str}")
|
|
97
|
+
elif data.get("has_content"):
|
|
98
|
+
console.print(f"\n [cyan]Model: Responding...[/cyan]{tok_str}")
|
|
99
|
+
elif event == "tool_start":
|
|
100
|
+
if thinking:
|
|
101
|
+
thinking.stop()
|
|
102
|
+
console.print() # spacing before tool action
|
|
103
|
+
tool = data["tool"]
|
|
104
|
+
args = data.get("args", {})
|
|
105
|
+
if tool == "write_file":
|
|
106
|
+
console.print(f" [green]>[/green] Creating file: [bold]{args.get('path', 'unknown')}[/bold]")
|
|
107
|
+
elif tool == "edit_file":
|
|
108
|
+
console.print(f" [yellow]>[/yellow] Editing file: [bold]{args.get('path', 'unknown')}[/bold]")
|
|
109
|
+
elif tool == "read_file":
|
|
110
|
+
console.print(f" [blue]>[/blue] Reading file: [bold]{args.get('path', 'unknown')}[/bold]")
|
|
111
|
+
elif tool == "list_files":
|
|
112
|
+
console.print(f" [blue]>[/blue] Listing directory: [bold]{args.get('path', '.')}[/bold]")
|
|
113
|
+
elif tool == "run_command":
|
|
114
|
+
cmd = args.get('command', 'unknown')
|
|
115
|
+
console.print(f" [magenta]>[/magenta] Running: [dim]{cmd[:60]}[/dim]...")
|
|
116
|
+
elif tool == "delete_file":
|
|
117
|
+
console.print(f" [red]>[/red] Deleting: [bold]{args.get('path', 'unknown')}[/bold]")
|
|
118
|
+
elif tool == "create_directory":
|
|
119
|
+
console.print(f" [green]>[/green] Creating directory: [bold]{args.get('path', 'unknown')}[/bold]")
|
|
120
|
+
elif tool == "search_files":
|
|
121
|
+
console.print(f" [blue]>[/blue] Searching: [bold]{args.get('pattern', 'unknown')}[/bold]")
|
|
122
|
+
elif tool == "grep":
|
|
123
|
+
console.print(f" [blue]>[/blue] Grepping: [bold]{args.get('pattern', 'unknown')}[/bold]")
|
|
124
|
+
else:
|
|
125
|
+
console.print(f" [dim]>[/dim] {tool}: {args}")
|
|
126
|
+
elif event == "tool_complete":
|
|
127
|
+
if thinking:
|
|
128
|
+
thinking.stop()
|
|
129
|
+
tool = data["tool"]
|
|
130
|
+
success = data.get("success", False)
|
|
131
|
+
metadata = data.get("metadata", {})
|
|
132
|
+
if tool == "write_file":
|
|
133
|
+
action = metadata.get("action", "written")
|
|
134
|
+
console.print(f" [green]OK[/green] File {action}\n")
|
|
135
|
+
elif tool == "edit_file":
|
|
136
|
+
replacements = data.get("output", {}).get("replacements", 0)
|
|
137
|
+
console.print(f" [yellow]OK[/yellow] File edited ({replacements} replacement(s))\n")
|
|
138
|
+
elif tool == "read_file":
|
|
139
|
+
output = data.get("output", {})
|
|
140
|
+
lines = output.get("total_lines", 0)
|
|
141
|
+
console.print(f" [blue]OK[/blue] Read {lines} lines\n")
|
|
142
|
+
elif tool == "list_files":
|
|
143
|
+
count = data.get("metadata", {}).get("count", 0)
|
|
144
|
+
console.print(f" [blue]OK[/blue] Found {count} items\n")
|
|
145
|
+
elif tool == "run_command":
|
|
146
|
+
if success:
|
|
147
|
+
if metadata.get("background") and metadata.get("process_id"):
|
|
148
|
+
pid_str = metadata.get("pid", "?")
|
|
149
|
+
proc_id = metadata["process_id"]
|
|
150
|
+
console.print(
|
|
151
|
+
f" [magenta]OK[/magenta] Started in background ([cyan]{proc_id}[/cyan], PID {pid_str}) "
|
|
152
|
+
f"— use [bold]/logs {proc_id}[/bold] to view logs\n"
|
|
153
|
+
)
|
|
154
|
+
else:
|
|
155
|
+
console.print(f" [magenta]OK[/magenta] Command completed\n")
|
|
156
|
+
else:
|
|
157
|
+
console.print(f" [red]FAIL[/red] Command failed\n")
|
|
158
|
+
elif tool == "delete_file":
|
|
159
|
+
action = metadata.get("action", "deleted")
|
|
160
|
+
console.print(f" [red]OK[/red] {action}\n")
|
|
161
|
+
elif tool == "create_directory":
|
|
162
|
+
console.print(f" [green]OK[/green] Directory created\n")
|
|
163
|
+
elif tool == "search_files" or tool == "grep":
|
|
164
|
+
console.print(f" [blue]OK[/blue] Search completed\n")
|
|
165
|
+
else:
|
|
166
|
+
if success:
|
|
167
|
+
console.print(f" [dim]OK[/dim] {tool} completed\n")
|
|
168
|
+
else:
|
|
169
|
+
console.print(f" [red]FAIL[/red] {tool} failed: {data.get('error', 'unknown')}\n")
|
|
170
|
+
elif event == "tool_error":
|
|
171
|
+
if thinking:
|
|
172
|
+
thinking.stop()
|
|
173
|
+
console.print(f" [red]FAIL[/red] {data['tool']} error: {data.get('error', 'unknown')}\n")
|
|
174
|
+
elif event == "tool_denied":
|
|
175
|
+
if thinking:
|
|
176
|
+
thinking.stop()
|
|
177
|
+
console.print(f" [yellow]DENIED[/yellow] {data['tool']} denied\n")
|
|
178
|
+
elif event == "model_error":
|
|
179
|
+
if thinking:
|
|
180
|
+
thinking.stop()
|
|
181
|
+
console.print(f"\n [red]Model error:[/red] {data.get('error', 'unknown')}\n")
|
|
182
|
+
elif event == "model_retry":
|
|
183
|
+
if thinking:
|
|
184
|
+
thinking.stop()
|
|
185
|
+
attempt = data.get("attempt", 1)
|
|
186
|
+
max_attempts = data.get("max_attempts", 6)
|
|
187
|
+
delay = data.get("delay", 1)
|
|
188
|
+
err = data.get("error", "Error")
|
|
189
|
+
delay_str = f"{delay // 60}m" if delay >= 60 else f"{delay}s"
|
|
190
|
+
console.print(f"\n [yellow]⚠ API error: {err}[/yellow]")
|
|
191
|
+
console.print(f" [yellow] Retrying in {delay_str} (attempt {attempt}/{max_attempts})...[/yellow]\n")
|
|
192
|
+
if thinking:
|
|
193
|
+
thinking.start(f"[bold bright_cyan]Waiting {delay_str} before retry ({attempt}/{max_attempts})...[/bold bright_cyan]")
|
|
194
|
+
elif event == "model_retry_success":
|
|
195
|
+
if thinking:
|
|
196
|
+
thinking.stop()
|
|
197
|
+
console.print(f"\n [green]✓[/green] API call recovered on retry attempt {data.get('attempt')}\n")
|
|
198
|
+
if thinking:
|
|
199
|
+
thinking.start("[bold bright_cyan]Thinking...[/bold bright_cyan]")
|
|
200
|
+
elif event == "model_timeout":
|
|
201
|
+
if thinking:
|
|
202
|
+
thinking.stop()
|
|
203
|
+
diagnostic = data.get("diagnostic", {})
|
|
204
|
+
summary = diagnostic.get("summary", "Could not diagnose connection issue.")
|
|
205
|
+
attempt = data.get("attempt", 1)
|
|
206
|
+
max_attempts = data.get("max_attempts", 6)
|
|
207
|
+
timeout_sec = int(data.get("timeout", 180))
|
|
208
|
+
console.print(f"\n [bold red]⚠ No response from model within {timeout_sec // 60} minutes ({timeout_sec}s).[/bold red]")
|
|
209
|
+
console.print(f" [cyan]🔍 Diagnostic:[/cyan] [dim]{summary}[/dim]")
|
|
210
|
+
console.print(f" [bold green]🔄 Reloaded client connection pool.[/bold green] [yellow]Retrying (attempt {attempt}/{max_attempts})...[/yellow]\n")
|
|
211
|
+
if thinking:
|
|
212
|
+
thinking.start("[bold bright_cyan]Retrying request with reloaded connection...[/bold bright_cyan]")
|
|
213
|
+
elif event == "error_encountered":
|
|
214
|
+
if thinking:
|
|
215
|
+
thinking.stop()
|
|
216
|
+
err = data.get("error", "Unknown error")
|
|
217
|
+
console.print(f"\n [bold yellow]⚠ Error encountered:[/bold yellow] [yellow]{err}[/yellow]")
|
|
218
|
+
console.print(f" [cyan]↳ Automatically sent to model for analysis and corrective action...[/cyan]\n")
|
|
219
|
+
if thinking:
|
|
220
|
+
thinking.start("[bold bright_cyan]Model analyzing error and taking corrective action...[/bold bright_cyan]")
|
|
221
|
+
|
|
222
|
+
|
|
223
|
+
class _AwaitableNone:
|
|
224
|
+
def __await__(self):
|
|
225
|
+
async def _noop():
|
|
226
|
+
return None
|
|
227
|
+
return _noop().__await__()
|
|
228
|
+
|
|
229
|
+
|
|
230
|
+
class ThinkingIndicator:
|
|
231
|
+
"""Status indicator for when the agent/model is thinking."""
|
|
232
|
+
|
|
233
|
+
def __init__(self, console: Console):
|
|
234
|
+
self.console = console
|
|
235
|
+
self._status = None
|
|
236
|
+
|
|
237
|
+
def start(self, message: str = "[bold bright_cyan]Thinking...[/bold bright_cyan]"):
|
|
238
|
+
"""Start the status spinner."""
|
|
239
|
+
if self._status is None:
|
|
240
|
+
try:
|
|
241
|
+
self._status = self.console.status(message, spinner="dots")
|
|
242
|
+
self._status.start()
|
|
243
|
+
except Exception:
|
|
244
|
+
pass
|
|
245
|
+
return _AwaitableNone()
|
|
246
|
+
|
|
247
|
+
def stop(self):
|
|
248
|
+
"""Stop the status spinner."""
|
|
249
|
+
if self._status is not None:
|
|
250
|
+
try:
|
|
251
|
+
self._status.stop()
|
|
252
|
+
except Exception:
|
|
253
|
+
pass
|
|
254
|
+
self._status = None
|
|
255
|
+
return _AwaitableNone()
|
|
256
|
+
|
|
257
|
+
|
|
258
|
+
async def _prompt_arrow_menu(
|
|
259
|
+
title: str,
|
|
260
|
+
options: List[Dict[str, Any]],
|
|
261
|
+
hotkeys: Optional[Dict[str, str]] = None,
|
|
262
|
+
subtitle: str = "Use ↑/↓ arrows + Enter to select (or press shortcut key)",
|
|
263
|
+
) -> Optional[str]:
|
|
264
|
+
"""Render an interactive arrow-key selection menu using prompt_toolkit.
|
|
265
|
+
|
|
266
|
+
Returns the selected option's 'key', or None if cancelled/unavailable.
|
|
267
|
+
"""
|
|
268
|
+
if not sys.stdin.isatty():
|
|
269
|
+
raise RuntimeError("stdin is not a TTY")
|
|
270
|
+
|
|
271
|
+
from prompt_toolkit.application import Application
|
|
272
|
+
from prompt_toolkit.key_binding import KeyBindings
|
|
273
|
+
from prompt_toolkit.layout import Layout, HSplit, Window
|
|
274
|
+
from prompt_toolkit.layout.controls import FormattedTextControl
|
|
275
|
+
from prompt_toolkit.styles import Style
|
|
276
|
+
|
|
277
|
+
selected_idx = 0
|
|
278
|
+
kb = KeyBindings()
|
|
279
|
+
|
|
280
|
+
@kb.add("up")
|
|
281
|
+
@kb.add("k")
|
|
282
|
+
def _up(event):
|
|
283
|
+
nonlocal selected_idx
|
|
284
|
+
selected_idx = (selected_idx - 1) % len(options)
|
|
285
|
+
|
|
286
|
+
@kb.add("down")
|
|
287
|
+
@kb.add("j")
|
|
288
|
+
def _down(event):
|
|
289
|
+
nonlocal selected_idx
|
|
290
|
+
selected_idx = (selected_idx + 1) % len(options)
|
|
291
|
+
|
|
292
|
+
@kb.add("enter")
|
|
293
|
+
def _enter(event):
|
|
294
|
+
event.app.exit(result=options[selected_idx]["key"])
|
|
295
|
+
|
|
296
|
+
@kb.add("escape")
|
|
297
|
+
@kb.add("c-c")
|
|
298
|
+
def _cancel(event):
|
|
299
|
+
event.app.exit(result=None)
|
|
300
|
+
|
|
301
|
+
if hotkeys:
|
|
302
|
+
for hk, target_key in hotkeys.items():
|
|
303
|
+
@kb.add(hk)
|
|
304
|
+
def _hotkey(event, _target=target_key):
|
|
305
|
+
event.app.exit(result=_target)
|
|
306
|
+
|
|
307
|
+
def _get_formatted_text():
|
|
308
|
+
lines = []
|
|
309
|
+
if title:
|
|
310
|
+
lines.append(("class:title", f" {title}\n"))
|
|
311
|
+
if subtitle:
|
|
312
|
+
lines.append(("class:subtitle", f" {subtitle}\n"))
|
|
313
|
+
for idx, opt in enumerate(options):
|
|
314
|
+
is_sel = idx == selected_idx
|
|
315
|
+
pointer = " ❯ " if is_sel else " "
|
|
316
|
+
style_cls = "class:selected" if is_sel else opt.get("pt_style", "class:item")
|
|
317
|
+
lines.append((style_cls, f"{pointer}{opt['label']}\n"))
|
|
318
|
+
return lines
|
|
319
|
+
|
|
320
|
+
style = Style.from_dict({
|
|
321
|
+
"title": "bold ansibrightcyan",
|
|
322
|
+
"subtitle": "ansibrightblack",
|
|
323
|
+
"selected": "bold ansibrightyellow reverse",
|
|
324
|
+
"item": "ansiwhite",
|
|
325
|
+
"allow": "ansigreen",
|
|
326
|
+
"deny": "ansired",
|
|
327
|
+
"accent": "ansicyan",
|
|
328
|
+
})
|
|
329
|
+
|
|
330
|
+
app = Application(
|
|
331
|
+
layout=Layout(HSplit([Window(content=FormattedTextControl(_get_formatted_text))])),
|
|
332
|
+
key_bindings=kb,
|
|
333
|
+
style=style,
|
|
334
|
+
full_screen=False,
|
|
335
|
+
erase_when_done=True,
|
|
336
|
+
)
|
|
337
|
+
return await app.run_async()
|
|
338
|
+
|
|
339
|
+
|
|
340
|
+
async def _prompt_tool_approval_interactive(
|
|
341
|
+
tool_name: str,
|
|
342
|
+
args: Dict[str, Any],
|
|
343
|
+
dangerous: bool,
|
|
344
|
+
controller: AgentController,
|
|
345
|
+
) -> Optional[bool]:
|
|
346
|
+
"""Interactive arrow-key selector for tool approval.
|
|
347
|
+
|
|
348
|
+
Returns True (approved), False (denied), or raises RuntimeError if TTY is unavailable.
|
|
349
|
+
"""
|
|
350
|
+
from agent.config import _save_global_config
|
|
351
|
+
|
|
352
|
+
while True:
|
|
353
|
+
options = [
|
|
354
|
+
{"key": "approve_once", "label": "[y] ✓ Approve once", "pt_style": "class:allow"},
|
|
355
|
+
{"key": "deny_once", "label": "[n] ✗ Deny once", "pt_style": "class:deny"},
|
|
356
|
+
{"key": "always_allow", "label": f"[p] ★ Always allow '{tool_name}' (save to /settings)", "pt_style": "class:allow"},
|
|
357
|
+
{"key": "always_deny", "label": f"[b] ⊘ Never allow '{tool_name}' (save deny to /settings)", "pt_style": "class:deny"},
|
|
358
|
+
{"key": "approve_all", "label": "[a] ✓✓ Approve all for this session", "pt_style": "class:accent"},
|
|
359
|
+
{"key": "deny_all", "label": "[d] ✗✗ Deny all for this session", "pt_style": "class:deny"},
|
|
360
|
+
{"key": "chat", "label": "[/] 💬 Ask model (/btw) or queue a message", "pt_style": "class:item"},
|
|
361
|
+
]
|
|
362
|
+
hotkeys = {
|
|
363
|
+
"y": "approve_once",
|
|
364
|
+
"Y": "approve_once",
|
|
365
|
+
"n": "deny_once",
|
|
366
|
+
"N": "deny_once",
|
|
367
|
+
"p": "always_allow",
|
|
368
|
+
"P": "always_allow",
|
|
369
|
+
"b": "always_deny",
|
|
370
|
+
"B": "always_deny",
|
|
371
|
+
"a": "approve_all",
|
|
372
|
+
"A": "approve_all",
|
|
373
|
+
"d": "deny_all",
|
|
374
|
+
"D": "deny_all",
|
|
375
|
+
"/": "chat",
|
|
376
|
+
}
|
|
377
|
+
|
|
378
|
+
choice = await _prompt_arrow_menu(
|
|
379
|
+
title=f"Choose action for '{tool_name}':",
|
|
380
|
+
options=options,
|
|
381
|
+
hotkeys=hotkeys,
|
|
382
|
+
)
|
|
383
|
+
|
|
384
|
+
if choice is None or choice == "deny_once":
|
|
385
|
+
console.print(" [red]✗ Denied[/red]")
|
|
386
|
+
return False
|
|
387
|
+
elif choice == "approve_once":
|
|
388
|
+
console.print(" [green]✓ Approved[/green]")
|
|
389
|
+
return True
|
|
390
|
+
elif choice == "always_allow":
|
|
391
|
+
controller.config.set_tool_access(tool_name, "allow")
|
|
392
|
+
_save_global_config(controller.config)
|
|
393
|
+
console.print(render_system_message(f"[green]✓ Always allowing '{tool_name}' (saved to /settings)[/green]"))
|
|
394
|
+
return True
|
|
395
|
+
elif choice == "always_deny":
|
|
396
|
+
controller.config.set_tool_access(tool_name, "deny")
|
|
397
|
+
_save_global_config(controller.config)
|
|
398
|
+
console.print(render_system_message(f"[red]⊘ Tool '{tool_name}' set to deny (saved to /settings)[/red]"))
|
|
399
|
+
return False
|
|
400
|
+
elif choice == "approve_all":
|
|
401
|
+
controller.set_approve_all(True)
|
|
402
|
+
console.print(render_system_message("[green]✓✓ Approved all future tool calls for this session[/green]"))
|
|
403
|
+
return True
|
|
404
|
+
elif choice == "deny_all":
|
|
405
|
+
controller.set_deny_all(True)
|
|
406
|
+
console.print(render_system_message("[red]✗✗ Denied all future tool calls for this session[/red]"))
|
|
407
|
+
return False
|
|
408
|
+
elif choice == "chat":
|
|
409
|
+
loop = asyncio.get_event_loop()
|
|
410
|
+
msg = await loop.run_in_executor(
|
|
411
|
+
None,
|
|
412
|
+
lambda: Prompt.ask("[bold cyan]Enter /btw <question> or message to queue (blank to go back)[/bold cyan]", default="")
|
|
413
|
+
)
|
|
414
|
+
cleaned = msg.strip()
|
|
415
|
+
if not cleaned:
|
|
416
|
+
continue
|
|
417
|
+
if cleaned.lower().startswith("/btw"):
|
|
418
|
+
question = cleaned[4:].strip()
|
|
419
|
+
if question:
|
|
420
|
+
await _handle_btw_command(question, controller)
|
|
421
|
+
else:
|
|
422
|
+
console.print("[yellow]Usage: /btw <question>[/yellow]")
|
|
423
|
+
else:
|
|
424
|
+
q_len = controller.queue_message(cleaned)
|
|
425
|
+
console.print(render_system_message(f"[green]✓ Queued message #{q_len}:[/green] [white]{cleaned}[/white]"))
|
|
426
|
+
# Loop back to the approval selector
|
|
427
|
+
|
|
428
|
+
|
|
429
|
+
async def _chat_async(
|
|
430
|
+
project: Optional[Path],
|
|
431
|
+
model: Optional[str],
|
|
432
|
+
base_url: Optional[str],
|
|
433
|
+
api_key: Optional[str],
|
|
434
|
+
max_iterations: Optional[int] = None,
|
|
435
|
+
auto_approve: bool = False,
|
|
436
|
+
new_session: bool = False,
|
|
437
|
+
):
|
|
438
|
+
"""Async implementation of chat."""
|
|
439
|
+
reset_config()
|
|
440
|
+
config = get_config()
|
|
441
|
+
|
|
442
|
+
# Override config with CLI args
|
|
443
|
+
# workspace_root always defaults to current directory unless --project specified
|
|
444
|
+
if project:
|
|
445
|
+
config.workspace_root = project.resolve()
|
|
446
|
+
else:
|
|
447
|
+
config.workspace_root = Path.cwd().resolve()
|
|
448
|
+
if model:
|
|
449
|
+
config.openai_model = model
|
|
450
|
+
if base_url:
|
|
451
|
+
config.openai_base_url = base_url
|
|
452
|
+
if api_key:
|
|
453
|
+
config.openai_api_key = api_key
|
|
454
|
+
if max_iterations is not None:
|
|
455
|
+
config.max_iterations = max_iterations
|
|
456
|
+
|
|
457
|
+
# Validate
|
|
458
|
+
if not config.openai_api_key:
|
|
459
|
+
console.print("[red]Error: API key required. Set OPENAI_API_KEY in .env or use --api-key[/red]")
|
|
460
|
+
raise typer.Exit(1)
|
|
461
|
+
|
|
462
|
+
# Welcome banner - IRERI CODE in large font
|
|
463
|
+
console.print()
|
|
464
|
+
banner_lines = [
|
|
465
|
+
" ██╗██████╗ ███████╗██████╗ ██╗ ██████╗ ██████╗ ██████╗ ███████╗",
|
|
466
|
+
" ██║██╔══██╗██╔════╝██╔══██╗██║ ██╔════╝██╔═══██╗██╔══██╗██╔════╝",
|
|
467
|
+
" ██║██████╔╝█████╗ ██████╔╝██║ ██║ ██║ ██║██║ ██║█████╗ ",
|
|
468
|
+
" ██║██╔══██╗██╔══╝ ██╔══██╗██║ ██║ ██║ ██║██║ ██║██╔══╝ ",
|
|
469
|
+
" ██║██║ ██║███████╗██║ ██║██║ ╚██████╗╚██████╔╝██████╔╝███████╗",
|
|
470
|
+
" ╚═╝╚═╝ ╚═╝╚══════╝╚═╝ ╚═╝╚═╝ ╚═════╝ ╚═════╝ ╚═════╝ ╚══════╝",
|
|
471
|
+
]
|
|
472
|
+
for line in banner_lines:
|
|
473
|
+
console.print(f"[bold bright_cyan]{line}[/bold bright_cyan]")
|
|
474
|
+
console.print()
|
|
475
|
+
console.print("[bold bright_green] Terminal AI Coding Agent v2.0.0[/bold bright_green]")
|
|
476
|
+
console.print()
|
|
477
|
+
console.print(render_system_message(
|
|
478
|
+
f"Model: [green]{config.openai_model}[/green] • "
|
|
479
|
+
f"Workspace: [green]{config.workspace_root}[/green] • Max iterations: [green]{config.max_iterations}[/green]"
|
|
480
|
+
))
|
|
481
|
+
console.print(render_system_message("[dim]Type 'exit' or 'quit' to leave. Type '/help' for commands.[/dim]"))
|
|
482
|
+
console.print()
|
|
483
|
+
|
|
484
|
+
# Initialize controller
|
|
485
|
+
controller = AgentController()
|
|
486
|
+
global _current_controller
|
|
487
|
+
_current_controller = controller
|
|
488
|
+
if auto_approve:
|
|
489
|
+
controller.set_approve_all(True)
|
|
490
|
+
|
|
491
|
+
# Check for preserved previous session to continue
|
|
492
|
+
if not new_session and controller.has_saved_session():
|
|
493
|
+
restored = controller.load_session()
|
|
494
|
+
if restored:
|
|
495
|
+
user_msg_count = len([m for m in controller.context.messages if m.role == "user"])
|
|
496
|
+
console.print(render_system_message(
|
|
497
|
+
f"[green]Preserved session loaded[/green] ([bold cyan]{user_msg_count}[/bold cyan] previous interaction(s) restored). "
|
|
498
|
+
f"[dim]Type '/history' to view, or '/reset' to start fresh.[/dim]"
|
|
499
|
+
))
|
|
500
|
+
console.print()
|
|
501
|
+
|
|
502
|
+
thinking = ThinkingIndicator(console)
|
|
503
|
+
|
|
504
|
+
# Initialize prompt_toolkit session with auto-completion and dynamic prompt
|
|
505
|
+
from prompt_toolkit import PromptSession
|
|
506
|
+
from prompt_toolkit.shortcuts import CompleteStyle
|
|
507
|
+
pt_completer = SlashCommandCompleter()
|
|
508
|
+
pt_session = PromptSession(
|
|
509
|
+
erase_when_done=True,
|
|
510
|
+
completer=pt_completer,
|
|
511
|
+
complete_while_typing=True,
|
|
512
|
+
complete_style=CompleteStyle.COLUMN,
|
|
513
|
+
style=SLASH_COMPLETION_STYLE,
|
|
514
|
+
)
|
|
515
|
+
approval_handoff_event = asyncio.Event()
|
|
516
|
+
|
|
517
|
+
# Define approval callback for interactive mode
|
|
518
|
+
async def _approval_callback(tool_name: str, args: Dict[str, Any], dangerous: bool) -> bool:
|
|
519
|
+
"""Prompt user for tool approval with interactive arrow selection and /btw support."""
|
|
520
|
+
if controller._approve_all:
|
|
521
|
+
return True
|
|
522
|
+
if controller._deny_all:
|
|
523
|
+
return False
|
|
524
|
+
|
|
525
|
+
thinking.stop()
|
|
526
|
+
from rich.markup import escape
|
|
527
|
+
|
|
528
|
+
# Format args for display
|
|
529
|
+
args_display = ", ".join(f"{k}={v}" for k, v in args.items())
|
|
530
|
+
if len(args_display) > 100:
|
|
531
|
+
args_display = args_display[:97] + "..."
|
|
532
|
+
|
|
533
|
+
# Build prompt message
|
|
534
|
+
danger_indicator = " [red]! DANGEROUS[/red]" if dangerous else ""
|
|
535
|
+
console.print()
|
|
536
|
+
approval_text = Text.from_markup(
|
|
537
|
+
f"[yellow]Approval required:[/yellow] {escape(tool_name)}({escape(args_display)}){danger_indicator}",
|
|
538
|
+
justify="center",
|
|
539
|
+
)
|
|
540
|
+
console.print(Panel(approval_text, border_style="yellow" if not dangerous else "red", box=ROUNDED, padding=(0, 1), width=console.width - 4))
|
|
541
|
+
|
|
542
|
+
loop = asyncio.get_event_loop()
|
|
543
|
+
future = loop.create_future()
|
|
544
|
+
controller.active_approval = future
|
|
545
|
+
|
|
546
|
+
# Hand off stdin from pt_session if it is currently running
|
|
547
|
+
try:
|
|
548
|
+
if pt_session.app.is_running:
|
|
549
|
+
approval_handoff_event.clear()
|
|
550
|
+
pt_session.app.exit(result="__APPROVAL_HANDOFF__")
|
|
551
|
+
try:
|
|
552
|
+
await asyncio.wait_for(approval_handoff_event.wait(), timeout=1.0)
|
|
553
|
+
except asyncio.TimeoutError:
|
|
554
|
+
pass
|
|
555
|
+
except Exception:
|
|
556
|
+
pass
|
|
557
|
+
|
|
558
|
+
try:
|
|
559
|
+
# Try interactive arrow-key selector first
|
|
560
|
+
try:
|
|
561
|
+
approved = await _prompt_tool_approval_interactive(tool_name, args, dangerous, controller)
|
|
562
|
+
if not future.done():
|
|
563
|
+
future.set_result(approved)
|
|
564
|
+
return approved
|
|
565
|
+
except asyncio.CancelledError:
|
|
566
|
+
raise
|
|
567
|
+
except Exception:
|
|
568
|
+
# Fallback to text-based prompt for non-TTY / automated environments
|
|
569
|
+
options_text = Text.from_markup(
|
|
570
|
+
"Options: [bold]y[/bold]=approve [bold]n[/bold]=deny [bold]a[/bold]=approve all [bold]d[/bold]=deny all [bold]/btw <q>[/bold]=ask model",
|
|
571
|
+
justify="center",
|
|
572
|
+
)
|
|
573
|
+
console.print(Panel(options_text, border_style="dim", box=ROUNDED, padding=(0, 1), width=console.width - 4))
|
|
574
|
+
approved = await future
|
|
575
|
+
return approved
|
|
576
|
+
except asyncio.CancelledError:
|
|
577
|
+
return False
|
|
578
|
+
finally:
|
|
579
|
+
controller.active_approval = None
|
|
580
|
+
|
|
581
|
+
controller.approval_callback = _approval_callback
|
|
582
|
+
|
|
583
|
+
background_worker_task: Optional[asyncio.Task] = None
|
|
584
|
+
|
|
585
|
+
async def _run_task_and_drain_queue(task: str):
|
|
586
|
+
"""Background worker executing tasks from the queue in sequence while prompt stays active."""
|
|
587
|
+
current_task = task
|
|
588
|
+
while current_task and not controller.cancelled:
|
|
589
|
+
try:
|
|
590
|
+
result = await controller.run_task(
|
|
591
|
+
current_task,
|
|
592
|
+
progress_callback=lambda event, data: _progress_callback(event, data, thinking),
|
|
593
|
+
)
|
|
594
|
+
except asyncio.CancelledError:
|
|
595
|
+
break
|
|
596
|
+
except Exception as e:
|
|
597
|
+
controller.session_manager.log_error("TASK_ERROR", str(e))
|
|
598
|
+
if not controller.cancelled:
|
|
599
|
+
console.print()
|
|
600
|
+
console.print(render_system_message(
|
|
601
|
+
f"[yellow]⚠ Error encountered: {e}[/yellow]\n"
|
|
602
|
+
f"[cyan]→ Sending error to model for automatic corrective actions...[/cyan]"
|
|
603
|
+
))
|
|
604
|
+
try:
|
|
605
|
+
thinking.start("[bold bright_cyan]Model taking corrective actions...[/bold bright_cyan]")
|
|
606
|
+
result = await controller.recover_from_error(
|
|
607
|
+
error=str(e),
|
|
608
|
+
progress_callback=lambda event, data: _progress_callback(event, data, thinking),
|
|
609
|
+
)
|
|
610
|
+
except Exception as recovery_err:
|
|
611
|
+
result = f"Error during task: {e}\nAutomatic recovery failed: {recovery_err}"
|
|
612
|
+
else:
|
|
613
|
+
result = "Task cancelled by user"
|
|
614
|
+
finally:
|
|
615
|
+
thinking.stop()
|
|
616
|
+
|
|
617
|
+
# Display result on the left
|
|
618
|
+
console.print()
|
|
619
|
+
console.print(render_agent_message(result))
|
|
620
|
+
|
|
621
|
+
# Display token metrics and context summary
|
|
622
|
+
stats = controller.context.get_token_stats()
|
|
623
|
+
console.print(Align.left(
|
|
624
|
+
f" [dim]Session Tokens: [cyan]↑ {stats['tokens_up']:,} sent[/cyan] • "
|
|
625
|
+
f"[green]↓ {stats['tokens_down']:,} received[/green] • "
|
|
626
|
+
f"[magenta]{stats['total_tokens']:,} total[/magenta] • "
|
|
627
|
+
f"Context: [yellow]~{stats['approx_context_tokens']:,} tokens[/yellow][/dim]"
|
|
628
|
+
))
|
|
629
|
+
|
|
630
|
+
# Process next queued message if available
|
|
631
|
+
if controller.has_queued_messages() and not controller.cancelled:
|
|
632
|
+
current_task = controller.pop_queued_message()
|
|
633
|
+
remaining = len(controller.message_queue)
|
|
634
|
+
console.print()
|
|
635
|
+
console.print(render_system_message(
|
|
636
|
+
f"[bold cyan]▶ Running queued task ({remaining} remaining in queue):[/bold cyan]\n"
|
|
637
|
+
f"[white]{current_task}[/white]"
|
|
638
|
+
))
|
|
639
|
+
console.print(render_user_message(current_task))
|
|
640
|
+
else:
|
|
641
|
+
current_task = None
|
|
642
|
+
|
|
643
|
+
# Chat loop
|
|
644
|
+
async def _chat_loop():
|
|
645
|
+
nonlocal background_worker_task
|
|
646
|
+
while True:
|
|
647
|
+
try:
|
|
648
|
+
# If interactive approval is currently active on TTY, wait for it to finish
|
|
649
|
+
if controller.active_approval and not controller.active_approval.done() and sys.stdin.isatty():
|
|
650
|
+
try:
|
|
651
|
+
await asyncio.shield(controller.active_approval)
|
|
652
|
+
except (asyncio.CancelledError, Exception):
|
|
653
|
+
pass
|
|
654
|
+
continue
|
|
655
|
+
|
|
656
|
+
console.print()
|
|
657
|
+
# Get user input with prompt_toolkit, falling back to readline/input
|
|
658
|
+
try:
|
|
659
|
+
user_input = await pt_session.prompt_async(
|
|
660
|
+
_get_dynamic_prompt,
|
|
661
|
+
completer=pt_completer,
|
|
662
|
+
complete_while_typing=True,
|
|
663
|
+
complete_style=CompleteStyle.COLUMN,
|
|
664
|
+
style=SLASH_COMPLETION_STYLE,
|
|
665
|
+
)
|
|
666
|
+
except (EOFError, KeyboardInterrupt):
|
|
667
|
+
raise
|
|
668
|
+
except Exception:
|
|
669
|
+
loop = asyncio.get_event_loop()
|
|
670
|
+
user_input = await loop.run_in_executor(
|
|
671
|
+
None,
|
|
672
|
+
lambda: _get_input_with_readline()
|
|
673
|
+
)
|
|
674
|
+
|
|
675
|
+
if user_input == "__APPROVAL_HANDOFF__":
|
|
676
|
+
approval_handoff_event.set()
|
|
677
|
+
if controller.active_approval and not controller.active_approval.done():
|
|
678
|
+
try:
|
|
679
|
+
await asyncio.shield(controller.active_approval)
|
|
680
|
+
except (asyncio.CancelledError, Exception):
|
|
681
|
+
pass
|
|
682
|
+
continue
|
|
683
|
+
|
|
684
|
+
if user_input.lower() in ("exit", "quit", "q"):
|
|
685
|
+
if background_worker_task and not background_worker_task.done():
|
|
686
|
+
controller.cancel()
|
|
687
|
+
background_worker_task.cancel()
|
|
688
|
+
console.print()
|
|
689
|
+
console.print(render_system_message("[yellow]Goodbye from ireri![/yellow]"))
|
|
690
|
+
break
|
|
691
|
+
|
|
692
|
+
if not user_input.strip():
|
|
693
|
+
continue
|
|
694
|
+
|
|
695
|
+
# Check if tool approval is currently waiting
|
|
696
|
+
if controller.active_approval and not controller.active_approval.done():
|
|
697
|
+
cleaned = user_input.strip()
|
|
698
|
+
if cleaned.lower().startswith("/btw"):
|
|
699
|
+
question = cleaned[4:].strip()
|
|
700
|
+
if question:
|
|
701
|
+
await _handle_btw_command(question, controller)
|
|
702
|
+
else:
|
|
703
|
+
console.print("[yellow]Usage: /btw <question>[/yellow]")
|
|
704
|
+
continue
|
|
705
|
+
|
|
706
|
+
if cleaned.lower().startswith("/queue"):
|
|
707
|
+
_handle_queue_command(cleaned.split(), controller)
|
|
708
|
+
continue
|
|
709
|
+
|
|
710
|
+
choice = cleaned.lower()
|
|
711
|
+
if choice == "a":
|
|
712
|
+
controller.set_approve_all(True)
|
|
713
|
+
console.print(render_system_message("[green]Approved all future tool calls for this session[/green]"))
|
|
714
|
+
controller.active_approval.set_result(True)
|
|
715
|
+
continue
|
|
716
|
+
elif choice == "d":
|
|
717
|
+
controller.set_deny_all(True)
|
|
718
|
+
console.print(render_system_message("[red]Denied all future tool calls for this session[/red]"))
|
|
719
|
+
controller.active_approval.set_result(False)
|
|
720
|
+
continue
|
|
721
|
+
elif choice in ("y", "yes"):
|
|
722
|
+
controller.active_approval.set_result(True)
|
|
723
|
+
continue
|
|
724
|
+
elif choice in ("n", "no"):
|
|
725
|
+
controller.active_approval.set_result(False)
|
|
726
|
+
continue
|
|
727
|
+
else:
|
|
728
|
+
q_len = controller.queue_message(cleaned)
|
|
729
|
+
console.print(render_system_message(
|
|
730
|
+
f"[green]✓ Queued message #{q_len}:[/green] [white]{cleaned}[/white]\n"
|
|
731
|
+
f"[dim]Please approve or deny the current tool call with [bold]y[/bold] or [bold]n[/bold].[/dim]"
|
|
732
|
+
))
|
|
733
|
+
continue
|
|
734
|
+
|
|
735
|
+
# Handle /cancel command
|
|
736
|
+
if user_input.lower() in ("/cancel", "cancel"):
|
|
737
|
+
is_working = controller.running or (background_worker_task and not background_worker_task.done())
|
|
738
|
+
if is_working:
|
|
739
|
+
controller.cancel()
|
|
740
|
+
if background_worker_task:
|
|
741
|
+
background_worker_task.cancel()
|
|
742
|
+
if controller.active_approval and not controller.active_approval.done():
|
|
743
|
+
controller.active_approval.cancel()
|
|
744
|
+
thinking.stop()
|
|
745
|
+
controller.cancelled = False
|
|
746
|
+
console.print(render_system_message("[yellow]⚠ Task cancelled by user.[/yellow]"))
|
|
747
|
+
else:
|
|
748
|
+
console.print(render_system_message("[dim]No active task running to cancel.[/dim]"))
|
|
749
|
+
continue
|
|
750
|
+
|
|
751
|
+
# Handle /btw side-chat (works both when working and when idle!)
|
|
752
|
+
if user_input.lower().startswith("/btw"):
|
|
753
|
+
question = user_input[4:].strip()
|
|
754
|
+
if question:
|
|
755
|
+
await _handle_btw_command(question, controller)
|
|
756
|
+
else:
|
|
757
|
+
console.print("[yellow]Usage: /btw <your question or side note>[/yellow]")
|
|
758
|
+
console.print("[dim]Example: /btw what database are we using?[/dim]")
|
|
759
|
+
continue
|
|
760
|
+
|
|
761
|
+
# Handle /queue command
|
|
762
|
+
if user_input.lower().startswith("/queue"):
|
|
763
|
+
_handle_queue_command(user_input.split(), controller)
|
|
764
|
+
continue
|
|
765
|
+
|
|
766
|
+
# Handle other slash commands
|
|
767
|
+
if user_input.strip().startswith("/"):
|
|
768
|
+
should_continue = await _handle_slash_command(user_input.strip(), controller)
|
|
769
|
+
if should_continue is False:
|
|
770
|
+
break
|
|
771
|
+
continue
|
|
772
|
+
|
|
773
|
+
# If the agent is currently working on a task, queue the message!
|
|
774
|
+
is_working = controller.running or (background_worker_task and not background_worker_task.done())
|
|
775
|
+
if is_working:
|
|
776
|
+
console.print(render_user_message(user_input))
|
|
777
|
+
q_len = controller.queue_message(user_input)
|
|
778
|
+
console.print(render_system_message(
|
|
779
|
+
f"[bold cyan]📥 Message queued for next run[/bold cyan] [dim](Position #{q_len} in queue). "
|
|
780
|
+
f"It will execute automatically when the current task finishes.[/dim]"
|
|
781
|
+
))
|
|
782
|
+
continue
|
|
783
|
+
|
|
784
|
+
# Agent is idle: display user message
|
|
785
|
+
console.print(render_user_message(user_input))
|
|
786
|
+
|
|
787
|
+
# Handle conversational messages directly
|
|
788
|
+
if controller._is_conversational(user_input):
|
|
789
|
+
responses = {
|
|
790
|
+
"hi": "Hello! How can I help you today?",
|
|
791
|
+
"hello": "Hello! What would you like to work on?",
|
|
792
|
+
"hey": "Hey! What can I do for you?",
|
|
793
|
+
"thanks": "You're welcome!",
|
|
794
|
+
"thank you": "You're welcome!",
|
|
795
|
+
"thx": "You're welcome!",
|
|
796
|
+
"ty": "You're welcome!",
|
|
797
|
+
"bye": "Goodbye! Have a great day!",
|
|
798
|
+
"goodbye": "Goodbye! Take care!",
|
|
799
|
+
"see you": "See you later!",
|
|
800
|
+
"cya": "See you!",
|
|
801
|
+
"how are you": "I'm doing well, thanks for asking! How can I help?",
|
|
802
|
+
"how's it going": "Going great! What would you like to work on?",
|
|
803
|
+
"what's up": "I'm ready to help! What's on your mind?",
|
|
804
|
+
"ok": "Great! What would you like to do?",
|
|
805
|
+
"okay": "Great! What would you like to do?",
|
|
806
|
+
"sure": "Sounds good! What task would you like me to tackle?",
|
|
807
|
+
"yeah": "Great! What would you like to work on?",
|
|
808
|
+
"yep": "Great! What would you like to work on?",
|
|
809
|
+
"yup": "Great! What would you like to work on?",
|
|
810
|
+
"no": "No problem! Let me know if you need anything.",
|
|
811
|
+
"nope": "No problem! Let me know if you need anything.",
|
|
812
|
+
"nah": "No problem! Let me know if you need anything.",
|
|
813
|
+
}
|
|
814
|
+
msg_lower = user_input.strip().lower()
|
|
815
|
+
response = responses.get(msg_lower, "Hello! How can I help you with your code?")
|
|
816
|
+
controller.context.add_user_message(user_input)
|
|
817
|
+
controller.context.add_assistant_message(response)
|
|
818
|
+
controller.session_manager.log_message("USER", user_input)
|
|
819
|
+
controller.session_manager.log_message("AGENT", response)
|
|
820
|
+
controller.save_session()
|
|
821
|
+
console.print(render_agent_message(response))
|
|
822
|
+
continue
|
|
823
|
+
|
|
824
|
+
# Launch task in background and KEEP THE INPUT PROMPT VISIBLE!
|
|
825
|
+
background_worker_task = asyncio.create_task(_run_task_and_drain_queue(user_input))
|
|
826
|
+
|
|
827
|
+
except (typer.Exit, SystemExit):
|
|
828
|
+
break
|
|
829
|
+
except KeyboardInterrupt:
|
|
830
|
+
console.print()
|
|
831
|
+
is_working = controller.running or (background_worker_task and not background_worker_task.done())
|
|
832
|
+
if is_working:
|
|
833
|
+
thinking.stop()
|
|
834
|
+
controller.cancel()
|
|
835
|
+
if background_worker_task:
|
|
836
|
+
background_worker_task.cancel()
|
|
837
|
+
if controller.active_approval and not controller.active_approval.done():
|
|
838
|
+
controller.active_approval.cancel()
|
|
839
|
+
controller.cancelled = False
|
|
840
|
+
controller.session_manager.log_error("USER_INTERRUPT", "Task cancelled by Ctrl+C")
|
|
841
|
+
controller.save_session()
|
|
842
|
+
console.print(render_system_message("[yellow]⚠ Task interrupted — returning to prompt.[/yellow]"))
|
|
843
|
+
if controller.has_queued_messages():
|
|
844
|
+
console.print(render_system_message(
|
|
845
|
+
f"[dim]Note: {len(controller.message_queue)} queued message(s) preserved. Type '/queue' to view or '/queue clear' to remove.[/dim]"
|
|
846
|
+
))
|
|
847
|
+
else:
|
|
848
|
+
console.print(render_system_message("[dim]Type 'exit' or '/exit' to leave.[/dim]"))
|
|
849
|
+
except EOFError:
|
|
850
|
+
break
|
|
851
|
+
except Exception as e:
|
|
852
|
+
console.print()
|
|
853
|
+
console.print(render_system_message(f"[red]Error: {e}[/red]"))
|
|
854
|
+
controller.session_manager.log_error("CHAT_ERROR", str(e))
|
|
855
|
+
|
|
856
|
+
# Run the async chat loop
|
|
857
|
+
await _chat_loop()
|
|
858
|
+
|
|
859
|
+
|
|
860
|
+
# Available slash commands for auto-completion
|
|
861
|
+
SLASH_COMMANDS = {
|
|
862
|
+
"/btw": "Ask a direct question to the model & enlighten the agent without disrupting running tasks",
|
|
863
|
+
"/queue": "View, add, or clear queued tasks for upcoming runs",
|
|
864
|
+
"/logs": "View or follow live logs of an ongoing process (/logs [id|follow])",
|
|
865
|
+
"/ps": "List or stop ongoing background processes (/ps [stop <id>])",
|
|
866
|
+
"/tokens": "View session tokens sent/received and approximate context length",
|
|
867
|
+
"/help": "Display all available commands",
|
|
868
|
+
"/provider": "Configure AI providers (NVIDIA, OpenAI, etc.)",
|
|
869
|
+
"/settings": "Open interactive settings & API profiles",
|
|
870
|
+
"/model": "View or switch AI models",
|
|
871
|
+
"/models": "List available models",
|
|
872
|
+
"/status": "Show current agent status",
|
|
873
|
+
"/config": "View, set or edit configuration (e.g. /config set max_iterations 1000)",
|
|
874
|
+
"/history": "View conversation history and past messages",
|
|
875
|
+
"/continue": "Continue previous conversation session",
|
|
876
|
+
"/errors": "View recent errors from debug log",
|
|
877
|
+
"/clear": "Clear terminal conversation",
|
|
878
|
+
"/reset": "Reset current session",
|
|
879
|
+
"/version": "Show agent version",
|
|
880
|
+
"/update": "Check for and install updates",
|
|
881
|
+
"/about": "Information about the agent",
|
|
882
|
+
"/exit": "Exit the agent",
|
|
883
|
+
}
|
|
884
|
+
|
|
885
|
+
# Command icons for auto-completion display
|
|
886
|
+
SLASH_COMMAND_ICONS = {
|
|
887
|
+
"/btw": "💡",
|
|
888
|
+
"/queue": "📥",
|
|
889
|
+
"/logs": "📜",
|
|
890
|
+
"/ps": "⚙",
|
|
891
|
+
"/tokens": "📊",
|
|
892
|
+
"/help": "✦",
|
|
893
|
+
"/provider": "⚡",
|
|
894
|
+
"/settings": "⚙",
|
|
895
|
+
"/model": "◈",
|
|
896
|
+
"/models": "≡",
|
|
897
|
+
"/status": "●",
|
|
898
|
+
"/config": "⚙",
|
|
899
|
+
"/history": "◷",
|
|
900
|
+
"/continue": "▶",
|
|
901
|
+
"/errors": "⚠",
|
|
902
|
+
"/clear": "✕",
|
|
903
|
+
"/reset": "↺",
|
|
904
|
+
"/version": "◆",
|
|
905
|
+
"/update": "▲",
|
|
906
|
+
"/about": "ℹ",
|
|
907
|
+
"/exit": "⏻",
|
|
908
|
+
}
|
|
909
|
+
|
|
910
|
+
# Extract just command names for completion
|
|
911
|
+
SLASH_COMMAND_NAMES = list(SLASH_COMMANDS.keys())
|
|
912
|
+
|
|
913
|
+
from prompt_toolkit.completion import Completer, Completion
|
|
914
|
+
from prompt_toolkit.formatted_text import HTML
|
|
915
|
+
from prompt_toolkit.styles import Style
|
|
916
|
+
|
|
917
|
+
# Modern styled theme for slash command auto-completion popup
|
|
918
|
+
SLASH_COMPLETION_STYLE = Style.from_dict({
|
|
919
|
+
# Completion menu popup container
|
|
920
|
+
"completion-menu": "bg:#16161e #c0caf5",
|
|
921
|
+
"completion-menu.completion": "bg:#1e2030 #7aa2f7 bold",
|
|
922
|
+
"completion-menu.completion.current": "bg:#283457 #7dcfff bold",
|
|
923
|
+
"completion-menu.meta.completion": "bg:#16161e #787c99",
|
|
924
|
+
"completion-menu.meta.completion.current": "bg:#283457 #e0af68 bold",
|
|
925
|
+
"completion-menu.multi-column-meta": "bg:#16161e #787c99",
|
|
926
|
+
# Scrollbar
|
|
927
|
+
"scrollbar.background": "bg:#16161e",
|
|
928
|
+
"scrollbar.button": "bg:#3b4261",
|
|
929
|
+
})
|
|
930
|
+
|
|
931
|
+
|
|
932
|
+
class SlashCommandCompleter(Completer):
|
|
933
|
+
"""Auto-completion for slash commands with icons and stylish formatting."""
|
|
934
|
+
|
|
935
|
+
def get_completions(self, document, complete_event):
|
|
936
|
+
text = document.text_before_cursor
|
|
937
|
+
if text.startswith("/"):
|
|
938
|
+
for cmd, desc in SLASH_COMMANDS.items():
|
|
939
|
+
if cmd.startswith(text):
|
|
940
|
+
icon = SLASH_COMMAND_ICONS.get(cmd, "✦")
|
|
941
|
+
yield Completion(
|
|
942
|
+
cmd,
|
|
943
|
+
start_position=-len(text),
|
|
944
|
+
display=f"{icon} {cmd:<11}",
|
|
945
|
+
display_meta=f" {desc}",
|
|
946
|
+
)
|
|
947
|
+
|
|
948
|
+
|
|
949
|
+
_current_controller: Optional[AgentController] = None
|
|
950
|
+
|
|
951
|
+
|
|
952
|
+
def _get_dynamic_prompt():
|
|
953
|
+
"""Show clean prompt when idle, [working] when busy, and 'You: ' dynamically once the user begins typing."""
|
|
954
|
+
from prompt_toolkit.application.current import get_app
|
|
955
|
+
try:
|
|
956
|
+
app = get_app()
|
|
957
|
+
if app and app.current_buffer and app.current_buffer.text:
|
|
958
|
+
return HTML("<ansicyan><b>You: </b></ansicyan>")
|
|
959
|
+
except Exception:
|
|
960
|
+
pass
|
|
961
|
+
if _current_controller:
|
|
962
|
+
if _current_controller.active_approval and not _current_controller.active_approval.done():
|
|
963
|
+
return HTML("<ansiyellow><b>Approve? [y/n/a/d] (or /btw) ❯ </b></ansiyellow>")
|
|
964
|
+
if _current_controller.running:
|
|
965
|
+
return HTML("<ansiyellow><b>[working] ❯ </b></ansiyellow>")
|
|
966
|
+
return HTML("<ansicyan><b>❯ </b></ansicyan>")
|
|
967
|
+
|
|
968
|
+
|
|
969
|
+
def setup_readline_completion():
|
|
970
|
+
"""Set up readline for tab completion of slash commands."""
|
|
971
|
+
# Only works on Unix-like systems and Windows with pyreadline3
|
|
972
|
+
try:
|
|
973
|
+
import readline
|
|
974
|
+
readline.parse_and_bind("tab: complete")
|
|
975
|
+
# Create a completer function
|
|
976
|
+
def completer(text, state):
|
|
977
|
+
if text.startswith("/"):
|
|
978
|
+
matches = [cmd for cmd in SLASH_COMMAND_NAMES if cmd.startswith(text)]
|
|
979
|
+
else:
|
|
980
|
+
matches = []
|
|
981
|
+
if state < len(matches):
|
|
982
|
+
return matches[state]
|
|
983
|
+
return None
|
|
984
|
+
readline.set_completer(completer)
|
|
985
|
+
# Also bind '?' to show completions
|
|
986
|
+
readline.parse_and_bind('"?": complete')
|
|
987
|
+
except ImportError:
|
|
988
|
+
pass # readline not available
|
|
989
|
+
|
|
990
|
+
|
|
991
|
+
def _get_input_with_readline() -> str:
|
|
992
|
+
"""Get user input with readline tab completion support (fallback)."""
|
|
993
|
+
try:
|
|
994
|
+
import readline
|
|
995
|
+
# Set up completion each time (in case it wasn't set up)
|
|
996
|
+
readline.parse_and_bind("tab: complete")
|
|
997
|
+
def completer(text, state):
|
|
998
|
+
if text.startswith("/"):
|
|
999
|
+
matches = [cmd for cmd in SLASH_COMMAND_NAMES if cmd.startswith(text)]
|
|
1000
|
+
else:
|
|
1001
|
+
matches = []
|
|
1002
|
+
if state < len(matches):
|
|
1003
|
+
return matches[state]
|
|
1004
|
+
return None
|
|
1005
|
+
readline.set_completer(completer)
|
|
1006
|
+
readline.parse_and_bind('"?": complete')
|
|
1007
|
+
except ImportError:
|
|
1008
|
+
pass
|
|
1009
|
+
if _current_controller:
|
|
1010
|
+
if _current_controller.active_approval and not _current_controller.active_approval.done():
|
|
1011
|
+
return input("\x1b[1;33mApprove? [y/n/a/d] (or /btw) ❯\x1b[0m ")
|
|
1012
|
+
if _current_controller.running:
|
|
1013
|
+
return input("\x1b[1;33m[working] ❯\x1b[0m ")
|
|
1014
|
+
return input("\x1b[1;36m❯\x1b[0m ")
|
|
1015
|
+
|
|
1016
|
+
|
|
1017
|
+
async def _handle_slash_command(command: str, controller: AgentController) -> None:
|
|
1018
|
+
"""Handle slash commands in chat."""
|
|
1019
|
+
from agent.config import get_config, update_config, get_profiles, save_profile, delete_profile, load_profile
|
|
1020
|
+
from agent.model import get_model_client, reset_model_client
|
|
1021
|
+
from agent.controller import AgentController
|
|
1022
|
+
|
|
1023
|
+
parts = command.split()
|
|
1024
|
+
cmd = parts[0].lower()
|
|
1025
|
+
|
|
1026
|
+
if cmd == "/btw":
|
|
1027
|
+
question = command[4:].strip() if len(command) > 4 else ""
|
|
1028
|
+
if not question:
|
|
1029
|
+
console.print("[yellow]Usage: /btw <your question or side note>[/yellow]")
|
|
1030
|
+
console.print("[dim]Example: /btw what database are we using?[/dim]")
|
|
1031
|
+
console.print("[dim]Example: /btw make sure to write clean docstrings[/dim]")
|
|
1032
|
+
return True
|
|
1033
|
+
await _handle_btw_command(question, controller)
|
|
1034
|
+
return True
|
|
1035
|
+
|
|
1036
|
+
elif cmd == "/queue":
|
|
1037
|
+
_handle_queue_command(parts, controller)
|
|
1038
|
+
return True
|
|
1039
|
+
|
|
1040
|
+
elif cmd == "/help":
|
|
1041
|
+
_show_help()
|
|
1042
|
+
return True
|
|
1043
|
+
|
|
1044
|
+
elif cmd == "/model":
|
|
1045
|
+
config = get_config()
|
|
1046
|
+
await _show_models_command(config)
|
|
1047
|
+
return True
|
|
1048
|
+
|
|
1049
|
+
elif cmd == "/models":
|
|
1050
|
+
config = get_config()
|
|
1051
|
+
await _show_models_list(config)
|
|
1052
|
+
return True
|
|
1053
|
+
|
|
1054
|
+
elif cmd in ("/settings", "/provider"):
|
|
1055
|
+
await _handle_provider_command(parts, controller)
|
|
1056
|
+
return True
|
|
1057
|
+
|
|
1058
|
+
elif cmd == "/status":
|
|
1059
|
+
_show_status_command(controller)
|
|
1060
|
+
return True
|
|
1061
|
+
|
|
1062
|
+
elif cmd == "/tokens":
|
|
1063
|
+
_show_tokens_command(controller)
|
|
1064
|
+
return True
|
|
1065
|
+
|
|
1066
|
+
elif cmd == "/config":
|
|
1067
|
+
await _handle_config_command(parts, controller)
|
|
1068
|
+
return True
|
|
1069
|
+
|
|
1070
|
+
elif cmd == "/history":
|
|
1071
|
+
_show_history_command(controller, parts)
|
|
1072
|
+
return True
|
|
1073
|
+
|
|
1074
|
+
elif cmd == "/continue":
|
|
1075
|
+
if controller.has_saved_session():
|
|
1076
|
+
controller.load_session()
|
|
1077
|
+
count = len([m for m in controller.context.messages if m.role == "user"])
|
|
1078
|
+
console.print(render_system_message(f"[green]Continued previous session ({count} user interactions restored).[/green]"))
|
|
1079
|
+
else:
|
|
1080
|
+
console.print(render_system_message("[yellow]No saved session found to continue.[/yellow]"))
|
|
1081
|
+
return True
|
|
1082
|
+
|
|
1083
|
+
elif cmd in ("/exit", "/quit", "/q"):
|
|
1084
|
+
console.print(render_system_message("[yellow]Goodbye from ireri![/yellow]"))
|
|
1085
|
+
return False
|
|
1086
|
+
|
|
1087
|
+
elif cmd == "/clear":
|
|
1088
|
+
console.clear()
|
|
1089
|
+
return True
|
|
1090
|
+
|
|
1091
|
+
elif cmd == "/errors":
|
|
1092
|
+
_show_errors_command(controller, parts)
|
|
1093
|
+
return True
|
|
1094
|
+
|
|
1095
|
+
elif cmd in ("/logs", "/log"):
|
|
1096
|
+
await _handle_logs_command(parts)
|
|
1097
|
+
return True
|
|
1098
|
+
|
|
1099
|
+
elif cmd in ("/ps", "/processes"):
|
|
1100
|
+
await _handle_ps_command(parts)
|
|
1101
|
+
return True
|
|
1102
|
+
|
|
1103
|
+
elif cmd == "/reset":
|
|
1104
|
+
controller.reset()
|
|
1105
|
+
console.print(render_system_message("[green]Session reset.[/green]"))
|
|
1106
|
+
return True
|
|
1107
|
+
|
|
1108
|
+
elif cmd == "/version":
|
|
1109
|
+
_show_version_command()
|
|
1110
|
+
return True
|
|
1111
|
+
|
|
1112
|
+
elif cmd == "/update":
|
|
1113
|
+
_show_update_command()
|
|
1114
|
+
return True
|
|
1115
|
+
|
|
1116
|
+
elif cmd == "/about":
|
|
1117
|
+
_show_about_command()
|
|
1118
|
+
return True
|
|
1119
|
+
|
|
1120
|
+
else:
|
|
1121
|
+
console.print(f"[yellow]Unknown command: {cmd}. Type /help for available commands.[/yellow]")
|
|
1122
|
+
return True
|
|
1123
|
+
|
|
1124
|
+
|
|
1125
|
+
def _show_history_command(controller: AgentController, parts: list) -> None:
|
|
1126
|
+
"""Handle /history command - display recent conversation history."""
|
|
1127
|
+
limit = 10
|
|
1128
|
+
if len(parts) > 1:
|
|
1129
|
+
try:
|
|
1130
|
+
limit = int(parts[1])
|
|
1131
|
+
except ValueError:
|
|
1132
|
+
pass
|
|
1133
|
+
|
|
1134
|
+
history = controller.session_manager.get_recent_history(limit=limit)
|
|
1135
|
+
if not history:
|
|
1136
|
+
console.print(render_system_message("[dim]No previous conversation history found.[/dim]"))
|
|
1137
|
+
return
|
|
1138
|
+
|
|
1139
|
+
table = Table(title=f"Recent Conversation History (Last {len(history)} messages)", box=ROUNDED, border_style="bright_blue")
|
|
1140
|
+
table.add_column("#", style="dim", width=4)
|
|
1141
|
+
table.add_column("Speaker", style="cyan", width=12)
|
|
1142
|
+
table.add_column("Message Preview", style="white")
|
|
1143
|
+
|
|
1144
|
+
for idx, msg in enumerate(history, 1):
|
|
1145
|
+
role = "[bold cyan]You[/bold cyan]" if msg.get("role") == "user" else "[bold green]ireri[/bold green]"
|
|
1146
|
+
content = msg.get("content", "").strip().replace("\n", " ")
|
|
1147
|
+
if len(content) > 90:
|
|
1148
|
+
content = content[:87] + "..."
|
|
1149
|
+
table.add_row(str(idx), role, content)
|
|
1150
|
+
|
|
1151
|
+
console.print()
|
|
1152
|
+
console.print(table)
|
|
1153
|
+
console.print(render_system_message(
|
|
1154
|
+
f"[dim]Full transcript logged at: [underline]{controller.session_manager.history_file}[/underline][/dim]"
|
|
1155
|
+
))
|
|
1156
|
+
console.print()
|
|
1157
|
+
|
|
1158
|
+
|
|
1159
|
+
def _show_errors_command(controller: AgentController, parts: list) -> None:
|
|
1160
|
+
"""Handle /errors command - display recent errors from .ireri/errors.log."""
|
|
1161
|
+
limit = 10
|
|
1162
|
+
if len(parts) > 1:
|
|
1163
|
+
try:
|
|
1164
|
+
limit = int(parts[1])
|
|
1165
|
+
except ValueError:
|
|
1166
|
+
pass
|
|
1167
|
+
|
|
1168
|
+
errors = controller.session_manager.get_recent_errors(limit=limit)
|
|
1169
|
+
if not errors:
|
|
1170
|
+
console.print(render_system_message(
|
|
1171
|
+
f"[dim]No errors encountered yet in: [underline]{controller.session_manager.error_log_file}[/underline][/dim]"
|
|
1172
|
+
))
|
|
1173
|
+
return
|
|
1174
|
+
|
|
1175
|
+
table = Table(title=f"Recent Errors (Last {len(errors)} entries)", box=ROUNDED, border_style="red")
|
|
1176
|
+
table.add_column("Timestamp", style="dim", width=19)
|
|
1177
|
+
table.add_column("Type", style="bold red", width=16)
|
|
1178
|
+
table.add_column("Message", style="white")
|
|
1179
|
+
|
|
1180
|
+
for err in errors:
|
|
1181
|
+
msg = err.get("message", "").strip().replace("\n", " ")
|
|
1182
|
+
if len(msg) > 80:
|
|
1183
|
+
msg = msg[:77] + "..."
|
|
1184
|
+
table.add_row(err.get("timestamp", ""), err.get("type", "ERROR"), msg)
|
|
1185
|
+
|
|
1186
|
+
console.print()
|
|
1187
|
+
console.print(table)
|
|
1188
|
+
console.print(render_system_message(
|
|
1189
|
+
f"[dim]Full error log at: [underline]{controller.session_manager.error_log_file}[/underline][/dim]"
|
|
1190
|
+
))
|
|
1191
|
+
console.print()
|
|
1192
|
+
|
|
1193
|
+
|
|
1194
|
+
async def _handle_ps_command(parts: list) -> None:
|
|
1195
|
+
"""Handle /ps command - list or stop ongoing/recent processes."""
|
|
1196
|
+
from agent.tools.terminal import get_process_manager
|
|
1197
|
+
|
|
1198
|
+
pm = get_process_manager()
|
|
1199
|
+
sub = parts[1].lower() if len(parts) > 1 else ""
|
|
1200
|
+
|
|
1201
|
+
if sub == "stop":
|
|
1202
|
+
target = parts[2] if len(parts) > 2 else ""
|
|
1203
|
+
if not target:
|
|
1204
|
+
console.print("[yellow]Usage: /ps stop <process_id|all>[/yellow]")
|
|
1205
|
+
return
|
|
1206
|
+
if target.lower() == "all":
|
|
1207
|
+
count = pm.stop_all()
|
|
1208
|
+
console.print(render_system_message(f"[yellow]Stopped {count} running process(es).[/yellow]"))
|
|
1209
|
+
return
|
|
1210
|
+
ok, msg = await pm.stop_process(target)
|
|
1211
|
+
color = "green" if ok else "red"
|
|
1212
|
+
console.print(render_system_message(f"[{color}]{msg}[/{color}]"))
|
|
1213
|
+
return
|
|
1214
|
+
|
|
1215
|
+
procs = pm.list_processes()
|
|
1216
|
+
if not procs:
|
|
1217
|
+
console.print(render_system_message("[dim]No processes have been started in this session yet.[/dim]"))
|
|
1218
|
+
return
|
|
1219
|
+
|
|
1220
|
+
table = Table(title="Managed Processes", box=ROUNDED, border_style="bright_blue")
|
|
1221
|
+
table.add_column("ID", style="cyan", width=10)
|
|
1222
|
+
table.add_column("PID", style="dim", width=8)
|
|
1223
|
+
table.add_column("Status", width=14)
|
|
1224
|
+
table.add_column("Mode", style="dim", width=12)
|
|
1225
|
+
table.add_column("Uptime", style="dim", width=9)
|
|
1226
|
+
table.add_column("Command", style="white")
|
|
1227
|
+
|
|
1228
|
+
for p in procs:
|
|
1229
|
+
status_str = "[bold green]RUNNING[/bold green]" if p.is_running else f"[dim]EXIT ({p.returncode})[/dim]"
|
|
1230
|
+
mode_str = "background" if p.background else "foreground"
|
|
1231
|
+
uptime_str = f"{p.uptime_seconds:.1f}s"
|
|
1232
|
+
cmd_str = p.command if len(p.command) <= 60 else p.command[:57] + "..."
|
|
1233
|
+
table.add_row(p.process_id, str(p.pid or "-"), status_str, mode_str, uptime_str, cmd_str)
|
|
1234
|
+
|
|
1235
|
+
console.print()
|
|
1236
|
+
console.print(table)
|
|
1237
|
+
console.print(render_system_message(
|
|
1238
|
+
"[dim]Commands: [cyan]/logs <id>[/cyan] (view logs) • [cyan]/logs follow <id>[/cyan] (stream live) • [cyan]/ps stop <id>[/cyan] (stop)[/dim]"
|
|
1239
|
+
))
|
|
1240
|
+
console.print()
|
|
1241
|
+
|
|
1242
|
+
|
|
1243
|
+
async def _handle_logs_command(parts: list) -> None:
|
|
1244
|
+
"""Handle /logs command - view or follow live logs of an ongoing or recent process."""
|
|
1245
|
+
from rich.markup import escape
|
|
1246
|
+
from agent.tools.terminal import get_process_manager
|
|
1247
|
+
|
|
1248
|
+
pm = get_process_manager()
|
|
1249
|
+
args = parts[1:]
|
|
1250
|
+
|
|
1251
|
+
follow = False
|
|
1252
|
+
proc_id: Optional[str] = None
|
|
1253
|
+
tail = 80
|
|
1254
|
+
|
|
1255
|
+
for arg in args:
|
|
1256
|
+
low = arg.lower()
|
|
1257
|
+
if low in ("follow", "-f", "--follow", "live"):
|
|
1258
|
+
follow = True
|
|
1259
|
+
elif arg.isdigit():
|
|
1260
|
+
tail = int(arg)
|
|
1261
|
+
elif not proc_id:
|
|
1262
|
+
proc_id = arg
|
|
1263
|
+
|
|
1264
|
+
proc = pm.get_process(proc_id)
|
|
1265
|
+
if not proc:
|
|
1266
|
+
msg = f"Process '{proc_id}' not found." if proc_id else "No ongoing or recent processes found."
|
|
1267
|
+
console.print(render_system_message(f"[yellow]{msg}[/yellow] [dim]Run /ps to list processes.[/dim]"))
|
|
1268
|
+
return
|
|
1269
|
+
|
|
1270
|
+
status_label = "[bold green]RUNNING[/bold green]" if proc.is_running else f"[dim]EXITED ({proc.returncode})[/dim]"
|
|
1271
|
+
header = (
|
|
1272
|
+
f"[bold cyan]{proc.process_id}[/bold cyan] (PID {proc.pid}) • {status_label} • "
|
|
1273
|
+
f"[dim]Uptime: {proc.uptime_seconds:.1f}s[/dim]\n"
|
|
1274
|
+
f"[dim]Command: {escape(proc.command)}[/dim]"
|
|
1275
|
+
)
|
|
1276
|
+
|
|
1277
|
+
if not follow:
|
|
1278
|
+
logs = proc.get_recent_logs(tail=tail)
|
|
1279
|
+
body = escape(logs) if logs else "[dim](No output captured yet)[/dim]"
|
|
1280
|
+
console.print()
|
|
1281
|
+
console.print(Panel(
|
|
1282
|
+
f"{header}\n\n{body}",
|
|
1283
|
+
title=f"[bold bright_blue]Process Logs (last {tail} lines)[/bold bright_blue]",
|
|
1284
|
+
border_style="bright_blue",
|
|
1285
|
+
box=ROUNDED,
|
|
1286
|
+
padding=(0, 1),
|
|
1287
|
+
))
|
|
1288
|
+
if proc.is_running:
|
|
1289
|
+
console.print(render_system_message(
|
|
1290
|
+
f"[dim]Process is still running. Use [cyan]/logs follow {proc.process_id}[/cyan] to stream live logs or [cyan]/ps stop {proc.process_id}[/cyan] to stop.[/dim]"
|
|
1291
|
+
))
|
|
1292
|
+
console.print()
|
|
1293
|
+
return
|
|
1294
|
+
|
|
1295
|
+
# Live follow mode
|
|
1296
|
+
console.print()
|
|
1297
|
+
console.print(Panel(
|
|
1298
|
+
f"{header}\n[dim]Streaming live logs... Press Ctrl+C to stop watching (the process will keep running).[/dim]",
|
|
1299
|
+
title="[bold bright_cyan]Live Process Logs[/bold bright_cyan]",
|
|
1300
|
+
border_style="bright_cyan",
|
|
1301
|
+
box=ROUNDED,
|
|
1302
|
+
))
|
|
1303
|
+
|
|
1304
|
+
# Print existing recent lines first
|
|
1305
|
+
all_lines = list(proc.combined_logs)
|
|
1306
|
+
start_idx = max(0, len(all_lines) - min(tail, 30))
|
|
1307
|
+
for line in all_lines[start_idx:]:
|
|
1308
|
+
console.print(f" {escape(line)}")
|
|
1309
|
+
seen_total = len(all_lines)
|
|
1310
|
+
|
|
1311
|
+
try:
|
|
1312
|
+
while True:
|
|
1313
|
+
cur_lines = list(proc.combined_logs)
|
|
1314
|
+
if len(cur_lines) > seen_total:
|
|
1315
|
+
for line in cur_lines[seen_total:]:
|
|
1316
|
+
console.print(f" {escape(line)}")
|
|
1317
|
+
seen_total = len(cur_lines)
|
|
1318
|
+
elif len(cur_lines) < seen_total:
|
|
1319
|
+
# Deque wrapped around
|
|
1320
|
+
seen_total = len(cur_lines)
|
|
1321
|
+
|
|
1322
|
+
if not proc.is_running:
|
|
1323
|
+
# Flush any final lines
|
|
1324
|
+
cur_lines = list(proc.combined_logs)
|
|
1325
|
+
if len(cur_lines) > seen_total:
|
|
1326
|
+
for line in cur_lines[seen_total:]:
|
|
1327
|
+
console.print(f" {escape(line)}")
|
|
1328
|
+
console.print(render_system_message(f"[dim]Process {proc.process_id} exited with code {proc.returncode}.[/dim]"))
|
|
1329
|
+
break
|
|
1330
|
+
await asyncio.sleep(0.25)
|
|
1331
|
+
except (asyncio.CancelledError, KeyboardInterrupt):
|
|
1332
|
+
console.print(render_system_message(f"[yellow]Stopped watching logs for {proc.process_id} (process still {'running' if proc.is_running else 'exited'}).[/yellow]"))
|
|
1333
|
+
|
|
1334
|
+
|
|
1335
|
+
async def _handle_btw_command(question: str, controller: AgentController) -> None:
|
|
1336
|
+
"""Execute direct side-question to model and display enlightened response."""
|
|
1337
|
+
console.print()
|
|
1338
|
+
console.print(Panel(
|
|
1339
|
+
f"[bold bright_yellow]Q:[/bold bright_yellow] {question}\n\n[dim]Consulting model directly...[/dim]",
|
|
1340
|
+
title="[bold yellow]💡 By the Way (Direct Side-Chat)[/bold yellow]",
|
|
1341
|
+
border_style="yellow",
|
|
1342
|
+
box=ROUNDED,
|
|
1343
|
+
padding=(0, 1),
|
|
1344
|
+
))
|
|
1345
|
+
|
|
1346
|
+
answer = await controller.ask_direct(question)
|
|
1347
|
+
|
|
1348
|
+
console.print()
|
|
1349
|
+
console.print(Panel(
|
|
1350
|
+
Markdown(answer),
|
|
1351
|
+
title="[bold bright_green]ireri (Direct Answer)[/bold bright_green]",
|
|
1352
|
+
subtitle="[dim]✓ Injected into agent context to guide ongoing & subsequent steps[/dim]",
|
|
1353
|
+
border_style="bright_yellow",
|
|
1354
|
+
box=ROUNDED,
|
|
1355
|
+
padding=(0, 1),
|
|
1356
|
+
))
|
|
1357
|
+
console.print()
|
|
1358
|
+
|
|
1359
|
+
|
|
1360
|
+
def _handle_queue_command(parts: list, controller: AgentController) -> None:
|
|
1361
|
+
"""Handle /queue slash command to view, add, or clear queued messages."""
|
|
1362
|
+
sub = parts[1].lower() if len(parts) > 1 else ""
|
|
1363
|
+
|
|
1364
|
+
if sub in ("clear", "reset"):
|
|
1365
|
+
count = controller.clear_message_queue()
|
|
1366
|
+
console.print(render_system_message(f"[green]Cleared {count} queued message(s).[/green]"))
|
|
1367
|
+
return
|
|
1368
|
+
|
|
1369
|
+
if sub == "add" and len(parts) > 2:
|
|
1370
|
+
msg = " ".join(parts[2:]).strip()
|
|
1371
|
+
q_len = controller.queue_message(msg)
|
|
1372
|
+
console.print(render_system_message(f"[green]✓ Queued task #{q_len}:[/green] [white]{msg}[/white]"))
|
|
1373
|
+
return
|
|
1374
|
+
|
|
1375
|
+
# If sub is not a reserved keyword but user typed: /queue do something
|
|
1376
|
+
if sub and sub not in ("list", "show") and len(parts) >= 2:
|
|
1377
|
+
msg = " ".join(parts[1:]).strip()
|
|
1378
|
+
q_len = controller.queue_message(msg)
|
|
1379
|
+
console.print(render_system_message(f"[green]✓ Queued task #{q_len}:[/green] [white]{msg}[/white]"))
|
|
1380
|
+
return
|
|
1381
|
+
|
|
1382
|
+
queued = controller.get_queued_messages()
|
|
1383
|
+
if not queued:
|
|
1384
|
+
console.print(render_system_message(
|
|
1385
|
+
"[dim]Message queue is currently empty.\n"
|
|
1386
|
+
"Queue upcoming tasks with [bold cyan]/queue <message>[/bold cyan] or while running.\n"
|
|
1387
|
+
"They will automatically execute in order after the active task finishes.[/dim]"
|
|
1388
|
+
))
|
|
1389
|
+
return
|
|
1390
|
+
|
|
1391
|
+
table = Table(title=f"Queued Messages ({len(queued)} pending)", box=ROUNDED, border_style="cyan")
|
|
1392
|
+
table.add_column("#", style="dim", width=4)
|
|
1393
|
+
table.add_column("Queued Task", style="white")
|
|
1394
|
+
|
|
1395
|
+
for idx, msg in enumerate(queued, 1):
|
|
1396
|
+
preview = msg.replace("\n", " ")
|
|
1397
|
+
if len(preview) > 85:
|
|
1398
|
+
preview = preview[:82] + "..."
|
|
1399
|
+
table.add_row(str(idx), preview)
|
|
1400
|
+
|
|
1401
|
+
console.print()
|
|
1402
|
+
console.print(table)
|
|
1403
|
+
console.print(render_system_message(
|
|
1404
|
+
"[dim]These tasks will automatically run in sequence after the current task finishes.\n"
|
|
1405
|
+
"Use [bold cyan]/queue add <task>[/bold cyan] to queue more, or [bold cyan]/queue clear[/bold cyan] to remove all.[/dim]"
|
|
1406
|
+
))
|
|
1407
|
+
console.print()
|
|
1408
|
+
|
|
1409
|
+
|
|
1410
|
+
# Configuration key mappings and aliases
|
|
1411
|
+
CONFIG_KEY_MAP = {
|
|
1412
|
+
"max_iterations": "max_iterations",
|
|
1413
|
+
"iterations": "max_iterations",
|
|
1414
|
+
"iter": "max_iterations",
|
|
1415
|
+
"max-iterations": "max_iterations",
|
|
1416
|
+
"max_iter": "max_iterations",
|
|
1417
|
+
"max_tool_calls": "max_tool_calls",
|
|
1418
|
+
"tool_calls": "max_tool_calls",
|
|
1419
|
+
"tools": "max_tool_calls",
|
|
1420
|
+
"max-tool-calls": "max_tool_calls",
|
|
1421
|
+
"max_tools": "max_tool_calls",
|
|
1422
|
+
"command_timeout": "command_timeout",
|
|
1423
|
+
"timeout": "command_timeout",
|
|
1424
|
+
"cmd_timeout": "command_timeout",
|
|
1425
|
+
"command-timeout": "command_timeout",
|
|
1426
|
+
"model": "openai_model",
|
|
1427
|
+
"openai_model": "openai_model",
|
|
1428
|
+
"base_url": "openai_base_url",
|
|
1429
|
+
"url": "openai_base_url",
|
|
1430
|
+
"openai_base_url": "openai_base_url",
|
|
1431
|
+
"api_key": "openai_api_key",
|
|
1432
|
+
"key": "openai_api_key",
|
|
1433
|
+
"openai_api_key": "openai_api_key",
|
|
1434
|
+
"log_level": "log_level",
|
|
1435
|
+
"log": "log_level",
|
|
1436
|
+
"level": "log_level",
|
|
1437
|
+
}
|
|
1438
|
+
|
|
1439
|
+
|
|
1440
|
+
def set_config_value(key: str, value: Any, controller: Optional[AgentController] = None) -> tuple[bool, str]:
|
|
1441
|
+
"""Set and persist a configuration value immediately to global config and active controller."""
|
|
1442
|
+
from agent.config import get_config, update_config
|
|
1443
|
+
from agent.model import reset_model_client, get_model_client
|
|
1444
|
+
|
|
1445
|
+
key_normalized = key.lower().replace("-", "_")
|
|
1446
|
+
target_field = CONFIG_KEY_MAP.get(key_normalized)
|
|
1447
|
+
if not target_field:
|
|
1448
|
+
valid_keys = ", ".join(["max_iterations", "max_tool_calls", "command_timeout", "model", "base_url", "api_key", "log_level"])
|
|
1449
|
+
return False, f"Unknown setting '{key}'. Valid settings: {valid_keys}"
|
|
1450
|
+
|
|
1451
|
+
# Type validation & conversion
|
|
1452
|
+
if target_field in ("max_iterations", "max_tool_calls", "command_timeout"):
|
|
1453
|
+
try:
|
|
1454
|
+
val = int(value)
|
|
1455
|
+
if val <= 0:
|
|
1456
|
+
return False, f"{target_field} must be a positive integer"
|
|
1457
|
+
except (ValueError, TypeError):
|
|
1458
|
+
return False, f"Invalid integer value for {target_field}: {value}"
|
|
1459
|
+
elif target_field == "log_level":
|
|
1460
|
+
val = str(value).upper()
|
|
1461
|
+
if val not in ("DEBUG", "INFO", "WARNING", "ERROR", "CRITICAL"):
|
|
1462
|
+
return False, f"Invalid log level: {value}. Choose from: DEBUG, INFO, WARNING, ERROR, CRITICAL"
|
|
1463
|
+
else:
|
|
1464
|
+
val = str(value).strip()
|
|
1465
|
+
if not val:
|
|
1466
|
+
return False, f"{target_field} cannot be empty"
|
|
1467
|
+
|
|
1468
|
+
update_config(**{target_field: val})
|
|
1469
|
+
|
|
1470
|
+
# Update active controller and model client if in active chat session
|
|
1471
|
+
if controller is not None:
|
|
1472
|
+
controller.config = get_config()
|
|
1473
|
+
if target_field in ("openai_model", "openai_base_url", "openai_api_key"):
|
|
1474
|
+
reset_model_client()
|
|
1475
|
+
controller.model_client = get_model_client()
|
|
1476
|
+
|
|
1477
|
+
return True, f"Updated [bold cyan]{target_field}[/bold cyan] to [bold green]{val}[/bold green]"
|
|
1478
|
+
|
|
1479
|
+
|
|
1480
|
+
def _show_config_table(config: AgentConfig) -> None:
|
|
1481
|
+
"""Render the configuration table with editing instructions."""
|
|
1482
|
+
table = Table(title="ireri Configuration", box=ROUNDED, border_style="bright_blue")
|
|
1483
|
+
table.add_column("Setting", style="cyan", width=18)
|
|
1484
|
+
table.add_column("Value", style="white")
|
|
1485
|
+
table.add_column("Description", style="dim")
|
|
1486
|
+
|
|
1487
|
+
table.add_row("Model", config.openai_model, "Active LLM model name")
|
|
1488
|
+
table.add_row("Base URL", config.openai_base_url, "API endpoint base URL")
|
|
1489
|
+
table.add_row("API Key", ("***" + config.openai_api_key[-4:]) if config.openai_api_key else "Not set", "Provider API secret key")
|
|
1490
|
+
table.add_row("Workspace", str(config.workspace_root), "Current working workspace directory")
|
|
1491
|
+
table.add_row("Max Iterations", str(config.max_iterations), "Max reasoning/tool iterations per task")
|
|
1492
|
+
table.add_row("Max Tool Calls", str(config.max_tool_calls), "Max total tool executions per task")
|
|
1493
|
+
table.add_row("Command Timeout", f"{config.command_timeout}s", "Timeout for shell commands in seconds")
|
|
1494
|
+
table.add_row("Log Level", config.log_level, "Logging verbosity (DEBUG, INFO, WARNING, ERROR)")
|
|
1495
|
+
|
|
1496
|
+
console.print()
|
|
1497
|
+
console.print(table)
|
|
1498
|
+
console.print()
|
|
1499
|
+
help_panel = (
|
|
1500
|
+
"[bold cyan]How to change settings:[/bold cyan]\n"
|
|
1501
|
+
" • [yellow]/config set <setting> <value>[/yellow] (e.g., [green]/config set max_iterations 1000[/green])\n"
|
|
1502
|
+
" • [yellow]/config <setting> <value>[/yellow] (shorthand, e.g. [green]/config max_tool_calls 1000[/green])\n"
|
|
1503
|
+
" • [yellow]/config edit[/yellow] (interactive configuration wizard)\n"
|
|
1504
|
+
" • [yellow]/config get <setting>[/yellow] (view specific value)\n"
|
|
1505
|
+
" • [yellow]/settings set <setting> <val>[/yellow] (works in /settings too!)"
|
|
1506
|
+
)
|
|
1507
|
+
console.print(Panel(help_panel, title="[bold]Configuration Controls[/bold]", border_style="dim", box=ROUNDED))
|
|
1508
|
+
console.print()
|
|
1509
|
+
|
|
1510
|
+
|
|
1511
|
+
async def _interactive_tool_access_edit(controller: Optional[AgentController] = None) -> None:
|
|
1512
|
+
"""Interactive arrow-key editor for per-tool access policies (allow / ask / deny)."""
|
|
1513
|
+
from agent.config import _save_global_config
|
|
1514
|
+
|
|
1515
|
+
config = controller.config if controller else get_config()
|
|
1516
|
+
registry = get_registry()
|
|
1517
|
+
tools = sorted(registry.get_all(), key=lambda t: t.name)
|
|
1518
|
+
|
|
1519
|
+
if not tools:
|
|
1520
|
+
console.print("[yellow]No tools registered.[/yellow]")
|
|
1521
|
+
return
|
|
1522
|
+
|
|
1523
|
+
policy_order = ["allow", "ask", "deny"]
|
|
1524
|
+
|
|
1525
|
+
def _cycle_policy(tool, direction: int = 1):
|
|
1526
|
+
default_p = "ask" if tool.requires_approval else "allow"
|
|
1527
|
+
cur = config.get_tool_access(tool.name, default=default_p)
|
|
1528
|
+
idx = policy_order.index(cur) if cur in policy_order else 1
|
|
1529
|
+
nxt = policy_order[(idx + direction) % len(policy_order)]
|
|
1530
|
+
config.set_tool_access(tool.name, nxt)
|
|
1531
|
+
_save_global_config(config)
|
|
1532
|
+
|
|
1533
|
+
# Interactive prompt_toolkit mode when TTY is available
|
|
1534
|
+
if sys.stdin.isatty():
|
|
1535
|
+
try:
|
|
1536
|
+
from prompt_toolkit.application import Application
|
|
1537
|
+
from prompt_toolkit.key_binding import KeyBindings
|
|
1538
|
+
from prompt_toolkit.layout import Layout, HSplit, Window
|
|
1539
|
+
from prompt_toolkit.layout.controls import FormattedTextControl
|
|
1540
|
+
from prompt_toolkit.styles import Style
|
|
1541
|
+
|
|
1542
|
+
selected_idx = 0
|
|
1543
|
+
total_items = len(tools) + 2 # tools + Reset all + Done
|
|
1544
|
+
kb = KeyBindings()
|
|
1545
|
+
|
|
1546
|
+
@kb.add("up")
|
|
1547
|
+
@kb.add("k")
|
|
1548
|
+
def _up(event):
|
|
1549
|
+
nonlocal selected_idx
|
|
1550
|
+
selected_idx = (selected_idx - 1) % total_items
|
|
1551
|
+
|
|
1552
|
+
@kb.add("down")
|
|
1553
|
+
@kb.add("j")
|
|
1554
|
+
def _down(event):
|
|
1555
|
+
nonlocal selected_idx
|
|
1556
|
+
selected_idx = (selected_idx + 1) % total_items
|
|
1557
|
+
|
|
1558
|
+
@kb.add("right")
|
|
1559
|
+
@kb.add("l")
|
|
1560
|
+
@kb.add(" ")
|
|
1561
|
+
def _cycle_next(event):
|
|
1562
|
+
if selected_idx < len(tools):
|
|
1563
|
+
_cycle_policy(tools[selected_idx], 1)
|
|
1564
|
+
|
|
1565
|
+
@kb.add("left")
|
|
1566
|
+
@kb.add("h")
|
|
1567
|
+
def _cycle_prev(event):
|
|
1568
|
+
if selected_idx < len(tools):
|
|
1569
|
+
_cycle_policy(tools[selected_idx], -1)
|
|
1570
|
+
|
|
1571
|
+
@kb.add("enter")
|
|
1572
|
+
def _enter(event):
|
|
1573
|
+
if selected_idx < len(tools):
|
|
1574
|
+
_cycle_policy(tools[selected_idx], 1)
|
|
1575
|
+
elif selected_idx == len(tools):
|
|
1576
|
+
config.reset_tool_access()
|
|
1577
|
+
_save_global_config(config)
|
|
1578
|
+
else:
|
|
1579
|
+
event.app.exit(result=True)
|
|
1580
|
+
|
|
1581
|
+
@kb.add("q")
|
|
1582
|
+
@kb.add("escape")
|
|
1583
|
+
@kb.add("c-c")
|
|
1584
|
+
def _exit(event):
|
|
1585
|
+
event.app.exit(result=True)
|
|
1586
|
+
|
|
1587
|
+
def _render():
|
|
1588
|
+
lines = [
|
|
1589
|
+
("class:title", " Tool Access Settings (/settings tools)\n"),
|
|
1590
|
+
("class:subtitle", " ↑/↓: navigate • ←/→/Space/Enter: change [ALLOW / ASK / DENY] • q/Esc: save & exit\n\n"),
|
|
1591
|
+
]
|
|
1592
|
+
for idx, tool in enumerate(tools):
|
|
1593
|
+
is_sel = idx == selected_idx
|
|
1594
|
+
default_p = "ask" if tool.requires_approval else "allow"
|
|
1595
|
+
policy = config.get_tool_access(tool.name, default=default_p)
|
|
1596
|
+
danger = " !DANGEROUS" if tool.dangerous else ""
|
|
1597
|
+
pointer = " ❯ " if is_sel else " "
|
|
1598
|
+
badge = f"[{policy.upper():5}]"
|
|
1599
|
+
row_text = f"{pointer}{tool.name:<18} {badge} {tool.description[:42]}{danger}\n"
|
|
1600
|
+
if is_sel:
|
|
1601
|
+
lines.append(("class:selected", row_text))
|
|
1602
|
+
elif policy == "allow":
|
|
1603
|
+
lines.append(("class:allow", row_text))
|
|
1604
|
+
elif policy == "deny":
|
|
1605
|
+
lines.append(("class:deny", row_text))
|
|
1606
|
+
else:
|
|
1607
|
+
lines.append(("class:ask", row_text))
|
|
1608
|
+
|
|
1609
|
+
lines.append(("class:subtitle", "\n"))
|
|
1610
|
+
reset_sel = selected_idx == len(tools)
|
|
1611
|
+
done_sel = selected_idx == len(tools) + 1
|
|
1612
|
+
lines.append((
|
|
1613
|
+
"class:selected" if reset_sel else "class:subtitle",
|
|
1614
|
+
f"{' ❯ ' if reset_sel else ' '}↺ Reset all tools to defaults\n",
|
|
1615
|
+
))
|
|
1616
|
+
lines.append((
|
|
1617
|
+
"class:selected" if done_sel else "class:allow",
|
|
1618
|
+
f"{' ❯ ' if done_sel else ' '}✓ Save & Done\n",
|
|
1619
|
+
))
|
|
1620
|
+
return lines
|
|
1621
|
+
|
|
1622
|
+
style = Style.from_dict({
|
|
1623
|
+
"title": "bold ansibrightcyan",
|
|
1624
|
+
"subtitle": "ansibrightblack",
|
|
1625
|
+
"selected": "bold ansibrightyellow reverse",
|
|
1626
|
+
"allow": "ansigreen",
|
|
1627
|
+
"ask": "ansiyellow",
|
|
1628
|
+
"deny": "ansired",
|
|
1629
|
+
})
|
|
1630
|
+
|
|
1631
|
+
app = Application(
|
|
1632
|
+
layout=Layout(HSplit([Window(content=FormattedTextControl(_render))])),
|
|
1633
|
+
key_bindings=kb,
|
|
1634
|
+
style=style,
|
|
1635
|
+
full_screen=False,
|
|
1636
|
+
erase_when_done=True,
|
|
1637
|
+
)
|
|
1638
|
+
await app.run_async()
|
|
1639
|
+
console.print(render_system_message("[green]✓ Tool access settings saved.[/green]"))
|
|
1640
|
+
return
|
|
1641
|
+
except Exception:
|
|
1642
|
+
pass
|
|
1643
|
+
|
|
1644
|
+
# Fallback numbered prompt for non-TTY / automated environments
|
|
1645
|
+
loop = asyncio.get_event_loop()
|
|
1646
|
+
while True:
|
|
1647
|
+
console.print()
|
|
1648
|
+
console.print("[bold bright_cyan]Tool Access Settings[/bold bright_cyan]")
|
|
1649
|
+
for i, tool in enumerate(tools, 1):
|
|
1650
|
+
default_p = "ask" if tool.requires_approval else "allow"
|
|
1651
|
+
policy = config.get_tool_access(tool.name, default=default_p)
|
|
1652
|
+
color = "green" if policy == "allow" else ("red" if policy == "deny" else "yellow")
|
|
1653
|
+
console.print(f" [bold]{i}[/bold]) {tool.name:<18} [{color}]{policy.upper()}[/{color}] [dim]- {tool.description}[/dim]")
|
|
1654
|
+
console.print(" [bold]r[/bold]) Reset all to defaults")
|
|
1655
|
+
console.print(" [bold]0[/bold]) Done")
|
|
1656
|
+
|
|
1657
|
+
valid = [str(i) for i in range(len(tools) + 1)] + ["r"]
|
|
1658
|
+
choice = await loop.run_in_executor(
|
|
1659
|
+
None,
|
|
1660
|
+
lambda: Prompt.ask("[bold cyan]Select tool to toggle[/bold cyan]", choices=valid, default="0")
|
|
1661
|
+
)
|
|
1662
|
+
if choice == "0":
|
|
1663
|
+
break
|
|
1664
|
+
elif choice == "r":
|
|
1665
|
+
config.reset_tool_access()
|
|
1666
|
+
_save_global_config(config)
|
|
1667
|
+
console.print(render_system_message("[green]Reset all tool access policies to defaults.[/green]"))
|
|
1668
|
+
else:
|
|
1669
|
+
tool = tools[int(choice) - 1]
|
|
1670
|
+
_cycle_policy(tool, 1)
|
|
1671
|
+
new_p = config.get_tool_access(tool.name)
|
|
1672
|
+
console.print(render_system_message(f"[green]{tool.name} access set to '{new_p}'.[/green]"))
|
|
1673
|
+
|
|
1674
|
+
|
|
1675
|
+
async def _handle_tools_settings_command(args: list, controller: Optional[AgentController] = None) -> None:
|
|
1676
|
+
"""Handle `/settings tools` subcommands."""
|
|
1677
|
+
from agent.config import _save_global_config
|
|
1678
|
+
|
|
1679
|
+
config = controller.config if controller else get_config()
|
|
1680
|
+
registry = get_registry()
|
|
1681
|
+
valid_tools = {t.name: t for t in registry.get_all()}
|
|
1682
|
+
|
|
1683
|
+
if not args:
|
|
1684
|
+
await _interactive_tool_access_edit(controller)
|
|
1685
|
+
return
|
|
1686
|
+
|
|
1687
|
+
if args[0].lower() == "reset":
|
|
1688
|
+
if len(args) > 1 and args[1] in valid_tools:
|
|
1689
|
+
config.reset_tool_access(args[1])
|
|
1690
|
+
_save_global_config(config)
|
|
1691
|
+
console.print(render_system_message(f"[green]Reset '{args[1]}' access to default.[/green]"))
|
|
1692
|
+
else:
|
|
1693
|
+
config.reset_tool_access()
|
|
1694
|
+
_save_global_config(config)
|
|
1695
|
+
console.print(render_system_message("[green]Reset all tool access policies to defaults.[/green]"))
|
|
1696
|
+
return
|
|
1697
|
+
|
|
1698
|
+
if len(args) < 2:
|
|
1699
|
+
console.print("[red]Usage: /settings tools <tool_name|all> <allow|ask|deny|reset>[/red]")
|
|
1700
|
+
return
|
|
1701
|
+
|
|
1702
|
+
target_tool = args[0]
|
|
1703
|
+
policy = args[1].lower()
|
|
1704
|
+
|
|
1705
|
+
if policy == "reset":
|
|
1706
|
+
if target_tool == "all":
|
|
1707
|
+
config.reset_tool_access()
|
|
1708
|
+
_save_global_config(config)
|
|
1709
|
+
console.print(render_system_message("[green]Reset all tool access policies to defaults.[/green]"))
|
|
1710
|
+
elif target_tool in valid_tools:
|
|
1711
|
+
config.reset_tool_access(target_tool)
|
|
1712
|
+
_save_global_config(config)
|
|
1713
|
+
console.print(render_system_message(f"[green]Reset '{target_tool}' access to default.[/green]"))
|
|
1714
|
+
else:
|
|
1715
|
+
console.print(render_system_message(f"[red]Unknown tool: {target_tool}[/red]"))
|
|
1716
|
+
return
|
|
1717
|
+
|
|
1718
|
+
if policy not in ("allow", "ask", "deny"):
|
|
1719
|
+
console.print(render_system_message(f"[red]Invalid policy '{policy}'. Use: allow, ask, deny, or reset.[/red]"))
|
|
1720
|
+
return
|
|
1721
|
+
|
|
1722
|
+
if target_tool == "all":
|
|
1723
|
+
for name in valid_tools:
|
|
1724
|
+
config.set_tool_access(name, policy)
|
|
1725
|
+
_save_global_config(config)
|
|
1726
|
+
console.print(render_system_message(f"[green]Set access for ALL tools to '{policy}'.[/green]"))
|
|
1727
|
+
elif target_tool in valid_tools:
|
|
1728
|
+
config.set_tool_access(target_tool, policy)
|
|
1729
|
+
_save_global_config(config)
|
|
1730
|
+
console.print(render_system_message(f"[green]Set '{target_tool}' access to '{policy}'.[/green]"))
|
|
1731
|
+
else:
|
|
1732
|
+
console.print(render_system_message(f"[red]Unknown tool: {target_tool}. Available: {', '.join(sorted(valid_tools))}[/red]"))
|
|
1733
|
+
|
|
1734
|
+
|
|
1735
|
+
async def _interactive_config_edit(controller: Optional[AgentController] = None) -> None:
|
|
1736
|
+
"""Interactive wizard to change any configuration setting."""
|
|
1737
|
+
config = get_config()
|
|
1738
|
+
console.print()
|
|
1739
|
+
console.print("[bold bright_cyan]Interactive Configuration Editor[/bold bright_cyan]")
|
|
1740
|
+
console.print(f" [bold]1[/bold]) Max Iterations [dim](current: {config.max_iterations})[/dim]")
|
|
1741
|
+
console.print(f" [bold]2[/bold]) Max Tool Calls [dim](current: {config.max_tool_calls})[/dim]")
|
|
1742
|
+
console.print(f" [bold]3[/bold]) Command Timeout [dim](current: {config.command_timeout}s)[/dim]")
|
|
1743
|
+
console.print(f" [bold]4[/bold]) Model [dim](current: {config.openai_model})[/dim]")
|
|
1744
|
+
console.print(f" [bold]5[/bold]) Base URL [dim](current: {config.openai_base_url})[/dim]")
|
|
1745
|
+
console.print(f" [bold]6[/bold]) API Key [dim](current: {('***' + config.openai_api_key[-4:]) if config.openai_api_key else 'Not set'})[/dim]")
|
|
1746
|
+
console.print(f" [bold]7[/bold]) Log Level [dim](current: {config.log_level})[/dim]")
|
|
1747
|
+
console.print(f" [bold]8[/bold]) Tool Access [dim]({len(config.tool_access)} custom rule(s))[/dim]")
|
|
1748
|
+
console.print(" [bold]0[/bold]) Cancel")
|
|
1749
|
+
|
|
1750
|
+
import asyncio
|
|
1751
|
+
loop = asyncio.get_event_loop()
|
|
1752
|
+
choice = await loop.run_in_executor(
|
|
1753
|
+
None,
|
|
1754
|
+
lambda: Prompt.ask("[bold cyan]Select setting to edit[/bold cyan]", choices=["0", "1", "2", "3", "4", "5", "6", "7", "8"], default="1")
|
|
1755
|
+
)
|
|
1756
|
+
|
|
1757
|
+
if choice == "0":
|
|
1758
|
+
console.print("[dim]Edit cancelled.[/dim]")
|
|
1759
|
+
return
|
|
1760
|
+
|
|
1761
|
+
if choice == "8":
|
|
1762
|
+
await _interactive_tool_access_edit(controller)
|
|
1763
|
+
return
|
|
1764
|
+
|
|
1765
|
+
mapping = {
|
|
1766
|
+
"1": ("max_iterations", str(config.max_iterations)),
|
|
1767
|
+
"2": ("max_tool_calls", str(config.max_tool_calls)),
|
|
1768
|
+
"3": ("command_timeout", str(config.command_timeout)),
|
|
1769
|
+
"4": ("model", config.openai_model),
|
|
1770
|
+
"5": ("base_url", config.openai_base_url),
|
|
1771
|
+
"6": ("api_key", ""),
|
|
1772
|
+
"7": ("log_level", config.log_level),
|
|
1773
|
+
}
|
|
1774
|
+
|
|
1775
|
+
setting_key, default_val = mapping[choice]
|
|
1776
|
+
new_val = await loop.run_in_executor(
|
|
1777
|
+
None,
|
|
1778
|
+
lambda: Prompt.ask(f"[bold cyan]Enter new value for {setting_key}[/bold cyan]", default=default_val)
|
|
1779
|
+
)
|
|
1780
|
+
|
|
1781
|
+
if not new_val.strip():
|
|
1782
|
+
console.print("[yellow]No change made.[/yellow]")
|
|
1783
|
+
return
|
|
1784
|
+
|
|
1785
|
+
ok, msg = set_config_value(setting_key, new_val.strip(), controller)
|
|
1786
|
+
if ok:
|
|
1787
|
+
console.print(render_system_message(f"[green]{msg}[/green]"))
|
|
1788
|
+
else:
|
|
1789
|
+
console.print(render_system_message(f"[red]{msg}[/red]"))
|
|
1790
|
+
|
|
1791
|
+
|
|
1792
|
+
async def _handle_config_command(parts: list, controller: Optional[AgentController] = None) -> None:
|
|
1793
|
+
"""Handle /config slash command and its subcommands."""
|
|
1794
|
+
if len(parts) == 1:
|
|
1795
|
+
_show_config_table(get_config())
|
|
1796
|
+
return
|
|
1797
|
+
|
|
1798
|
+
sub = parts[1].lower()
|
|
1799
|
+
|
|
1800
|
+
if sub in ("help", "-h", "--help"):
|
|
1801
|
+
_show_config_table(get_config())
|
|
1802
|
+
return
|
|
1803
|
+
|
|
1804
|
+
elif sub in ("edit", "wizard", "interactive"):
|
|
1805
|
+
await _interactive_config_edit(controller)
|
|
1806
|
+
return
|
|
1807
|
+
|
|
1808
|
+
elif sub == "set":
|
|
1809
|
+
if len(parts) < 4:
|
|
1810
|
+
console.print("[red]Usage: /config set <setting> <value>[/red]")
|
|
1811
|
+
console.print("[dim]Example: /config set max_iterations 1000[/dim]")
|
|
1812
|
+
return
|
|
1813
|
+
key = parts[2]
|
|
1814
|
+
val = " ".join(parts[3:])
|
|
1815
|
+
ok, msg = set_config_value(key, val, controller)
|
|
1816
|
+
if ok:
|
|
1817
|
+
console.print(render_system_message(f"[green]{msg}[/green]"))
|
|
1818
|
+
else:
|
|
1819
|
+
console.print(render_system_message(f"[red]{msg}[/red]"))
|
|
1820
|
+
return
|
|
1821
|
+
|
|
1822
|
+
elif sub == "get":
|
|
1823
|
+
if len(parts) < 3:
|
|
1824
|
+
console.print("[red]Usage: /config get <setting>[/red]")
|
|
1825
|
+
return
|
|
1826
|
+
key = parts[2].lower().replace("-", "_")
|
|
1827
|
+
mapped = CONFIG_KEY_MAP.get(key, key)
|
|
1828
|
+
config = get_config()
|
|
1829
|
+
if hasattr(config, mapped):
|
|
1830
|
+
val = getattr(config, mapped)
|
|
1831
|
+
if mapped == "openai_api_key" and val:
|
|
1832
|
+
val = "***" + val[-4:]
|
|
1833
|
+
console.print(render_system_message(f"[bold cyan]{mapped}[/bold cyan]: {val}"))
|
|
1834
|
+
else:
|
|
1835
|
+
console.print(render_system_message(f"[red]Unknown setting: {parts[2]}[/red]"))
|
|
1836
|
+
return
|
|
1837
|
+
|
|
1838
|
+
elif sub == "reset":
|
|
1839
|
+
set_config_value("max_iterations", 1000, controller)
|
|
1840
|
+
set_config_value("max_tool_calls", 1000, controller)
|
|
1841
|
+
set_config_value("command_timeout", 60, controller)
|
|
1842
|
+
console.print(render_system_message("[green]Reset iterations, tool calls, and timeout to defaults (1000 / 1000 / 60s).[/green]"))
|
|
1843
|
+
return
|
|
1844
|
+
|
|
1845
|
+
# Check if user passed shorthand: /config <setting> <value>
|
|
1846
|
+
key_normalized = sub.replace("-", "_")
|
|
1847
|
+
if key_normalized in CONFIG_KEY_MAP and len(parts) >= 3:
|
|
1848
|
+
val = " ".join(parts[2:])
|
|
1849
|
+
ok, msg = set_config_value(sub, val, controller)
|
|
1850
|
+
if ok:
|
|
1851
|
+
console.print(render_system_message(f"[green]{msg}[/green]"))
|
|
1852
|
+
else:
|
|
1853
|
+
console.print(render_system_message(f"[red]{msg}[/red]"))
|
|
1854
|
+
return
|
|
1855
|
+
|
|
1856
|
+
console.print(f"[yellow]Unknown config subcommand: '{sub}'. Type /config for available options.[/yellow]")
|
|
1857
|
+
|
|
1858
|
+
|
|
1859
|
+
async def _handle_provider_command(parts: list, controller: AgentController) -> None:
|
|
1860
|
+
"""Handle /provider and /settings slash commands for configuring AI providers and settings."""
|
|
1861
|
+
from agent.config import get_config, get_profiles, save_profile, delete_profile, load_profile
|
|
1862
|
+
from agent.model import reset_model_client, get_model_client
|
|
1863
|
+
|
|
1864
|
+
subcommand = parts[1].lower() if len(parts) > 1 else ""
|
|
1865
|
+
|
|
1866
|
+
if subcommand == "set":
|
|
1867
|
+
if len(parts) < 4:
|
|
1868
|
+
console.print("[red]Usage: /settings set <setting> <value>[/red]")
|
|
1869
|
+
console.print("[dim]Example: /settings set max_iterations 1000[/dim]")
|
|
1870
|
+
return
|
|
1871
|
+
key = parts[2]
|
|
1872
|
+
val = " ".join(parts[3:])
|
|
1873
|
+
ok, msg = set_config_value(key, val, controller)
|
|
1874
|
+
if ok:
|
|
1875
|
+
console.print(render_system_message(f"[green]{msg}[/green]"))
|
|
1876
|
+
else:
|
|
1877
|
+
console.print(render_system_message(f"[red]{msg}[/red]"))
|
|
1878
|
+
return
|
|
1879
|
+
|
|
1880
|
+
elif subcommand in ("edit", "wizard"):
|
|
1881
|
+
await _interactive_config_edit(controller)
|
|
1882
|
+
return
|
|
1883
|
+
|
|
1884
|
+
elif subcommand in ("tools", "tool", "access"):
|
|
1885
|
+
await _handle_tools_settings_command(parts[2:], controller)
|
|
1886
|
+
return
|
|
1887
|
+
|
|
1888
|
+
if not subcommand or subcommand == "list":
|
|
1889
|
+
config = get_config()
|
|
1890
|
+
profiles = get_profiles()
|
|
1891
|
+
|
|
1892
|
+
# Summarize tool access
|
|
1893
|
+
custom_rules = len(config.tool_access)
|
|
1894
|
+
tool_access_summary = f"{custom_rules} custom rule(s)" if custom_rules else "Default (safe reads=allow, writes/commands=ask)"
|
|
1895
|
+
|
|
1896
|
+
# Header panel with instructions & NVIDIA recommendation
|
|
1897
|
+
info_text = (
|
|
1898
|
+
f"[bold bright_green]Active Model:[/bold bright_green] [cyan]{config.openai_model}[/cyan]\n"
|
|
1899
|
+
f"[bold bright_green]Active Base URL:[/bold bright_green] [dim]{config.openai_base_url}[/dim]\n"
|
|
1900
|
+
f"[bold bright_green]API Key:[/bold bright_green] [dim]{('***' + config.openai_api_key[-4:]) if config.openai_api_key else 'Not set'}[/dim]\n"
|
|
1901
|
+
f"[bold bright_green]Max Iterations:[/bold bright_green] [green]{config.max_iterations}[/green] • "
|
|
1902
|
+
f"[bold bright_green]Max Tool Calls:[/bold bright_green] [green]{config.max_tool_calls}[/green]\n"
|
|
1903
|
+
f"[bold bright_green]Tool Access:[/bold bright_green] [yellow]{tool_access_summary}[/yellow]\n\n"
|
|
1904
|
+
"[bold bright_yellow]★ RECOMMENDED: NVIDIA NIM Free Models ★[/bold bright_yellow]\n"
|
|
1905
|
+
"NVIDIA provides 1,000 free API credits with access to top-tier open models.\n"
|
|
1906
|
+
"• [bold]Register for free key:[/bold] [underline cyan]https://build.nvidia.com/[/underline cyan]\n"
|
|
1907
|
+
"• [bold]Base URL:[/bold] [cyan]https://integrate.api.nvidia.com/v1[/cyan]\n"
|
|
1908
|
+
"• [bold]Top Models:[/bold] [green]nvidia/nemotron-3.5-bolt-e4b[/green], [green]meta/llama-3.3-70b-instruct[/green], [green]deepseek-ai/deepseek-r1[/green]\n\n"
|
|
1909
|
+
"[bold]Quick Commands:[/bold]\n"
|
|
1910
|
+
"• [cyan]/provider nvidia[/cyan] -> Fast 1-step setup for NVIDIA NIM\n"
|
|
1911
|
+
"• [cyan]/provider add[/cyan] -> Guided wizard to add any provider (NVIDIA, OpenAI, Groq...)\n"
|
|
1912
|
+
"• [cyan]/provider use <name>[/cyan] -> Switch active provider profile\n"
|
|
1913
|
+
"• [cyan]/provider list[/cyan] -> List all saved profiles\n"
|
|
1914
|
+
"• [cyan]/settings tools[/cyan] -> Interactive tool access editor (allow / ask / deny)\n"
|
|
1915
|
+
"• [cyan]/settings set <name> <val>[/cyan] -> Change setting (e.g. /settings set max_iterations 1000)\n"
|
|
1916
|
+
"• [cyan]/settings edit[/cyan] -> Interactive configuration editor\n"
|
|
1917
|
+
"• [cyan]/config[/cyan] -> Full configuration table"
|
|
1918
|
+
)
|
|
1919
|
+
console.print()
|
|
1920
|
+
console.print(Panel(
|
|
1921
|
+
Text.from_markup(info_text),
|
|
1922
|
+
title="[bold bright_blue]AI Provider & API Settings[/bold bright_blue]",
|
|
1923
|
+
border_style="bright_blue",
|
|
1924
|
+
box=ROUNDED,
|
|
1925
|
+
padding=(1, 2),
|
|
1926
|
+
))
|
|
1927
|
+
|
|
1928
|
+
if profiles:
|
|
1929
|
+
table = Table(title="Saved Profiles", box=ROUNDED, border_style="dim")
|
|
1930
|
+
table.add_column("Name", style="cyan")
|
|
1931
|
+
table.add_column("Base URL", style="white")
|
|
1932
|
+
table.add_column("Model", style="dim")
|
|
1933
|
+
table.add_column("Status", style="green")
|
|
1934
|
+
|
|
1935
|
+
for name, profile in profiles.items():
|
|
1936
|
+
is_active = (profile.get("api_key") == config.openai_api_key and
|
|
1937
|
+
profile.get("base_url") == config.openai_base_url)
|
|
1938
|
+
table.add_row(
|
|
1939
|
+
name,
|
|
1940
|
+
profile.get("base_url", ""),
|
|
1941
|
+
profile.get("model", "default"),
|
|
1942
|
+
"[bold green]Active[/bold green]" if is_active else ""
|
|
1943
|
+
)
|
|
1944
|
+
console.print()
|
|
1945
|
+
console.print(table)
|
|
1946
|
+
console.print()
|
|
1947
|
+
return
|
|
1948
|
+
|
|
1949
|
+
elif subcommand == "nvidia":
|
|
1950
|
+
console.print()
|
|
1951
|
+
console.print(Panel(
|
|
1952
|
+
"[bold bright_cyan]NVIDIA NIM Provider Setup[/bold bright_cyan]\n"
|
|
1953
|
+
"NVIDIA provides 1,000 free API credits on registration!\n"
|
|
1954
|
+
"Register & get your free key at: [bold underline cyan]https://build.nvidia.com/[/bold underline cyan]",
|
|
1955
|
+
title="[bold green]NVIDIA Free Tier[/bold green]",
|
|
1956
|
+
border_style="green",
|
|
1957
|
+
box=ROUNDED,
|
|
1958
|
+
))
|
|
1959
|
+
|
|
1960
|
+
api_key = Prompt.ask("[bold cyan]Enter NVIDIA API Key (nvapi-...)[/bold cyan]").strip()
|
|
1961
|
+
if not api_key:
|
|
1962
|
+
console.print("[yellow]Setup cancelled: API key required.[/yellow]")
|
|
1963
|
+
return
|
|
1964
|
+
|
|
1965
|
+
base_url = "https://integrate.api.nvidia.com/v1"
|
|
1966
|
+
console.print("\n[dim]Recommended models: nvidia/nemotron-3.5-bolt-e4b, meta/llama-3.3-70b-instruct, deepseek-ai/deepseek-r1[/dim]")
|
|
1967
|
+
model = Prompt.ask("[bold cyan]Default Model[/bold cyan]", default="nvidia/nemotron-3.5-bolt-e4b").strip()
|
|
1968
|
+
|
|
1969
|
+
save_profile("nvidia", api_key, base_url, model)
|
|
1970
|
+
load_profile("nvidia")
|
|
1971
|
+
reset_model_client()
|
|
1972
|
+
controller.model_client = get_model_client()
|
|
1973
|
+
console.print(render_system_message(f"[green]NVIDIA provider configured and activated with model '{model}'![/green]"))
|
|
1974
|
+
return
|
|
1975
|
+
|
|
1976
|
+
elif subcommand == "add":
|
|
1977
|
+
name = parts[2] if len(parts) > 2 else ""
|
|
1978
|
+
|
|
1979
|
+
if not name:
|
|
1980
|
+
console.print()
|
|
1981
|
+
console.print("[bold cyan]Select provider template:[/bold cyan]")
|
|
1982
|
+
console.print(" [bold]1[/bold]) NVIDIA NIM ([green]Recommended Free Tier[/green] - https://build.nvidia.com/)")
|
|
1983
|
+
console.print(" [bold]2[/bold]) OpenAI (https://api.openai.com/v1)")
|
|
1984
|
+
console.print(" [bold]3[/bold]) OpenRouter (https://openrouter.ai/api/v1)")
|
|
1985
|
+
console.print(" [bold]4[/bold]) Groq (https://api.groq.com/openai/v1)")
|
|
1986
|
+
console.print(" [bold]5[/bold]) Custom OpenAI-compatible URL")
|
|
1987
|
+
choice = Prompt.ask("[bold cyan]Choice[/bold cyan]", choices=["1", "2", "3", "4", "5"], default="1")
|
|
1988
|
+
|
|
1989
|
+
if choice == "1":
|
|
1990
|
+
name = "nvidia"
|
|
1991
|
+
default_url = "https://integrate.api.nvidia.com/v1"
|
|
1992
|
+
default_model = "nvidia/nemotron-3.5-bolt-e4b"
|
|
1993
|
+
console.print("[dim]Register for free key: https://build.nvidia.com/[/dim]")
|
|
1994
|
+
elif choice == "2":
|
|
1995
|
+
name = "openai"
|
|
1996
|
+
default_url = "https://api.openai.com/v1"
|
|
1997
|
+
default_model = "gpt-4o-mini"
|
|
1998
|
+
elif choice == "3":
|
|
1999
|
+
name = "openrouter"
|
|
2000
|
+
default_url = "https://openrouter.ai/api/v1"
|
|
2001
|
+
default_model = "meta-llama/llama-3.3-70b-instruct"
|
|
2002
|
+
elif choice == "4":
|
|
2003
|
+
name = "groq"
|
|
2004
|
+
default_url = "https://api.groq.com/openai/v1"
|
|
2005
|
+
default_model = "llama-3.3-70b-versatile"
|
|
2006
|
+
else:
|
|
2007
|
+
name = Prompt.ask("[bold cyan]Profile Name[/bold cyan]", default="custom").strip()
|
|
2008
|
+
default_url = "https://api.openai.com/v1"
|
|
2009
|
+
default_model = "gpt-4o-mini"
|
|
2010
|
+
else:
|
|
2011
|
+
if name.lower() == "nvidia":
|
|
2012
|
+
default_url = "https://integrate.api.nvidia.com/v1"
|
|
2013
|
+
default_model = "nvidia/nemotron-3.5-bolt-e4b"
|
|
2014
|
+
console.print("[dim]Register for free key: https://build.nvidia.com/[/dim]")
|
|
2015
|
+
else:
|
|
2016
|
+
default_url = "https://api.openai.com/v1"
|
|
2017
|
+
default_model = "gpt-4o-mini"
|
|
2018
|
+
|
|
2019
|
+
base_url = Prompt.ask("[bold cyan]Base URL[/bold cyan]", default=default_url).strip()
|
|
2020
|
+
api_key = Prompt.ask("[bold cyan]API Key[/bold cyan]").strip()
|
|
2021
|
+
if not api_key:
|
|
2022
|
+
console.print("[yellow]API key cannot be empty.[/yellow]")
|
|
2023
|
+
return
|
|
2024
|
+
|
|
2025
|
+
model = Prompt.ask("[bold cyan]Default Model[/bold cyan]", default=default_model).strip()
|
|
2026
|
+
|
|
2027
|
+
save_profile(name, api_key, base_url, model)
|
|
2028
|
+
console.print(f"[green]Profile '{name}' saved.[/green]")
|
|
2029
|
+
|
|
2030
|
+
if Confirm.ask(f"Set '{name}' as active profile?", default=True):
|
|
2031
|
+
load_profile(name)
|
|
2032
|
+
reset_model_client()
|
|
2033
|
+
controller.model_client = get_model_client()
|
|
2034
|
+
console.print(render_system_message(f"[green]Active profile set to '{name}'.[/green]"))
|
|
2035
|
+
return
|
|
2036
|
+
|
|
2037
|
+
elif subcommand == "delete":
|
|
2038
|
+
if len(parts) < 3:
|
|
2039
|
+
console.print("[red]Usage: /provider delete <name>[/red]")
|
|
2040
|
+
return
|
|
2041
|
+
|
|
2042
|
+
name = parts[2]
|
|
2043
|
+
if delete_profile(name):
|
|
2044
|
+
console.print(f"[green]Profile '{name}' deleted.[/green]")
|
|
2045
|
+
else:
|
|
2046
|
+
console.print(f"[red]Profile '{name}' not found.[/red]")
|
|
2047
|
+
return
|
|
2048
|
+
|
|
2049
|
+
elif subcommand == "use":
|
|
2050
|
+
if len(parts) < 3:
|
|
2051
|
+
console.print("[red]Usage: /provider use <name>[/red]")
|
|
2052
|
+
return
|
|
2053
|
+
|
|
2054
|
+
name = parts[2]
|
|
2055
|
+
if load_profile(name):
|
|
2056
|
+
reset_model_client()
|
|
2057
|
+
controller.model_client = get_model_client()
|
|
2058
|
+
console.print(render_system_message(f"[green]Active profile set to '{name}'.[/green]"))
|
|
2059
|
+
else:
|
|
2060
|
+
console.print(f"[red]Profile '{name}' not found.[/red]")
|
|
2061
|
+
return
|
|
2062
|
+
|
|
2063
|
+
elif subcommand == "show":
|
|
2064
|
+
config = get_config()
|
|
2065
|
+
table = Table(title="Current Settings", box=ROUNDED, border_style="bright_blue")
|
|
2066
|
+
table.add_column("Setting", style="cyan")
|
|
2067
|
+
table.add_column("Value", style="white")
|
|
2068
|
+
|
|
2069
|
+
table.add_row("Model", config.openai_model)
|
|
2070
|
+
table.add_row("Base URL", config.openai_base_url)
|
|
2071
|
+
table.add_row("API Key", "***" + config.openai_api_key[-4:] if config.openai_api_key else "Not set")
|
|
2072
|
+
table.add_row("Max Iterations", str(config.max_iterations))
|
|
2073
|
+
table.add_row("Max Tool Calls", str(config.max_tool_calls))
|
|
2074
|
+
table.add_row("Command Timeout", f"{config.command_timeout}s")
|
|
2075
|
+
table.add_row("Log Level", config.log_level)
|
|
2076
|
+
console.print()
|
|
2077
|
+
console.print(table)
|
|
2078
|
+
console.print()
|
|
2079
|
+
return
|
|
2080
|
+
|
|
2081
|
+
else:
|
|
2082
|
+
# Check if subcommand is a profile name to use directly
|
|
2083
|
+
profiles = get_profiles()
|
|
2084
|
+
if subcommand in profiles:
|
|
2085
|
+
load_profile(subcommand)
|
|
2086
|
+
reset_model_client()
|
|
2087
|
+
controller.model_client = get_model_client()
|
|
2088
|
+
console.print(render_system_message(f"[green]Active profile set to '{subcommand}'.[/green]"))
|
|
2089
|
+
return
|
|
2090
|
+
|
|
2091
|
+
console.print(f"[yellow]Unknown command option: {subcommand}. Use /provider for help.[/yellow]")
|
|
2092
|
+
|
|
2093
|
+
|
|
2094
|
+
async def _fetch_models(base_url: str, api_key: str) -> list:
|
|
2095
|
+
"""Fetch available models from OpenAI-compatible API."""
|
|
2096
|
+
import httpx
|
|
2097
|
+
url = base_url.rstrip("/") + "/models"
|
|
2098
|
+
headers = {"Authorization": f"Bearer {api_key}"}
|
|
2099
|
+
|
|
2100
|
+
try:
|
|
2101
|
+
async with httpx.AsyncClient(timeout=10.0) as client:
|
|
2102
|
+
response = await client.get(url, headers=headers)
|
|
2103
|
+
response.raise_for_status()
|
|
2104
|
+
data = response.json()
|
|
2105
|
+
return data.get("data", [])
|
|
2106
|
+
except Exception:
|
|
2107
|
+
return []
|
|
2108
|
+
|
|
2109
|
+
|
|
2110
|
+
@app.command()
|
|
2111
|
+
def chat(
|
|
2112
|
+
project: Optional[Path] = typer.Option(
|
|
2113
|
+
None, "--project", "-p", help="Project directory"
|
|
2114
|
+
),
|
|
2115
|
+
model: Optional[str] = typer.Option(
|
|
2116
|
+
None, "--model", "-m", help="Model to use"
|
|
2117
|
+
),
|
|
2118
|
+
base_url: Optional[str] = typer.Option(
|
|
2119
|
+
None, "--base-url", "-u", help="API base URL"
|
|
2120
|
+
),
|
|
2121
|
+
api_key: Optional[str] = typer.Option(
|
|
2122
|
+
None, "--api-key", "-k", help="API key"
|
|
2123
|
+
),
|
|
2124
|
+
max_iterations: Optional[int] = typer.Option(
|
|
2125
|
+
None, "--max-iterations", "-i", help="Maximum iterations (default: 1000)"
|
|
2126
|
+
),
|
|
2127
|
+
auto_approve: bool = typer.Option(
|
|
2128
|
+
False, "--yes", "-y", "--auto-approve", help="Auto-approve all tool calls"
|
|
2129
|
+
),
|
|
2130
|
+
new_session: bool = typer.Option(
|
|
2131
|
+
False, "--new", help="Start a new session without resuming previous history"
|
|
2132
|
+
),
|
|
2133
|
+
):
|
|
2134
|
+
"""Start an interactive chat session with ireri."""
|
|
2135
|
+
import asyncio
|
|
2136
|
+
# Use existing event loop if running, otherwise create new
|
|
2137
|
+
try:
|
|
2138
|
+
loop = asyncio.get_running_loop()
|
|
2139
|
+
except RuntimeError:
|
|
2140
|
+
loop = asyncio.new_event_loop()
|
|
2141
|
+
asyncio.set_event_loop(loop)
|
|
2142
|
+
try:
|
|
2143
|
+
loop.run_until_complete(_chat_async(project, model, base_url, api_key, max_iterations, auto_approve, new_session))
|
|
2144
|
+
finally:
|
|
2145
|
+
# Don't close if we didn't create it
|
|
2146
|
+
if not loop.is_closed() and loop != asyncio.get_event_loop():
|
|
2147
|
+
loop.close()
|
|
2148
|
+
|
|
2149
|
+
|
|
2150
|
+
@app.command()
|
|
2151
|
+
def run(
|
|
2152
|
+
task: str = typer.Argument(..., help="Task to execute"),
|
|
2153
|
+
project: Optional[Path] = typer.Option(
|
|
2154
|
+
None, "--project", "-p", help="Project directory"
|
|
2155
|
+
),
|
|
2156
|
+
model: Optional[str] = typer.Option(
|
|
2157
|
+
None, "--model", "-m", help="Model to use"
|
|
2158
|
+
),
|
|
2159
|
+
base_url: Optional[str] = typer.Option(
|
|
2160
|
+
None, "--base-url", "-u", help="API base URL"
|
|
2161
|
+
),
|
|
2162
|
+
api_key: Optional[str] = typer.Option(
|
|
2163
|
+
None, "--api-key", "-k", help="API key"
|
|
2164
|
+
),
|
|
2165
|
+
max_iterations: Optional[int] = typer.Option(
|
|
2166
|
+
None, "--max-iterations", "-i", help="Maximum iterations (default: 1000)"
|
|
2167
|
+
),
|
|
2168
|
+
json_output: bool = typer.Option(
|
|
2169
|
+
False, "--json", "-j", help="Output result as JSON"
|
|
2170
|
+
),
|
|
2171
|
+
):
|
|
2172
|
+
"""Execute a one-shot task with ireri."""
|
|
2173
|
+
from agent.config import reset_config
|
|
2174
|
+
from agent.model import reset_model_client
|
|
2175
|
+
|
|
2176
|
+
reset_config()
|
|
2177
|
+
reset_model_client()
|
|
2178
|
+
config = get_config()
|
|
2179
|
+
|
|
2180
|
+
# Override config with CLI args
|
|
2181
|
+
# workspace_root always defaults to current directory unless --project specified
|
|
2182
|
+
if project:
|
|
2183
|
+
config.workspace_root = project.resolve()
|
|
2184
|
+
else:
|
|
2185
|
+
config.workspace_root = Path.cwd().resolve()
|
|
2186
|
+
if model:
|
|
2187
|
+
config.openai_model = model
|
|
2188
|
+
if base_url:
|
|
2189
|
+
config.openai_base_url = base_url
|
|
2190
|
+
if api_key:
|
|
2191
|
+
config.openai_api_key = api_key
|
|
2192
|
+
if max_iterations is not None:
|
|
2193
|
+
config.max_iterations = max_iterations
|
|
2194
|
+
|
|
2195
|
+
# Validate
|
|
2196
|
+
if not config.openai_api_key:
|
|
2197
|
+
console.print("[red]Error: API key required. Set OPENAI_API_KEY in .env or use --api-key[/red]")
|
|
2198
|
+
raise typer.Exit(1)
|
|
2199
|
+
|
|
2200
|
+
console.print()
|
|
2201
|
+
console.print(render_system_message(f"[bold]Task:[/bold] {task}"))
|
|
2202
|
+
console.print(render_system_message(f"[bold]Workspace:[/bold] {config.workspace_root}"))
|
|
2203
|
+
console.print(render_system_message("[dim]Working...[/dim]"))
|
|
2204
|
+
console.print()
|
|
2205
|
+
|
|
2206
|
+
try:
|
|
2207
|
+
result = asyncio.run(run_agent_task(task, str(config.workspace_root)))
|
|
2208
|
+
|
|
2209
|
+
if json_output:
|
|
2210
|
+
import json
|
|
2211
|
+
console.print(json.dumps({"result": result}))
|
|
2212
|
+
else:
|
|
2213
|
+
# Replace problematic Unicode characters for Windows console
|
|
2214
|
+
safe_result = result.replace('\u2705', '[OK]').replace('\u274c', '[X]').replace('\u26a0', '[!]')
|
|
2215
|
+
console.print(render_agent_message(safe_result))
|
|
2216
|
+
|
|
2217
|
+
except Exception as e:
|
|
2218
|
+
console.print()
|
|
2219
|
+
console.print(render_system_message(f"[red]Error: {e}[/red]"))
|
|
2220
|
+
raise typer.Exit(1)
|
|
2221
|
+
|
|
2222
|
+
|
|
2223
|
+
@app.command()
|
|
2224
|
+
def tools():
|
|
2225
|
+
"""List available tools."""
|
|
2226
|
+
registry = get_registry()
|
|
2227
|
+
tools = registry.get_all()
|
|
2228
|
+
config = get_config()
|
|
2229
|
+
|
|
2230
|
+
table = Table(title="ireri Available Tools", box=ROUNDED, border_style="bright_blue")
|
|
2231
|
+
table.add_column("Name", style="cyan")
|
|
2232
|
+
table.add_column("Description", style="white")
|
|
2233
|
+
table.add_column("Access Policy", style="yellow")
|
|
2234
|
+
table.add_column("Dangerous", style="red")
|
|
2235
|
+
|
|
2236
|
+
for tool in tools:
|
|
2237
|
+
default_p = "ask" if tool.requires_approval else "allow"
|
|
2238
|
+
policy = config.get_tool_access(tool.name, default=default_p)
|
|
2239
|
+
p_style = "green" if policy == "allow" else ("red" if policy == "deny" else "yellow")
|
|
2240
|
+
table.add_row(
|
|
2241
|
+
tool.name,
|
|
2242
|
+
tool.description,
|
|
2243
|
+
f"[{p_style}]{policy.upper()}[/{p_style}]",
|
|
2244
|
+
"Yes" if tool.dangerous else "No",
|
|
2245
|
+
)
|
|
2246
|
+
|
|
2247
|
+
console.print()
|
|
2248
|
+
console.print(table)
|
|
2249
|
+
console.print()
|
|
2250
|
+
|
|
2251
|
+
|
|
2252
|
+
@app.command(name="config")
|
|
2253
|
+
def config_cli(
|
|
2254
|
+
action: Optional[str] = typer.Argument(None, help="Action: show, set, get, edit"),
|
|
2255
|
+
key: Optional[str] = typer.Argument(None, help="Setting name (for set/get)"),
|
|
2256
|
+
value: Optional[str] = typer.Argument(None, help="Setting value (for set)"),
|
|
2257
|
+
):
|
|
2258
|
+
"""View or modify ireri configuration."""
|
|
2259
|
+
if action is None or action == "show":
|
|
2260
|
+
_show_config_table(get_config())
|
|
2261
|
+
elif action == "set":
|
|
2262
|
+
if not key or not value:
|
|
2263
|
+
console.print("[red]Usage: ireri config set <setting> <value>[/red]")
|
|
2264
|
+
console.print("[dim]Example: ireri config set max_iterations 1000[/dim]")
|
|
2265
|
+
raise typer.Exit(1)
|
|
2266
|
+
ok, msg = set_config_value(key, value)
|
|
2267
|
+
if ok:
|
|
2268
|
+
console.print(render_system_message(f"[green]{msg}[/green]"))
|
|
2269
|
+
else:
|
|
2270
|
+
console.print(render_system_message(f"[red]{msg}[/red]"))
|
|
2271
|
+
raise typer.Exit(1)
|
|
2272
|
+
elif action == "get":
|
|
2273
|
+
if not key:
|
|
2274
|
+
console.print("[red]Usage: ireri config get <setting>[/red]")
|
|
2275
|
+
raise typer.Exit(1)
|
|
2276
|
+
key_norm = key.lower().replace("-", "_")
|
|
2277
|
+
mapped = CONFIG_KEY_MAP.get(key_norm, key_norm)
|
|
2278
|
+
cfg = get_config()
|
|
2279
|
+
if hasattr(cfg, mapped):
|
|
2280
|
+
val = getattr(cfg, mapped)
|
|
2281
|
+
if mapped == "openai_api_key" and val:
|
|
2282
|
+
val = "***" + val[-4:]
|
|
2283
|
+
console.print(f"{mapped}: {val}")
|
|
2284
|
+
else:
|
|
2285
|
+
console.print(f"[red]Unknown setting: {key}[/red]")
|
|
2286
|
+
raise typer.Exit(1)
|
|
2287
|
+
elif action.lower().replace("-", "_") in CONFIG_KEY_MAP and key is not None:
|
|
2288
|
+
# Shorthand: ireri config max_iterations 1000
|
|
2289
|
+
ok, msg = set_config_value(action, key)
|
|
2290
|
+
if ok:
|
|
2291
|
+
console.print(render_system_message(f"[green]{msg}[/green]"))
|
|
2292
|
+
else:
|
|
2293
|
+
console.print(render_system_message(f"[red]{msg}[/red]"))
|
|
2294
|
+
raise typer.Exit(1)
|
|
2295
|
+
else:
|
|
2296
|
+
_show_config_table(get_config())
|
|
2297
|
+
|
|
2298
|
+
|
|
2299
|
+
@app.command()
|
|
2300
|
+
def config_show():
|
|
2301
|
+
"""Show current configuration."""
|
|
2302
|
+
_show_config_table(get_config())
|
|
2303
|
+
|
|
2304
|
+
|
|
2305
|
+
@app.command()
|
|
2306
|
+
def init(
|
|
2307
|
+
path: Path = typer.Argument(Path.cwd(), help="Project directory"),
|
|
2308
|
+
force: bool = typer.Option(False, "--force", "-f", help="Overwrite existing files"),
|
|
2309
|
+
):
|
|
2310
|
+
"""Initialize a new project with ireri configuration."""
|
|
2311
|
+
env_path = path / ".env"
|
|
2312
|
+
gitignore_path = path / ".gitignore"
|
|
2313
|
+
|
|
2314
|
+
console.print()
|
|
2315
|
+
|
|
2316
|
+
if env_path.exists() and not force:
|
|
2317
|
+
console.print(render_system_message("[yellow].env already exists. Use --force to overwrite.[/yellow]"))
|
|
2318
|
+
else:
|
|
2319
|
+
# Copy from example
|
|
2320
|
+
example_path = Path(__file__).parent.parent / ".env.example"
|
|
2321
|
+
if example_path.exists():
|
|
2322
|
+
env_path.write_text(example_path.read_text())
|
|
2323
|
+
console.print(render_system_message(f"[green]Created {env_path}[/green]"))
|
|
2324
|
+
else:
|
|
2325
|
+
console.print(render_system_message("[red]No .env.example found[/red]"))
|
|
2326
|
+
|
|
2327
|
+
if gitignore_path.exists() and not force:
|
|
2328
|
+
console.print(render_system_message("[yellow].gitignore already exists. Use --force to overwrite.[/yellow]"))
|
|
2329
|
+
else:
|
|
2330
|
+
example_path = Path(__file__).parent.parent / ".gitignore"
|
|
2331
|
+
if example_path.exists():
|
|
2332
|
+
gitignore_path.write_text(example_path.read_text())
|
|
2333
|
+
console.print(render_system_message(f"[green]Created {gitignore_path}[/green]"))
|
|
2334
|
+
|
|
2335
|
+
console.print()
|
|
2336
|
+
console.print(render_system_message("[bold]Next steps:[/bold]"))
|
|
2337
|
+
console.print(render_system_message("1. Edit .env with your API key"))
|
|
2338
|
+
console.print(render_system_message("2. Run 'ireri chat' to start"))
|
|
2339
|
+
console.print()
|
|
2340
|
+
|
|
2341
|
+
|
|
2342
|
+
async def _show_models_command(config: AgentConfig) -> None:
|
|
2343
|
+
"""Handle /model command - fetch and switch models."""
|
|
2344
|
+
from agent.config import update_config
|
|
2345
|
+
from agent.model import reset_model_client
|
|
2346
|
+
console.print("[dim]Fetching available models...[/dim]")
|
|
2347
|
+
|
|
2348
|
+
try:
|
|
2349
|
+
models = await _fetch_models(config.openai_base_url, config.openai_api_key)
|
|
2350
|
+
|
|
2351
|
+
if not models:
|
|
2352
|
+
console.print("[yellow]No models found or error fetching models[/yellow]")
|
|
2353
|
+
return
|
|
2354
|
+
|
|
2355
|
+
# Display models in a table
|
|
2356
|
+
table = Table(title="Available Models")
|
|
2357
|
+
table.add_column("#", style="cyan", width=4)
|
|
2358
|
+
table.add_column("Model ID", style="white")
|
|
2359
|
+
table.add_column("Created", style="dim")
|
|
2360
|
+
table.add_column("Owned By", style="dim")
|
|
2361
|
+
|
|
2362
|
+
for i, model in enumerate(models, 1):
|
|
2363
|
+
created = model.get("created", "")
|
|
2364
|
+
if created:
|
|
2365
|
+
from datetime import datetime
|
|
2366
|
+
created = datetime.fromtimestamp(created).strftime("%Y-%m-%d")
|
|
2367
|
+
table.add_row(
|
|
2368
|
+
str(i),
|
|
2369
|
+
model.get("id", "unknown"),
|
|
2370
|
+
created,
|
|
2371
|
+
model.get("owned_by", "unknown")
|
|
2372
|
+
)
|
|
2373
|
+
|
|
2374
|
+
console.print(table)
|
|
2375
|
+
|
|
2376
|
+
# Prompt for selection
|
|
2377
|
+
choice = Prompt.ask(
|
|
2378
|
+
"[bold cyan]Select model number[/bold cyan]",
|
|
2379
|
+
default="1"
|
|
2380
|
+
)
|
|
2381
|
+
|
|
2382
|
+
try:
|
|
2383
|
+
idx = int(choice) - 1
|
|
2384
|
+
if 0 <= idx < len(models):
|
|
2385
|
+
selected_model = models[idx]["id"]
|
|
2386
|
+
update_config(openai_model=selected_model)
|
|
2387
|
+
reset_model_client()
|
|
2388
|
+
|
|
2389
|
+
console.print(Panel(
|
|
2390
|
+
f"Model changed to: [green]{selected_model}[/green]\n"
|
|
2391
|
+
f"Saved to global config (~/.ireri-code/config.json)",
|
|
2392
|
+
title="[bold green]Model Updated[/bold green]",
|
|
2393
|
+
border_style="green",
|
|
2394
|
+
))
|
|
2395
|
+
else:
|
|
2396
|
+
console.print("[red]Invalid selection[/red]")
|
|
2397
|
+
except ValueError:
|
|
2398
|
+
console.print("[red]Invalid input[/red]")
|
|
2399
|
+
|
|
2400
|
+
except Exception as e:
|
|
2401
|
+
console.print(f"[red]Error: {e}[/red]")
|
|
2402
|
+
|
|
2403
|
+
|
|
2404
|
+
async def _show_models_list(config: AgentConfig) -> None:
|
|
2405
|
+
"""Handle /models command - just list models."""
|
|
2406
|
+
console.print("[dim]Fetching available models...[/dim]")
|
|
2407
|
+
|
|
2408
|
+
try:
|
|
2409
|
+
models = await _fetch_models(config.openai_base_url, config.openai_api_key)
|
|
2410
|
+
|
|
2411
|
+
if not models:
|
|
2412
|
+
console.print("[yellow]No models found or error fetching models[/yellow]")
|
|
2413
|
+
return
|
|
2414
|
+
|
|
2415
|
+
table = Table(title="Available Models", box=ROUNDED, border_style="bright_blue")
|
|
2416
|
+
table.add_column("#", style="cyan", width=4)
|
|
2417
|
+
table.add_column("Model ID", style="white")
|
|
2418
|
+
table.add_column("Created", style="dim")
|
|
2419
|
+
table.add_column("Owned By", style="dim")
|
|
2420
|
+
|
|
2421
|
+
for i, model in enumerate(models, 1):
|
|
2422
|
+
created = model.get("created", "")
|
|
2423
|
+
if created:
|
|
2424
|
+
from datetime import datetime
|
|
2425
|
+
created = datetime.fromtimestamp(created).strftime("%Y-%m-%d")
|
|
2426
|
+
table.add_row(
|
|
2427
|
+
str(i),
|
|
2428
|
+
model.get("id", "unknown"),
|
|
2429
|
+
created,
|
|
2430
|
+
model.get("owned_by", "unknown")
|
|
2431
|
+
)
|
|
2432
|
+
|
|
2433
|
+
console.print()
|
|
2434
|
+
console.print(table)
|
|
2435
|
+
console.print()
|
|
2436
|
+
|
|
2437
|
+
except Exception as e:
|
|
2438
|
+
console.print(f"[red]Error: {e}[/red]")
|
|
2439
|
+
|
|
2440
|
+
|
|
2441
|
+
def _show_help() -> None:
|
|
2442
|
+
"""Display all available slash commands."""
|
|
2443
|
+
table = Table(title="ireri Slash Commands", box=ROUNDED, border_style="bright_blue")
|
|
2444
|
+
table.add_column("Command", style="cyan")
|
|
2445
|
+
table.add_column("Description", style="white")
|
|
2446
|
+
|
|
2447
|
+
for cmd, desc in SLASH_COMMANDS.items():
|
|
2448
|
+
table.add_row(cmd, desc)
|
|
2449
|
+
|
|
2450
|
+
console.print()
|
|
2451
|
+
console.print(table)
|
|
2452
|
+
console.print()
|
|
2453
|
+
|
|
2454
|
+
|
|
2455
|
+
def _show_provider_command() -> None:
|
|
2456
|
+
"""Handle /provider command - configure AI providers."""
|
|
2457
|
+
from agent.config import get_config
|
|
2458
|
+
config = get_config()
|
|
2459
|
+
info_text = (
|
|
2460
|
+
f"[bold bright_green]Active Model:[/bold bright_green] [cyan]{config.openai_model}[/cyan]\n"
|
|
2461
|
+
f"[bold bright_green]Active Base URL:[/bold bright_green] [dim]{config.openai_base_url}[/dim]\n"
|
|
2462
|
+
f"[bold bright_green]API Key:[/bold bright_green] [dim]{('***' + config.openai_api_key[-4:]) if config.openai_api_key else 'Not set'}[/dim]\n\n"
|
|
2463
|
+
"[bold bright_yellow]★ RECOMMENDED: NVIDIA NIM Free Models ★[/bold bright_yellow]\n"
|
|
2464
|
+
"NVIDIA provides 1,000 free API credits with access to top-tier open models.\n"
|
|
2465
|
+
"• [bold]Register for free key:[/bold] [underline cyan]https://build.nvidia.com/[/underline cyan]\n"
|
|
2466
|
+
"• [bold]Base URL:[/bold] [cyan]https://integrate.api.nvidia.com/v1[/cyan]\n"
|
|
2467
|
+
"• [bold]Top Models:[/bold] [green]nvidia/nemotron-3.5-bolt-e4b[/green], [green]meta/llama-3.3-70b-instruct[/green], [green]deepseek-ai/deepseek-r1[/green]\n\n"
|
|
2468
|
+
"[bold]Quick Commands:[/bold]\n"
|
|
2469
|
+
"• [cyan]/provider nvidia[/cyan] -> Fast 1-step setup for NVIDIA NIM\n"
|
|
2470
|
+
"• [cyan]/provider add[/cyan] -> Guided wizard to add any provider\n"
|
|
2471
|
+
"• [cyan]/provider use <name>[/cyan] -> Switch active provider profile\n"
|
|
2472
|
+
"• [cyan]/provider list[/cyan] -> List all saved profiles"
|
|
2473
|
+
)
|
|
2474
|
+
console.print()
|
|
2475
|
+
console.print(Panel(
|
|
2476
|
+
Text.from_markup(info_text),
|
|
2477
|
+
title="[bold bright_blue]AI Provider & API Settings[/bold bright_blue]",
|
|
2478
|
+
border_style="bright_blue",
|
|
2479
|
+
box=ROUNDED,
|
|
2480
|
+
padding=(1, 2),
|
|
2481
|
+
))
|
|
2482
|
+
console.print()
|
|
2483
|
+
|
|
2484
|
+
|
|
2485
|
+
def _show_tokens_command(controller: AgentController) -> None:
|
|
2486
|
+
"""Handle /tokens command - display session token analytics and approximate context length."""
|
|
2487
|
+
stats = controller.context.get_token_stats()
|
|
2488
|
+
table = Table(title="Session Token Analytics & Context", box=ROUNDED, border_style="bright_blue")
|
|
2489
|
+
table.add_column("Metric", style="cyan", width=26)
|
|
2490
|
+
table.add_column("Value", style="bold white")
|
|
2491
|
+
table.add_column("Description", style="dim")
|
|
2492
|
+
table.add_row("Tokens Sent (↑ Up)", f"{stats['tokens_up']:,}", "Input prompt tokens transmitted to model")
|
|
2493
|
+
table.add_row("Tokens Received (↓ Down)", f"{stats['tokens_down']:,}", "Output completion tokens generated by model")
|
|
2494
|
+
table.add_row("Total Session Tokens", f"{stats['total_tokens']:,}", "Total tokens consumed during this session")
|
|
2495
|
+
table.add_row("Approx. Active Context", f"~{stats['approx_context_tokens']:,} tokens", f"Estimated active context memory ({len(controller.context.messages)} conversation items)")
|
|
2496
|
+
console.print()
|
|
2497
|
+
console.print(table)
|
|
2498
|
+
console.print()
|
|
2499
|
+
|
|
2500
|
+
|
|
2501
|
+
def _show_status_command(controller: AgentController) -> None:
|
|
2502
|
+
"""Handle /status command - show agent status."""
|
|
2503
|
+
config = get_config()
|
|
2504
|
+
stats = controller.context.get_token_stats()
|
|
2505
|
+
table = Table(title="ireri Status", box=ROUNDED, border_style="bright_blue")
|
|
2506
|
+
table.add_column("Property", style="cyan")
|
|
2507
|
+
table.add_column("Value", style="white")
|
|
2508
|
+
|
|
2509
|
+
table.add_row("Model", config.openai_model)
|
|
2510
|
+
table.add_row("Base URL", config.openai_base_url)
|
|
2511
|
+
table.add_row("Workspace", str(config.workspace_root))
|
|
2512
|
+
table.add_row("Max Iterations", str(config.max_iterations))
|
|
2513
|
+
table.add_row("Max Tool Calls", str(config.max_tool_calls))
|
|
2514
|
+
table.add_row("Queued Tasks", str(len(controller.message_queue)))
|
|
2515
|
+
table.add_row("Tokens Sent (↑)", f"{stats['tokens_up']:,}")
|
|
2516
|
+
table.add_row("Tokens Received (↓)", f"{stats['tokens_down']:,}")
|
|
2517
|
+
table.add_row("Total Session Tokens", f"{stats['total_tokens']:,}")
|
|
2518
|
+
table.add_row("Approx. Context Length", f"~{stats['approx_context_tokens']:,} tokens")
|
|
2519
|
+
table.add_row("Session", "Active")
|
|
2520
|
+
|
|
2521
|
+
console.print()
|
|
2522
|
+
console.print(table)
|
|
2523
|
+
console.print()
|
|
2524
|
+
|
|
2525
|
+
|
|
2526
|
+
def _show_config_command() -> None:
|
|
2527
|
+
"""Handle /config command - view or edit configuration."""
|
|
2528
|
+
_show_config_table(get_config())
|
|
2529
|
+
|
|
2530
|
+
|
|
2531
|
+
def _show_version_command() -> None:
|
|
2532
|
+
"""Handle /version command."""
|
|
2533
|
+
console.print(Panel(
|
|
2534
|
+
"[bold bright_blue]IRERI CODE[/bold bright_blue] [bright_green]v2.0.0[/bright_green]\n"
|
|
2535
|
+
"Terminal AI Coding Agent\n"
|
|
2536
|
+
"https://github.com/ekusafamily/ireri-code",
|
|
2537
|
+
title="[bold]Version Info[/bold]",
|
|
2538
|
+
border_style="bright_blue",
|
|
2539
|
+
))
|
|
2540
|
+
|
|
2541
|
+
|
|
2542
|
+
def _show_update_command() -> None:
|
|
2543
|
+
"""Handle /update command."""
|
|
2544
|
+
console.print(Panel(
|
|
2545
|
+
"To update ireri, run:\n"
|
|
2546
|
+
"[cyan]pip install --upgrade ireri-code[/cyan]\n\n"
|
|
2547
|
+
"Or if installed from source:\n"
|
|
2548
|
+
"[cyan]git pull && pip install -e .[/cyan]",
|
|
2549
|
+
title="[bold]Update[/bold]",
|
|
2550
|
+
border_style="bright_blue",
|
|
2551
|
+
))
|
|
2552
|
+
|
|
2553
|
+
|
|
2554
|
+
def _show_about_command() -> None:
|
|
2555
|
+
"""Handle /about command."""
|
|
2556
|
+
console.print(Panel(
|
|
2557
|
+
"[bold bright_blue]IRERI CODE[/bold bright_blue] - Terminal AI Coding Agent\n\n"
|
|
2558
|
+
"An intelligent coding assistant that lives in your terminal.\n"
|
|
2559
|
+
"Features: file operations, code search, command execution,\n"
|
|
2560
|
+
"multi-step tasks, and interactive approval system.\n\n"
|
|
2561
|
+
"Created with [red]<3[/red] by the ireri team",
|
|
2562
|
+
title="[bold]About ireri[/bold]",
|
|
2563
|
+
border_style="bright_blue",
|
|
2564
|
+
))
|
|
2565
|
+
|
|
2566
|
+
|
|
2567
|
+
def main():
|
|
2568
|
+
"""Entry point."""
|
|
2569
|
+
app()
|
|
2570
|
+
|
|
2571
|
+
|
|
2572
|
+
if __name__ == "__main__":
|
|
2573
|
+
main()
|