mini-code-cli 0.1.1.4__py3-none-any.whl → 0.2.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- mini_code_cli/agent_loop.py +448 -77
- mini_code_cli/background.py +494 -0
- mini_code_cli/persistence.py +14 -7
- mini_code_cli/runner.py +10 -2
- mini_code_cli/sandbox.py +1 -0
- mini_code_cli/subagents/__init__.py +4 -3
- mini_code_cli/subagents/base.py +3 -2
- mini_code_cli/tools.py +215 -23
- mini_code_cli/tui.py +1060 -0
- mini_code_cli/ui.py +141 -59
- mini_code_cli/utils.py +25 -10
- {mini_code_cli-0.1.1.4.dist-info → mini_code_cli-0.2.1.0.dist-info}/METADATA +62 -10
- mini_code_cli-0.2.1.0.dist-info/RECORD +30 -0
- mini_code_cli-0.1.1.4.dist-info/RECORD +0 -28
- {mini_code_cli-0.1.1.4.dist-info → mini_code_cli-0.2.1.0.dist-info}/WHEEL +0 -0
- {mini_code_cli-0.1.1.4.dist-info → mini_code_cli-0.2.1.0.dist-info}/entry_points.txt +0 -0
- {mini_code_cli-0.1.1.4.dist-info → mini_code_cli-0.2.1.0.dist-info}/licenses/LICENSE +0 -0
- {mini_code_cli-0.1.1.4.dist-info → mini_code_cli-0.2.1.0.dist-info}/top_level.txt +0 -0
mini_code_cli/agent_loop.py
CHANGED
|
@@ -25,14 +25,17 @@ without the tests reaching into every module.
|
|
|
25
25
|
|
|
26
26
|
import os
|
|
27
27
|
import json
|
|
28
|
+
import time
|
|
28
29
|
import argparse
|
|
29
30
|
|
|
31
|
+
from . import background as background_mod
|
|
30
32
|
from . import prompts
|
|
31
33
|
from . import shell_safety_utils
|
|
32
34
|
from . import tools
|
|
33
35
|
from . import utils
|
|
34
36
|
from .utils import oneline, plural
|
|
35
37
|
from . import ui
|
|
38
|
+
from . import tui as tui_mod
|
|
36
39
|
from . import subagents
|
|
37
40
|
from . import skills
|
|
38
41
|
from . import agent_files
|
|
@@ -164,9 +167,13 @@ def parse_args():
|
|
|
164
167
|
parser.add_argument("--plan-strategy", choices=planning.PLAN_STRATEGIES, default=None,
|
|
165
168
|
help="Planning strategy (implies --plan when given). plan-verify-step (default): author a plan, review it, and run one final step. plan-verify: same, but a final no-tool step is not appended to the transcript. open-plan: the agent maintains its own plan document in --allowed-dir/.mini and the loop does not author or review it.")
|
|
166
169
|
parser.add_argument("--scratchpad", action="store_true", help="Give the agent a scratch-pad file in --allowed-dir/.mini (SCRATCHPAD.md) plus permission to create further scratch files there for thoughts, plans and learnings.")
|
|
170
|
+
parser.add_argument("--background", action="store_true", help="Enable background tasks: the agent may start long-running shell commands or sub-agent tasks and inspect/cancel them with the `background` tool and /background. Requires --enable-shell or --enable-subagents. default= False")
|
|
171
|
+
parser.add_argument("--tui", nargs="?", const="on", default="auto",
|
|
172
|
+
choices=("auto", "on", "off"),
|
|
173
|
+
help="Fixed-screen TUI: auto (default; only on a known TTY), on, or off. Includes history, scrolling, colours and Shift+Enter multiline input.")
|
|
167
174
|
|
|
168
|
-
parser.add_argument("--all", action="store_true", help="Enable: --plan, --enable-subagents, --enable-shell, --skills, --auto-mode, --sudo")
|
|
169
|
-
parser.add_argument("--all-last", action="store_true", help="Enable: --plan, --enable-subagents, --enable-shell, --skills, --auto-mode, --sudo, --load-last-session")
|
|
175
|
+
parser.add_argument("--all", action="store_true", help="Enable: --plan, --enable-subagents, --enable-shell, --skills, --auto-mode, --sudo, --background")
|
|
176
|
+
parser.add_argument("--all-last", action="store_true", help="Enable: --plan, --enable-subagents, --enable-shell, --skills, --auto-mode, --sudo, --background, --load-last-session")
|
|
170
177
|
|
|
171
178
|
# Output verbosity
|
|
172
179
|
parser.add_argument("--verbose", action="store_true", help="Print the full, detailed output. Without it (default), only user/assistant turns, token usage and tool calls are shown.")
|
|
@@ -180,6 +187,7 @@ def parse_args():
|
|
|
180
187
|
args.sudo = True
|
|
181
188
|
args.auto_mode = True
|
|
182
189
|
args.enable_skills = True
|
|
190
|
+
args.background = True
|
|
183
191
|
|
|
184
192
|
if args.all_last:
|
|
185
193
|
args.load_last_session = True
|
|
@@ -196,40 +204,46 @@ def parse_args():
|
|
|
196
204
|
# banners / helpers
|
|
197
205
|
# ---------------------------------------------------------------------------
|
|
198
206
|
|
|
199
|
-
def print_help(args):
|
|
207
|
+
def print_help(args, console=None):
|
|
200
208
|
"""Print the interactive command list (``/help``)."""
|
|
201
|
-
ui.console
|
|
209
|
+
console = console if console is not None else ui.console
|
|
210
|
+
console.rule("help", fg="cyan")
|
|
202
211
|
if args.auto_mode:
|
|
203
212
|
help_message = ("Auto-mode: the agent keeps calling the LLM until no "
|
|
204
213
|
"further tool calls are possible.")
|
|
205
214
|
else:
|
|
206
215
|
help_message = "Manual-mode: the agent asks for your input after each LLM prediction."
|
|
207
|
-
|
|
208
|
-
|
|
216
|
+
console.emit(console.style(help_message, dim=True, fg="cyan"))
|
|
217
|
+
console.emit(console.style("History / navigation commands:", bold=True, fg="cyan"))
|
|
209
218
|
for command, description in (
|
|
210
219
|
("/history", "list the conversation (turn number, what happened, where)"),
|
|
211
220
|
("/history <n>", "show the full messages recorded for turn n"),
|
|
212
221
|
("/history last", "...for the most recent turn"),
|
|
213
222
|
("/plan", "show the current goal + plan (plan mode only)"),
|
|
214
223
|
("/context", "show how the context window is used (tokens + percentages)"),
|
|
224
|
+
("/background [id]", "show foreground activity + background tasks (or one task's output)"),
|
|
225
|
+
("/expand [n]", "show the full detail of the nth most recent tool call"),
|
|
215
226
|
("/skip-plan <prompt>", "send a prompt without generating/reviewing a plan"),
|
|
216
227
|
("/reset [<n>|last]", "rewind to the end of turn n (drops everything after it);"),
|
|
217
228
|
("", "a bare /reset only re-saves the current state (no data loss)"),
|
|
218
|
-
("/clear", "
|
|
229
|
+
("/clear", "dismiss command output/notices (keeps the conversation)"),
|
|
219
230
|
("/help", "show this help"),
|
|
220
231
|
("/quit, /exit", "save the session and exit"),
|
|
221
232
|
("", "Shift+Enter (or Ctrl-J) inserts a new line; Enter sends."),
|
|
222
233
|
):
|
|
223
|
-
|
|
234
|
+
console.emit(f" {command:16} {description}")
|
|
235
|
+
if tui_mod.tui_mode(getattr(args, "tui", "auto")) != "off":
|
|
236
|
+
console.emit(" TUI input ↑/↓ history, ←/→ edit, Home/End, "
|
|
237
|
+
"Ctrl-A/E/K/U/L.")
|
|
224
238
|
if getattr(args, "enable_subagents", False) or args.verbose:
|
|
225
|
-
|
|
239
|
+
console.emit(console.style("Sub-agents:", bold=True, fg="cyan"))
|
|
226
240
|
for sa in subagents.get_registry().values():
|
|
227
|
-
|
|
241
|
+
console.emit(f" {sa.name:16} {sa.description}")
|
|
228
242
|
if getattr(args, "enable_skills", False) or args.verbose:
|
|
229
|
-
|
|
243
|
+
console.emit(console.style("Skills:", bold=True, fg="cyan"))
|
|
230
244
|
for name in skills.SKILL_TOOL_NAMES:
|
|
231
|
-
|
|
232
|
-
|
|
245
|
+
console.emit(f" {name:16} (from the local .mini directory)")
|
|
246
|
+
console.rule(char="═", fg="cyan")
|
|
233
247
|
|
|
234
248
|
|
|
235
249
|
def print_welcome(allowed_dir, server_url, args, unique_id, cache_dir, model_name=None,
|
|
@@ -455,6 +469,7 @@ def maybe_compact(messages, server_url, model, api_key, llm_timeout, token_stats
|
|
|
455
469
|
server_url=server_url,
|
|
456
470
|
api_key=api_key,
|
|
457
471
|
timeout=llm_timeout,
|
|
472
|
+
console=console,
|
|
458
473
|
))
|
|
459
474
|
finally:
|
|
460
475
|
console.stop_thinking()
|
|
@@ -591,8 +606,14 @@ class AgentSession:
|
|
|
591
606
|
# start_session) can differ from the id in the banner.
|
|
592
607
|
self.unique_id = generate_unique_id()
|
|
593
608
|
self.session_dir = os.path.join(self.cache_dir, self.unique_id)
|
|
594
|
-
|
|
595
|
-
|
|
609
|
+
self.started_at = time.monotonic()
|
|
610
|
+
|
|
611
|
+
self.tui_mode = tui_mod.tui_mode(getattr(args, "tui", "auto"))
|
|
612
|
+
if console is None:
|
|
613
|
+
use_tui = (self.tui_mode == "on"
|
|
614
|
+
or (self.tui_mode == "auto" and tui_mod.TuiConsole.supported()))
|
|
615
|
+
console = tui_mod.TuiConsole() if use_tui else ui.console
|
|
616
|
+
self.console = console
|
|
596
617
|
self.console.verbose = getattr(args, "verbose", False)
|
|
597
618
|
|
|
598
619
|
# LLM / server configuration.
|
|
@@ -600,6 +621,18 @@ class AgentSession:
|
|
|
600
621
|
self.api_key = args.api_key if args.api_key else os.environ.get("MINI_CODE_API_KEY", "")
|
|
601
622
|
self.model = self._resolve_model(args)
|
|
602
623
|
|
|
624
|
+
# Background task registry. It is independent of the foreground loop;
|
|
625
|
+
# tools and /background read snapshots from it.
|
|
626
|
+
self.background_tasks = background_mod.BackgroundTaskManager(
|
|
627
|
+
os.path.join(self.session_dir, "background"))
|
|
628
|
+
|
|
629
|
+
# What the foreground loop is doing *right now* (or last did), for
|
|
630
|
+
# /background. The loop is synchronous, so this is most useful when
|
|
631
|
+
# read between steps; it is updated at every blocking boundary.
|
|
632
|
+
self._activity_label = None
|
|
633
|
+
self._activity_started = None
|
|
634
|
+
self._last_activity = None
|
|
635
|
+
|
|
603
636
|
self._register_tools(args)
|
|
604
637
|
|
|
605
638
|
# report_path is set on a *sub-agent child* session (by
|
|
@@ -625,6 +658,9 @@ class AgentSession:
|
|
|
625
658
|
or requested_plan_strategy is not None)
|
|
626
659
|
|
|
627
660
|
self.scratchpad = bool(getattr(self.args, "scratchpad", False))
|
|
661
|
+
self.tui = (self.tui_mode != "off"
|
|
662
|
+
and isinstance(self.console, tui_mod.TuiConsole))
|
|
663
|
+
self.restored_session = False
|
|
628
664
|
self.compaction_strategy = getattr(
|
|
629
665
|
self.args, "compaction_strategy",
|
|
630
666
|
compaction_mod.DEFAULT_COMPACTION_STRATEGY)
|
|
@@ -765,9 +801,12 @@ class AgentSession:
|
|
|
765
801
|
"""
|
|
766
802
|
self.unique_id = self.unique_id or generate_unique_id()
|
|
767
803
|
self.session_dir = os.path.join(self.cache_dir, self.unique_id)
|
|
804
|
+
self.restored_session = False
|
|
768
805
|
|
|
769
806
|
self.plan_manager = plan_utils.PlanManager(
|
|
770
807
|
self.session_dir, enabled=self.plan_mode)
|
|
808
|
+
self.background_tasks.set_log_dir(
|
|
809
|
+
os.path.join(self.session_dir, "background"))
|
|
771
810
|
self._prepare_agent_files()
|
|
772
811
|
|
|
773
812
|
self.history_index = 0
|
|
@@ -849,6 +888,8 @@ class AgentSession:
|
|
|
849
888
|
self.session_dir = restore_directory
|
|
850
889
|
self.plan_manager = plan_utils.PlanManager(
|
|
851
890
|
self.session_dir, enabled=self.plan_mode)
|
|
891
|
+
self.background_tasks.set_log_dir(
|
|
892
|
+
os.path.join(self.session_dir, "background"))
|
|
852
893
|
self._prepare_agent_files()
|
|
853
894
|
self.messages = restored
|
|
854
895
|
self.summary = records
|
|
@@ -872,6 +913,7 @@ class AgentSession:
|
|
|
872
913
|
self.last_prompt_tokens = 0
|
|
873
914
|
self.last_prompt_message_count = 0
|
|
874
915
|
self._restore_usage_if_available(restore_directory)
|
|
916
|
+
self.restored_session = True
|
|
875
917
|
|
|
876
918
|
# Continuing a session in place makes it the latest one again: keep
|
|
877
919
|
# the pointer aimed at it so a later --load-last-session finds the
|
|
@@ -901,6 +943,7 @@ class AgentSession:
|
|
|
901
943
|
self.last_prompt_tokens = 0
|
|
902
944
|
self.last_prompt_message_count = 0
|
|
903
945
|
self._persistent_messages = []
|
|
946
|
+
self.restored_session = False
|
|
904
947
|
return False
|
|
905
948
|
|
|
906
949
|
def _resolve_model(self, args):
|
|
@@ -972,6 +1015,18 @@ class AgentSession:
|
|
|
972
1015
|
self.tools_dict.update(skills.get_skills_file_tools_dict(self.allowed_dir))
|
|
973
1016
|
self.llm_tools.extend(skills.get_skills_file_tools(self.allowed_dir))
|
|
974
1017
|
|
|
1018
|
+
# Background tasks are opt-in: --background (or --all) plus shell
|
|
1019
|
+
# execution or sub-agents. A background session (a sub-agent child)
|
|
1020
|
+
# never gets its own task list.
|
|
1021
|
+
self.enable_background = (
|
|
1022
|
+
bool(getattr(args, "background", False))
|
|
1023
|
+
and not getattr(self, "background_mode", False)
|
|
1024
|
+
and (shell_execution_enabled(args) or self.enable_subagents))
|
|
1025
|
+
if self.enable_background:
|
|
1026
|
+
self.tools_dict.update(background_mod.background_tools_dict(
|
|
1027
|
+
self.background_tasks, self._run_background_subagent))
|
|
1028
|
+
self.llm_tools.extend(background_mod.background_tools())
|
|
1029
|
+
|
|
975
1030
|
|
|
976
1031
|
def _prepare_agent_files(self):
|
|
977
1032
|
"""Create the opt-in agent-owned files under ``--allowed-dir/.mini``.
|
|
@@ -1127,6 +1182,29 @@ class AgentSession:
|
|
|
1127
1182
|
danger = min(max(self.compaction_budget.token_limit / float(window), 0.0), 1.0)
|
|
1128
1183
|
return self.console.context_bar(fraction, warn=danger * 0.85, danger=danger)
|
|
1129
1184
|
|
|
1185
|
+
# -- foreground activity (for /background) -----------------------------
|
|
1186
|
+
|
|
1187
|
+
def _begin_activity(self, label):
|
|
1188
|
+
self._activity_label = str(label)
|
|
1189
|
+
self._activity_started = time.monotonic()
|
|
1190
|
+
|
|
1191
|
+
def _end_activity(self):
|
|
1192
|
+
if self._activity_label is None:
|
|
1193
|
+
return
|
|
1194
|
+
elapsed = max(time.monotonic() - (self._activity_started or time.monotonic()), 0.0)
|
|
1195
|
+
self._last_activity = (self._activity_label, elapsed)
|
|
1196
|
+
self._activity_label = None
|
|
1197
|
+
self._activity_started = None
|
|
1198
|
+
|
|
1199
|
+
def _activity_summary(self):
|
|
1200
|
+
if self._activity_label:
|
|
1201
|
+
elapsed = max(time.monotonic() - (self._activity_started or time.monotonic()), 0.0)
|
|
1202
|
+
return f"{self._activity_label} ({elapsed:.1f}s)"
|
|
1203
|
+
if self._last_activity:
|
|
1204
|
+
label, elapsed = self._last_activity
|
|
1205
|
+
return f"waiting for your input (last: {label}, {elapsed:.1f}s)"
|
|
1206
|
+
return "waiting for your input"
|
|
1207
|
+
|
|
1130
1208
|
def _bill_compaction(self, segment_before):
|
|
1131
1209
|
"""Carry the compaction call's spend over into the session total.
|
|
1132
1210
|
|
|
@@ -1376,7 +1454,8 @@ class AgentSession:
|
|
|
1376
1454
|
f"Could not persist the rewind ({e}); the session is unchanged.", "error")
|
|
1377
1455
|
return False
|
|
1378
1456
|
|
|
1379
|
-
removed = delete_segments_above(self.session_dir, target_index
|
|
1457
|
+
removed = delete_segments_above(self.session_dir, target_index,
|
|
1458
|
+
console=self.console)
|
|
1380
1459
|
|
|
1381
1460
|
self.messages = messages
|
|
1382
1461
|
self.history_index = target_index
|
|
@@ -1416,6 +1495,78 @@ class AgentSession:
|
|
|
1416
1495
|
fg="red",
|
|
1417
1496
|
)
|
|
1418
1497
|
|
|
1498
|
+
def _tui_info_line(self):
|
|
1499
|
+
"""A one-line session summary for the fixed dashboard."""
|
|
1500
|
+
usage = getattr(self, "total_usage", {}) or {}
|
|
1501
|
+
tasks = (self.background_tasks.list()
|
|
1502
|
+
if hasattr(self, "background_tasks") else [])
|
|
1503
|
+
|
|
1504
|
+
def count(key):
|
|
1505
|
+
# The dashboard refreshes on every turn: a display detail must
|
|
1506
|
+
# never raise, even if a server reported a null/odd usage value.
|
|
1507
|
+
try:
|
|
1508
|
+
return int(usage.get(key) or 0)
|
|
1509
|
+
except (TypeError, ValueError):
|
|
1510
|
+
return 0
|
|
1511
|
+
|
|
1512
|
+
running = sum(1 for task in tasks
|
|
1513
|
+
if task.get("status") in ("running", "cancelling"))
|
|
1514
|
+
if tasks:
|
|
1515
|
+
background = (f"{running} of "
|
|
1516
|
+
f"{plural(len(tasks), 'background task')} running")
|
|
1517
|
+
else:
|
|
1518
|
+
background = "no background tasks"
|
|
1519
|
+
return (f"{plural(count('tool_calls'), 'tool call')} · "
|
|
1520
|
+
f"{plural(count('llm_calls'), 'LLM call')} · {background}")
|
|
1521
|
+
|
|
1522
|
+
def _tui_header_lines(self):
|
|
1523
|
+
"""The fixed dashboard content for --tui."""
|
|
1524
|
+
from . import __version__ as version
|
|
1525
|
+
if getattr(self.args, "sudo", False):
|
|
1526
|
+
permission = "sudo"
|
|
1527
|
+
elif getattr(self.args, "ask_permission", False):
|
|
1528
|
+
permission = "ask"
|
|
1529
|
+
else:
|
|
1530
|
+
permission = "auto"
|
|
1531
|
+
shell = "on" if shell_execution_enabled(self.args) else "off"
|
|
1532
|
+
planning = self.plan_strategy if self.plan_mode else "off"
|
|
1533
|
+
sep = f" {self.console.glyph('v')} "
|
|
1534
|
+
session_line = sep.join((
|
|
1535
|
+
f"version: {version}",
|
|
1536
|
+
f"session: {self.unique_id}",
|
|
1537
|
+
))
|
|
1538
|
+
if self.restored_session:
|
|
1539
|
+
session_line += f"{sep}[restored]"
|
|
1540
|
+
lines = [
|
|
1541
|
+
session_line,
|
|
1542
|
+
f"model: {oneline(self.model or '(auto)', 56)}",
|
|
1543
|
+
f"server: {oneline(self.server_url, 56)}",
|
|
1544
|
+
f"dir: {oneline(self.allowed_dir, 56)}",
|
|
1545
|
+
sep.join((f"permissions: {permission}", f"shell: {shell}")),
|
|
1546
|
+
sep.join((f"compaction: {self.compaction_strategy}",
|
|
1547
|
+
f"planning: {planning}")),
|
|
1548
|
+
]
|
|
1549
|
+
badge = self._context_badge()
|
|
1550
|
+
if badge:
|
|
1551
|
+
lines.append(f"context: {badge}")
|
|
1552
|
+
return lines
|
|
1553
|
+
|
|
1554
|
+
def _tui_history_turns(self):
|
|
1555
|
+
"""User/assistant turns to prime the TUI core view after a restore."""
|
|
1556
|
+
persistent = {id(message) for message in self._persistent_messages}
|
|
1557
|
+
turns = []
|
|
1558
|
+
for message in self.messages:
|
|
1559
|
+
role = message.get("role")
|
|
1560
|
+
content = message.get("content")
|
|
1561
|
+
if role not in ("user", "assistant") or not content:
|
|
1562
|
+
continue
|
|
1563
|
+
if id(message) in persistent:
|
|
1564
|
+
continue
|
|
1565
|
+
if role == "user" and _is_loop_injected(message):
|
|
1566
|
+
continue
|
|
1567
|
+
turns.append((role, content))
|
|
1568
|
+
return turns[-40:]
|
|
1569
|
+
|
|
1419
1570
|
def print_welcome(self):
|
|
1420
1571
|
"""Render the startup banner for this session."""
|
|
1421
1572
|
print_welcome(self.allowed_dir, self.server_url, self.args,
|
|
@@ -1476,16 +1627,18 @@ class AgentSession:
|
|
|
1476
1627
|
degrades cleanly on a non-TTY / piped console: an EOF / Ctrl-C (``read_line``
|
|
1477
1628
|
returns None) is treated as ``"exit"`` so the loop never spins on unread input.
|
|
1478
1629
|
"""
|
|
1479
|
-
self.console.emit(
|
|
1480
|
-
self.console.style(
|
|
1481
|
-
"A previous session was found. What would you like to do?", dim=True,
|
|
1482
|
-
fg="cyan"))
|
|
1483
|
-
self.console.emit(" 1) Resume the previous session (continue where you left off)")
|
|
1484
|
-
self.console.emit(" 2) Start a new session (empty history)")
|
|
1485
|
-
self.console.emit(" 3) Exit (start nothing)")
|
|
1486
1630
|
while True:
|
|
1487
|
-
|
|
1488
|
-
|
|
1631
|
+
self.console.question_box("Question to User", [
|
|
1632
|
+
"Resume previous session? A previous session was found.",
|
|
1633
|
+
"",
|
|
1634
|
+
"1) Resume the previous session (continue where you left off)",
|
|
1635
|
+
"2) Start a new session (empty history)",
|
|
1636
|
+
"3) Exit (start nothing)",
|
|
1637
|
+
])
|
|
1638
|
+
prompt = (""
|
|
1639
|
+
if self.tui_active else
|
|
1640
|
+
self.console.style("Type 1, 2, or 3: ", fg="yellow"))
|
|
1641
|
+
answer = self.console.read_line(prompt)
|
|
1489
1642
|
if answer is None:
|
|
1490
1643
|
# EOF / Ctrl-C at the offer -> graceful exit, no session written.
|
|
1491
1644
|
return "exit"
|
|
@@ -1508,51 +1661,98 @@ class AgentSession:
|
|
|
1508
1661
|
# consume stdin). None of them depends on which session is finally used:
|
|
1509
1662
|
# they read args, allowed_dir, cache_dir, server_url and the resolved
|
|
1510
1663
|
# model, plus the provisional id minted in __init__.
|
|
1511
|
-
self.
|
|
1512
|
-
|
|
1513
|
-
|
|
1514
|
-
|
|
1515
|
-
|
|
1516
|
-
|
|
1517
|
-
|
|
1518
|
-
|
|
1519
|
-
|
|
1520
|
-
|
|
1521
|
-
self.
|
|
1522
|
-
|
|
1523
|
-
|
|
1524
|
-
#
|
|
1525
|
-
#
|
|
1526
|
-
pending = initial_prompt
|
|
1664
|
+
if self.tui and isinstance(self.console, tui_mod.TuiConsole):
|
|
1665
|
+
if not self.console.start_tui():
|
|
1666
|
+
# --tui on requested the fixed view, but this terminal cannot
|
|
1667
|
+
# host it (piped output, an unsupported TERM, ...). Fall back
|
|
1668
|
+
# to the scrolling console instead of leaving self.tui true
|
|
1669
|
+
# with no frame on screen.
|
|
1670
|
+
self.tui = False
|
|
1671
|
+
self.console.note(
|
|
1672
|
+
"TUI is not available on this terminal; using the "
|
|
1673
|
+
"scrolling console.", "warn")
|
|
1674
|
+
if not self.tui_active:
|
|
1675
|
+
self.print_welcome()
|
|
1676
|
+
|
|
1677
|
+
# Startup (including the resume offer, which may raise SystemExit) is
|
|
1678
|
+
# inside the guarded region so the alternate screen is always restored.
|
|
1527
1679
|
try:
|
|
1680
|
+
self.print_announcements()
|
|
1681
|
+
self._warn_compaction_budget()
|
|
1682
|
+
|
|
1683
|
+
# Only now resolve the session (resume offer / restore / fresh start),
|
|
1684
|
+
# because all of that can consume input and can replace the id. The id
|
|
1685
|
+
# line and the tip therefore come after it and show the id actually in
|
|
1686
|
+
# use (the banner may have shown the provisional one).
|
|
1687
|
+
self.start_session()
|
|
1688
|
+
if self.tui_active:
|
|
1689
|
+
self.console.set_summary(self._tui_header_lines())
|
|
1690
|
+
self.console.set_info_provider(self._tui_info_line)
|
|
1691
|
+
if self.restored_session:
|
|
1692
|
+
self.console.load_history(self._tui_history_turns())
|
|
1693
|
+
else:
|
|
1694
|
+
self._print_session_id()
|
|
1695
|
+
self._emit_tip()
|
|
1696
|
+
|
|
1697
|
+
# The --prompt value is a one-shot initial turn: it is sent verbatim
|
|
1698
|
+
# and then cleared, so later turns come from the user (manual mode) or
|
|
1699
|
+
# are produced automatically by the loop (auto mode).
|
|
1700
|
+
pending = initial_prompt
|
|
1528
1701
|
while True:
|
|
1529
1702
|
user_input = pending if pending is not None else self._read_user_line()
|
|
1530
1703
|
if user_input is None or user_input.lower() in self.EXIT_COMMANDS:
|
|
1531
1704
|
self.console.note("Thank you. Goodbye! Saving history...", "info")
|
|
1532
1705
|
break
|
|
1533
|
-
|
|
1706
|
+
was_preset = pending is not None
|
|
1707
|
+
if was_preset:
|
|
1534
1708
|
self.console.rule(title="Preset prompt", char="=", fg="cyan")
|
|
1535
1709
|
self.console.short_divider()
|
|
1536
1710
|
self.console.turn("You", user_input, accent="cyan")
|
|
1537
1711
|
pending = None
|
|
1538
1712
|
# Interactive slash commands are handled in place and never
|
|
1539
|
-
# reach the LLM.
|
|
1713
|
+
# reach the LLM (and do not appear as a "You" turn in the TUI).
|
|
1540
1714
|
if user_input.startswith("/") and self._handle_command(user_input):
|
|
1541
1715
|
continue
|
|
1716
|
+
if self.tui_active and not was_preset:
|
|
1717
|
+
self.console.turn("You", user_input, accent="cyan")
|
|
1542
1718
|
self._run_turn(user_input)
|
|
1543
1719
|
except _Abort:
|
|
1544
1720
|
# Ctrl-C during a permission prompt already saved the session.
|
|
1545
1721
|
return
|
|
1546
1722
|
except KeyboardInterrupt:
|
|
1547
|
-
|
|
1548
|
-
|
|
1723
|
+
# Stop the fixed view first so the reason, the save note and the
|
|
1724
|
+
# good-bye box all land on the normal screen. A cancellation is a
|
|
1725
|
+
# normal end to the session: keep the farewell summary (including
|
|
1726
|
+
# any background tasks this interrupt cancelled).
|
|
1727
|
+
if self.tui_active:
|
|
1728
|
+
self.console.stop_tui()
|
|
1729
|
+
self.console.note(
|
|
1730
|
+
"Interrupting: Mini Code Exiting... Background tasks "
|
|
1731
|
+
"cancelled; session saved.", "error")
|
|
1732
|
+
self.shutdown()
|
|
1549
1733
|
return
|
|
1550
1734
|
except Exception as e:
|
|
1551
|
-
self.console.note(f"Exception {e}. Exiting...", "error")
|
|
1552
1735
|
self.shutdown(farewell=False)
|
|
1736
|
+
self.console.note(f"Exception {e}. Exiting...", "error")
|
|
1553
1737
|
return
|
|
1738
|
+
finally:
|
|
1739
|
+
# A SystemExit/fatal path can bypass shutdown(); make sure
|
|
1740
|
+
# background work never outlives the session.
|
|
1741
|
+
background_cancelled = len(self.background_tasks.running())
|
|
1742
|
+
self.background_tasks.shutdown()
|
|
1743
|
+
if background_cancelled:
|
|
1744
|
+
self._exit_background = max(
|
|
1745
|
+
getattr(self, "_exit_background", 0), background_cancelled)
|
|
1746
|
+
if self.tui_active:
|
|
1747
|
+
self.console.stop_tui()
|
|
1554
1748
|
self.shutdown()
|
|
1555
1749
|
|
|
1750
|
+
@property
|
|
1751
|
+
def tui_active(self):
|
|
1752
|
+
"""Whether the fixed TUI frame is currently on screen."""
|
|
1753
|
+
return (self.tui and isinstance(self.console, tui_mod.TuiConsole)
|
|
1754
|
+
and self.console.active)
|
|
1755
|
+
|
|
1556
1756
|
def _emit_tip(self):
|
|
1557
1757
|
"""Point at the history/navigation commands once, at startup."""
|
|
1558
1758
|
tip = ("Tip: Shift+Enter (or Ctrl-J) for a new line, Enter to send. "
|
|
@@ -1564,6 +1764,9 @@ class AgentSession:
|
|
|
1564
1764
|
"send one prompt without planning, /history to browse the "
|
|
1565
1765
|
"conversation, /history <n> to inspect a turn, /reset <n> to "
|
|
1566
1766
|
"rewind. Type /help for all commands.")
|
|
1767
|
+
if self.tui:
|
|
1768
|
+
tip = (tip + " TUI: ↑/↓ history, ←/→ edit, Home/End, "
|
|
1769
|
+
"Ctrl-A/E/K/U/L.")
|
|
1567
1770
|
self.console.emit(self.console.style(tip, dim=True, fg="cyan"))
|
|
1568
1771
|
|
|
1569
1772
|
def _warn_compaction_budget(self):
|
|
@@ -1662,11 +1865,12 @@ class AgentSession:
|
|
|
1662
1865
|
"""
|
|
1663
1866
|
if self.background_mode or not self.allowed_dir:
|
|
1664
1867
|
return
|
|
1665
|
-
save_last_session_pointer(self.allowed_dir, self.session_dir
|
|
1868
|
+
save_last_session_pointer(self.allowed_dir, self.session_dir,
|
|
1869
|
+
console=self.console)
|
|
1666
1870
|
|
|
1667
1871
|
# -- autonomous drive (used by sub-agents) ------------------------------
|
|
1668
1872
|
|
|
1669
|
-
def _drive_auto(self, initial_task, max_steps=None):
|
|
1873
|
+
def _drive_auto(self, initial_task, max_steps=None, should_stop=None):
|
|
1670
1874
|
"""Run unattended to completion and return the final assistant answer.
|
|
1671
1875
|
|
|
1672
1876
|
Appends ``initial_task`` as a user turn, then keeps stepping until the
|
|
@@ -1695,6 +1899,10 @@ class AgentSession:
|
|
|
1695
1899
|
self.steps_taken = 0
|
|
1696
1900
|
try:
|
|
1697
1901
|
while True:
|
|
1902
|
+
if should_stop is not None and should_stop():
|
|
1903
|
+
self.console.note("Sub-agent task cancelled; stopping.", "warn")
|
|
1904
|
+
self.stop_reason = "cancelled"
|
|
1905
|
+
break
|
|
1698
1906
|
should_continue = self._step()
|
|
1699
1907
|
self._persist()
|
|
1700
1908
|
steps += 1
|
|
@@ -1735,6 +1943,7 @@ class AgentSession:
|
|
|
1735
1943
|
"""
|
|
1736
1944
|
plan_prompt_text = prompts.plan_prompt(self.messages, current_instruction)
|
|
1737
1945
|
plan_text = ""
|
|
1946
|
+
self._begin_activity("generating plan")
|
|
1738
1947
|
try:
|
|
1739
1948
|
self.console.note("Generating a plan for the current goal...", "info")
|
|
1740
1949
|
self.console.start_thinking("planning")
|
|
@@ -1754,8 +1963,8 @@ class AgentSession:
|
|
|
1754
1963
|
server_url=self.server_url,
|
|
1755
1964
|
api_key=self.api_key,
|
|
1756
1965
|
timeout=self.args.llm_timeout,
|
|
1966
|
+
console=self.console,
|
|
1757
1967
|
))
|
|
1758
|
-
self.console.stop_thinking()
|
|
1759
1968
|
|
|
1760
1969
|
self._record_usage(usage)
|
|
1761
1970
|
# The plan prompt is one message holding a flattened copy of the whole
|
|
@@ -1766,14 +1975,16 @@ class AgentSession:
|
|
|
1766
1975
|
plan_text = response or ""
|
|
1767
1976
|
except Exception as exc:
|
|
1768
1977
|
self.console.note(f"Could not generate a plan: {exc}", "warn")
|
|
1978
|
+
finally:
|
|
1979
|
+
self.console.stop_thinking()
|
|
1980
|
+
self._end_activity()
|
|
1769
1981
|
|
|
1770
1982
|
self.plan_manager.write_plan(plan_text)
|
|
1771
1983
|
if plan_text and plan_text.strip():
|
|
1772
1984
|
# Show the plan immediately; otherwise the user only sees it via
|
|
1773
1985
|
# /plan or the file on disk.
|
|
1774
|
-
self.console.
|
|
1775
|
-
|
|
1776
|
-
fg="cyan", dim=True)
|
|
1986
|
+
self.console.plan_box(plan_text.strip().splitlines(),
|
|
1987
|
+
title="Plan for the current goal")
|
|
1777
1988
|
else:
|
|
1778
1989
|
self.console.note("No plan text was generated.", "warn")
|
|
1779
1990
|
if plan_text and plan_text.strip():
|
|
@@ -1791,6 +2002,7 @@ class AgentSession:
|
|
|
1791
2002
|
plan_prompt_text = prompts.plan_review_prompt(
|
|
1792
2003
|
self.messages, self.plan_manager.goal or "")
|
|
1793
2004
|
summary = ""
|
|
2005
|
+
self._begin_activity("reviewing plan")
|
|
1794
2006
|
try:
|
|
1795
2007
|
self.console.note("Reviewing the current plan...", "info")
|
|
1796
2008
|
self.console.start_thinking("reviewing plan")
|
|
@@ -1803,13 +2015,16 @@ class AgentSession:
|
|
|
1803
2015
|
server_url=self.server_url,
|
|
1804
2016
|
api_key=self.api_key,
|
|
1805
2017
|
timeout=self.args.llm_timeout,
|
|
2018
|
+
console=self.console,
|
|
1806
2019
|
))
|
|
1807
|
-
self.console.stop_thinking()
|
|
1808
2020
|
self._record_usage(usage)
|
|
1809
2021
|
self._note_prompt_size(usage, len(self.messages))
|
|
1810
2022
|
summary = response or ""
|
|
1811
2023
|
except Exception as exc:
|
|
1812
2024
|
self.console.note(f"Could not review the plan: {exc}", "warn")
|
|
2025
|
+
finally:
|
|
2026
|
+
self.console.stop_thinking()
|
|
2027
|
+
self._end_activity()
|
|
1813
2028
|
|
|
1814
2029
|
# Persist the review summary to the plan document and re-inject it so
|
|
1815
2030
|
# the model works from the review result.
|
|
@@ -1937,6 +2152,7 @@ class AgentSession:
|
|
|
1937
2152
|
tools=read_tools,
|
|
1938
2153
|
api_key=self.api_key,
|
|
1939
2154
|
timeout=self.args.llm_timeout,
|
|
2155
|
+
console=self.console,
|
|
1940
2156
|
))
|
|
1941
2157
|
except Exception as exc:
|
|
1942
2158
|
self.console.note(
|
|
@@ -1995,6 +2211,7 @@ class AgentSession:
|
|
|
1995
2211
|
server_url=self.server_url,
|
|
1996
2212
|
api_key=self.api_key,
|
|
1997
2213
|
timeout=self.args.llm_timeout,
|
|
2214
|
+
console=self.console,
|
|
1998
2215
|
))
|
|
1999
2216
|
except Exception as exc:
|
|
2000
2217
|
self.console.note(
|
|
@@ -2058,11 +2275,17 @@ class AgentSession:
|
|
|
2058
2275
|
# A loop, not recursion: holding Enter used to recurse once per blank
|
|
2059
2276
|
# line, so a long run of empty input could exhaust the interpreter stack.
|
|
2060
2277
|
while True:
|
|
2061
|
-
self.
|
|
2278
|
+
if not self.tui_active:
|
|
2279
|
+
self.console.short_divider()
|
|
2062
2280
|
|
|
2281
|
+
if self.tui_active:
|
|
2282
|
+
prompt = ""
|
|
2283
|
+
else:
|
|
2284
|
+
prompt = (self.console.style("You › ", bold=True, fg="cyan")
|
|
2285
|
+
if self.tui else
|
|
2286
|
+
self.console.style("You:", bold=True, fg="cyan") + " ")
|
|
2063
2287
|
user_input = self.console.read_line(
|
|
2064
|
-
|
|
2065
|
-
multiline=True)
|
|
2288
|
+
prompt, multiline=True, tui=self.tui)
|
|
2066
2289
|
|
|
2067
2290
|
# EOF / Ctrl-C at the prompt: the caller treats None as "quit", so it
|
|
2068
2291
|
# must not be dereferenced here (a piped or closed stdin would
|
|
@@ -2088,6 +2311,10 @@ class AgentSession:
|
|
|
2088
2311
|
(plan mode only)
|
|
2089
2312
|
/context show how the context window is used, by category
|
|
2090
2313
|
(tokens and percentages)
|
|
2314
|
+
/background [id] show what the loop is doing and the background
|
|
2315
|
+
tasks (or the output of one task)
|
|
2316
|
+
/expand [n] show the full detail of the nth most recent tool
|
|
2317
|
+
call (default: the last one)
|
|
2091
2318
|
/skip-plan <text> send <text> without generating or reviewing a plan
|
|
2092
2319
|
/clear clear the screen (keeps the conversation)
|
|
2093
2320
|
/help show the command help
|
|
@@ -2112,7 +2339,7 @@ class AgentSession:
|
|
|
2112
2339
|
self._do_reset(arg)
|
|
2113
2340
|
return True
|
|
2114
2341
|
if cmd == "help":
|
|
2115
|
-
print_help(self.args)
|
|
2342
|
+
print_help(self.args, console=self.console)
|
|
2116
2343
|
return True
|
|
2117
2344
|
if cmd in self.CLEAR_COMMANDS:
|
|
2118
2345
|
self._clear_and_show_last()
|
|
@@ -2123,6 +2350,12 @@ class AgentSession:
|
|
|
2123
2350
|
if cmd == "context":
|
|
2124
2351
|
self._show_context()
|
|
2125
2352
|
return True
|
|
2353
|
+
if cmd in ("background", "bg", "tasks"):
|
|
2354
|
+
self._show_background(arg)
|
|
2355
|
+
return True
|
|
2356
|
+
if cmd in ("expand", "tool"):
|
|
2357
|
+
self.console.expand_tool(arg or 1)
|
|
2358
|
+
return True
|
|
2126
2359
|
if cmd in ("skip-plan", "skip_plan", "skipplan"):
|
|
2127
2360
|
self._run_skipped_plan(arg)
|
|
2128
2361
|
return True
|
|
@@ -2265,14 +2498,81 @@ class AgentSession:
|
|
|
2265
2498
|
self.console.status_box(lines, title="Context usage",
|
|
2266
2499
|
fg="green", dim=True)
|
|
2267
2500
|
|
|
2501
|
+
def _show_background(self, arg=""):
|
|
2502
|
+
"""Show background tasks and the foreground activity (``/background``).
|
|
2503
|
+
|
|
2504
|
+
``/background`` renders a table of tasks; ``/background bg-1`` renders
|
|
2505
|
+
that task's state and output tail. The foreground line is the loop's
|
|
2506
|
+
last/current blocking step (LLM call, tool, plan, ...). Because the
|
|
2507
|
+
loop is synchronous this is read between steps, but it tells the user
|
|
2508
|
+
what the LLM was waiting on for the last operation.
|
|
2509
|
+
"""
|
|
2510
|
+
requested = (arg or "").strip()
|
|
2511
|
+
self.console.rule(title="Background", char="═", fg="cyan")
|
|
2512
|
+
if requested:
|
|
2513
|
+
snapshot = self.background_tasks.get(requested)
|
|
2514
|
+
if snapshot is None:
|
|
2515
|
+
self.console.note(
|
|
2516
|
+
f"No background task {requested!r}. Use /background to list them.",
|
|
2517
|
+
"warn")
|
|
2518
|
+
return
|
|
2519
|
+
snapshot = snapshot.snapshot()
|
|
2520
|
+
lines = [
|
|
2521
|
+
f"id : {snapshot['id']}",
|
|
2522
|
+
f"kind : {snapshot['kind']}",
|
|
2523
|
+
f"status : {snapshot['status']}",
|
|
2524
|
+
f"age : {snapshot['age_seconds']:.1f}s",
|
|
2525
|
+
f"label : {oneline(snapshot['label'], 100)}",
|
|
2526
|
+
f"pid : {snapshot['pid'] if snapshot['pid'] is not None else '-'}",
|
|
2527
|
+
f"exit code: {snapshot['exit_code'] if snapshot['exit_code'] is not None else '-'}",
|
|
2528
|
+
f"log file : {snapshot['log_path']}",
|
|
2529
|
+
]
|
|
2530
|
+
if snapshot.get("result"):
|
|
2531
|
+
lines += ["", "result:", oneline(snapshot["result"], 400)]
|
|
2532
|
+
if snapshot.get("error"):
|
|
2533
|
+
lines += ["", "error:", oneline(snapshot["error"], 400)]
|
|
2534
|
+
output = self.background_tasks.tail(requested, 60)
|
|
2535
|
+
if output:
|
|
2536
|
+
lines += ["", "output (tail):"]
|
|
2537
|
+
lines.extend(output.rstrip().splitlines())
|
|
2538
|
+
self.console.status_box(
|
|
2539
|
+
lines, title=f"Background task {snapshot['id']}",
|
|
2540
|
+
fg="cyan", dim=True)
|
|
2541
|
+
return
|
|
2542
|
+
|
|
2543
|
+
lines = [f"Foreground : {self._activity_summary()}", ""]
|
|
2544
|
+
snapshots = self.background_tasks.list()
|
|
2545
|
+
if not snapshots:
|
|
2546
|
+
lines.append("Background : none")
|
|
2547
|
+
else:
|
|
2548
|
+
running = sum(1 for item in snapshots
|
|
2549
|
+
if item["status"] in ("running", "cancelling"))
|
|
2550
|
+
lines.append(f"Background : {running} running, {len(snapshots)} total")
|
|
2551
|
+
lines.append(
|
|
2552
|
+
f" {'id':<6} {'state':<10} {'age':>7} {'kind':<8} label")
|
|
2553
|
+
for item in snapshots:
|
|
2554
|
+
lines.append(
|
|
2555
|
+
f" {item['id']:<6} {item['status']:<10} "
|
|
2556
|
+
f"{item['age_seconds']:>6.1f}s {item['kind']:<8} "
|
|
2557
|
+
f"{oneline(item['label'], 48)}")
|
|
2558
|
+
lines.append("")
|
|
2559
|
+
lines.append("Use /background <id> for the output tail.")
|
|
2560
|
+
self.console.status_box(lines, title="Background tasks",
|
|
2561
|
+
fg="cyan", dim=True)
|
|
2562
|
+
|
|
2268
2563
|
def _clear_and_show_last(self):
|
|
2269
|
-
"""Handle /clear:
|
|
2564
|
+
"""Handle /clear: dismiss transient output and re-orient the view.
|
|
2270
2565
|
|
|
2271
|
-
The conversation itself is unchanged
|
|
2272
|
-
|
|
2273
|
-
|
|
2566
|
+
The conversation itself is unchanged. In the fixed TUI this behaves
|
|
2567
|
+
like Escape in command mode: it closes command output, returns a
|
|
2568
|
+
scrolled view to the bottom, and drops info/warning notices, while the
|
|
2569
|
+
core conversation stays on screen. The scrolling console clears the
|
|
2570
|
+
terminal and re-prints the last turn instead.
|
|
2274
2571
|
"""
|
|
2275
2572
|
self.console.clear_screen()
|
|
2573
|
+
if self.tui_active:
|
|
2574
|
+
# The TUI keeps the conversation visible; do not re-print it.
|
|
2575
|
+
return
|
|
2276
2576
|
last_role = last_text = None
|
|
2277
2577
|
for m in reversed(self.messages):
|
|
2278
2578
|
role = m.get("role")
|
|
@@ -2298,7 +2598,12 @@ class AgentSession:
|
|
|
2298
2598
|
|
|
2299
2599
|
try:
|
|
2300
2600
|
for call in tool_calls:
|
|
2301
|
-
|
|
2601
|
+
name = ((call or {}).get("function") or {}).get("name", "?")
|
|
2602
|
+
self._begin_activity(f"running tool {name}")
|
|
2603
|
+
try:
|
|
2604
|
+
self._run_one_tool_call(call)
|
|
2605
|
+
finally:
|
|
2606
|
+
self._end_activity()
|
|
2302
2607
|
finally:
|
|
2303
2608
|
self.console.stop_tool_call()
|
|
2304
2609
|
|
|
@@ -2361,6 +2666,27 @@ class AgentSession:
|
|
|
2361
2666
|
return
|
|
2362
2667
|
|
|
2363
2668
|
# 2) Shell-safety classifier (DENY / ASK / ALLOW), always enforced.
|
|
2669
|
+
background_action = (str(tool_params.get("action", "")).lower()
|
|
2670
|
+
if name == "background" else "")
|
|
2671
|
+
background_kind = (str(tool_params.get("kind", background_mod.SHELL)).lower()
|
|
2672
|
+
if name == "background" else background_mod.SHELL)
|
|
2673
|
+
background_shell = (name == "background"
|
|
2674
|
+
and background_action == "start"
|
|
2675
|
+
and background_kind == background_mod.SHELL)
|
|
2676
|
+
background_subagent = (name == "background"
|
|
2677
|
+
and background_action == "start"
|
|
2678
|
+
and background_kind == background_mod.SUBAGENT)
|
|
2679
|
+
if background_subagent and not self.enable_subagents:
|
|
2680
|
+
self.console.note("Background sub-agent requested but sub-agents are disabled.", "error")
|
|
2681
|
+
self._append_tool_result(call_id,
|
|
2682
|
+
"Error: sub-agents are not enabled in this session.")
|
|
2683
|
+
return
|
|
2684
|
+
if background_shell and not shell_execution_enabled(self.args):
|
|
2685
|
+
self.console.note("Background shell requested but shell execution is disabled.", "error")
|
|
2686
|
+
self._append_tool_result(call_id,
|
|
2687
|
+
"Error: shell execution is disabled in this session.")
|
|
2688
|
+
return
|
|
2689
|
+
|
|
2364
2690
|
shell_cmd = None
|
|
2365
2691
|
if name == "run_shell_command":
|
|
2366
2692
|
shell_cmd = str(tool_params.get("command", ""))
|
|
@@ -2370,6 +2696,14 @@ class AgentSession:
|
|
|
2370
2696
|
self._append_tool_result(call_id,
|
|
2371
2697
|
f"Command refused for safety reasons ({reason}): {shell_cmd!r}. Please choose a safer command.")
|
|
2372
2698
|
return
|
|
2699
|
+
elif background_shell:
|
|
2700
|
+
shell_cmd = str(tool_params.get("command", ""))
|
|
2701
|
+
tier, reason = shell_safety_utils.classify_command(shell_cmd)
|
|
2702
|
+
if shell_safety_utils.is_deny(tier):
|
|
2703
|
+
self.console.note(f"Refusing to run dangerous command: {shell_cmd!r} ({reason})", "error")
|
|
2704
|
+
self._append_tool_result(call_id,
|
|
2705
|
+
f"Command refused for safety reasons ({reason}): {shell_cmd!r}. Please choose a safer command.")
|
|
2706
|
+
return
|
|
2373
2707
|
else:
|
|
2374
2708
|
tier = reason = None
|
|
2375
2709
|
|
|
@@ -2406,6 +2740,17 @@ class AgentSession:
|
|
|
2406
2740
|
self.console.tool_call_display(name, tool_params, result, transient=transient)
|
|
2407
2741
|
self._append_tool_result(call_id, str(result))
|
|
2408
2742
|
|
|
2743
|
+
def _run_background_subagent(self, name, task, max_steps, should_stop):
|
|
2744
|
+
"""Worker for a background sub-agent task (called from its thread)."""
|
|
2745
|
+
subagent = self.subagents_registry.get(name)
|
|
2746
|
+
if subagent is None:
|
|
2747
|
+
return f"Error: unknown sub-agent {name!r}."
|
|
2748
|
+
try:
|
|
2749
|
+
return subagent.run(task, parent=self, max_steps=max_steps,
|
|
2750
|
+
should_stop=should_stop)
|
|
2751
|
+
except Exception as e: # noqa: BLE001 - reported as the task result
|
|
2752
|
+
return f"Error: sub-agent {name!r} failed: {e}"
|
|
2753
|
+
|
|
2409
2754
|
def _run_subagent(self, name, tool_params):
|
|
2410
2755
|
"""Run a sub-agent for ``task`` and return the text to feed back."""
|
|
2411
2756
|
subagent = self.subagents_registry[name]
|
|
@@ -2486,12 +2831,19 @@ class AgentSession:
|
|
|
2486
2831
|
def shutdown(self, farewell=True):
|
|
2487
2832
|
"""Persist and print a final summary (called on quit / exit).
|
|
2488
2833
|
|
|
2489
|
-
``farewell=False`` is used by the
|
|
2490
|
-
which
|
|
2834
|
+
``farewell=False`` is used by the fatal-exception path in :meth:`run`,
|
|
2835
|
+
which has already told the user (in red) that the session is being torn
|
|
2491
2836
|
down: a cheerful "thanks and here is your state" box on top of a crash is
|
|
2492
2837
|
the wrong note, and the state it would recap is the state that just
|
|
2493
|
-
failed.
|
|
2838
|
+
failed. A user cancellation is different -- it is a normal end -- so the
|
|
2839
|
+
interrupt path still prints the farewell box.
|
|
2494
2840
|
"""
|
|
2841
|
+
if self.tui_active:
|
|
2842
|
+
self.console.stop_tui()
|
|
2843
|
+
background_cancelled = len(self.background_tasks.running())
|
|
2844
|
+
self.background_tasks.shutdown()
|
|
2845
|
+
self._exit_background = max(
|
|
2846
|
+
getattr(self, "_exit_background", 0), background_cancelled)
|
|
2495
2847
|
self._persist()
|
|
2496
2848
|
segments = history_segment_indices(self.session_dir)
|
|
2497
2849
|
# List what is really on disk. The old message claimed
|
|
@@ -2550,17 +2902,29 @@ class AgentSession:
|
|
|
2550
2902
|
except (TypeError, ValueError):
|
|
2551
2903
|
return 0
|
|
2552
2904
|
|
|
2905
|
+
elapsed = max(time.monotonic() - getattr(self, "started_at",
|
|
2906
|
+
time.monotonic()), 0.0)
|
|
2907
|
+
hours, remainder = divmod(int(elapsed), 3600)
|
|
2908
|
+
minutes, seconds = divmod(remainder, 60)
|
|
2909
|
+
duration = (f"{hours}h {minutes:02d}m" if hours
|
|
2910
|
+
else f"{minutes}m {seconds:02d}s")
|
|
2911
|
+
cancelled = getattr(self, "_exit_background", 0)
|
|
2553
2912
|
rows = [
|
|
2554
2913
|
("session id", self.unique_id),
|
|
2914
|
+
("model", self.model or "(auto)"),
|
|
2555
2915
|
("saved under", f"{self.cache_dir}/{self.unique_id}/"),
|
|
2556
2916
|
("history", f"{where} (segment {self.history_index}), "
|
|
2557
2917
|
f"{plural(len(self.messages), 'message')}"),
|
|
2558
2918
|
("conversation", plural(turns, "recorded turn")),
|
|
2919
|
+
("duration", duration),
|
|
2559
2920
|
("tokens", f"{count('prompt_tokens'):,} in / "
|
|
2560
2921
|
f"{count('completion_tokens'):,} out "
|
|
2561
2922
|
f"({count('total_tokens'):,} total)"),
|
|
2562
2923
|
("calls", f"{count('llm_calls'):,} LLM, "
|
|
2563
2924
|
f"{count('tool_calls'):,} tool"),
|
|
2925
|
+
("background", (f"{plural(cancelled, 'task')} cancelled on exit"
|
|
2926
|
+
if cancelled else "none running")),
|
|
2927
|
+
("resume", "mini-code --load-last-session"),
|
|
2564
2928
|
]
|
|
2565
2929
|
self.console.farewell(version, rows)
|
|
2566
2930
|
|
|
@@ -2644,18 +3008,25 @@ class AgentSession:
|
|
|
2644
3008
|
# many messages the reported prompt_tokens describe.
|
|
2645
3009
|
sent_message_count = len(self.messages)
|
|
2646
3010
|
self.console.start_thinking()
|
|
2647
|
-
|
|
2648
|
-
|
|
2649
|
-
|
|
2650
|
-
|
|
2651
|
-
|
|
2652
|
-
|
|
2653
|
-
|
|
2654
|
-
|
|
2655
|
-
|
|
2656
|
-
|
|
2657
|
-
|
|
2658
|
-
|
|
3011
|
+
self._begin_activity(
|
|
3012
|
+
f"waiting for LLM response ({self.model or 'model'})")
|
|
3013
|
+
try:
|
|
3014
|
+
response_text, tool_calls, usage, reasoning_content = \
|
|
3015
|
+
utils.unpack_llm_result(
|
|
3016
|
+
utils.call_openai_server(
|
|
3017
|
+
self.messages,
|
|
3018
|
+
max_tokens=self.args.max_tokens,
|
|
3019
|
+
temperature=self.args.temperature,
|
|
3020
|
+
model=self.model,
|
|
3021
|
+
server_url=self.server_url,
|
|
3022
|
+
tools=self.llm_tools,
|
|
3023
|
+
api_key=self.api_key,
|
|
3024
|
+
timeout=self.args.llm_timeout,
|
|
3025
|
+
console=self.console,
|
|
3026
|
+
))
|
|
3027
|
+
finally:
|
|
3028
|
+
self.console.stop_thinking()
|
|
3029
|
+
self._end_activity()
|
|
2659
3030
|
|
|
2660
3031
|
# A failed LLM call returns (None, None, None, None): treat it as "nothing
|
|
2661
3032
|
# happened this step" so the loop degrades gracefully (records a note
|