mini-code-cli 0.1.1.4__py3-none-any.whl → 0.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.
- mini_code_cli/agent_loop.py +443 -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 +1046 -0
- mini_code_cli/ui.py +114 -59
- mini_code_cli/utils.py +25 -10
- {mini_code_cli-0.1.1.4.dist-info → mini_code_cli-0.2.0.0.dist-info}/METADATA +60 -10
- mini_code_cli-0.2.0.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.0.0.dist-info}/WHEEL +0 -0
- {mini_code_cli-0.1.1.4.dist-info → mini_code_cli-0.2.0.0.dist-info}/entry_points.txt +0 -0
- {mini_code_cli-0.1.1.4.dist-info → mini_code_cli-0.2.0.0.dist-info}/licenses/LICENSE +0 -0
- {mini_code_cli-0.1.1.4.dist-info → mini_code_cli-0.2.0.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,73 @@ 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
|
+
session_line = f"version {version} session {self.unique_id}"
|
|
1534
|
+
if self.restored_session:
|
|
1535
|
+
session_line += " [restored]"
|
|
1536
|
+
lines = [
|
|
1537
|
+
session_line,
|
|
1538
|
+
f"model {oneline(self.model or '(auto)', 56)}",
|
|
1539
|
+
f"server {oneline(self.server_url, 56)}",
|
|
1540
|
+
f"dir {oneline(self.allowed_dir, 56)}",
|
|
1541
|
+
f"perm {permission} shell {shell}",
|
|
1542
|
+
f"compact {self.compaction_strategy} planning {planning}",
|
|
1543
|
+
]
|
|
1544
|
+
badge = self._context_badge()
|
|
1545
|
+
if badge:
|
|
1546
|
+
lines.append(f"context {badge}")
|
|
1547
|
+
return lines
|
|
1548
|
+
|
|
1549
|
+
def _tui_history_turns(self):
|
|
1550
|
+
"""User/assistant turns to prime the TUI core view after a restore."""
|
|
1551
|
+
persistent = {id(message) for message in self._persistent_messages}
|
|
1552
|
+
turns = []
|
|
1553
|
+
for message in self.messages:
|
|
1554
|
+
role = message.get("role")
|
|
1555
|
+
content = message.get("content")
|
|
1556
|
+
if role not in ("user", "assistant") or not content:
|
|
1557
|
+
continue
|
|
1558
|
+
if id(message) in persistent:
|
|
1559
|
+
continue
|
|
1560
|
+
if role == "user" and _is_loop_injected(message):
|
|
1561
|
+
continue
|
|
1562
|
+
turns.append((role, content))
|
|
1563
|
+
return turns[-40:]
|
|
1564
|
+
|
|
1419
1565
|
def print_welcome(self):
|
|
1420
1566
|
"""Render the startup banner for this session."""
|
|
1421
1567
|
print_welcome(self.allowed_dir, self.server_url, self.args,
|
|
@@ -1476,16 +1622,18 @@ class AgentSession:
|
|
|
1476
1622
|
degrades cleanly on a non-TTY / piped console: an EOF / Ctrl-C (``read_line``
|
|
1477
1623
|
returns None) is treated as ``"exit"`` so the loop never spins on unread input.
|
|
1478
1624
|
"""
|
|
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
1625
|
while True:
|
|
1487
|
-
|
|
1488
|
-
|
|
1626
|
+
self.console.question_box("Question to User", [
|
|
1627
|
+
"Resume previous session? A previous session was found.",
|
|
1628
|
+
"",
|
|
1629
|
+
"1) Resume the previous session (continue where you left off)",
|
|
1630
|
+
"2) Start a new session (empty history)",
|
|
1631
|
+
"3) Exit (start nothing)",
|
|
1632
|
+
])
|
|
1633
|
+
prompt = (""
|
|
1634
|
+
if self.tui_active else
|
|
1635
|
+
self.console.style("Type 1, 2, or 3: ", fg="yellow"))
|
|
1636
|
+
answer = self.console.read_line(prompt)
|
|
1489
1637
|
if answer is None:
|
|
1490
1638
|
# EOF / Ctrl-C at the offer -> graceful exit, no session written.
|
|
1491
1639
|
return "exit"
|
|
@@ -1508,51 +1656,98 @@ class AgentSession:
|
|
|
1508
1656
|
# consume stdin). None of them depends on which session is finally used:
|
|
1509
1657
|
# they read args, allowed_dir, cache_dir, server_url and the resolved
|
|
1510
1658
|
# 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
|
|
1659
|
+
if self.tui and isinstance(self.console, tui_mod.TuiConsole):
|
|
1660
|
+
if not self.console.start_tui():
|
|
1661
|
+
# --tui on requested the fixed view, but this terminal cannot
|
|
1662
|
+
# host it (piped output, an unsupported TERM, ...). Fall back
|
|
1663
|
+
# to the scrolling console instead of leaving self.tui true
|
|
1664
|
+
# with no frame on screen.
|
|
1665
|
+
self.tui = False
|
|
1666
|
+
self.console.note(
|
|
1667
|
+
"TUI is not available on this terminal; using the "
|
|
1668
|
+
"scrolling console.", "warn")
|
|
1669
|
+
if not self.tui_active:
|
|
1670
|
+
self.print_welcome()
|
|
1671
|
+
|
|
1672
|
+
# Startup (including the resume offer, which may raise SystemExit) is
|
|
1673
|
+
# inside the guarded region so the alternate screen is always restored.
|
|
1527
1674
|
try:
|
|
1675
|
+
self.print_announcements()
|
|
1676
|
+
self._warn_compaction_budget()
|
|
1677
|
+
|
|
1678
|
+
# Only now resolve the session (resume offer / restore / fresh start),
|
|
1679
|
+
# because all of that can consume input and can replace the id. The id
|
|
1680
|
+
# line and the tip therefore come after it and show the id actually in
|
|
1681
|
+
# use (the banner may have shown the provisional one).
|
|
1682
|
+
self.start_session()
|
|
1683
|
+
if self.tui_active:
|
|
1684
|
+
self.console.set_summary(self._tui_header_lines())
|
|
1685
|
+
self.console.set_info_provider(self._tui_info_line)
|
|
1686
|
+
if self.restored_session:
|
|
1687
|
+
self.console.load_history(self._tui_history_turns())
|
|
1688
|
+
else:
|
|
1689
|
+
self._print_session_id()
|
|
1690
|
+
self._emit_tip()
|
|
1691
|
+
|
|
1692
|
+
# The --prompt value is a one-shot initial turn: it is sent verbatim
|
|
1693
|
+
# and then cleared, so later turns come from the user (manual mode) or
|
|
1694
|
+
# are produced automatically by the loop (auto mode).
|
|
1695
|
+
pending = initial_prompt
|
|
1528
1696
|
while True:
|
|
1529
1697
|
user_input = pending if pending is not None else self._read_user_line()
|
|
1530
1698
|
if user_input is None or user_input.lower() in self.EXIT_COMMANDS:
|
|
1531
1699
|
self.console.note("Thank you. Goodbye! Saving history...", "info")
|
|
1532
1700
|
break
|
|
1533
|
-
|
|
1701
|
+
was_preset = pending is not None
|
|
1702
|
+
if was_preset:
|
|
1534
1703
|
self.console.rule(title="Preset prompt", char="=", fg="cyan")
|
|
1535
1704
|
self.console.short_divider()
|
|
1536
1705
|
self.console.turn("You", user_input, accent="cyan")
|
|
1537
1706
|
pending = None
|
|
1538
1707
|
# Interactive slash commands are handled in place and never
|
|
1539
|
-
# reach the LLM.
|
|
1708
|
+
# reach the LLM (and do not appear as a "You" turn in the TUI).
|
|
1540
1709
|
if user_input.startswith("/") and self._handle_command(user_input):
|
|
1541
1710
|
continue
|
|
1711
|
+
if self.tui_active and not was_preset:
|
|
1712
|
+
self.console.turn("You", user_input, accent="cyan")
|
|
1542
1713
|
self._run_turn(user_input)
|
|
1543
1714
|
except _Abort:
|
|
1544
1715
|
# Ctrl-C during a permission prompt already saved the session.
|
|
1545
1716
|
return
|
|
1546
1717
|
except KeyboardInterrupt:
|
|
1547
|
-
|
|
1548
|
-
|
|
1718
|
+
# Stop the fixed view first so the reason, the save note and the
|
|
1719
|
+
# good-bye box all land on the normal screen. A cancellation is a
|
|
1720
|
+
# normal end to the session: keep the farewell summary (including
|
|
1721
|
+
# any background tasks this interrupt cancelled).
|
|
1722
|
+
if self.tui_active:
|
|
1723
|
+
self.console.stop_tui()
|
|
1724
|
+
self.console.note(
|
|
1725
|
+
"Interrupting: Mini Code Exiting... Background tasks "
|
|
1726
|
+
"cancelled; session saved.", "error")
|
|
1727
|
+
self.shutdown()
|
|
1549
1728
|
return
|
|
1550
1729
|
except Exception as e:
|
|
1551
|
-
self.console.note(f"Exception {e}. Exiting...", "error")
|
|
1552
1730
|
self.shutdown(farewell=False)
|
|
1731
|
+
self.console.note(f"Exception {e}. Exiting...", "error")
|
|
1553
1732
|
return
|
|
1733
|
+
finally:
|
|
1734
|
+
# A SystemExit/fatal path can bypass shutdown(); make sure
|
|
1735
|
+
# background work never outlives the session.
|
|
1736
|
+
background_cancelled = len(self.background_tasks.running())
|
|
1737
|
+
self.background_tasks.shutdown()
|
|
1738
|
+
if background_cancelled:
|
|
1739
|
+
self._exit_background = max(
|
|
1740
|
+
getattr(self, "_exit_background", 0), background_cancelled)
|
|
1741
|
+
if self.tui_active:
|
|
1742
|
+
self.console.stop_tui()
|
|
1554
1743
|
self.shutdown()
|
|
1555
1744
|
|
|
1745
|
+
@property
|
|
1746
|
+
def tui_active(self):
|
|
1747
|
+
"""Whether the fixed TUI frame is currently on screen."""
|
|
1748
|
+
return (self.tui and isinstance(self.console, tui_mod.TuiConsole)
|
|
1749
|
+
and self.console.active)
|
|
1750
|
+
|
|
1556
1751
|
def _emit_tip(self):
|
|
1557
1752
|
"""Point at the history/navigation commands once, at startup."""
|
|
1558
1753
|
tip = ("Tip: Shift+Enter (or Ctrl-J) for a new line, Enter to send. "
|
|
@@ -1564,6 +1759,9 @@ class AgentSession:
|
|
|
1564
1759
|
"send one prompt without planning, /history to browse the "
|
|
1565
1760
|
"conversation, /history <n> to inspect a turn, /reset <n> to "
|
|
1566
1761
|
"rewind. Type /help for all commands.")
|
|
1762
|
+
if self.tui:
|
|
1763
|
+
tip = (tip + " TUI: ↑/↓ history, ←/→ edit, Home/End, "
|
|
1764
|
+
"Ctrl-A/E/K/U/L.")
|
|
1567
1765
|
self.console.emit(self.console.style(tip, dim=True, fg="cyan"))
|
|
1568
1766
|
|
|
1569
1767
|
def _warn_compaction_budget(self):
|
|
@@ -1662,11 +1860,12 @@ class AgentSession:
|
|
|
1662
1860
|
"""
|
|
1663
1861
|
if self.background_mode or not self.allowed_dir:
|
|
1664
1862
|
return
|
|
1665
|
-
save_last_session_pointer(self.allowed_dir, self.session_dir
|
|
1863
|
+
save_last_session_pointer(self.allowed_dir, self.session_dir,
|
|
1864
|
+
console=self.console)
|
|
1666
1865
|
|
|
1667
1866
|
# -- autonomous drive (used by sub-agents) ------------------------------
|
|
1668
1867
|
|
|
1669
|
-
def _drive_auto(self, initial_task, max_steps=None):
|
|
1868
|
+
def _drive_auto(self, initial_task, max_steps=None, should_stop=None):
|
|
1670
1869
|
"""Run unattended to completion and return the final assistant answer.
|
|
1671
1870
|
|
|
1672
1871
|
Appends ``initial_task`` as a user turn, then keeps stepping until the
|
|
@@ -1695,6 +1894,10 @@ class AgentSession:
|
|
|
1695
1894
|
self.steps_taken = 0
|
|
1696
1895
|
try:
|
|
1697
1896
|
while True:
|
|
1897
|
+
if should_stop is not None and should_stop():
|
|
1898
|
+
self.console.note("Sub-agent task cancelled; stopping.", "warn")
|
|
1899
|
+
self.stop_reason = "cancelled"
|
|
1900
|
+
break
|
|
1698
1901
|
should_continue = self._step()
|
|
1699
1902
|
self._persist()
|
|
1700
1903
|
steps += 1
|
|
@@ -1735,6 +1938,7 @@ class AgentSession:
|
|
|
1735
1938
|
"""
|
|
1736
1939
|
plan_prompt_text = prompts.plan_prompt(self.messages, current_instruction)
|
|
1737
1940
|
plan_text = ""
|
|
1941
|
+
self._begin_activity("generating plan")
|
|
1738
1942
|
try:
|
|
1739
1943
|
self.console.note("Generating a plan for the current goal...", "info")
|
|
1740
1944
|
self.console.start_thinking("planning")
|
|
@@ -1754,8 +1958,8 @@ class AgentSession:
|
|
|
1754
1958
|
server_url=self.server_url,
|
|
1755
1959
|
api_key=self.api_key,
|
|
1756
1960
|
timeout=self.args.llm_timeout,
|
|
1961
|
+
console=self.console,
|
|
1757
1962
|
))
|
|
1758
|
-
self.console.stop_thinking()
|
|
1759
1963
|
|
|
1760
1964
|
self._record_usage(usage)
|
|
1761
1965
|
# The plan prompt is one message holding a flattened copy of the whole
|
|
@@ -1766,14 +1970,16 @@ class AgentSession:
|
|
|
1766
1970
|
plan_text = response or ""
|
|
1767
1971
|
except Exception as exc:
|
|
1768
1972
|
self.console.note(f"Could not generate a plan: {exc}", "warn")
|
|
1973
|
+
finally:
|
|
1974
|
+
self.console.stop_thinking()
|
|
1975
|
+
self._end_activity()
|
|
1769
1976
|
|
|
1770
1977
|
self.plan_manager.write_plan(plan_text)
|
|
1771
1978
|
if plan_text and plan_text.strip():
|
|
1772
1979
|
# Show the plan immediately; otherwise the user only sees it via
|
|
1773
1980
|
# /plan or the file on disk.
|
|
1774
|
-
self.console.
|
|
1775
|
-
|
|
1776
|
-
fg="cyan", dim=True)
|
|
1981
|
+
self.console.plan_box(plan_text.strip().splitlines(),
|
|
1982
|
+
title="Plan for the current goal")
|
|
1777
1983
|
else:
|
|
1778
1984
|
self.console.note("No plan text was generated.", "warn")
|
|
1779
1985
|
if plan_text and plan_text.strip():
|
|
@@ -1791,6 +1997,7 @@ class AgentSession:
|
|
|
1791
1997
|
plan_prompt_text = prompts.plan_review_prompt(
|
|
1792
1998
|
self.messages, self.plan_manager.goal or "")
|
|
1793
1999
|
summary = ""
|
|
2000
|
+
self._begin_activity("reviewing plan")
|
|
1794
2001
|
try:
|
|
1795
2002
|
self.console.note("Reviewing the current plan...", "info")
|
|
1796
2003
|
self.console.start_thinking("reviewing plan")
|
|
@@ -1803,13 +2010,16 @@ class AgentSession:
|
|
|
1803
2010
|
server_url=self.server_url,
|
|
1804
2011
|
api_key=self.api_key,
|
|
1805
2012
|
timeout=self.args.llm_timeout,
|
|
2013
|
+
console=self.console,
|
|
1806
2014
|
))
|
|
1807
|
-
self.console.stop_thinking()
|
|
1808
2015
|
self._record_usage(usage)
|
|
1809
2016
|
self._note_prompt_size(usage, len(self.messages))
|
|
1810
2017
|
summary = response or ""
|
|
1811
2018
|
except Exception as exc:
|
|
1812
2019
|
self.console.note(f"Could not review the plan: {exc}", "warn")
|
|
2020
|
+
finally:
|
|
2021
|
+
self.console.stop_thinking()
|
|
2022
|
+
self._end_activity()
|
|
1813
2023
|
|
|
1814
2024
|
# Persist the review summary to the plan document and re-inject it so
|
|
1815
2025
|
# the model works from the review result.
|
|
@@ -1937,6 +2147,7 @@ class AgentSession:
|
|
|
1937
2147
|
tools=read_tools,
|
|
1938
2148
|
api_key=self.api_key,
|
|
1939
2149
|
timeout=self.args.llm_timeout,
|
|
2150
|
+
console=self.console,
|
|
1940
2151
|
))
|
|
1941
2152
|
except Exception as exc:
|
|
1942
2153
|
self.console.note(
|
|
@@ -1995,6 +2206,7 @@ class AgentSession:
|
|
|
1995
2206
|
server_url=self.server_url,
|
|
1996
2207
|
api_key=self.api_key,
|
|
1997
2208
|
timeout=self.args.llm_timeout,
|
|
2209
|
+
console=self.console,
|
|
1998
2210
|
))
|
|
1999
2211
|
except Exception as exc:
|
|
2000
2212
|
self.console.note(
|
|
@@ -2058,11 +2270,17 @@ class AgentSession:
|
|
|
2058
2270
|
# A loop, not recursion: holding Enter used to recurse once per blank
|
|
2059
2271
|
# line, so a long run of empty input could exhaust the interpreter stack.
|
|
2060
2272
|
while True:
|
|
2061
|
-
self.
|
|
2273
|
+
if not self.tui_active:
|
|
2274
|
+
self.console.short_divider()
|
|
2062
2275
|
|
|
2276
|
+
if self.tui_active:
|
|
2277
|
+
prompt = ""
|
|
2278
|
+
else:
|
|
2279
|
+
prompt = (self.console.style("You › ", bold=True, fg="cyan")
|
|
2280
|
+
if self.tui else
|
|
2281
|
+
self.console.style("You:", bold=True, fg="cyan") + " ")
|
|
2063
2282
|
user_input = self.console.read_line(
|
|
2064
|
-
|
|
2065
|
-
multiline=True)
|
|
2283
|
+
prompt, multiline=True, tui=self.tui)
|
|
2066
2284
|
|
|
2067
2285
|
# EOF / Ctrl-C at the prompt: the caller treats None as "quit", so it
|
|
2068
2286
|
# must not be dereferenced here (a piped or closed stdin would
|
|
@@ -2088,6 +2306,10 @@ class AgentSession:
|
|
|
2088
2306
|
(plan mode only)
|
|
2089
2307
|
/context show how the context window is used, by category
|
|
2090
2308
|
(tokens and percentages)
|
|
2309
|
+
/background [id] show what the loop is doing and the background
|
|
2310
|
+
tasks (or the output of one task)
|
|
2311
|
+
/expand [n] show the full detail of the nth most recent tool
|
|
2312
|
+
call (default: the last one)
|
|
2091
2313
|
/skip-plan <text> send <text> without generating or reviewing a plan
|
|
2092
2314
|
/clear clear the screen (keeps the conversation)
|
|
2093
2315
|
/help show the command help
|
|
@@ -2112,7 +2334,7 @@ class AgentSession:
|
|
|
2112
2334
|
self._do_reset(arg)
|
|
2113
2335
|
return True
|
|
2114
2336
|
if cmd == "help":
|
|
2115
|
-
print_help(self.args)
|
|
2337
|
+
print_help(self.args, console=self.console)
|
|
2116
2338
|
return True
|
|
2117
2339
|
if cmd in self.CLEAR_COMMANDS:
|
|
2118
2340
|
self._clear_and_show_last()
|
|
@@ -2123,6 +2345,12 @@ class AgentSession:
|
|
|
2123
2345
|
if cmd == "context":
|
|
2124
2346
|
self._show_context()
|
|
2125
2347
|
return True
|
|
2348
|
+
if cmd in ("background", "bg", "tasks"):
|
|
2349
|
+
self._show_background(arg)
|
|
2350
|
+
return True
|
|
2351
|
+
if cmd in ("expand", "tool"):
|
|
2352
|
+
self.console.expand_tool(arg or 1)
|
|
2353
|
+
return True
|
|
2126
2354
|
if cmd in ("skip-plan", "skip_plan", "skipplan"):
|
|
2127
2355
|
self._run_skipped_plan(arg)
|
|
2128
2356
|
return True
|
|
@@ -2265,14 +2493,81 @@ class AgentSession:
|
|
|
2265
2493
|
self.console.status_box(lines, title="Context usage",
|
|
2266
2494
|
fg="green", dim=True)
|
|
2267
2495
|
|
|
2496
|
+
def _show_background(self, arg=""):
|
|
2497
|
+
"""Show background tasks and the foreground activity (``/background``).
|
|
2498
|
+
|
|
2499
|
+
``/background`` renders a table of tasks; ``/background bg-1`` renders
|
|
2500
|
+
that task's state and output tail. The foreground line is the loop's
|
|
2501
|
+
last/current blocking step (LLM call, tool, plan, ...). Because the
|
|
2502
|
+
loop is synchronous this is read between steps, but it tells the user
|
|
2503
|
+
what the LLM was waiting on for the last operation.
|
|
2504
|
+
"""
|
|
2505
|
+
requested = (arg or "").strip()
|
|
2506
|
+
self.console.rule(title="Background", char="═", fg="cyan")
|
|
2507
|
+
if requested:
|
|
2508
|
+
snapshot = self.background_tasks.get(requested)
|
|
2509
|
+
if snapshot is None:
|
|
2510
|
+
self.console.note(
|
|
2511
|
+
f"No background task {requested!r}. Use /background to list them.",
|
|
2512
|
+
"warn")
|
|
2513
|
+
return
|
|
2514
|
+
snapshot = snapshot.snapshot()
|
|
2515
|
+
lines = [
|
|
2516
|
+
f"id : {snapshot['id']}",
|
|
2517
|
+
f"kind : {snapshot['kind']}",
|
|
2518
|
+
f"status : {snapshot['status']}",
|
|
2519
|
+
f"age : {snapshot['age_seconds']:.1f}s",
|
|
2520
|
+
f"label : {oneline(snapshot['label'], 100)}",
|
|
2521
|
+
f"pid : {snapshot['pid'] if snapshot['pid'] is not None else '-'}",
|
|
2522
|
+
f"exit code: {snapshot['exit_code'] if snapshot['exit_code'] is not None else '-'}",
|
|
2523
|
+
f"log file : {snapshot['log_path']}",
|
|
2524
|
+
]
|
|
2525
|
+
if snapshot.get("result"):
|
|
2526
|
+
lines += ["", "result:", oneline(snapshot["result"], 400)]
|
|
2527
|
+
if snapshot.get("error"):
|
|
2528
|
+
lines += ["", "error:", oneline(snapshot["error"], 400)]
|
|
2529
|
+
output = self.background_tasks.tail(requested, 60)
|
|
2530
|
+
if output:
|
|
2531
|
+
lines += ["", "output (tail):"]
|
|
2532
|
+
lines.extend(output.rstrip().splitlines())
|
|
2533
|
+
self.console.status_box(
|
|
2534
|
+
lines, title=f"Background task {snapshot['id']}",
|
|
2535
|
+
fg="cyan", dim=True)
|
|
2536
|
+
return
|
|
2537
|
+
|
|
2538
|
+
lines = [f"Foreground : {self._activity_summary()}", ""]
|
|
2539
|
+
snapshots = self.background_tasks.list()
|
|
2540
|
+
if not snapshots:
|
|
2541
|
+
lines.append("Background : none")
|
|
2542
|
+
else:
|
|
2543
|
+
running = sum(1 for item in snapshots
|
|
2544
|
+
if item["status"] in ("running", "cancelling"))
|
|
2545
|
+
lines.append(f"Background : {running} running, {len(snapshots)} total")
|
|
2546
|
+
lines.append(
|
|
2547
|
+
f" {'id':<6} {'state':<10} {'age':>7} {'kind':<8} label")
|
|
2548
|
+
for item in snapshots:
|
|
2549
|
+
lines.append(
|
|
2550
|
+
f" {item['id']:<6} {item['status']:<10} "
|
|
2551
|
+
f"{item['age_seconds']:>6.1f}s {item['kind']:<8} "
|
|
2552
|
+
f"{oneline(item['label'], 48)}")
|
|
2553
|
+
lines.append("")
|
|
2554
|
+
lines.append("Use /background <id> for the output tail.")
|
|
2555
|
+
self.console.status_box(lines, title="Background tasks",
|
|
2556
|
+
fg="cyan", dim=True)
|
|
2557
|
+
|
|
2268
2558
|
def _clear_and_show_last(self):
|
|
2269
|
-
"""Handle /clear:
|
|
2559
|
+
"""Handle /clear: dismiss transient output and re-orient the view.
|
|
2270
2560
|
|
|
2271
|
-
The conversation itself is unchanged
|
|
2272
|
-
|
|
2273
|
-
|
|
2561
|
+
The conversation itself is unchanged. In the fixed TUI this behaves
|
|
2562
|
+
like Escape in command mode: it closes command output, returns a
|
|
2563
|
+
scrolled view to the bottom, and drops info/warning notices, while the
|
|
2564
|
+
core conversation stays on screen. The scrolling console clears the
|
|
2565
|
+
terminal and re-prints the last turn instead.
|
|
2274
2566
|
"""
|
|
2275
2567
|
self.console.clear_screen()
|
|
2568
|
+
if self.tui_active:
|
|
2569
|
+
# The TUI keeps the conversation visible; do not re-print it.
|
|
2570
|
+
return
|
|
2276
2571
|
last_role = last_text = None
|
|
2277
2572
|
for m in reversed(self.messages):
|
|
2278
2573
|
role = m.get("role")
|
|
@@ -2298,7 +2593,12 @@ class AgentSession:
|
|
|
2298
2593
|
|
|
2299
2594
|
try:
|
|
2300
2595
|
for call in tool_calls:
|
|
2301
|
-
|
|
2596
|
+
name = ((call or {}).get("function") or {}).get("name", "?")
|
|
2597
|
+
self._begin_activity(f"running tool {name}")
|
|
2598
|
+
try:
|
|
2599
|
+
self._run_one_tool_call(call)
|
|
2600
|
+
finally:
|
|
2601
|
+
self._end_activity()
|
|
2302
2602
|
finally:
|
|
2303
2603
|
self.console.stop_tool_call()
|
|
2304
2604
|
|
|
@@ -2361,6 +2661,27 @@ class AgentSession:
|
|
|
2361
2661
|
return
|
|
2362
2662
|
|
|
2363
2663
|
# 2) Shell-safety classifier (DENY / ASK / ALLOW), always enforced.
|
|
2664
|
+
background_action = (str(tool_params.get("action", "")).lower()
|
|
2665
|
+
if name == "background" else "")
|
|
2666
|
+
background_kind = (str(tool_params.get("kind", background_mod.SHELL)).lower()
|
|
2667
|
+
if name == "background" else background_mod.SHELL)
|
|
2668
|
+
background_shell = (name == "background"
|
|
2669
|
+
and background_action == "start"
|
|
2670
|
+
and background_kind == background_mod.SHELL)
|
|
2671
|
+
background_subagent = (name == "background"
|
|
2672
|
+
and background_action == "start"
|
|
2673
|
+
and background_kind == background_mod.SUBAGENT)
|
|
2674
|
+
if background_subagent and not self.enable_subagents:
|
|
2675
|
+
self.console.note("Background sub-agent requested but sub-agents are disabled.", "error")
|
|
2676
|
+
self._append_tool_result(call_id,
|
|
2677
|
+
"Error: sub-agents are not enabled in this session.")
|
|
2678
|
+
return
|
|
2679
|
+
if background_shell and not shell_execution_enabled(self.args):
|
|
2680
|
+
self.console.note("Background shell requested but shell execution is disabled.", "error")
|
|
2681
|
+
self._append_tool_result(call_id,
|
|
2682
|
+
"Error: shell execution is disabled in this session.")
|
|
2683
|
+
return
|
|
2684
|
+
|
|
2364
2685
|
shell_cmd = None
|
|
2365
2686
|
if name == "run_shell_command":
|
|
2366
2687
|
shell_cmd = str(tool_params.get("command", ""))
|
|
@@ -2370,6 +2691,14 @@ class AgentSession:
|
|
|
2370
2691
|
self._append_tool_result(call_id,
|
|
2371
2692
|
f"Command refused for safety reasons ({reason}): {shell_cmd!r}. Please choose a safer command.")
|
|
2372
2693
|
return
|
|
2694
|
+
elif background_shell:
|
|
2695
|
+
shell_cmd = str(tool_params.get("command", ""))
|
|
2696
|
+
tier, reason = shell_safety_utils.classify_command(shell_cmd)
|
|
2697
|
+
if shell_safety_utils.is_deny(tier):
|
|
2698
|
+
self.console.note(f"Refusing to run dangerous command: {shell_cmd!r} ({reason})", "error")
|
|
2699
|
+
self._append_tool_result(call_id,
|
|
2700
|
+
f"Command refused for safety reasons ({reason}): {shell_cmd!r}. Please choose a safer command.")
|
|
2701
|
+
return
|
|
2373
2702
|
else:
|
|
2374
2703
|
tier = reason = None
|
|
2375
2704
|
|
|
@@ -2406,6 +2735,17 @@ class AgentSession:
|
|
|
2406
2735
|
self.console.tool_call_display(name, tool_params, result, transient=transient)
|
|
2407
2736
|
self._append_tool_result(call_id, str(result))
|
|
2408
2737
|
|
|
2738
|
+
def _run_background_subagent(self, name, task, max_steps, should_stop):
|
|
2739
|
+
"""Worker for a background sub-agent task (called from its thread)."""
|
|
2740
|
+
subagent = self.subagents_registry.get(name)
|
|
2741
|
+
if subagent is None:
|
|
2742
|
+
return f"Error: unknown sub-agent {name!r}."
|
|
2743
|
+
try:
|
|
2744
|
+
return subagent.run(task, parent=self, max_steps=max_steps,
|
|
2745
|
+
should_stop=should_stop)
|
|
2746
|
+
except Exception as e: # noqa: BLE001 - reported as the task result
|
|
2747
|
+
return f"Error: sub-agent {name!r} failed: {e}"
|
|
2748
|
+
|
|
2409
2749
|
def _run_subagent(self, name, tool_params):
|
|
2410
2750
|
"""Run a sub-agent for ``task`` and return the text to feed back."""
|
|
2411
2751
|
subagent = self.subagents_registry[name]
|
|
@@ -2486,12 +2826,19 @@ class AgentSession:
|
|
|
2486
2826
|
def shutdown(self, farewell=True):
|
|
2487
2827
|
"""Persist and print a final summary (called on quit / exit).
|
|
2488
2828
|
|
|
2489
|
-
``farewell=False`` is used by the
|
|
2490
|
-
which
|
|
2829
|
+
``farewell=False`` is used by the fatal-exception path in :meth:`run`,
|
|
2830
|
+
which has already told the user (in red) that the session is being torn
|
|
2491
2831
|
down: a cheerful "thanks and here is your state" box on top of a crash is
|
|
2492
2832
|
the wrong note, and the state it would recap is the state that just
|
|
2493
|
-
failed.
|
|
2833
|
+
failed. A user cancellation is different -- it is a normal end -- so the
|
|
2834
|
+
interrupt path still prints the farewell box.
|
|
2494
2835
|
"""
|
|
2836
|
+
if self.tui_active:
|
|
2837
|
+
self.console.stop_tui()
|
|
2838
|
+
background_cancelled = len(self.background_tasks.running())
|
|
2839
|
+
self.background_tasks.shutdown()
|
|
2840
|
+
self._exit_background = max(
|
|
2841
|
+
getattr(self, "_exit_background", 0), background_cancelled)
|
|
2495
2842
|
self._persist()
|
|
2496
2843
|
segments = history_segment_indices(self.session_dir)
|
|
2497
2844
|
# List what is really on disk. The old message claimed
|
|
@@ -2550,17 +2897,29 @@ class AgentSession:
|
|
|
2550
2897
|
except (TypeError, ValueError):
|
|
2551
2898
|
return 0
|
|
2552
2899
|
|
|
2900
|
+
elapsed = max(time.monotonic() - getattr(self, "started_at",
|
|
2901
|
+
time.monotonic()), 0.0)
|
|
2902
|
+
hours, remainder = divmod(int(elapsed), 3600)
|
|
2903
|
+
minutes, seconds = divmod(remainder, 60)
|
|
2904
|
+
duration = (f"{hours}h {minutes:02d}m" if hours
|
|
2905
|
+
else f"{minutes}m {seconds:02d}s")
|
|
2906
|
+
cancelled = getattr(self, "_exit_background", 0)
|
|
2553
2907
|
rows = [
|
|
2554
2908
|
("session id", self.unique_id),
|
|
2909
|
+
("model", self.model or "(auto)"),
|
|
2555
2910
|
("saved under", f"{self.cache_dir}/{self.unique_id}/"),
|
|
2556
2911
|
("history", f"{where} (segment {self.history_index}), "
|
|
2557
2912
|
f"{plural(len(self.messages), 'message')}"),
|
|
2558
2913
|
("conversation", plural(turns, "recorded turn")),
|
|
2914
|
+
("duration", duration),
|
|
2559
2915
|
("tokens", f"{count('prompt_tokens'):,} in / "
|
|
2560
2916
|
f"{count('completion_tokens'):,} out "
|
|
2561
2917
|
f"({count('total_tokens'):,} total)"),
|
|
2562
2918
|
("calls", f"{count('llm_calls'):,} LLM, "
|
|
2563
2919
|
f"{count('tool_calls'):,} tool"),
|
|
2920
|
+
("background", (f"{plural(cancelled, 'task')} cancelled on exit"
|
|
2921
|
+
if cancelled else "none running")),
|
|
2922
|
+
("resume", "mini-code --load-last-session"),
|
|
2564
2923
|
]
|
|
2565
2924
|
self.console.farewell(version, rows)
|
|
2566
2925
|
|
|
@@ -2644,18 +3003,25 @@ class AgentSession:
|
|
|
2644
3003
|
# many messages the reported prompt_tokens describe.
|
|
2645
3004
|
sent_message_count = len(self.messages)
|
|
2646
3005
|
self.console.start_thinking()
|
|
2647
|
-
|
|
2648
|
-
|
|
2649
|
-
|
|
2650
|
-
|
|
2651
|
-
|
|
2652
|
-
|
|
2653
|
-
|
|
2654
|
-
|
|
2655
|
-
|
|
2656
|
-
|
|
2657
|
-
|
|
2658
|
-
|
|
3006
|
+
self._begin_activity(
|
|
3007
|
+
f"waiting for LLM response ({self.model or 'model'})")
|
|
3008
|
+
try:
|
|
3009
|
+
response_text, tool_calls, usage, reasoning_content = \
|
|
3010
|
+
utils.unpack_llm_result(
|
|
3011
|
+
utils.call_openai_server(
|
|
3012
|
+
self.messages,
|
|
3013
|
+
max_tokens=self.args.max_tokens,
|
|
3014
|
+
temperature=self.args.temperature,
|
|
3015
|
+
model=self.model,
|
|
3016
|
+
server_url=self.server_url,
|
|
3017
|
+
tools=self.llm_tools,
|
|
3018
|
+
api_key=self.api_key,
|
|
3019
|
+
timeout=self.args.llm_timeout,
|
|
3020
|
+
console=self.console,
|
|
3021
|
+
))
|
|
3022
|
+
finally:
|
|
3023
|
+
self.console.stop_thinking()
|
|
3024
|
+
self._end_activity()
|
|
2659
3025
|
|
|
2660
3026
|
# A failed LLM call returns (None, None, None, None): treat it as "nothing
|
|
2661
3027
|
# happened this step" so the loop degrades gracefully (records a note
|