mini-code-cli 0.2.1.1__py3-none-any.whl → 0.3.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 +1290 -152
- mini_code_cli/compaction.py +53 -0
- mini_code_cli/config.py +21 -1
- mini_code_cli/media.py +194 -0
- mini_code_cli/persistence.py +6 -7
- mini_code_cli/planning.py +70 -9
- mini_code_cli/prompts.py +172 -10
- mini_code_cli/recovery.py +157 -0
- mini_code_cli/runner.py +1 -1
- mini_code_cli/settings.py +918 -0
- mini_code_cli/shell_safety_utils.py +0 -4
- mini_code_cli/skills.py +0 -20
- mini_code_cli/subagents/base.py +0 -1
- mini_code_cli/todos.py +202 -0
- mini_code_cli/tokens.py +6 -1
- mini_code_cli/tools.py +258 -47
- mini_code_cli/tui.py +682 -76
- mini_code_cli/ui.py +148 -44
- mini_code_cli/utils.py +148 -25
- {mini_code_cli-0.2.1.1.dist-info → mini_code_cli-0.3.0.0.dist-info}/METADATA +210 -20
- mini_code_cli-0.3.0.0.dist-info/RECORD +34 -0
- mini_code_cli-0.2.1.1.dist-info/RECORD +0 -30
- {mini_code_cli-0.2.1.1.dist-info → mini_code_cli-0.3.0.0.dist-info}/WHEEL +0 -0
- {mini_code_cli-0.2.1.1.dist-info → mini_code_cli-0.3.0.0.dist-info}/entry_points.txt +0 -0
- {mini_code_cli-0.2.1.1.dist-info → mini_code_cli-0.3.0.0.dist-info}/licenses/LICENSE +0 -0
- {mini_code_cli-0.2.1.1.dist-info → mini_code_cli-0.3.0.0.dist-info}/top_level.txt +0 -0
mini_code_cli/agent_loop.py
CHANGED
|
@@ -25,6 +25,7 @@ without the tests reaching into every module.
|
|
|
25
25
|
|
|
26
26
|
import os
|
|
27
27
|
import json
|
|
28
|
+
import re
|
|
28
29
|
import time
|
|
29
30
|
import argparse
|
|
30
31
|
|
|
@@ -33,16 +34,20 @@ from . import prompts
|
|
|
33
34
|
from . import shell_safety_utils
|
|
34
35
|
from . import tools
|
|
35
36
|
from . import utils
|
|
36
|
-
from .utils import oneline, plural
|
|
37
|
+
from .utils import oneline, plural, usage_int
|
|
37
38
|
from . import ui
|
|
38
39
|
from . import tui as tui_mod
|
|
39
40
|
from . import subagents
|
|
40
41
|
from . import skills
|
|
41
42
|
from . import agent_files
|
|
42
43
|
from . import compaction as compaction_mod
|
|
44
|
+
from . import media
|
|
43
45
|
from . import planning
|
|
46
|
+
from . import recovery
|
|
44
47
|
from . import plan as plan_utils
|
|
48
|
+
from . import settings as settings_mod
|
|
45
49
|
from . import tokens as tokens_mod
|
|
50
|
+
from . import todos as todos_mod
|
|
46
51
|
from .config import (
|
|
47
52
|
DEFAULT_CACHE_LOCATION,
|
|
48
53
|
DEFAULT_MODEL_URL,
|
|
@@ -50,6 +55,7 @@ from .config import (
|
|
|
50
55
|
DEFAULT_TOOL_TIMEOUT,
|
|
51
56
|
DEFAULT_HTTP_TIMEOUT,
|
|
52
57
|
compaction_budget,
|
|
58
|
+
default_max_output_tokens,
|
|
53
59
|
)
|
|
54
60
|
from .persistence import (
|
|
55
61
|
save_history,
|
|
@@ -134,13 +140,14 @@ def parse_args():
|
|
|
134
140
|
description="Agent loop for interacting with a language model")
|
|
135
141
|
# MODEL / LLM related
|
|
136
142
|
parser.add_argument("--url", type=str, default=f"{DEFAULT_MODEL_URL}", help=f"API host, default={DEFAULT_MODEL_URL}")
|
|
137
|
-
parser.add_argument("--max-tokens", type=int, help="Maximum tokens for a single LLM response (the reply budget),
|
|
143
|
+
parser.add_argument("--max-tokens", type=int, default=None, help="Maximum tokens for a single LLM response (the reply budget). Unset (default): 32768 for a large-context model, clamped to half the model's context window. It is also used as the output headroom reserved when deriving the compaction limit from the model's context window.")
|
|
138
144
|
parser.add_argument("--temperature", type=float, default=DEFAULT_TEMPERATURE, help=f"Temperature for LLM, default={DEFAULT_TEMPERATURE}")
|
|
139
145
|
parser.add_argument("--model", type=str, help="Model name, default=None")
|
|
140
146
|
parser.add_argument("--api-key", type=str, default=None, help="API key for authentication. If not set, it tries to find it in env variable: MINI_CODE_API_KEY.")
|
|
141
147
|
|
|
142
148
|
# Other settings:
|
|
143
149
|
parser.add_argument("--cache-dir", type=str, help=f"The cache dir for the session histories. default={DEFAULT_CACHE_LOCATION}")
|
|
150
|
+
parser.add_argument("--no-settings", action="store_true", help="Do not load, prompt for, or save session settings. Useful for CI and benchmark runs.")
|
|
144
151
|
parser.add_argument("--restore-session", type=str, help="A previous session to continue: its directory (e.g. ~/.cache/mini/sessions/1792028090823027-a9d77653/) or a bare session id under --cache-dir. A session folder must hold a summary_history.json recorder plus the history_{n}.json segment it names; anything else starts a fresh session.")
|
|
145
152
|
parser.add_argument("-l","--load-last-session", action="store_true", help="Continue the most recent previous session recorded in the --allowed-dir .mini pointer, in place and without the resume prompt, instead of starting fresh. --restore-session takes precedence if also given.")
|
|
146
153
|
|
|
@@ -165,8 +172,18 @@ def parse_args():
|
|
|
165
172
|
help="How to compact history. summarise: summary only (default). predict-files: summary + re-read the files the model predicts it needs. predict-messages: summary + the original messages the model predicts are worth keeping.")
|
|
166
173
|
parser.add_argument("-p","--plan", action="store_true", help="Enable plan mode: the agent keeps a CURRENT_PLAN.md (its step-by-step plan, marked finished when the goal is done) and CURRENT_GOAL.md (the user's latest instruction) in the session directory. Also changes how history compaction works.")
|
|
167
174
|
parser.add_argument("--plan-strategy", choices=planning.PLAN_STRATEGIES, default=None,
|
|
168
|
-
help="Planning strategy (implies --plan when given). plan-
|
|
175
|
+
help="Planning strategy (implies --plan when given). plan-verify2 (default): author a plan, verify with a machine-readable DONE/INCOMPLETE verdict and skip the final step on DONE. plan-verify: author a plan, review it, and keep the final step only when it calls a tool. plan-verify-step: same as plan-verify, but always run and keep one final step. open-plan: the agent maintains its own plan document in --allowed-dir/.mini and the loop does not author or review it.")
|
|
176
|
+
parser.add_argument("--strict-verify", action="store_true",
|
|
177
|
+
help="Use the evidence-based strict verification prompt for every planning verify/review stage (plan-verify, plan-verify2, plan-verify-step) and also verify after open-plan work settles. Unproven requirements count as unfinished.")
|
|
178
|
+
parser.add_argument("--runtime-strategy", choices=recovery.RUNTIME_STRATEGIES,
|
|
179
|
+
default=recovery.DEFAULT_RUNTIME_STRATEGY,
|
|
180
|
+
help="Runtime recovery strategy. normal (default): no automatic prompts. prompt-change: after 3 consecutive failures of the same call or tool, prompt the model to rethink its approach. prompt-change-plan: also start a fresh plan for the current goal.")
|
|
181
|
+
parser.add_argument("--allow-nudge", action="store_true",
|
|
182
|
+
help="Plan mode only: when the model replies without a tool call, ask it to continue (or reply DONE) before running the plan review. Works with every --plan-strategy.")
|
|
183
|
+
parser.add_argument("--nudge-limit", type=int, default=1,
|
|
184
|
+
help="Maximum continuation nudges per text-only stop with --allow-nudge. default=1")
|
|
169
185
|
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.")
|
|
186
|
+
parser.add_argument("--dynamic-todo-tracking", action="store_true", help="Give the agent a structured, session-local todo list (todo_write/todo_update/todo_list) and a /todo view. Works independently of plan mode and the scratchpad.")
|
|
170
187
|
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
188
|
parser.add_argument("--tui", nargs="?", const="on", default="auto",
|
|
172
189
|
choices=("auto", "on", "off"),
|
|
@@ -174,6 +191,8 @@ def parse_args():
|
|
|
174
191
|
|
|
175
192
|
parser.add_argument("--all", action="store_true", help="Enable: --plan, --enable-subagents, --enable-shell, --skills, --auto-mode, --sudo, --background")
|
|
176
193
|
parser.add_argument("--all-last", action="store_true", help="Enable: --plan, --enable-subagents, --enable-shell, --skills, --auto-mode, --sudo, --background, --load-last-session")
|
|
194
|
+
parser.add_argument("--super", action="store_true",
|
|
195
|
+
help="The kitchen-sink behaviour preset: --plan with plan-verify2 and strict verification, --enable-shell/--enable-subagents/--skills/--sudo/--background, --auto-mode, --runtime-strategy prompt-change, --dynamic-todo-tracking, and the default nudge/compaction/timeouts/verbose/scratchpad values. It leaves the model, URL and API key untouched.")
|
|
177
196
|
|
|
178
197
|
# Output verbosity
|
|
179
198
|
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.")
|
|
@@ -192,10 +211,20 @@ def parse_args():
|
|
|
192
211
|
if args.all_last:
|
|
193
212
|
args.load_last_session = True
|
|
194
213
|
|
|
214
|
+
if args.super:
|
|
215
|
+
# A behaviour preset: the model, URL and API key stay exactly as
|
|
216
|
+
# configured on the command line/environment.
|
|
217
|
+
for attr, value in settings_mod.SUPER_PRESET.items():
|
|
218
|
+
setattr(args, attr, value)
|
|
219
|
+
|
|
195
220
|
# A planning strategy is only meaningful in plan mode, so asking for one
|
|
196
221
|
# implies the flag (the banner and help then agree with the session).
|
|
197
222
|
if getattr(args, "plan_strategy", None):
|
|
198
223
|
args.plan = True
|
|
224
|
+
# Strict verification only runs in plan mode; enabling it alone should not
|
|
225
|
+
# silently do nothing.
|
|
226
|
+
if getattr(args, "strict_verify", False):
|
|
227
|
+
args.plan = True
|
|
199
228
|
|
|
200
229
|
return args
|
|
201
230
|
|
|
@@ -220,8 +249,11 @@ def print_help(args, console=None):
|
|
|
220
249
|
("/history <n>", "show the full messages recorded for turn n"),
|
|
221
250
|
("/history last", "...for the most recent turn"),
|
|
222
251
|
("/plan", "show the current goal + plan (plan mode only)"),
|
|
252
|
+
("/todo", "show the dynamic todo list (/todo clear empties it)"),
|
|
253
|
+
("/image <path>", "stage an image for the next message (/image clear)"),
|
|
223
254
|
("/context", "show how the context window is used (tokens + percentages)"),
|
|
224
255
|
("/background [id]", "show foreground activity + background tasks (or one task's output)"),
|
|
256
|
+
("/settings", "show/change session settings (number or name)"),
|
|
225
257
|
("/expand [n]", "show the full detail of the nth most recent tool call"),
|
|
226
258
|
("/skip-plan <prompt>", "send a prompt without generating/reviewing a plan"),
|
|
227
259
|
("/reset [<n>|last]", "rewind to the end of turn n (drops everything after it);"),
|
|
@@ -314,16 +346,21 @@ def _compaction_trigger(messages, token_limit, reserved_output_tokens, current_t
|
|
|
314
346
|
return False, ""
|
|
315
347
|
|
|
316
348
|
|
|
317
|
-
#: Prefixes of user messages the *loop* injects (plan authoring and
|
|
318
|
-
#:
|
|
319
|
-
#: in-flight-tail scan must skip them when it looks for the turn to carry
|
|
320
|
-
#: a compaction -- otherwise, right after a plan is generated, the plan
|
|
321
|
-
#: would be treated as the user's request and the real instruction
|
|
322
|
-
#: away. The matching injection points are in
|
|
323
|
-
#: ``_review_plan_completion
|
|
349
|
+
#: Prefixes of user messages the *loop* injects (plan authoring, review and
|
|
350
|
+
#: verification). They are loop bookkeeping, not instructions from the user, so
|
|
351
|
+
#: the in-flight-tail scan must skip them when it looks for the turn to carry
|
|
352
|
+
#: across a compaction -- otherwise, right after a plan is generated, the plan
|
|
353
|
+
#: text would be treated as the user's request and the real instruction
|
|
354
|
+
#: summarised away. The matching injection points are in
|
|
355
|
+
#: ``_generate_plan_and_inject``, ``_review_plan_completion`` and the
|
|
356
|
+
#: ``plan-verify2`` branch of ``_run_turn``.
|
|
324
357
|
_LOOP_INJECTED_USER_PREFIXES = (
|
|
325
358
|
"Current plan for the goal (from CURRENT_PLAN.md):",
|
|
359
|
+
"Recovery plan for the goal:",
|
|
326
360
|
"Plan completion summary (from CURRENT_PLAN.md):",
|
|
361
|
+
"Plan verification (from CURRENT_PLAN.md):",
|
|
362
|
+
"Plan verification (open-plan):",
|
|
363
|
+
"Image read from the task:",
|
|
327
364
|
)
|
|
328
365
|
|
|
329
366
|
|
|
@@ -331,7 +368,7 @@ def _is_loop_injected(message):
|
|
|
331
368
|
"""Whether ``message`` is a user turn this loop injected, not the user's own."""
|
|
332
369
|
if not isinstance(message, dict) or message.get("role") != "user":
|
|
333
370
|
return False
|
|
334
|
-
content = message.get("content") or ""
|
|
371
|
+
content = media.content_text(message.get("content") or "")
|
|
335
372
|
return str(content).lstrip().startswith(_LOOP_INJECTED_USER_PREFIXES)
|
|
336
373
|
|
|
337
374
|
|
|
@@ -369,6 +406,15 @@ def _in_flight_tail(messages):
|
|
|
369
406
|
return []
|
|
370
407
|
|
|
371
408
|
|
|
409
|
+
#: Cap the transcript portion of the summariser prompt. A summary request that
|
|
410
|
+
#: repeats the whole over-long history can hit the model's hard context limit
|
|
411
|
+
#: itself (observed at ~261k input tokens), leaving every later request stuck.
|
|
412
|
+
MAX_SUMMARY_PROMPT_TOKENS = 50_000
|
|
413
|
+
|
|
414
|
+
#: Headroom for the summary template, the reply, and token-estimate error.
|
|
415
|
+
SUMMARY_PROMPT_HEADROOM_TOKENS = 4_096
|
|
416
|
+
|
|
417
|
+
|
|
372
418
|
def maybe_compact(messages, server_url, model, api_key, llm_timeout, token_stats,
|
|
373
419
|
history_index=0, token_limit=None, reserved_output_tokens=0,
|
|
374
420
|
current_tokens=None, plan_hook=None, console=None, preserve=(),
|
|
@@ -447,51 +493,64 @@ def maybe_compact(messages, server_url, model, api_key, llm_timeout, token_stats
|
|
|
447
493
|
console.note(
|
|
448
494
|
f"Compacting the conversation: {plural(len(messages), 'message')} "
|
|
449
495
|
f"-> a summary ({reason}).{kept_note}", "warn")
|
|
450
|
-
|
|
451
|
-
|
|
452
|
-
|
|
453
|
-
|
|
454
|
-
|
|
455
|
-
|
|
456
|
-
|
|
457
|
-
|
|
458
|
-
|
|
496
|
+
summary_budget = min(
|
|
497
|
+
int(token_limit or MAX_SUMMARY_PROMPT_TOKENS),
|
|
498
|
+
MAX_SUMMARY_PROMPT_TOKENS)
|
|
499
|
+
summary_budget = max(
|
|
500
|
+
4_096,
|
|
501
|
+
summary_budget - int(reserved_output_tokens or 0)
|
|
502
|
+
- SUMMARY_PROMPT_HEADROOM_TOKENS)
|
|
503
|
+
try:
|
|
504
|
+
summary_prompt = prompts.compaction_prompt(
|
|
505
|
+
messages, max_tokens=summary_budget)
|
|
506
|
+
except Exception as exc:
|
|
507
|
+
summary_prompt = ""
|
|
508
|
+
console.note(
|
|
509
|
+
f"Could not build the summary prompt: {exc}. Using the "
|
|
510
|
+
f"mechanical fallback summary.", "warn")
|
|
511
|
+
|
|
512
|
+
# The summariser sometimes answers with nothing at all, or the request
|
|
513
|
+
# itself fails (network, a context-length 400). An empty/failed summary
|
|
514
|
+
# must never be mistaken for a successful compaction, but keeping the
|
|
515
|
+
# over-long transcript leaves every subsequent request over budget. So
|
|
516
|
+
# retry once, then fall back to a deterministic mechanical summary and
|
|
517
|
+
# still roll the segment over: compaction is the only thing that can
|
|
518
|
+
# recover an already-overflowing history.
|
|
459
519
|
summary = ""
|
|
460
|
-
|
|
461
|
-
|
|
462
|
-
|
|
463
|
-
|
|
464
|
-
|
|
465
|
-
|
|
466
|
-
|
|
467
|
-
|
|
468
|
-
|
|
469
|
-
|
|
470
|
-
|
|
471
|
-
|
|
472
|
-
|
|
473
|
-
|
|
474
|
-
|
|
475
|
-
|
|
520
|
+
if summary_prompt:
|
|
521
|
+
for attempt in (1, 2):
|
|
522
|
+
compact_usage = None
|
|
523
|
+
console.start_thinking("compacting history")
|
|
524
|
+
try:
|
|
525
|
+
reply, _, compact_usage, _ = utils.unpack_llm_result(
|
|
526
|
+
utils.call_openai_server(
|
|
527
|
+
[{"role": "user", "content": summary_prompt}],
|
|
528
|
+
max_tokens=1024,
|
|
529
|
+
temperature=0.0,
|
|
530
|
+
model=model,
|
|
531
|
+
server_url=server_url,
|
|
532
|
+
api_key=api_key,
|
|
533
|
+
timeout=llm_timeout,
|
|
534
|
+
console=console,
|
|
535
|
+
))
|
|
536
|
+
except Exception as exc:
|
|
537
|
+
console.note(f"Summariser call failed: {exc}", "warn")
|
|
538
|
+
reply = ""
|
|
539
|
+
finally:
|
|
540
|
+
console.stop_thinking()
|
|
476
541
|
|
|
477
|
-
|
|
478
|
-
|
|
479
|
-
|
|
480
|
-
|
|
481
|
-
|
|
482
|
-
|
|
542
|
+
accumulate_usage(token_stats, compact_usage)
|
|
543
|
+
summary = (reply or "").strip()
|
|
544
|
+
if summary:
|
|
545
|
+
break
|
|
546
|
+
if attempt == 1:
|
|
547
|
+
console.note("The summariser returned an empty summary; retrying once.", "warn")
|
|
483
548
|
|
|
484
549
|
if not summary:
|
|
485
|
-
|
|
486
|
-
# segment did not move -- only the shrink did, so the next request
|
|
487
|
-
# may still be too large.
|
|
550
|
+
summary = compaction_mod.fallback_summary(messages)
|
|
488
551
|
console.note(
|
|
489
|
-
|
|
490
|
-
|
|
491
|
-
f"and history_{history_index}.json as they are -- nothing was "
|
|
492
|
-
f"lost, but the next request may still be too large "
|
|
493
|
-
f"({reason}).", "warn")
|
|
494
|
-
return messages, False, history_index
|
|
552
|
+
"The summariser did not return usable text; using a mechanical "
|
|
553
|
+
"fallback summary so the history still shrinks.", "warn")
|
|
495
554
|
|
|
496
555
|
system_content = messages[0]["content"] if messages and messages[0].get("role") == "system" else ""
|
|
497
556
|
compacted = []
|
|
@@ -582,6 +641,75 @@ def maybe_compact(messages, server_url, model, api_key, llm_timeout, token_stats
|
|
|
582
641
|
# the agent session
|
|
583
642
|
# ---------------------------------------------------------------------------
|
|
584
643
|
|
|
644
|
+
#: How many times a truncated (``finish_reason == "length"``) reply may be
|
|
645
|
+
#: nudged to continue before the session gives up. Bounded on purpose: a model
|
|
646
|
+
#: that only ever rambles must still terminate.
|
|
647
|
+
TRUNCATED_RETRY_LIMIT = 3
|
|
648
|
+
|
|
649
|
+
#: Escalating continuation requests for truncated replies. The first is the
|
|
650
|
+
#: original nudge; later ones ask for a shorter answer explicitly. A thinking
|
|
651
|
+
#: model can otherwise burn every retry on the same long chain of thought.
|
|
652
|
+
TRUNCATED_RETRY_NUDGES = (
|
|
653
|
+
"Your previous reply was cut off by the output-token limit before you "
|
|
654
|
+
"produced any answer or tool call. Continue from where you stopped: either "
|
|
655
|
+
"call a tool or give the final answer, and keep your reasoning shorter than "
|
|
656
|
+
"the budget allows.",
|
|
657
|
+
"You hit the output-token limit again. Please be more precise in your "
|
|
658
|
+
"response and thinking: give only the next tool call (or a short final "
|
|
659
|
+
"answer), and do not repeat analysis you have already done.",
|
|
660
|
+
"Final retry: respond with exactly one tool call and no explanation. If the "
|
|
661
|
+
"task is complete, reply DONE.",
|
|
662
|
+
)
|
|
663
|
+
|
|
664
|
+
#: A text-only reply only counts as finished when it carries an explicit marker.
|
|
665
|
+
#: "I will complete X" is not enough; the nudge asks the model to say DONE.
|
|
666
|
+
_COMPLETION_MARKER_RE = re.compile(
|
|
667
|
+
r"(?i)\b(done|complete|completed|finished)\b")
|
|
668
|
+
_NEGATED_COMPLETION_RE = re.compile(
|
|
669
|
+
r"(?i)\b(?:not|never|haven't|hasn't|isn't|aren't|wasn't|weren't)\s+"
|
|
670
|
+
r"(?:done|complete|completed|finished)\b")
|
|
671
|
+
|
|
672
|
+
TEXT_ONLY_NUDGE = (
|
|
673
|
+
"You stopped without a tool call. If the task is not complete, continue "
|
|
674
|
+
"with the next tool call now. If it is complete, reply DONE.")
|
|
675
|
+
|
|
676
|
+
|
|
677
|
+
def _looks_complete(text):
|
|
678
|
+
"""Whether a text-only reply explicitly claims completion."""
|
|
679
|
+
text = str(text or "")
|
|
680
|
+
if not _COMPLETION_MARKER_RE.search(text):
|
|
681
|
+
return False
|
|
682
|
+
return not _NEGATED_COMPLETION_RE.search(text)
|
|
683
|
+
|
|
684
|
+
|
|
685
|
+
|
|
686
|
+
def print_no_session_farewell(console, model=None, started_at=None):
|
|
687
|
+
"""Print the good-bye mark/box when an interactive startup is cancelled."""
|
|
688
|
+
from . import __version__ as version
|
|
689
|
+
|
|
690
|
+
elapsed = max(time.monotonic() - (started_at or time.monotonic()), 0.0)
|
|
691
|
+
hours, remainder = divmod(int(elapsed), 3600)
|
|
692
|
+
minutes, seconds = divmod(remainder, 60)
|
|
693
|
+
duration = (f"{hours}h {minutes:02d}m" if hours
|
|
694
|
+
else f"{minutes}m {seconds:02d}s")
|
|
695
|
+
rows = [
|
|
696
|
+
("model", model or "(auto)"),
|
|
697
|
+
("session", "not started"),
|
|
698
|
+
("duration", duration),
|
|
699
|
+
("resume", "mini-code"),
|
|
700
|
+
]
|
|
701
|
+
console.farewell(
|
|
702
|
+
version, rows, sign_off="No session was started. Goodbye!")
|
|
703
|
+
|
|
704
|
+
|
|
705
|
+
def build_console(args):
|
|
706
|
+
"""Return ``(console, tui_mode)`` for these args."""
|
|
707
|
+
mode = tui_mod.tui_mode(getattr(args, "tui", "auto"))
|
|
708
|
+
use_tui = (mode == "on"
|
|
709
|
+
or (mode == "auto" and tui_mod.TuiConsole.supported()))
|
|
710
|
+
return (tui_mod.TuiConsole() if use_tui else ui.console), mode
|
|
711
|
+
|
|
712
|
+
|
|
585
713
|
class AgentSession:
|
|
586
714
|
"""A single interactive agent session.
|
|
587
715
|
|
|
@@ -594,8 +722,12 @@ class AgentSession:
|
|
|
594
722
|
EXIT_COMMANDS = {"quit", "exit", "/quit", "/exit", "exit()", "quit()"}
|
|
595
723
|
CLEAR_COMMANDS = {"clear", "/clear"}
|
|
596
724
|
|
|
597
|
-
def __init__(self, args, console=None, background_mode = False
|
|
725
|
+
def __init__(self, args, console=None, background_mode = False,
|
|
726
|
+
settings=None, defer_model=False):
|
|
598
727
|
self.args = args
|
|
728
|
+
self.settings = settings or settings_mod.Settings.from_args(args)
|
|
729
|
+
if settings is None:
|
|
730
|
+
self.settings.apply_to_args(args)
|
|
599
731
|
self.allowed_dir = os.path.abspath(args.allowed_dir)
|
|
600
732
|
self.cache_dir = args.cache_dir if args.cache_dir else DEFAULT_CACHE_LOCATION
|
|
601
733
|
|
|
@@ -610,16 +742,28 @@ class AgentSession:
|
|
|
610
742
|
|
|
611
743
|
self.tui_mode = tui_mod.tui_mode(getattr(args, "tui", "auto"))
|
|
612
744
|
if console is None:
|
|
613
|
-
|
|
614
|
-
or (self.tui_mode == "auto" and tui_mod.TuiConsole.supported()))
|
|
615
|
-
console = tui_mod.TuiConsole() if use_tui else ui.console
|
|
745
|
+
console, _mode = build_console(args)
|
|
616
746
|
self.console = console
|
|
617
747
|
self.console.verbose = getattr(args, "verbose", False)
|
|
618
748
|
|
|
619
749
|
# LLM / server configuration.
|
|
620
750
|
self.server_url = f"{args.url}"
|
|
621
751
|
self.api_key = args.api_key if args.api_key else os.environ.get("MINI_CODE_API_KEY", "")
|
|
622
|
-
|
|
752
|
+
# Startup construction may defer model resolution until the session
|
|
753
|
+
# decision, so no settings/model probe output precedes the resume offer.
|
|
754
|
+
self.model = (args.model if defer_model
|
|
755
|
+
else self._resolve_model(args))
|
|
756
|
+
# A higher reply budget is the CLI default; an explicit --max-tokens
|
|
757
|
+
# always wins, and a small-window model gets at most half its window.
|
|
758
|
+
# With deferred settings/model resolution this is filled in after the
|
|
759
|
+
# session decision, so a saved --max-tokens value is not shadowed.
|
|
760
|
+
if not defer_model and getattr(args, "max_tokens", None) is None:
|
|
761
|
+
args.max_tokens = default_max_output_tokens(self.model)
|
|
762
|
+
self.settings.capture_from_args(args)
|
|
763
|
+
if self.settings.api_key or self.settings.api_key_env:
|
|
764
|
+
# The model may have been detected from the server, so associate
|
|
765
|
+
# the active key with the model actually in use.
|
|
766
|
+
self.settings.remember_key()
|
|
623
767
|
|
|
624
768
|
# Background task registry. It is independent of the foreground loop;
|
|
625
769
|
# tools and /background read snapshots from it.
|
|
@@ -632,6 +776,9 @@ class AgentSession:
|
|
|
632
776
|
self._activity_label = None
|
|
633
777
|
self._activity_started = None
|
|
634
778
|
self._last_activity = None
|
|
779
|
+
self.dynamic_todo_tracking = bool(
|
|
780
|
+
getattr(args, "dynamic_todo_tracking", False))
|
|
781
|
+
self.todo_store = None
|
|
635
782
|
|
|
636
783
|
self._register_tools(args)
|
|
637
784
|
|
|
@@ -656,6 +803,26 @@ class AgentSession:
|
|
|
656
803
|
self.plan_strategy = planning.DEFAULT_PLAN_STRATEGY
|
|
657
804
|
self.plan_mode = (bool(getattr(self.args, "plan", False))
|
|
658
805
|
or requested_plan_strategy is not None)
|
|
806
|
+
self.allow_nudge = bool(getattr(self.args, "allow_nudge", False))
|
|
807
|
+
try:
|
|
808
|
+
self.nudge_limit = max(0, int(getattr(self.args, "nudge_limit", 1)))
|
|
809
|
+
except (TypeError, ValueError):
|
|
810
|
+
self.nudge_limit = 1
|
|
811
|
+
if self.allow_nudge and not self.plan_mode:
|
|
812
|
+
self.console.note(
|
|
813
|
+
"--allow-nudge only applies in plan mode; ignoring it.", "warn")
|
|
814
|
+
self._text_only_nudges = 0
|
|
815
|
+
self.strict_verify = bool(getattr(self.args, "strict_verify", False))
|
|
816
|
+
self.runtime_strategy = recovery.normalise(
|
|
817
|
+
getattr(self.args, "runtime_strategy",
|
|
818
|
+
recovery.DEFAULT_RUNTIME_STRATEGY))
|
|
819
|
+
self._reset_runtime_recovery()
|
|
820
|
+
self._runtime_prompts_this_turn = 0
|
|
821
|
+
self._runtime_pending_prompt = None
|
|
822
|
+
self._runtime_pending_replan = False
|
|
823
|
+
self._last_tool_result_text = ""
|
|
824
|
+
self._turn_goal = ""
|
|
825
|
+
self._pending_images = []
|
|
659
826
|
|
|
660
827
|
self.scratchpad = bool(getattr(self.args, "scratchpad", False))
|
|
661
828
|
self.tui = (self.tui_mode != "off"
|
|
@@ -674,6 +841,9 @@ class AgentSession:
|
|
|
674
841
|
# funnel through there (quit, exit, EOF, a /quit command) and a repeated
|
|
675
842
|
# box would read like a second session had ended.
|
|
676
843
|
self._farewell_shown = False
|
|
844
|
+
# False until start_new_session/restore_previous_session has produced
|
|
845
|
+
# a real session. shutdown() must not try to persist an unstarted one.
|
|
846
|
+
self._session_started = False
|
|
677
847
|
|
|
678
848
|
# Token accounting. ``token_stats`` covers the *current history
|
|
679
849
|
# segment* and is reset when compaction rolls over to a new one;
|
|
@@ -681,6 +851,7 @@ class AgentSession:
|
|
|
681
851
|
# Keeping the two apart is what lets usage survive a compaction.
|
|
682
852
|
self.token_stats = empty_usage()
|
|
683
853
|
self.total_usage = empty_usage()
|
|
854
|
+
self._truncated_retries = 0
|
|
684
855
|
|
|
685
856
|
# Compaction budget. History is compacted when the *projected input size*
|
|
686
857
|
# of the next request would not leave room for the reply inside the
|
|
@@ -753,6 +924,11 @@ class AgentSession:
|
|
|
753
924
|
"""
|
|
754
925
|
try:
|
|
755
926
|
if self.restore_previous_session(restore_directory):
|
|
927
|
+
ask = (settings_mod.interactive_startup(self.args)
|
|
928
|
+
and not self.background_mode)
|
|
929
|
+
self._adopt_settings(settings_mod.resolve_for_startup(
|
|
930
|
+
self.args, self.console, source_dir=restore_directory,
|
|
931
|
+
new_session=False, ask=ask))
|
|
756
932
|
return True
|
|
757
933
|
except Exception as e:
|
|
758
934
|
self.console.note(
|
|
@@ -777,7 +953,13 @@ class AgentSession:
|
|
|
777
953
|
|
|
778
954
|
answer = self.show_resume_choice()
|
|
779
955
|
if answer == "exit":
|
|
956
|
+
# This exit happens before a session exists, so it cannot use
|
|
957
|
+
# shutdown() (which persists an empty session). Print the same
|
|
958
|
+
# good-bye mark/box directly instead.
|
|
959
|
+
if self.tui_active:
|
|
960
|
+
self.console.stop_tui()
|
|
780
961
|
self.console.note("User chose to exit! Exiting.", "warn")
|
|
962
|
+
self._farewell_no_session()
|
|
781
963
|
raise SystemExit("")
|
|
782
964
|
if answer != "resume":
|
|
783
965
|
self.console.note("Will start with new session!", "warn")
|
|
@@ -802,12 +984,28 @@ class AgentSession:
|
|
|
802
984
|
self.unique_id = self.unique_id or generate_unique_id()
|
|
803
985
|
self.session_dir = os.path.join(self.cache_dir, self.unique_id)
|
|
804
986
|
self.restored_session = False
|
|
987
|
+
# A new session starts from defaults (plus CLI/environment), not from
|
|
988
|
+
# the previous session in this folder. The previous API-key archive is
|
|
989
|
+
# the one thing retained; selecting a model can load its stored key.
|
|
990
|
+
source = None
|
|
991
|
+
if not self.background_mode:
|
|
992
|
+
try:
|
|
993
|
+
source = find_last_session_dir(self.allowed_dir)
|
|
994
|
+
except Exception as e:
|
|
995
|
+
self.console.note(
|
|
996
|
+
f"Could not load previous API keys: {e}", "warn")
|
|
997
|
+
ask = (settings_mod.interactive_startup(self.args)
|
|
998
|
+
and not self.background_mode)
|
|
999
|
+
self._adopt_settings(settings_mod.resolve_for_startup(
|
|
1000
|
+
self.args, self.console, source_dir=source, new_session=True,
|
|
1001
|
+
ask=ask, keep_saved_values=False))
|
|
805
1002
|
|
|
806
1003
|
self.plan_manager = plan_utils.PlanManager(
|
|
807
1004
|
self.session_dir, enabled=self.plan_mode)
|
|
808
1005
|
self.background_tasks.set_log_dir(
|
|
809
1006
|
os.path.join(self.session_dir, "background"))
|
|
810
1007
|
self._prepare_agent_files()
|
|
1008
|
+
self._save_settings()
|
|
811
1009
|
|
|
812
1010
|
self.history_index = 0
|
|
813
1011
|
self.summary = []
|
|
@@ -823,6 +1021,7 @@ class AgentSession:
|
|
|
823
1021
|
# Record this session in --allowed-dir/.mini so a later
|
|
824
1022
|
# --load-last-session (or the interactive resume offer) can find it.
|
|
825
1023
|
self._save_last_session_pointer()
|
|
1024
|
+
self._session_started = True
|
|
826
1025
|
|
|
827
1026
|
|
|
828
1027
|
def restore_previous_session(self, restore_directory):
|
|
@@ -890,6 +1089,9 @@ class AgentSession:
|
|
|
890
1089
|
self.session_dir, enabled=self.plan_mode)
|
|
891
1090
|
self.background_tasks.set_log_dir(
|
|
892
1091
|
os.path.join(self.session_dir, "background"))
|
|
1092
|
+
if self.dynamic_todo_tracking:
|
|
1093
|
+
# Rebind the todo tools to the restored session's store.
|
|
1094
|
+
self._register_tools(self.args)
|
|
893
1095
|
self._prepare_agent_files()
|
|
894
1096
|
self.messages = restored
|
|
895
1097
|
self.summary = records
|
|
@@ -914,6 +1116,7 @@ class AgentSession:
|
|
|
914
1116
|
self.last_prompt_message_count = 0
|
|
915
1117
|
self._restore_usage_if_available(restore_directory)
|
|
916
1118
|
self.restored_session = True
|
|
1119
|
+
self._session_started = True
|
|
917
1120
|
|
|
918
1121
|
# Continuing a session in place makes it the latest one again: keep
|
|
919
1122
|
# the pointer aimed at it so a later --load-last-session finds the
|
|
@@ -934,6 +1137,7 @@ class AgentSession:
|
|
|
934
1137
|
"""
|
|
935
1138
|
self.unique_id = None
|
|
936
1139
|
self.session_dir = None
|
|
1140
|
+
self._session_started = False
|
|
937
1141
|
self.plan_manager = None
|
|
938
1142
|
self.messages = []
|
|
939
1143
|
self.summary = []
|
|
@@ -1027,6 +1231,23 @@ class AgentSession:
|
|
|
1027
1231
|
self.background_tasks, self._run_background_subagent))
|
|
1028
1232
|
self.llm_tools.extend(background_mod.background_tools())
|
|
1029
1233
|
|
|
1234
|
+
# Structured dynamic todo tracking is orthogonal to plan mode, shell
|
|
1235
|
+
# and the scratchpad. Its store lives in the session cache, not the
|
|
1236
|
+
# worktree.
|
|
1237
|
+
self.dynamic_todo_tracking = bool(
|
|
1238
|
+
getattr(args, "dynamic_todo_tracking", False))
|
|
1239
|
+
if self.dynamic_todo_tracking:
|
|
1240
|
+
expected = os.path.join(self.session_dir, todos_mod.TODO_FILENAME)
|
|
1241
|
+
if self.todo_store is None or self.todo_store.path != expected:
|
|
1242
|
+
self.todo_store = todos_mod.TodoStore(self.session_dir)
|
|
1243
|
+
todo_functions = todos_mod.todo_functions(self.todo_store)
|
|
1244
|
+
self.tools_dict.update(
|
|
1245
|
+
tools.util_get_tools_dict(functions=todo_functions))
|
|
1246
|
+
self.llm_tools.extend(
|
|
1247
|
+
tools.util_get_tools(functions=todo_functions))
|
|
1248
|
+
else:
|
|
1249
|
+
self.todo_store = None
|
|
1250
|
+
|
|
1030
1251
|
|
|
1031
1252
|
def _prepare_agent_files(self):
|
|
1032
1253
|
"""Create the opt-in agent-owned files under ``--allowed-dir/.mini``.
|
|
@@ -1043,27 +1264,37 @@ class AgentSession:
|
|
|
1043
1264
|
path = agent_files.ensure_open_plan(self.allowed_dir)
|
|
1044
1265
|
self.console.note(f"Open-plan document: {path}", "info")
|
|
1045
1266
|
|
|
1046
|
-
def
|
|
1047
|
-
"""
|
|
1267
|
+
def _render_system_prompt(self):
|
|
1268
|
+
"""Return the effective system prompt for the current settings.
|
|
1269
|
+
|
|
1270
|
+
A user-supplied ``--system-prompt`` is never regenerated. Everything
|
|
1271
|
+
else (the tool list, plan/skills/scratchpad blocks) is built from the
|
|
1272
|
+
live session state, so a settings change can rebuild it deliberately.
|
|
1273
|
+
"""
|
|
1048
1274
|
if self.args.system_prompt:
|
|
1049
|
-
|
|
1050
|
-
|
|
1051
|
-
|
|
1052
|
-
|
|
1053
|
-
|
|
1054
|
-
|
|
1055
|
-
|
|
1056
|
-
|
|
1057
|
-
|
|
1058
|
-
|
|
1059
|
-
|
|
1060
|
-
|
|
1061
|
-
|
|
1062
|
-
|
|
1063
|
-
|
|
1064
|
-
|
|
1065
|
-
|
|
1275
|
+
return self.args.system_prompt
|
|
1276
|
+
scratch_path = (agent_files.scratchpad_path(self.allowed_dir)
|
|
1277
|
+
if self.scratchpad else None)
|
|
1278
|
+
open_plan_path = None
|
|
1279
|
+
if self.plan_mode and self.plan_strategy == planning.OPEN_PLAN:
|
|
1280
|
+
open_plan_path = agent_files.open_plan_path(self.allowed_dir)
|
|
1281
|
+
todo_path = (self.todo_store.path
|
|
1282
|
+
if self.dynamic_todo_tracking and self.todo_store else None)
|
|
1283
|
+
return prompts.system_prompt(
|
|
1284
|
+
tools_dict=self.tools_dict, allowed_dir=self.allowed_dir,
|
|
1285
|
+
plan_mode=self.plan_mode,
|
|
1286
|
+
skills_dir=self.allowed_dir if self.enable_skills else None,
|
|
1287
|
+
session_dir=self.session_dir,
|
|
1288
|
+
scratchpad_path=scratch_path,
|
|
1289
|
+
scratchpad_dir=(agent_files.mini_dir(self.allowed_dir)
|
|
1290
|
+
if self.scratchpad else None),
|
|
1291
|
+
open_plan_path=open_plan_path,
|
|
1292
|
+
todo_path=todo_path,
|
|
1293
|
+
)
|
|
1066
1294
|
|
|
1295
|
+
def _build_initial_messages(self):
|
|
1296
|
+
"""Assemble the system prompt and optional Agent.md into the first turns."""
|
|
1297
|
+
system_prompt = self._render_system_prompt()
|
|
1067
1298
|
messages = [{"role": "system", "content": system_prompt}]
|
|
1068
1299
|
self._persistent_messages = []
|
|
1069
1300
|
|
|
@@ -1127,7 +1358,7 @@ class AgentSession:
|
|
|
1127
1358
|
"""
|
|
1128
1359
|
if not usage:
|
|
1129
1360
|
return
|
|
1130
|
-
prompt_tokens =
|
|
1361
|
+
prompt_tokens = usage_int(usage, "prompt_tokens")
|
|
1131
1362
|
if prompt_tokens <= 0:
|
|
1132
1363
|
return
|
|
1133
1364
|
if message_count is None:
|
|
@@ -1489,16 +1720,17 @@ class AgentSession:
|
|
|
1489
1720
|
the DENY-tier limits). We render it as a red box so it stands out on any
|
|
1490
1721
|
real terminal (it degrades to a plain ASCII box when colour is off).
|
|
1491
1722
|
"""
|
|
1492
|
-
|
|
1493
|
-
|
|
1494
|
-
|
|
1495
|
-
|
|
1496
|
-
|
|
1497
|
-
|
|
1498
|
-
|
|
1499
|
-
|
|
1500
|
-
|
|
1501
|
-
|
|
1723
|
+
lines = [
|
|
1724
|
+
"SUDO MODE: the agent will NEVER ask for permission.",
|
|
1725
|
+
"All tool calls and shell commands run automatically and unattended.",
|
|
1726
|
+
"Only clearly-destructive (DENY-tier) commands are still refused.",
|
|
1727
|
+
"You are responsible for everything it does on this machine.",
|
|
1728
|
+
]
|
|
1729
|
+
if self.tui_active:
|
|
1730
|
+
for line in lines:
|
|
1731
|
+
self.console.note(line, "error")
|
|
1732
|
+
else:
|
|
1733
|
+
self.console.print_box(lines, title="DANGER", fg="red")
|
|
1502
1734
|
|
|
1503
1735
|
def _tui_info_line(self):
|
|
1504
1736
|
"""A one-line session summary for the fixed dashboard."""
|
|
@@ -1506,14 +1738,6 @@ class AgentSession:
|
|
|
1506
1738
|
tasks = (self.background_tasks.list()
|
|
1507
1739
|
if hasattr(self, "background_tasks") else [])
|
|
1508
1740
|
|
|
1509
|
-
def count(key):
|
|
1510
|
-
# The dashboard refreshes on every turn: a display detail must
|
|
1511
|
-
# never raise, even if a server reported a null/odd usage value.
|
|
1512
|
-
try:
|
|
1513
|
-
return int(usage.get(key) or 0)
|
|
1514
|
-
except (TypeError, ValueError):
|
|
1515
|
-
return 0
|
|
1516
|
-
|
|
1517
1741
|
running = sum(1 for task in tasks
|
|
1518
1742
|
if task.get("status") in ("running", "cancelling"))
|
|
1519
1743
|
if tasks:
|
|
@@ -1521,8 +1745,9 @@ class AgentSession:
|
|
|
1521
1745
|
f"{plural(len(tasks), 'background task')} running")
|
|
1522
1746
|
else:
|
|
1523
1747
|
background = "no background tasks"
|
|
1524
|
-
return (f"{plural(
|
|
1525
|
-
f"{plural(
|
|
1748
|
+
return (f"{plural(usage_int(usage, 'tool_calls'), 'tool call')} · "
|
|
1749
|
+
f"{plural(usage_int(usage, 'llm_calls'), 'LLM call')} · "
|
|
1750
|
+
f"{background}")
|
|
1526
1751
|
|
|
1527
1752
|
def _tui_header_lines(self):
|
|
1528
1753
|
"""The fixed dashboard content for --tui."""
|
|
@@ -1562,7 +1787,7 @@ class AgentSession:
|
|
|
1562
1787
|
turns = []
|
|
1563
1788
|
for message in self.messages:
|
|
1564
1789
|
role = message.get("role")
|
|
1565
|
-
content = message.get("content")
|
|
1790
|
+
content = media.content_text(message.get("content"))
|
|
1566
1791
|
if role not in ("user", "assistant") or not content:
|
|
1567
1792
|
continue
|
|
1568
1793
|
if id(message) in persistent:
|
|
@@ -1586,7 +1811,10 @@ class AgentSession:
|
|
|
1586
1811
|
API key, unrestricted shell execution and --sudo are exactly the things
|
|
1587
1812
|
that must not be hidden behind --verbose.
|
|
1588
1813
|
"""
|
|
1589
|
-
self.console.announce_api_key(
|
|
1814
|
+
self.console.announce_api_key(
|
|
1815
|
+
present=bool(self.api_key),
|
|
1816
|
+
source=self.settings.api_key_env,
|
|
1817
|
+
model=self.model or "")
|
|
1590
1818
|
|
|
1591
1819
|
if shell_execution_enabled(self.args):
|
|
1592
1820
|
self.console.announce_shell(
|
|
@@ -1658,16 +1886,12 @@ class AgentSession:
|
|
|
1658
1886
|
|
|
1659
1887
|
def run(self, initial_prompt=None):
|
|
1660
1888
|
"""Drive the agent loop until the user quits."""
|
|
1661
|
-
|
|
1662
|
-
|
|
1663
|
-
|
|
1664
|
-
|
|
1665
|
-
# whether to resume an older conversation (and before anything can
|
|
1666
|
-
# consume stdin). None of them depends on which session is finally used:
|
|
1667
|
-
# they read args, allowed_dir, cache_dir, server_url and the resolved
|
|
1668
|
-
# model, plus the provisional id minted in __init__.
|
|
1889
|
+
if isinstance(self.console, tui_mod.TuiConsole):
|
|
1890
|
+
# Before a session exists we are still answering resume/settings
|
|
1891
|
+
# questions; "No conversation yet" would be misleading.
|
|
1892
|
+
self.console.set_empty_hint(False)
|
|
1669
1893
|
if self.tui and isinstance(self.console, tui_mod.TuiConsole):
|
|
1670
|
-
if not self.console.start_tui():
|
|
1894
|
+
if not self.console.active and not self.console.start_tui():
|
|
1671
1895
|
# --tui on requested the fixed view, but this terminal cannot
|
|
1672
1896
|
# host it (piped output, an unsupported TERM, ...). Fall back
|
|
1673
1897
|
# to the scrolling console instead of leaving self.tui true
|
|
@@ -1676,20 +1900,24 @@ class AgentSession:
|
|
|
1676
1900
|
self.console.note(
|
|
1677
1901
|
"TUI is not available on this terminal; using the "
|
|
1678
1902
|
"scrolling console.", "warn")
|
|
1903
|
+
|
|
1904
|
+
# The plain console shows the mark immediately, even before the resume
|
|
1905
|
+
# offer; print_welcome() shows it again with the session info once a
|
|
1906
|
+
# session has actually started. The TUI has the persistent banner.
|
|
1679
1907
|
if not self.tui_active:
|
|
1680
|
-
self.
|
|
1908
|
+
self.console.print_mark()
|
|
1681
1909
|
|
|
1682
|
-
#
|
|
1683
|
-
#
|
|
1910
|
+
# The resume offer comes first. Settings are loaded only after the
|
|
1911
|
+
# user chooses to resume or start a session, so the banner and the
|
|
1912
|
+
# announcements describe the session that was actually chosen.
|
|
1684
1913
|
try:
|
|
1914
|
+
self.start_session()
|
|
1915
|
+
if isinstance(self.console, tui_mod.TuiConsole):
|
|
1916
|
+
self.console.set_empty_hint(True)
|
|
1917
|
+
if not self.tui_active:
|
|
1918
|
+
self.print_welcome()
|
|
1685
1919
|
self.print_announcements()
|
|
1686
1920
|
self._warn_compaction_budget()
|
|
1687
|
-
|
|
1688
|
-
# Only now resolve the session (resume offer / restore / fresh start),
|
|
1689
|
-
# because all of that can consume input and can replace the id. The id
|
|
1690
|
-
# line and the tip therefore come after it and show the id actually in
|
|
1691
|
-
# use (the banner may have shown the provisional one).
|
|
1692
|
-
self.start_session()
|
|
1693
1921
|
if self.tui_active:
|
|
1694
1922
|
self.console.set_summary(self._tui_header_lines())
|
|
1695
1923
|
self.console.set_info_provider(self._tui_info_line)
|
|
@@ -1806,16 +2034,43 @@ class AgentSession:
|
|
|
1806
2034
|
|
|
1807
2035
|
The planning *strategy* changes the plan/review wiring only:
|
|
1808
2036
|
|
|
1809
|
-
* ``plan-
|
|
1810
|
-
|
|
1811
|
-
|
|
1812
|
-
|
|
1813
|
-
|
|
1814
|
-
|
|
2037
|
+
* ``plan-verify2`` (default) -- author a plan, then verify completion with one
|
|
2038
|
+
machine-readable verdict (``STATUS: DONE`` / ``INCOMPLETE``). DONE
|
|
2039
|
+
ends the turn immediately, with no post-review step. An unfinished
|
|
2040
|
+
verdict re-queues the outstanding work and lets the agent act; a
|
|
2041
|
+
second verify follows when the work settles again. If the agent
|
|
2042
|
+
makes no tool call after an unfinished verdict, the turn ends
|
|
2043
|
+
instead of verifying forever.
|
|
2044
|
+
* ``plan-verify`` -- author a plan, review it when the work settles,
|
|
2045
|
+
then keep the post-review step only when it calls a tool. A no-tool
|
|
2046
|
+
answer is shown to the user and ends the turn without being stored.
|
|
2047
|
+
* ``plan-verify-step`` -- same plan and review, but always run one
|
|
2048
|
+
extra step and keep whatever that step says.
|
|
1815
2049
|
* ``open-plan`` -- the agent owns a plan document and maintains it
|
|
1816
2050
|
itself; the loop neither authors nor reviews a plan.
|
|
2051
|
+
|
|
2052
|
+
``--allow-nudge`` applies to every strategy when plan mode is active:
|
|
2053
|
+
a text-only reply without an explicit completion marker gets up to
|
|
2054
|
+
``--nudge-limit`` continuation messages before the strategy's normal
|
|
2055
|
+
review/end path runs.
|
|
2056
|
+
|
|
2057
|
+
``--strict-verify`` swaps in evidence-based review/verify prompts and,
|
|
2058
|
+
with ``open-plan``, adds a verification pass after the work settles.
|
|
2059
|
+
``--runtime-strategy`` may inject a recovery prompt after repeated tool
|
|
2060
|
+
failures, and ``prompt-change-plan`` then starts a fresh plan.
|
|
1817
2061
|
"""
|
|
1818
2062
|
self.messages.append({"role": "user", "content": user_input})
|
|
2063
|
+
if self._pending_images:
|
|
2064
|
+
content = media.user_content(user_input, self._pending_images)
|
|
2065
|
+
self.messages[-1]["content"] = content
|
|
2066
|
+
self._pending_images = []
|
|
2067
|
+
self._text_only_nudges = 0
|
|
2068
|
+
verify_pending_action = False
|
|
2069
|
+
self._runtime_prompts_this_turn = 0
|
|
2070
|
+
self._turn_goal = user_input
|
|
2071
|
+
self._reset_runtime_recovery()
|
|
2072
|
+
self._runtime_pending_prompt = None
|
|
2073
|
+
self._runtime_pending_replan = False
|
|
1819
2074
|
|
|
1820
2075
|
if self.plan_mode and not skip_plan:
|
|
1821
2076
|
self._record_goal_request(user_input)
|
|
@@ -1835,13 +2090,70 @@ class AgentSession:
|
|
|
1835
2090
|
should_continue = self._step()
|
|
1836
2091
|
self._persist()
|
|
1837
2092
|
if should_continue:
|
|
2093
|
+
# A tool call or a recovered reply means the text-only nudge
|
|
2094
|
+
# budget starts fresh at the next settle.
|
|
2095
|
+
self._text_only_nudges = 0
|
|
2096
|
+
verify_pending_action = False
|
|
1838
2097
|
self.console.note(
|
|
1839
2098
|
"Continuing with LLM calls until no more tool calls.", "info")
|
|
1840
2099
|
continue
|
|
1841
2100
|
self.console.note("LLM seems to have to an end of the task.", "info")
|
|
1842
|
-
|
|
1843
|
-
|
|
2101
|
+
# A text-only reply is a checkpoint, not necessarily completion.
|
|
2102
|
+
# With --allow-nudge, ask the model to continue (bounded) before
|
|
2103
|
+
# paying for a full plan review. An explicit DONE/complete marker
|
|
2104
|
+
# skips the nudge and goes straight to the review.
|
|
2105
|
+
if (self.plan_mode and not skip_plan and self.allow_nudge
|
|
2106
|
+
and self._text_only_nudges < self.nudge_limit
|
|
2107
|
+
and not _looks_complete(self._last_assistant_text())):
|
|
2108
|
+
self._text_only_nudges += 1
|
|
2109
|
+
self.console.note(
|
|
2110
|
+
"The model stopped without a tool call; asking it to "
|
|
2111
|
+
"continue before reviewing the plan.", "info")
|
|
2112
|
+
self.messages.append({"role": "user",
|
|
2113
|
+
"content": TEXT_ONLY_NUDGE})
|
|
2114
|
+
self._persist()
|
|
2115
|
+
continue
|
|
2116
|
+
if (not self.plan_mode or skip_plan):
|
|
1844
2117
|
return
|
|
2118
|
+
if (self.plan_strategy == planning.OPEN_PLAN
|
|
2119
|
+
and not self.strict_verify):
|
|
2120
|
+
return
|
|
2121
|
+
if (self.plan_strategy == planning.PLAN_VERIFY2
|
|
2122
|
+
or (self.plan_strategy == planning.OPEN_PLAN
|
|
2123
|
+
and self.strict_verify)):
|
|
2124
|
+
if verify_pending_action:
|
|
2125
|
+
# The previous verdict said the plan was unfinished, but the
|
|
2126
|
+
# agent then stopped without a tool call. Verifying the same
|
|
2127
|
+
# transcript again would loop forever, so end the turn.
|
|
2128
|
+
self.console.note(
|
|
2129
|
+
"Plan verification reports unfinished work, but the "
|
|
2130
|
+
"model made no tool call; ending the turn.", "warn")
|
|
2131
|
+
return
|
|
2132
|
+
self.console.note("Verifying the plan status.", "info")
|
|
2133
|
+
status, summary = self._verify_plan_completion()
|
|
2134
|
+
self._persist()
|
|
2135
|
+
if status == planning.VERIFY_DONE:
|
|
2136
|
+
self.console.note("Plan verification: DONE.", "ok")
|
|
2137
|
+
return
|
|
2138
|
+
label = ("INCOMPLETE" if status == planning.VERIFY_INCOMPLETE
|
|
2139
|
+
else "UNKNOWN")
|
|
2140
|
+
self.console.note(
|
|
2141
|
+
f"Plan verification: {label}; letting the agent continue.",
|
|
2142
|
+
"info")
|
|
2143
|
+
if summary and summary.strip():
|
|
2144
|
+
# Loop bookkeeping, not user-authored (see
|
|
2145
|
+
# _LOOP_INJECTED_USER_PREFIXES). The next _step sees the
|
|
2146
|
+
# outstanding tasks and can act on them.
|
|
2147
|
+
label = ("Plan verification (open-plan):"
|
|
2148
|
+
if self.plan_strategy == planning.OPEN_PLAN
|
|
2149
|
+
else "Plan verification (from CURRENT_PLAN.md):")
|
|
2150
|
+
self.messages.append({
|
|
2151
|
+
"role": "user",
|
|
2152
|
+
"content": label + "\n%s" % summary.strip(),
|
|
2153
|
+
})
|
|
2154
|
+
self._persist()
|
|
2155
|
+
verify_pending_action = True
|
|
2156
|
+
continue
|
|
1845
2157
|
self.console.note("Reviewing the plan, if everything is done.", "info")
|
|
1846
2158
|
self._review_plan_completion()
|
|
1847
2159
|
self._persist()
|
|
@@ -1856,6 +2168,13 @@ class AgentSession:
|
|
|
1856
2168
|
if not should_continue:
|
|
1857
2169
|
return
|
|
1858
2170
|
|
|
2171
|
+
def _save_settings(self):
|
|
2172
|
+
"""Persist the effective settings into this session's cache folder."""
|
|
2173
|
+
try:
|
|
2174
|
+
self.settings.save(self.session_dir)
|
|
2175
|
+
except OSError as e:
|
|
2176
|
+
self.console.note(f"Could not save session settings: {e}", "warn")
|
|
2177
|
+
|
|
1859
2178
|
def _save_last_session_pointer(self):
|
|
1860
2179
|
"""Record this session's directory in --allowed-dir/.mini.
|
|
1861
2180
|
|
|
@@ -1930,7 +2249,7 @@ class AgentSession:
|
|
|
1930
2249
|
"""Return the content of the most recent assistant (non tool-call) turn."""
|
|
1931
2250
|
for m in reversed(self.messages):
|
|
1932
2251
|
if m.get("role") == "assistant" and not m.get("tool_calls"):
|
|
1933
|
-
return m.get("content")
|
|
2252
|
+
return media.content_text(m.get("content"))
|
|
1934
2253
|
return ""
|
|
1935
2254
|
|
|
1936
2255
|
# -- plan mode ---------------------------------------------------------
|
|
@@ -1943,14 +2262,21 @@ class AgentSession:
|
|
|
1943
2262
|
return
|
|
1944
2263
|
self.plan_manager.write_goal(stripped)
|
|
1945
2264
|
|
|
1946
|
-
def _generate_plan_and_inject(self, current_instruction):
|
|
2265
|
+
def _generate_plan_and_inject(self, current_instruction, recovery=False):
|
|
1947
2266
|
"""Ask the model to author a plan for the current instruction.
|
|
2267
|
+
|
|
2268
|
+
``recovery`` marks the plan as a post-failure re-plan: it gets its own
|
|
2269
|
+
label and, in ``open-plan`` mode, is not written into
|
|
2270
|
+
``CURRENT_PLAN.md`` because that document belongs to the agent.
|
|
1948
2271
|
"""
|
|
1949
2272
|
plan_prompt_text = prompts.plan_prompt(self.messages, current_instruction)
|
|
1950
2273
|
plan_text = ""
|
|
1951
2274
|
self._begin_activity("generating plan")
|
|
1952
2275
|
try:
|
|
1953
|
-
self.console.note(
|
|
2276
|
+
self.console.note(
|
|
2277
|
+
("Generating a recovery plan for the current goal..."
|
|
2278
|
+
if recovery else "Generating a plan for the current goal..."),
|
|
2279
|
+
"info")
|
|
1954
2280
|
self.console.start_thinking("planning")
|
|
1955
2281
|
# The loop's own bookkeeping requests (plan authoring / review /
|
|
1956
2282
|
# compaction) are single user turns with no ``tools``, so the
|
|
@@ -1984,28 +2310,44 @@ class AgentSession:
|
|
|
1984
2310
|
self.console.stop_thinking()
|
|
1985
2311
|
self._end_activity()
|
|
1986
2312
|
|
|
1987
|
-
self.
|
|
2313
|
+
if not (recovery and self.plan_mode
|
|
2314
|
+
and self.plan_strategy == planning.OPEN_PLAN):
|
|
2315
|
+
# open-plan owns its document; the loop must not overwrite it.
|
|
2316
|
+
self.plan_manager.write_plan(plan_text)
|
|
1988
2317
|
if plan_text and plan_text.strip():
|
|
1989
2318
|
# Show the plan immediately; otherwise the user only sees it via
|
|
1990
2319
|
# /plan or the file on disk.
|
|
1991
|
-
self.console.plan_box(
|
|
1992
|
-
|
|
2320
|
+
self.console.plan_box(
|
|
2321
|
+
plan_text.strip().splitlines(),
|
|
2322
|
+
title=("Recovery plan for the current goal" if recovery
|
|
2323
|
+
else "Plan for the current goal"))
|
|
1993
2324
|
else:
|
|
1994
2325
|
self.console.note("No plan text was generated.", "warn")
|
|
1995
2326
|
if plan_text and plan_text.strip():
|
|
1996
2327
|
# Loop bookkeeping, not a user instruction: the leading text is one
|
|
1997
2328
|
# of _LOOP_INJECTED_USER_PREFIXES, so the compaction tail scan skips
|
|
1998
2329
|
# it when looking for the turn being answered.
|
|
2330
|
+
label = ("Recovery plan for the goal:\n" if recovery
|
|
2331
|
+
else "Current plan for the goal (from CURRENT_PLAN.md):\n")
|
|
1999
2332
|
self.messages.append({
|
|
2000
2333
|
"role": "user",
|
|
2001
|
-
"content":
|
|
2334
|
+
"content": label + plan_text.strip(),
|
|
2002
2335
|
})
|
|
2003
2336
|
|
|
2337
|
+
def _open_plan_document(self):
|
|
2338
|
+
"""The agent-authored plan document, for strict open-plan verification."""
|
|
2339
|
+
try:
|
|
2340
|
+
return agent_files.read_text(
|
|
2341
|
+
agent_files.open_plan_path(self.allowed_dir), limit=8000)
|
|
2342
|
+
except Exception:
|
|
2343
|
+
return ""
|
|
2344
|
+
|
|
2004
2345
|
def _review_plan_completion(self):
|
|
2005
2346
|
"""Once the work looks done, review the plan's completion.
|
|
2006
2347
|
"""
|
|
2007
2348
|
plan_prompt_text = prompts.plan_review_prompt(
|
|
2008
|
-
self.messages, self.plan_manager.goal or ""
|
|
2349
|
+
self.messages, self.plan_manager.goal or "",
|
|
2350
|
+
strict=self.strict_verify)
|
|
2009
2351
|
summary = ""
|
|
2010
2352
|
self._begin_activity("reviewing plan")
|
|
2011
2353
|
try:
|
|
@@ -2045,6 +2387,53 @@ class AgentSession:
|
|
|
2045
2387
|
return True
|
|
2046
2388
|
|
|
2047
2389
|
|
|
2390
|
+
def _verify_plan_completion(self):
|
|
2391
|
+
"""Run the ``plan-verify2`` check and return ``(status, summary)``.
|
|
2392
|
+
|
|
2393
|
+
The verdict is parsed from the reply by
|
|
2394
|
+
:func:`mini_code_cli.planning.parse_verify_status`; a missing or
|
|
2395
|
+
unreadable verdict returns ``None`` as the status. The reply is always
|
|
2396
|
+
written to ``CURRENT_PLAN.md`` for inspection. Unlike the review path,
|
|
2397
|
+
this method does not inject anything into the transcript: the caller
|
|
2398
|
+
only re-queues the outstanding work when the verdict says it is not
|
|
2399
|
+
done, so a DONE turn ends without leaving an orphan user message.
|
|
2400
|
+
"""
|
|
2401
|
+
prompt_text = prompts.plan_verify_prompt(
|
|
2402
|
+
self.messages, self.plan_manager.goal or "",
|
|
2403
|
+
strict=self.strict_verify,
|
|
2404
|
+
plan_document=self._open_plan_document()
|
|
2405
|
+
if self.plan_strategy == planning.OPEN_PLAN else "")
|
|
2406
|
+
summary = ""
|
|
2407
|
+
self._begin_activity("verifying plan")
|
|
2408
|
+
try:
|
|
2409
|
+
self.console.start_thinking("verifying plan")
|
|
2410
|
+
response, _, usage, _ = utils.unpack_llm_result(
|
|
2411
|
+
utils.call_openai_server(
|
|
2412
|
+
[{"role": "user", "content": prompt_text}],
|
|
2413
|
+
max_tokens=2048 if self.strict_verify else 1024,
|
|
2414
|
+
temperature=0.0,
|
|
2415
|
+
model=self.model,
|
|
2416
|
+
server_url=self.server_url,
|
|
2417
|
+
api_key=self.api_key,
|
|
2418
|
+
timeout=self.args.llm_timeout,
|
|
2419
|
+
console=self.console,
|
|
2420
|
+
))
|
|
2421
|
+
self._record_usage(usage)
|
|
2422
|
+
self._note_prompt_size(usage, len(self.messages))
|
|
2423
|
+
summary = response or ""
|
|
2424
|
+
except Exception as exc:
|
|
2425
|
+
self.console.note(f"Could not verify the plan: {exc}", "warn")
|
|
2426
|
+
finally:
|
|
2427
|
+
self.console.stop_thinking()
|
|
2428
|
+
self._end_activity()
|
|
2429
|
+
|
|
2430
|
+
status = planning.parse_verify_status(summary)
|
|
2431
|
+
if not (self.plan_mode and self.plan_strategy == planning.OPEN_PLAN):
|
|
2432
|
+
# open-plan owns its document; do not add loop-authored sections.
|
|
2433
|
+
self.plan_manager.write_plan_summary(summary)
|
|
2434
|
+
return status, summary
|
|
2435
|
+
|
|
2436
|
+
|
|
2048
2437
|
def _handle_compaction(self, compacted, tail=()):
|
|
2049
2438
|
"""Re-inject goal + plan into the compacted messages (plan mode).
|
|
2050
2439
|
|
|
@@ -2111,7 +2500,7 @@ class AgentSession:
|
|
|
2111
2500
|
for message in reversed(list(tail or ())):
|
|
2112
2501
|
if (isinstance(message, dict) and message.get("role") == "user"
|
|
2113
2502
|
and not _is_loop_injected(message)):
|
|
2114
|
-
return message.get("content")
|
|
2503
|
+
return media.content_text(message.get("content"))
|
|
2115
2504
|
return ""
|
|
2116
2505
|
|
|
2117
2506
|
# -- compaction strategies --------------------------------------------
|
|
@@ -2364,9 +2753,607 @@ class AgentSession:
|
|
|
2364
2753
|
if cmd in ("skip-plan", "skip_plan", "skipplan"):
|
|
2365
2754
|
self._run_skipped_plan(arg)
|
|
2366
2755
|
return True
|
|
2756
|
+
if cmd == "image":
|
|
2757
|
+
self._handle_image_command(arg)
|
|
2758
|
+
return True
|
|
2759
|
+
if cmd == "todo":
|
|
2760
|
+
self._show_todos(arg)
|
|
2761
|
+
return True
|
|
2762
|
+
if cmd == "settings":
|
|
2763
|
+
self._handle_settings_command(arg)
|
|
2764
|
+
return True
|
|
2367
2765
|
self.console.note(f"Unknown command {stripped!r}. Try /help.", "warn")
|
|
2368
2766
|
return True
|
|
2369
2767
|
|
|
2768
|
+
def _show_todos(self, arg):
|
|
2769
|
+
"""Show or clear the dynamic todo list."""
|
|
2770
|
+
if self.todo_store is None:
|
|
2771
|
+
self.console.note(
|
|
2772
|
+
"Dynamic todo tracking is off (--dynamic-todo-tracking).",
|
|
2773
|
+
"info")
|
|
2774
|
+
return
|
|
2775
|
+
if (arg or "").strip().lower() in ("clear", "reset"):
|
|
2776
|
+
self.todo_store.replace([])
|
|
2777
|
+
self.console.note("Todo list cleared.", "info")
|
|
2778
|
+
return
|
|
2779
|
+
self.console.rule("todo", fg="cyan")
|
|
2780
|
+
for line in self.todo_store.render().splitlines():
|
|
2781
|
+
self.console.emit(line)
|
|
2782
|
+
self.console.rule(char="═", fg="cyan")
|
|
2783
|
+
|
|
2784
|
+
def _handle_image_command(self, arg):
|
|
2785
|
+
"""Stage an image for the next user message (``/image PATH``)."""
|
|
2786
|
+
arg = (arg or "").strip().strip("'\"")
|
|
2787
|
+
if not arg:
|
|
2788
|
+
self.console.note(
|
|
2789
|
+
"Usage: /image PATH (PNG/JPEG/WEBP/GIF), or /image clear.",
|
|
2790
|
+
"warn")
|
|
2791
|
+
return
|
|
2792
|
+
if arg.lower() == "clear":
|
|
2793
|
+
self._pending_images = []
|
|
2794
|
+
self.console.note("Pending images cleared.", "info")
|
|
2795
|
+
return
|
|
2796
|
+
try:
|
|
2797
|
+
ref = media.stage_image(arg, self.session_dir)
|
|
2798
|
+
except (OSError, ValueError) as exc:
|
|
2799
|
+
self.console.note(f"Could not attach image: {exc}", "error")
|
|
2800
|
+
return
|
|
2801
|
+
self._pending_images.append(ref)
|
|
2802
|
+
self.console.note(
|
|
2803
|
+
f"Image staged for the next message: {ref['name']} "
|
|
2804
|
+
f"({ref['mime']}, {ref['bytes']} bytes).", "ok")
|
|
2805
|
+
|
|
2806
|
+
def _attach_image_from_read(self, path):
|
|
2807
|
+
"""Prepare an image read by the agent's ``read_file`` tool.
|
|
2808
|
+
|
|
2809
|
+
Returns ``(tool_text, ref)``; the caller appends the tool result first
|
|
2810
|
+
and then the user content block, because OpenAI-style tool messages are
|
|
2811
|
+
text-only.
|
|
2812
|
+
"""
|
|
2813
|
+
ref = media.stage_image(path, self.session_dir)
|
|
2814
|
+
text = (f"Image read from {path}; it is attached in the next message "
|
|
2815
|
+
f"so you can inspect it.")
|
|
2816
|
+
return text, ref
|
|
2817
|
+
|
|
2818
|
+
# -- settings ---------------------------------------------------------
|
|
2819
|
+
|
|
2820
|
+
def _settings_lines(self):
|
|
2821
|
+
rows = self.settings.rows()
|
|
2822
|
+
lines = ["Settings:"]
|
|
2823
|
+
group_seen = None
|
|
2824
|
+
for row in rows:
|
|
2825
|
+
group = row.get("group", "Other")
|
|
2826
|
+
if group != group_seen:
|
|
2827
|
+
group_seen = group
|
|
2828
|
+
lines.append(f" {group}:")
|
|
2829
|
+
mutable = "" if row["mutable"] else " [immutable]"
|
|
2830
|
+
cache = f" cache:{row['cache']}" if row["cache"] != "none" else ""
|
|
2831
|
+
lines.append(f" {row['number']:2}. {row['name']:22} "
|
|
2832
|
+
f"{row.get('display', row['value']):28}"
|
|
2833
|
+
f"{cache}{mutable}")
|
|
2834
|
+
lines.append(" Immutable / session:")
|
|
2835
|
+
for name, description in settings_mod.IMMUTABLE:
|
|
2836
|
+
lines.append(f" {name:22} (cannot change: {description})")
|
|
2837
|
+
return lines
|
|
2838
|
+
|
|
2839
|
+
def _read_setting_value(self, name):
|
|
2840
|
+
"""Read one setting's new value; ``None`` means "go back"."""
|
|
2841
|
+
spec = settings_mod.BY_NAME.get(name) or settings_mod.BY_NAME.get(
|
|
2842
|
+
settings_mod.ALIASES.get(name, ""))
|
|
2843
|
+
row = next((item for item in self.settings.rows()
|
|
2844
|
+
if item["name"] == name), None)
|
|
2845
|
+
current = row["value"] if row else ""
|
|
2846
|
+
current_label = row.get("display", current) if row else ""
|
|
2847
|
+
if name == "api-key":
|
|
2848
|
+
# A focused, masked sub-window in the TUI; getpass on the plain
|
|
2849
|
+
# console. Both accept ``exit`` to go back.
|
|
2850
|
+
key = self.console.settings_secret(
|
|
2851
|
+
"api-key", current=current, current_label=current_label)
|
|
2852
|
+
key = "" if key is None else key.strip()
|
|
2853
|
+
if key.lower() == "exit":
|
|
2854
|
+
return None
|
|
2855
|
+
if not key:
|
|
2856
|
+
return ""
|
|
2857
|
+
keep = "No — keep it in memory for this session only"
|
|
2858
|
+
write = "Yes — write it to settings.json (mode 0600)"
|
|
2859
|
+
answer = self.console.settings_choose(
|
|
2860
|
+
"Store this API key?", [keep, write], current=keep)
|
|
2861
|
+
if answer is None:
|
|
2862
|
+
return None
|
|
2863
|
+
self.settings.persist_api_key = answer == write
|
|
2864
|
+
return key
|
|
2865
|
+
if spec is not None and spec.kind in ("bool", "choice"):
|
|
2866
|
+
options = (["on", "off"] if spec.kind == "bool"
|
|
2867
|
+
else list(spec.choices))
|
|
2868
|
+
value = self.console.settings_choose(
|
|
2869
|
+
name, options, current=current,
|
|
2870
|
+
current_label=current_label)
|
|
2871
|
+
return None if value is None else str(value)
|
|
2872
|
+
value = self.console.settings_edit(
|
|
2873
|
+
name, current=current,
|
|
2874
|
+
choices=spec.choices if spec is not None else (),
|
|
2875
|
+
current_label=current_label)
|
|
2876
|
+
if value is None:
|
|
2877
|
+
return None
|
|
2878
|
+
text = value.strip()
|
|
2879
|
+
return None if text.lower() == "exit" else text
|
|
2880
|
+
|
|
2881
|
+
def _ensure_key_for_current_model(self, stage=False):
|
|
2882
|
+
"""Load/ask for and validate the key after a model/url selection."""
|
|
2883
|
+
provider = settings_mod.provider_name(self.settings)
|
|
2884
|
+
key, env, _persisted = self.settings.key_for()
|
|
2885
|
+
if (key or env
|
|
2886
|
+
or (self.settings.api_key and self.settings.key_entered)):
|
|
2887
|
+
before = (self.settings.api_key, self.settings.api_key_env)
|
|
2888
|
+
settings_mod._validate_key(self.console, self.settings, provider)
|
|
2889
|
+
after = (self.settings.api_key, self.settings.api_key_env)
|
|
2890
|
+
if not stage and after != before:
|
|
2891
|
+
# _validate_key prompted for a replacement (or cleared a
|
|
2892
|
+
# rejected key); apply that result to the runtime.
|
|
2893
|
+
self._apply_settings(
|
|
2894
|
+
{"api-key": after[0]}, confirm_cache=False,
|
|
2895
|
+
announce=False)
|
|
2896
|
+
return
|
|
2897
|
+
if provider == "localhost":
|
|
2898
|
+
return
|
|
2899
|
+
key_text = self._read_setting_value("api-key")
|
|
2900
|
+
if not key_text:
|
|
2901
|
+
return
|
|
2902
|
+
self._apply_settings({"api-key": key_text}, confirm_cache=False,
|
|
2903
|
+
announce=False, stage=stage)
|
|
2904
|
+
applied = self.settings.api_key
|
|
2905
|
+
settings_mod._validate_key(self.console, self.settings, provider)
|
|
2906
|
+
if not stage and self.settings.api_key != applied:
|
|
2907
|
+
self._apply_settings(
|
|
2908
|
+
{"api-key": self.settings.api_key}, confirm_cache=False,
|
|
2909
|
+
announce=False)
|
|
2910
|
+
|
|
2911
|
+
def _change_setting_inline(self, row, value, rows):
|
|
2912
|
+
"""Stage a left/right settings change and refresh the visible table."""
|
|
2913
|
+
if not self._apply_settings({row["name"]: value},
|
|
2914
|
+
confirm_cache=False, announce=False,
|
|
2915
|
+
stage=True):
|
|
2916
|
+
return False
|
|
2917
|
+
rows[:] = self.settings.rows()
|
|
2918
|
+
return True
|
|
2919
|
+
|
|
2920
|
+
def _snapshot_settings(self):
|
|
2921
|
+
"""Capture the values needed to cancel a staged settings edit."""
|
|
2922
|
+
return (dict(self.settings.values), self.settings.api_key,
|
|
2923
|
+
self.settings.api_key_env, self.settings.persist_api_key,
|
|
2924
|
+
dict(self.settings.api_keys),
|
|
2925
|
+
dict(self.settings.api_key_envs),
|
|
2926
|
+
set(self.settings.persisted_key_ids),
|
|
2927
|
+
self.settings.key_entered, self.settings.key_asked)
|
|
2928
|
+
|
|
2929
|
+
def _restore_settings(self, snapshot):
|
|
2930
|
+
(values, api_key, api_key_env, persist_api_key, api_keys,
|
|
2931
|
+
api_key_envs, persisted_key_ids, key_entered, key_asked) = snapshot
|
|
2932
|
+
self.settings.values = dict(values)
|
|
2933
|
+
self.settings.api_key = api_key
|
|
2934
|
+
self.settings.api_key_env = api_key_env
|
|
2935
|
+
self.settings.persist_api_key = persist_api_key
|
|
2936
|
+
self.settings.api_keys = dict(api_keys)
|
|
2937
|
+
self.settings.api_key_envs = dict(api_key_envs)
|
|
2938
|
+
self.settings.persisted_key_ids = set(persisted_key_ids)
|
|
2939
|
+
self.settings.key_entered = key_entered
|
|
2940
|
+
self.settings.key_asked = key_asked
|
|
2941
|
+
|
|
2942
|
+
def _commit_staged_settings(self, snapshot):
|
|
2943
|
+
"""Apply all staged changes to the runtime and persist them."""
|
|
2944
|
+
(values, api_key, api_key_env, persist_api_key, _api_keys,
|
|
2945
|
+
_api_key_envs, _persisted_key_ids, _key_entered,
|
|
2946
|
+
_key_asked) = snapshot
|
|
2947
|
+
parsed = []
|
|
2948
|
+
for spec in settings_mod.SPECS:
|
|
2949
|
+
if spec.attr == "api_key":
|
|
2950
|
+
if (self.settings.api_key != api_key
|
|
2951
|
+
or self.settings.persist_api_key != persist_api_key
|
|
2952
|
+
or self.settings.api_key_env != api_key_env):
|
|
2953
|
+
parsed.append((spec, self.settings.api_key))
|
|
2954
|
+
continue
|
|
2955
|
+
value = self.settings.values.get(spec.attr, spec.default)
|
|
2956
|
+
if value != values.get(spec.attr):
|
|
2957
|
+
parsed.append((spec, value))
|
|
2958
|
+
if not parsed:
|
|
2959
|
+
self._save_settings()
|
|
2960
|
+
return True
|
|
2961
|
+
return self._apply_parsed_settings(
|
|
2962
|
+
parsed, {spec.name for spec, _ in parsed}, announce=False)
|
|
2963
|
+
|
|
2964
|
+
def _apply_settings(self, changes, confirm_cache=True, announce=True,
|
|
2965
|
+
stage=False):
|
|
2966
|
+
"""Validate and apply (or stage) one or more settings.
|
|
2967
|
+
|
|
2968
|
+
Cache-impacting changes are applied as one transaction, so a batch of
|
|
2969
|
+
tool/prompt edits rebuilds the prompt once. ``stage`` keeps the change
|
|
2970
|
+
in ``settings.values`` without touching the runtime or the disk; the
|
|
2971
|
+
TUI settings menu commits the batch with ``s``.
|
|
2972
|
+
"""
|
|
2973
|
+
parsed = []
|
|
2974
|
+
for name, raw in changes.items():
|
|
2975
|
+
canonical = settings_mod.BY_NAME.get(name)
|
|
2976
|
+
if canonical is None:
|
|
2977
|
+
canonical = settings_mod.BY_NAME.get(
|
|
2978
|
+
settings_mod.ALIASES.get(name, ""))
|
|
2979
|
+
if canonical is None:
|
|
2980
|
+
self.console.note(f"Unknown setting {name!r}.", "warn")
|
|
2981
|
+
return False
|
|
2982
|
+
if not canonical.mutable:
|
|
2983
|
+
self.console.note(f"{canonical.name} cannot be changed.",
|
|
2984
|
+
"warn")
|
|
2985
|
+
return False
|
|
2986
|
+
try:
|
|
2987
|
+
value = settings_mod.parse_value(canonical, raw)
|
|
2988
|
+
except (TypeError, ValueError) as exc:
|
|
2989
|
+
self.console.note(f"{canonical.name}: {exc}", "warn")
|
|
2990
|
+
return False
|
|
2991
|
+
parsed.append((canonical, value))
|
|
2992
|
+
|
|
2993
|
+
if stage:
|
|
2994
|
+
for spec, value in parsed:
|
|
2995
|
+
if spec.attr == "api_key":
|
|
2996
|
+
self.settings.api_key = value
|
|
2997
|
+
self.settings.key_entered = True
|
|
2998
|
+
self.settings.remember_key()
|
|
2999
|
+
else:
|
|
3000
|
+
self.settings.values[spec.attr] = value
|
|
3001
|
+
names = {spec.attr for spec, _ in parsed}
|
|
3002
|
+
if ("api-key" not in names and names & {"model", "url"}
|
|
3003
|
+
and not self.settings.key_entered):
|
|
3004
|
+
# A different model can have its own stored key. If it has
|
|
3005
|
+
# none, do not silently keep another model's key; the menu
|
|
3006
|
+
# will ask for one. An explicit CLI/env/typed key wins over a
|
|
3007
|
+
# stored key for the new model.
|
|
3008
|
+
if not self.settings.load_key_for():
|
|
3009
|
+
self.settings.api_key = ""
|
|
3010
|
+
self.settings.api_key_env = ""
|
|
3011
|
+
self.settings.persist_api_key = False
|
|
3012
|
+
return True
|
|
3013
|
+
|
|
3014
|
+
cache_effects = {spec.cache for spec, _ in parsed
|
|
3015
|
+
if spec.cache != "none"}
|
|
3016
|
+
if confirm_cache and cache_effects:
|
|
3017
|
+
answer = self.console.read_line(
|
|
3018
|
+
"Changing " + ", ".join(sorted(cache_effects)) +
|
|
3019
|
+
" rebuilds the generated system prompt/tool list and "
|
|
3020
|
+
"invalidates the LLM prompt cache for the next request. "
|
|
3021
|
+
"Apply now? [y/N] ")
|
|
3022
|
+
if answer is None or answer.strip().lower() not in ("y", "yes"):
|
|
3023
|
+
self.console.note("Settings were not applied.", "warn")
|
|
3024
|
+
return False
|
|
3025
|
+
|
|
3026
|
+
return self._apply_parsed_settings(
|
|
3027
|
+
parsed, {spec.name for spec, _ in parsed}, announce=announce)
|
|
3028
|
+
|
|
3029
|
+
def _apply_parsed_settings(self, parsed, changed_names=None, announce=True):
|
|
3030
|
+
"""Apply already-validated values and rebuild what they affect."""
|
|
3031
|
+
changed_names = set(changed_names or ())
|
|
3032
|
+
cache_effects = {spec.cache for spec, _ in parsed
|
|
3033
|
+
if spec.cache != "none"}
|
|
3034
|
+
old_model = self.model
|
|
3035
|
+
for spec, value in parsed:
|
|
3036
|
+
if spec.attr == "api_key":
|
|
3037
|
+
self.settings.api_key = value
|
|
3038
|
+
self.settings.key_entered = True
|
|
3039
|
+
# persist_api_key is set by _read_setting_value; an inline
|
|
3040
|
+
# /settings api-key value is not persisted unless confirmed.
|
|
3041
|
+
self.settings.remember_key()
|
|
3042
|
+
else:
|
|
3043
|
+
self.settings.values[spec.attr] = value
|
|
3044
|
+
if ("api-key" not in changed_names and changed_names & {"model", "url"}
|
|
3045
|
+
and not self.settings.key_entered):
|
|
3046
|
+
# Load the stored key for the newly selected endpoint/model. If
|
|
3047
|
+
# there is none, drop a key that belonged to the previous model.
|
|
3048
|
+
# An explicit CLI/env/typed key wins over a stored key.
|
|
3049
|
+
if not self.settings.load_key_for():
|
|
3050
|
+
self.settings.api_key = ""
|
|
3051
|
+
self.settings.api_key_env = ""
|
|
3052
|
+
self.settings.persist_api_key = False
|
|
3053
|
+
self.settings.apply_to_args(self.args)
|
|
3054
|
+
self.console.verbose = bool(getattr(self.args, "verbose", False))
|
|
3055
|
+
self.server_url = str(self.args.url).rstrip("/")
|
|
3056
|
+
self.api_key = self.args.api_key or ""
|
|
3057
|
+
if self.args.model:
|
|
3058
|
+
self.model = self.args.model
|
|
3059
|
+
elif old_model and "model" not in changed_names:
|
|
3060
|
+
self.model = old_model
|
|
3061
|
+
else:
|
|
3062
|
+
self.model = self._resolve_model(self.args)
|
|
3063
|
+
|
|
3064
|
+
self.plan_strategy = self.args.plan_strategy or planning.DEFAULT_PLAN_STRATEGY
|
|
3065
|
+
if self.plan_strategy not in planning.PLAN_STRATEGIES:
|
|
3066
|
+
self.plan_strategy = planning.DEFAULT_PLAN_STRATEGY
|
|
3067
|
+
# Plan mode is its own on/off setting; choosing a strategy does not
|
|
3068
|
+
# silently enable it (the CLI --plan-strategy implication is handled
|
|
3069
|
+
# once at startup, not by every settings edit).
|
|
3070
|
+
self.plan_mode = bool(self.args.plan)
|
|
3071
|
+
self.allow_nudge = bool(self.args.allow_nudge)
|
|
3072
|
+
self.nudge_limit = max(0, int(self.args.nudge_limit))
|
|
3073
|
+
self.strict_verify = bool(getattr(self.args, "strict_verify", False))
|
|
3074
|
+
self.runtime_strategy = recovery.normalise(
|
|
3075
|
+
getattr(self.args, "runtime_strategy",
|
|
3076
|
+
recovery.DEFAULT_RUNTIME_STRATEGY))
|
|
3077
|
+
self._reset_runtime_recovery()
|
|
3078
|
+
self._runtime_pending_prompt = None
|
|
3079
|
+
self._runtime_pending_replan = False
|
|
3080
|
+
self.compaction_strategy = self.args.compaction_strategy
|
|
3081
|
+
if not compaction_mod.is_strategy(self.compaction_strategy):
|
|
3082
|
+
self.compaction_strategy = compaction_mod.DEFAULT_COMPACTION_STRATEGY
|
|
3083
|
+
self.scratchpad = bool(self.args.scratchpad)
|
|
3084
|
+
self.dynamic_todo_tracking = bool(
|
|
3085
|
+
getattr(self.args, "dynamic_todo_tracking", False))
|
|
3086
|
+
|
|
3087
|
+
if ("model" in changed_names
|
|
3088
|
+
and self.settings.values.get("max_tokens") is None):
|
|
3089
|
+
self.args.max_tokens = default_max_output_tokens(self.model)
|
|
3090
|
+
self._register_tools(self.args)
|
|
3091
|
+
self._prepare_agent_files()
|
|
3092
|
+
if getattr(self, "plan_manager", None) is not None:
|
|
3093
|
+
goal = getattr(self.plan_manager, "goal", None)
|
|
3094
|
+
self.plan_manager = plan_utils.PlanManager(
|
|
3095
|
+
self.session_dir, enabled=self.plan_mode, goal=goal)
|
|
3096
|
+
self.compaction_budget = compaction_budget(
|
|
3097
|
+
model=self.model,
|
|
3098
|
+
explicit_limit=getattr(self.args, "max_context_tokens", None),
|
|
3099
|
+
max_output_tokens=getattr(self.args, "max_tokens", None),
|
|
3100
|
+
)
|
|
3101
|
+
if getattr(self, "messages", None) and not self.args.system_prompt:
|
|
3102
|
+
self.messages[0]["content"] = self._render_system_prompt()
|
|
3103
|
+
elif (announce and cache_effects & {"tools", "prompt"}
|
|
3104
|
+
and self.args.system_prompt):
|
|
3105
|
+
self.console.note(
|
|
3106
|
+
"The custom system prompt is kept verbatim; tool/prompt "
|
|
3107
|
+
"changes affect the tool registry only.", "warn")
|
|
3108
|
+
self.settings.capture_from_args(self.args)
|
|
3109
|
+
self._save_settings()
|
|
3110
|
+
if self.tui_active:
|
|
3111
|
+
# Permission/shell/planning/model lines live in the static header
|
|
3112
|
+
# summary; refresh them after any applied settings change.
|
|
3113
|
+
self.console.set_summary(self._tui_header_lines())
|
|
3114
|
+
if announce:
|
|
3115
|
+
self.console.note("Settings updated.", "ok")
|
|
3116
|
+
return True
|
|
3117
|
+
|
|
3118
|
+
def _stage_all_preset(self):
|
|
3119
|
+
for attr, value in settings_mod.ALL_PRESET.items():
|
|
3120
|
+
self.settings.values[attr] = value
|
|
3121
|
+
|
|
3122
|
+
def _stage_super_preset(self):
|
|
3123
|
+
for attr, value in settings_mod.SUPER_PRESET.items():
|
|
3124
|
+
self.settings.values[attr] = value
|
|
3125
|
+
|
|
3126
|
+
def _apply_super_settings(self):
|
|
3127
|
+
self._stage_super_preset()
|
|
3128
|
+
parsed = [(spec, self.settings.values.get(spec.attr, spec.default))
|
|
3129
|
+
for spec in settings_mod.SPECS if spec.attr != "api_key"]
|
|
3130
|
+
self._apply_parsed_settings(
|
|
3131
|
+
parsed, {spec.name for spec, _ in parsed}, announce=False)
|
|
3132
|
+
self.console.note("--super preset applied.", "ok")
|
|
3133
|
+
|
|
3134
|
+
def _apply_all_settings(self):
|
|
3135
|
+
self._stage_all_preset()
|
|
3136
|
+
parsed = [(spec, self.settings.values.get(spec.attr, spec.default))
|
|
3137
|
+
for spec in settings_mod.SPECS if spec.attr != "api_key"]
|
|
3138
|
+
self._apply_parsed_settings(
|
|
3139
|
+
parsed, {spec.name for spec, _ in parsed}, announce=False)
|
|
3140
|
+
self.console.note("--all preset applied.", "ok")
|
|
3141
|
+
|
|
3142
|
+
def _apply_default_settings(self):
|
|
3143
|
+
"""Reset ordinary settings to defaults, keeping the API key."""
|
|
3144
|
+
self.settings.reset_to_defaults()
|
|
3145
|
+
parsed = [(spec, self.settings.values.get(spec.attr, spec.default))
|
|
3146
|
+
for spec in settings_mod.SPECS if spec.attr != "api_key"]
|
|
3147
|
+
self._apply_parsed_settings(
|
|
3148
|
+
parsed, {spec.name for spec, _ in parsed}, announce=False)
|
|
3149
|
+
self.console.note("Settings reset to defaults (API key kept).", "ok")
|
|
3150
|
+
|
|
3151
|
+
def _adopt_settings(self, settings):
|
|
3152
|
+
"""Replace the session's settings and rebuild everything they affect.
|
|
3153
|
+
|
|
3154
|
+
Called only after the resume/new-session decision: startup runs with
|
|
3155
|
+
CLI/environment/defaults so it cannot print or prompt with stale
|
|
3156
|
+
previous-session settings.
|
|
3157
|
+
"""
|
|
3158
|
+
self.settings = settings
|
|
3159
|
+
parsed = [(spec, settings.values.get(spec.attr, spec.default))
|
|
3160
|
+
for spec in settings_mod.SPECS if spec.attr != "api_key"]
|
|
3161
|
+
if parsed:
|
|
3162
|
+
self._apply_parsed_settings(
|
|
3163
|
+
parsed, {spec.name for spec, _ in parsed}, announce=False)
|
|
3164
|
+
else:
|
|
3165
|
+
settings.apply_to_args(self.args)
|
|
3166
|
+
self._save_settings()
|
|
3167
|
+
return settings
|
|
3168
|
+
|
|
3169
|
+
def _handle_settings_command(self, arg):
|
|
3170
|
+
arg = (arg or "").strip()
|
|
3171
|
+
preset = arg.lower()
|
|
3172
|
+
tui_preset = preset in ("all", "a", "default", "def", "super")
|
|
3173
|
+
if ((not arg or tui_preset) and self.tui_active
|
|
3174
|
+
and hasattr(self.console, "settings_pick")):
|
|
3175
|
+
immutable = [f"{name}: cannot change ({desc})"
|
|
3176
|
+
for name, desc in settings_mod.IMMUTABLE]
|
|
3177
|
+
snapshot = self._snapshot_settings()
|
|
3178
|
+
state = {"dirty": False}
|
|
3179
|
+
selected = 0
|
|
3180
|
+
if preset in ("default", "def"):
|
|
3181
|
+
# Stage defaults so the user can review/save or cancel them.
|
|
3182
|
+
self.settings.reset_to_defaults()
|
|
3183
|
+
state["dirty"] = True
|
|
3184
|
+
elif preset in ("all", "a"):
|
|
3185
|
+
# Stage the same feature flags as the CLI --all preset.
|
|
3186
|
+
self._stage_all_preset()
|
|
3187
|
+
elif preset == "super":
|
|
3188
|
+
self._stage_super_preset()
|
|
3189
|
+
state["dirty"] = True
|
|
3190
|
+
|
|
3191
|
+
def stage_change(row, value, rows):
|
|
3192
|
+
if not self._change_setting_inline(row, value, rows):
|
|
3193
|
+
return False
|
|
3194
|
+
state["dirty"] = True
|
|
3195
|
+
return True
|
|
3196
|
+
|
|
3197
|
+
def defaults(rows):
|
|
3198
|
+
self.settings.reset_to_defaults()
|
|
3199
|
+
state["dirty"] = True
|
|
3200
|
+
rows[:] = self.settings.rows()
|
|
3201
|
+
self.console.note(
|
|
3202
|
+
"Defaults staged (API key kept); press s to save.", "info")
|
|
3203
|
+
|
|
3204
|
+
def all_preset(rows):
|
|
3205
|
+
self._stage_all_preset()
|
|
3206
|
+
state["dirty"] = True
|
|
3207
|
+
rows[:] = self.settings.rows()
|
|
3208
|
+
self.console.note(
|
|
3209
|
+
"--all preset staged; press s to save.", "info")
|
|
3210
|
+
|
|
3211
|
+
def super_preset(rows):
|
|
3212
|
+
self._stage_super_preset()
|
|
3213
|
+
state["dirty"] = True
|
|
3214
|
+
rows[:] = self.settings.rows()
|
|
3215
|
+
self.console.note(
|
|
3216
|
+
"--super preset staged; press s to save.", "info")
|
|
3217
|
+
|
|
3218
|
+
def save(rows):
|
|
3219
|
+
nonlocal snapshot
|
|
3220
|
+
if not self._commit_staged_settings(snapshot):
|
|
3221
|
+
self.console.note("Could not save settings.", "error")
|
|
3222
|
+
return
|
|
3223
|
+
state["dirty"] = False
|
|
3224
|
+
# Later cancels must restore to the last *saved* state, not
|
|
3225
|
+
# to the state that existed when the menu first opened.
|
|
3226
|
+
snapshot = self._snapshot_settings()
|
|
3227
|
+
rows[:] = self.settings.rows()
|
|
3228
|
+
self.console.note("Settings saved.", "ok")
|
|
3229
|
+
|
|
3230
|
+
while True:
|
|
3231
|
+
row = self.console.settings_pick(
|
|
3232
|
+
self.settings.rows(), immutable, selected=selected,
|
|
3233
|
+
on_change=stage_change, on_save=save,
|
|
3234
|
+
dirty=lambda: state["dirty"], on_defaults=defaults,
|
|
3235
|
+
on_all=all_preset, on_super=super_preset)
|
|
3236
|
+
if row is None:
|
|
3237
|
+
if not state["dirty"]:
|
|
3238
|
+
return
|
|
3239
|
+
choice = self.console.settings_choose(
|
|
3240
|
+
"Unsaved settings",
|
|
3241
|
+
["Save and quit", "Cancel changes and quit"],
|
|
3242
|
+
current="Save and quit")
|
|
3243
|
+
if choice is None:
|
|
3244
|
+
# Esc/exit from the prompt: stay in the menu.
|
|
3245
|
+
continue
|
|
3246
|
+
if choice == "Save and quit":
|
|
3247
|
+
if self._commit_staged_settings(snapshot):
|
|
3248
|
+
return
|
|
3249
|
+
continue
|
|
3250
|
+
self._restore_settings(snapshot)
|
|
3251
|
+
return
|
|
3252
|
+
selected = max(0, row["number"] - 1)
|
|
3253
|
+
if not row["mutable"]:
|
|
3254
|
+
self.console.note(f"{row['name']} cannot be changed.",
|
|
3255
|
+
"warn")
|
|
3256
|
+
continue
|
|
3257
|
+
raw = self._read_setting_value(row["name"])
|
|
3258
|
+
if raw is None or raw == "":
|
|
3259
|
+
continue
|
|
3260
|
+
if not self._apply_settings({row["name"]: raw},
|
|
3261
|
+
confirm_cache=False,
|
|
3262
|
+
announce=False, stage=True):
|
|
3263
|
+
continue
|
|
3264
|
+
state["dirty"] = True
|
|
3265
|
+
if row["name"] in ("model", "url"):
|
|
3266
|
+
self._ensure_key_for_current_model(stage=True)
|
|
3267
|
+
return
|
|
3268
|
+
if preset in ("default", "def"):
|
|
3269
|
+
self._apply_default_settings()
|
|
3270
|
+
return
|
|
3271
|
+
if preset in ("all", "a"):
|
|
3272
|
+
self._apply_all_settings()
|
|
3273
|
+
return
|
|
3274
|
+
if preset == "super":
|
|
3275
|
+
self._apply_super_settings()
|
|
3276
|
+
return
|
|
3277
|
+
if not arg:
|
|
3278
|
+
for line in self._settings_lines():
|
|
3279
|
+
self.console.emit(line)
|
|
3280
|
+
self.console.emit(
|
|
3281
|
+
"Use /settings <number|name> <value> or type it at the "
|
|
3282
|
+
"settings prompt. Type q to leave; cache-impacting values "
|
|
3283
|
+
"are staged until 'apply'.")
|
|
3284
|
+
pending = {}
|
|
3285
|
+
while True:
|
|
3286
|
+
line = self.console.read_line("settings> ")
|
|
3287
|
+
if line is None:
|
|
3288
|
+
return
|
|
3289
|
+
text = line.strip()
|
|
3290
|
+
if not text:
|
|
3291
|
+
continue
|
|
3292
|
+
if text.lower() in ("q", "quit", "exit"):
|
|
3293
|
+
if pending:
|
|
3294
|
+
self.console.note("Pending settings discarded.", "warn")
|
|
3295
|
+
return
|
|
3296
|
+
if text.lower() == "apply":
|
|
3297
|
+
if pending:
|
|
3298
|
+
self._apply_settings(pending)
|
|
3299
|
+
pending = {}
|
|
3300
|
+
continue
|
|
3301
|
+
parts = text.split(None, 1)
|
|
3302
|
+
key = parts[0]
|
|
3303
|
+
if key.isdigit():
|
|
3304
|
+
try:
|
|
3305
|
+
row = self.settings.by_number(key)
|
|
3306
|
+
except (ValueError, TypeError) as exc:
|
|
3307
|
+
self.console.note(str(exc), "warn")
|
|
3308
|
+
continue
|
|
3309
|
+
key = row["name"]
|
|
3310
|
+
raw = parts[1] if len(parts) > 1 else None
|
|
3311
|
+
spec = settings_mod.BY_NAME.get(key) or settings_mod.BY_NAME.get(
|
|
3312
|
+
settings_mod.ALIASES.get(key, ""))
|
|
3313
|
+
if spec is None:
|
|
3314
|
+
self.console.note(f"Unknown setting {key!r}.", "warn")
|
|
3315
|
+
continue
|
|
3316
|
+
if not spec.mutable:
|
|
3317
|
+
self.console.note(f"{spec.name} cannot be changed.", "warn")
|
|
3318
|
+
continue
|
|
3319
|
+
if raw is None:
|
|
3320
|
+
raw = self._read_setting_value(spec.name)
|
|
3321
|
+
if raw is None or raw == "":
|
|
3322
|
+
continue
|
|
3323
|
+
if spec.cache != "none":
|
|
3324
|
+
pending[spec.name] = raw
|
|
3325
|
+
self.console.note(
|
|
3326
|
+
f"{spec.name} staged (cache: {spec.cache}); type "
|
|
3327
|
+
f"'apply' to commit.", "info")
|
|
3328
|
+
else:
|
|
3329
|
+
self._apply_settings({spec.name: raw}, confirm_cache=False)
|
|
3330
|
+
return
|
|
3331
|
+
|
|
3332
|
+
parts = arg.split(None, 1)
|
|
3333
|
+
key = parts[0]
|
|
3334
|
+
if key.isdigit():
|
|
3335
|
+
try:
|
|
3336
|
+
key = self.settings.by_number(key)["name"]
|
|
3337
|
+
except (ValueError, TypeError) as exc:
|
|
3338
|
+
self.console.note(str(exc), "warn")
|
|
3339
|
+
return
|
|
3340
|
+
raw = parts[1] if len(parts) > 1 else None
|
|
3341
|
+
spec = settings_mod.BY_NAME.get(key) or settings_mod.BY_NAME.get(
|
|
3342
|
+
settings_mod.ALIASES.get(key, ""))
|
|
3343
|
+
if spec is None:
|
|
3344
|
+
self.console.note(f"Unknown setting {key!r}.", "warn")
|
|
3345
|
+
return
|
|
3346
|
+
if not spec.mutable:
|
|
3347
|
+
self.console.note(f"{spec.name} cannot be changed.", "warn")
|
|
3348
|
+
return
|
|
3349
|
+
if raw is None:
|
|
3350
|
+
raw = self._read_setting_value(spec.name)
|
|
3351
|
+
if raw is None or raw == "":
|
|
3352
|
+
return
|
|
3353
|
+
self._apply_settings({spec.name: raw}, confirm_cache=True)
|
|
3354
|
+
if spec.name in ("model", "url"):
|
|
3355
|
+
self._ensure_key_for_current_model(stage=False)
|
|
3356
|
+
|
|
2370
3357
|
def _run_skipped_plan(self, prompt):
|
|
2371
3358
|
"""Handle ``/skip-plan PROMPT``: run the prompt without planning it."""
|
|
2372
3359
|
prompt = (prompt or "").strip()
|
|
@@ -2581,7 +3568,7 @@ class AgentSession:
|
|
|
2581
3568
|
last_role = last_text = None
|
|
2582
3569
|
for m in reversed(self.messages):
|
|
2583
3570
|
role = m.get("role")
|
|
2584
|
-
content = m.get("content")
|
|
3571
|
+
content = media.content_text(m.get("content"))
|
|
2585
3572
|
if role == "assistant" and not m.get("tool_calls") and content:
|
|
2586
3573
|
last_role, last_text = "Assistant", content
|
|
2587
3574
|
break
|
|
@@ -2595,6 +3582,97 @@ class AgentSession:
|
|
|
2595
3582
|
|
|
2596
3583
|
# -- tool execution ----------------------------------------------------
|
|
2597
3584
|
|
|
3585
|
+
def _reset_runtime_recovery(self):
|
|
3586
|
+
"""Forget the current consecutive-failure streak (not the prompt cap)."""
|
|
3587
|
+
self._runtime_fail_key = None
|
|
3588
|
+
self._runtime_fail_key_count = 0
|
|
3589
|
+
self._runtime_fail_tool = None
|
|
3590
|
+
self._runtime_fail_tool_count = 0
|
|
3591
|
+
|
|
3592
|
+
def _note_tool_outcome(self, name, params, result):
|
|
3593
|
+
"""Track consecutive tool failures for the runtime strategy.
|
|
3594
|
+
|
|
3595
|
+
A success is progress and resets the streak. A failure counts towards
|
|
3596
|
+
two streaks: the *same call* (tool + normalised arguments) and the same
|
|
3597
|
+
*tool* with different arguments. Either reaching three triggers one
|
|
3598
|
+
recovery prompt, at most ``MAX_PROMPTS_PER_TURN`` times per turn.
|
|
3599
|
+
"""
|
|
3600
|
+
if self.runtime_strategy == recovery.NORMAL:
|
|
3601
|
+
return
|
|
3602
|
+
if not recovery.tool_result_failed(result):
|
|
3603
|
+
self._reset_runtime_recovery()
|
|
3604
|
+
return
|
|
3605
|
+
|
|
3606
|
+
key = recovery.approach_key(name, params)
|
|
3607
|
+
if key == self._runtime_fail_key:
|
|
3608
|
+
self._runtime_fail_key_count += 1
|
|
3609
|
+
else:
|
|
3610
|
+
self._runtime_fail_key = key
|
|
3611
|
+
self._runtime_fail_key_count = 1
|
|
3612
|
+
if name == self._runtime_fail_tool:
|
|
3613
|
+
self._runtime_fail_tool_count += 1
|
|
3614
|
+
else:
|
|
3615
|
+
self._runtime_fail_tool = name
|
|
3616
|
+
self._runtime_fail_tool_count = 1
|
|
3617
|
+
|
|
3618
|
+
if (self._runtime_prompts_this_turn
|
|
3619
|
+
>= recovery.MAX_PROMPTS_PER_TURN):
|
|
3620
|
+
return
|
|
3621
|
+
same_call = (self._runtime_fail_key_count
|
|
3622
|
+
>= recovery.FAILURE_THRESHOLD)
|
|
3623
|
+
same_tool = (self._runtime_fail_tool_count
|
|
3624
|
+
>= recovery.FAILURE_THRESHOLD)
|
|
3625
|
+
if not (same_call or same_tool):
|
|
3626
|
+
return
|
|
3627
|
+
|
|
3628
|
+
attempts = max(self._runtime_fail_key_count,
|
|
3629
|
+
self._runtime_fail_tool_count)
|
|
3630
|
+
can_search = any(
|
|
3631
|
+
tool_name in getattr(self, "tools_dict", {})
|
|
3632
|
+
for tool_name in ("web_search", "read_website"))
|
|
3633
|
+
self._runtime_pending_prompt = recovery.recovery_prompt(
|
|
3634
|
+
name, attempts, same_call=same_call, result=result,
|
|
3635
|
+
can_search=can_search)
|
|
3636
|
+
self._runtime_pending_replan = (
|
|
3637
|
+
self.runtime_strategy == recovery.PROMPT_CHANGE_PLAN)
|
|
3638
|
+
self._runtime_prompts_this_turn += 1
|
|
3639
|
+
# Start a new streak after speaking up: the next prompt should describe
|
|
3640
|
+
# the next three failures, not keep firing on the same one.
|
|
3641
|
+
self._runtime_fail_key = None
|
|
3642
|
+
self._runtime_fail_key_count = 0
|
|
3643
|
+
self._runtime_fail_tool = None
|
|
3644
|
+
self._runtime_fail_tool_count = 0
|
|
3645
|
+
|
|
3646
|
+
def _inject_runtime_recovery(self):
|
|
3647
|
+
"""Append the pending recovery prompt (and re-plan when configured).
|
|
3648
|
+
|
|
3649
|
+
Called after a whole tool batch so a batch with several calls produces
|
|
3650
|
+
one message, not one per call.
|
|
3651
|
+
"""
|
|
3652
|
+
prompt = self._runtime_pending_prompt
|
|
3653
|
+
if not prompt:
|
|
3654
|
+
return
|
|
3655
|
+
self._runtime_pending_prompt = None
|
|
3656
|
+
self.console.note(
|
|
3657
|
+
"Repeated failed tool use; prompting a change of approach.", "warn")
|
|
3658
|
+
self.messages.append({"role": "user", "content": prompt})
|
|
3659
|
+
if self._runtime_pending_replan:
|
|
3660
|
+
self._runtime_pending_replan = False
|
|
3661
|
+
self._generate_recovery_plan()
|
|
3662
|
+
|
|
3663
|
+
def _generate_recovery_plan(self):
|
|
3664
|
+
"""Start a fresh planning session after repeated failures."""
|
|
3665
|
+
goal = (getattr(self.plan_manager, "goal", "")
|
|
3666
|
+
or getattr(self, "_turn_goal", ""))
|
|
3667
|
+
if not str(goal or "").strip():
|
|
3668
|
+
self.console.note(
|
|
3669
|
+
"No current goal is recorded; skipping the recovery plan.",
|
|
3670
|
+
"warn")
|
|
3671
|
+
return
|
|
3672
|
+
self.console.note(
|
|
3673
|
+
"Starting a fresh plan after repeated failed attempts.", "info")
|
|
3674
|
+
self._generate_plan_and_inject(goal, recovery=True)
|
|
3675
|
+
|
|
2598
3676
|
def _run_tool_calls(self, tool_calls):
|
|
2599
3677
|
self.console.note(f"LLM is trying to call {len(tool_calls)} tool(s).", "info")
|
|
2600
3678
|
# Show a "… calling tool" spinner (in-place, non-scrolling) while the
|
|
@@ -2603,14 +3681,25 @@ class AgentSession:
|
|
|
2603
3681
|
|
|
2604
3682
|
try:
|
|
2605
3683
|
for call in tool_calls:
|
|
2606
|
-
|
|
3684
|
+
function = (call or {}).get("function") or {}
|
|
3685
|
+
name = function.get("name", "?")
|
|
3686
|
+
try:
|
|
3687
|
+
params = json.loads(function.get("arguments") or "{}")
|
|
3688
|
+
except (json.JSONDecodeError, TypeError):
|
|
3689
|
+
params = {}
|
|
3690
|
+
if not isinstance(params, dict):
|
|
3691
|
+
params = {}
|
|
2607
3692
|
self._begin_activity(f"running tool {name}")
|
|
3693
|
+
self._last_tool_result_text = ""
|
|
2608
3694
|
try:
|
|
2609
3695
|
self._run_one_tool_call(call)
|
|
2610
3696
|
finally:
|
|
2611
3697
|
self._end_activity()
|
|
3698
|
+
self._note_tool_outcome(name, params,
|
|
3699
|
+
self._last_tool_result_text)
|
|
2612
3700
|
finally:
|
|
2613
3701
|
self.console.stop_tool_call()
|
|
3702
|
+
self._inject_runtime_recovery()
|
|
2614
3703
|
|
|
2615
3704
|
def _run_one_tool_call(self, call):
|
|
2616
3705
|
|
|
@@ -2670,6 +3759,25 @@ class AgentSession:
|
|
|
2670
3759
|
f"Error: File operation not allowed outside allowed directory: {self.allowed_dir}")
|
|
2671
3760
|
return
|
|
2672
3761
|
|
|
3762
|
+
# 1b) read_file on a raster image: text tools cannot represent it, so
|
|
3763
|
+
# attach the image as a user content block after the tool result.
|
|
3764
|
+
if name == "read_file":
|
|
3765
|
+
image_path = tool_params.get("file_path")
|
|
3766
|
+
if media.is_image_path(image_path):
|
|
3767
|
+
try:
|
|
3768
|
+
text, ref = self._attach_image_from_read(image_path)
|
|
3769
|
+
except (OSError, ValueError) as exc:
|
|
3770
|
+
self._append_tool_result(
|
|
3771
|
+
call_id, f"Error: could not read image {image_path}: {exc}")
|
|
3772
|
+
return
|
|
3773
|
+
self._append_tool_result(call_id, text)
|
|
3774
|
+
self.messages.append({
|
|
3775
|
+
"role": "user",
|
|
3776
|
+
"content": media.user_content(
|
|
3777
|
+
f"Image read from the task: {image_path}", [ref]),
|
|
3778
|
+
})
|
|
3779
|
+
return
|
|
3780
|
+
|
|
2673
3781
|
# 2) Shell-safety classifier (DENY / ASK / ALLOW), always enforced.
|
|
2674
3782
|
background_action = (str(tool_params.get("action", "")).lower()
|
|
2675
3783
|
if name == "background" else "")
|
|
@@ -2792,6 +3900,7 @@ class AgentSession:
|
|
|
2792
3900
|
raise _Abort
|
|
2793
3901
|
|
|
2794
3902
|
def _append_tool_result(self, call_id, content):
|
|
3903
|
+
self._last_tool_result_text = str(content)
|
|
2795
3904
|
self.messages.append({"role": "tool", "tool_call_id": call_id, "content": str(content)})
|
|
2796
3905
|
|
|
2797
3906
|
def _print_assistant(self, text):
|
|
@@ -2849,6 +3958,13 @@ class AgentSession:
|
|
|
2849
3958
|
self.background_tasks.shutdown()
|
|
2850
3959
|
self._exit_background = max(
|
|
2851
3960
|
getattr(self, "_exit_background", 0), background_cancelled)
|
|
3961
|
+
if not getattr(self, "_session_started", False):
|
|
3962
|
+
# The user exited before a session was created (e.g. during the
|
|
3963
|
+
# resume/settings questions). There is nothing to persist, but the
|
|
3964
|
+
# good-bye box must still be shown.
|
|
3965
|
+
if farewell:
|
|
3966
|
+
self._farewell_no_session()
|
|
3967
|
+
return
|
|
2852
3968
|
self._persist()
|
|
2853
3969
|
segments = history_segment_indices(self.session_dir)
|
|
2854
3970
|
# List what is really on disk. The old message claimed
|
|
@@ -2872,6 +3988,13 @@ class AgentSession:
|
|
|
2872
3988
|
if farewell:
|
|
2873
3989
|
self._farewell(segments)
|
|
2874
3990
|
|
|
3991
|
+
def _farewell_no_session(self):
|
|
3992
|
+
"""Print a good-bye box when the user exits before a session starts."""
|
|
3993
|
+
if self._farewell_shown:
|
|
3994
|
+
return
|
|
3995
|
+
self._farewell_shown = True
|
|
3996
|
+
print_no_session_farewell(self.console, self.model, self.started_at)
|
|
3997
|
+
|
|
2875
3998
|
def _farewell(self, segments=None):
|
|
2876
3999
|
"""Print the good-bye box: version, sign-off and what the session left.
|
|
2877
4000
|
|
|
@@ -2898,15 +4021,6 @@ class AgentSession:
|
|
|
2898
4021
|
turns = len(self.summary)
|
|
2899
4022
|
usage = self.total_usage or {}
|
|
2900
4023
|
|
|
2901
|
-
def count(key):
|
|
2902
|
-
# A display detail on the exit path must never raise: a server that
|
|
2903
|
-
# reported ``null`` usage leaves a None here, and crashing while
|
|
2904
|
-
# saying goodbye would be the worst possible time to fail.
|
|
2905
|
-
try:
|
|
2906
|
-
return int(usage.get(key) or 0)
|
|
2907
|
-
except (TypeError, ValueError):
|
|
2908
|
-
return 0
|
|
2909
|
-
|
|
2910
4024
|
elapsed = max(time.monotonic() - getattr(self, "started_at",
|
|
2911
4025
|
time.monotonic()), 0.0)
|
|
2912
4026
|
hours, remainder = divmod(int(elapsed), 3600)
|
|
@@ -2922,11 +4036,11 @@ class AgentSession:
|
|
|
2922
4036
|
f"{plural(len(self.messages), 'message')}"),
|
|
2923
4037
|
("conversation", plural(turns, "recorded turn")),
|
|
2924
4038
|
("duration", duration),
|
|
2925
|
-
("tokens", f"{
|
|
2926
|
-
f"{
|
|
2927
|
-
f"({
|
|
2928
|
-
("calls", f"{
|
|
2929
|
-
f"{
|
|
4039
|
+
("tokens", f"{usage_int(usage, 'prompt_tokens'):,} in / "
|
|
4040
|
+
f"{usage_int(usage, 'completion_tokens'):,} out "
|
|
4041
|
+
f"({usage_int(usage, 'total_tokens'):,} total)"),
|
|
4042
|
+
("calls", f"{usage_int(usage, 'llm_calls'):,} LLM, "
|
|
4043
|
+
f"{usage_int(usage, 'tool_calls'):,} tool"),
|
|
2930
4044
|
("background", (f"{plural(cancelled, 'task')} cancelled on exit"
|
|
2931
4045
|
if cancelled else "none running")),
|
|
2932
4046
|
("resume", "mini-code --load-last-session"),
|
|
@@ -3052,8 +4166,7 @@ class AgentSession:
|
|
|
3052
4166
|
self.token_stats["tool_calls"] += len(tool_calls)
|
|
3053
4167
|
self.total_usage["tool_calls"] += len(tool_calls)
|
|
3054
4168
|
# The model predicted more tool calls: once the work settles down a
|
|
3055
|
-
# completion review is due again
|
|
3056
|
-
self.finalized_plan = True
|
|
4169
|
+
# completion review is due again.
|
|
3057
4170
|
|
|
3058
4171
|
if response_text:
|
|
3059
4172
|
self._print_assistant(response_text)
|
|
@@ -3086,7 +4199,30 @@ class AgentSession:
|
|
|
3086
4199
|
# not store it (or record it) as part of the conversation.
|
|
3087
4200
|
self.messages.pop()
|
|
3088
4201
|
|
|
4202
|
+
truncated = (usage or {}).get("finish_reason") == "length"
|
|
4203
|
+
if response_text or made_tool_calls:
|
|
4204
|
+
# The nudge budget is for a *consecutive* run of empty/truncated
|
|
4205
|
+
# replies. A successful step means the model recovered; a later
|
|
4206
|
+
# truncation gets a fresh set of retries instead of inheriting a
|
|
4207
|
+
# budget exhausted earlier in a long session.
|
|
4208
|
+
self._truncated_retries = 0
|
|
3089
4209
|
if not response_text and not made_tool_calls:
|
|
4210
|
+
if truncated and self._truncated_retries < TRUNCATED_RETRY_LIMIT:
|
|
4211
|
+
# A thinking model can spend the whole output budget on reasoning
|
|
4212
|
+
# and return neither text nor a tool call. Ending the session
|
|
4213
|
+
# there throws away a whole benchmark trial (the patch comes back
|
|
4214
|
+
# empty and the instance is scored unresolved), so nudge it --
|
|
4215
|
+
# bounded, so a model that only ever rambles still stops. Later
|
|
4216
|
+
# attempts are more explicit about the need to be concise.
|
|
4217
|
+
self._truncated_retries += 1
|
|
4218
|
+
self.console.note(
|
|
4219
|
+
"The reply hit the output-token limit before any answer or "
|
|
4220
|
+
"tool call; asking it to continue.", "warn")
|
|
4221
|
+
nudge = TRUNCATED_RETRY_NUDGES[
|
|
4222
|
+
min(self._truncated_retries - 1,
|
|
4223
|
+
len(TRUNCATED_RETRY_NUDGES) - 1)]
|
|
4224
|
+
self.messages.append({"role": "user", "content": nudge})
|
|
4225
|
+
return True
|
|
3090
4226
|
self.console.note("Warning: no response was given by the LLM.", "error")
|
|
3091
4227
|
|
|
3092
4228
|
# Mirror the running tool-call total into this call's usage dict so the
|
|
@@ -3137,7 +4273,9 @@ class _Abort(Exception):
|
|
|
3137
4273
|
|
|
3138
4274
|
def main():
|
|
3139
4275
|
args = parse_args()
|
|
3140
|
-
session
|
|
4276
|
+
# Startup deliberately does not load previous-session settings: the resume
|
|
4277
|
+
# offer comes first, then the chosen session imports its own settings.
|
|
4278
|
+
session = AgentSession(args, defer_model=True)
|
|
3141
4279
|
session.run(initial_prompt=args.prompt)
|
|
3142
4280
|
|
|
3143
4281
|
|