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.
@@ -25,6 +25,8 @@ in-flight-tail wiring for every strategy.
25
25
 
26
26
  import json
27
27
  import re
28
+
29
+ from . import media
28
30
  from dataclasses import dataclass, field
29
31
  from typing import Callable, Optional, Sequence
30
32
 
@@ -43,6 +45,54 @@ MAX_PREDICTED_FILE_CALLS = 6
43
45
  MAX_KEPT_MESSAGES = 20
44
46
  MAX_STRATEGY_CHARS = 40_000
45
47
 
48
+ #: Character budget for the mechanical summary used when the model summariser
49
+ #: fails. Small enough to fit any model, large enough to keep the goal and the
50
+ #: most recent turns useful.
51
+ FALLBACK_SUMMARY_CHARS = 6_000
52
+
53
+
54
+ def _clip(text, limit):
55
+ text = " ".join(media.content_text(text).split())
56
+ return text if len(text) <= limit else text[:limit] + " [...]"
57
+
58
+
59
+ def fallback_summary(messages, limit=FALLBACK_SUMMARY_CHARS):
60
+ """A deterministic summary used when the model cannot summarise.
61
+
62
+ Compaction is the mechanism that prevents an over-long transcript from
63
+ poisoning every later request. If the summariser itself fails (an empty
64
+ reply, a network error, or a context-length 400 because one tool output was
65
+ enormous), keeping the original transcript guarantees the next request fails
66
+ too. This fallback instead keeps the first user instruction and the newest
67
+ few turns, then marks the result as mechanical so the next model knows to
68
+ re-read files if it needs detail.
69
+ """
70
+ parts = []
71
+ first_user = next(
72
+ (message for message in messages
73
+ if message.get("role") == "user" and message.get("content")), None)
74
+ if first_user is not None:
75
+ parts.append("Initial request: "
76
+ + _clip(first_user.get("content"), 1_500))
77
+
78
+ recent = [message for message in messages
79
+ if message.get("role") in ("user", "assistant", "tool")][-8:]
80
+ for message in recent:
81
+ content = _clip(message.get("content"), 800)
82
+ if content:
83
+ parts.append(f"{message.get('role', '?')}: {content}")
84
+ if not parts:
85
+ return ("The conversation was compacted, but no summary text was "
86
+ "available. Re-read any files you still need.")
87
+ body = "\n".join(parts)
88
+ if len(body) > limit:
89
+ # Keep the goal even when the recent-turn tail has to be clipped.
90
+ head = parts[0]
91
+ room = max(0, limit - len(head) - 100)
92
+ body = head + ("\n" + "\n".join(parts[1:])[-room:] if room else "")
93
+ return ("Mechanical fallback summary (the model summariser did not return "
94
+ "usable text; re-read files if you need detail):\n" + body)
95
+
46
96
 
47
97
  @dataclass
48
98
  class CompactionContext:
@@ -153,6 +203,9 @@ def cap_messages(messages, limit=MAX_STRATEGY_CHARS):
153
203
  message = dict(message) if isinstance(message, dict) else message
154
204
  if isinstance(message, dict):
155
205
  content = message.get("content")
206
+ if isinstance(content, list):
207
+ content = media.content_text(content)
208
+ message["content"] = content
156
209
  if isinstance(content, str) and len(content) > remaining:
157
210
  message["content"] = (content[:remaining]
158
211
  + "\n[... truncated for compaction ...]")
mini_code_cli/config.py CHANGED
@@ -121,7 +121,13 @@ DEFAULT_CONTEXT_TOKENS = 125_000
121
121
  # How much of the window to keep free for the *reply*. A reply that gets
122
122
  # truncated mid-tool-call is useless, so this is reserved up front: a request is
123
123
  # "too big" once the input plus this reserve would not fit.
124
- DEFAULT_RESERVED_OUTPUT_TOKENS = 8_192
124
+ #
125
+ # This is also the CLI's default reply budget. It used to be 8k, which a
126
+ # thinking model could spend entirely on reasoning and return no tool call at
127
+ # all. 32k matches the output budget Claude Code and current local servers use;
128
+ # ``default_max_output_tokens`` clamps it for models with a smaller window.
129
+ DEFAULT_MAX_OUTPUT_TOKENS = 32_768
130
+ DEFAULT_RESERVED_OUTPUT_TOKENS = DEFAULT_MAX_OUTPUT_TOKENS
125
131
 
126
132
  # Fraction of the window kept as slack on top of the output reserve, covering
127
133
  # the gap between our estimate and the model's real tokenizer (tool schemas,
@@ -194,6 +200,20 @@ def context_window_for(model, default=None):
194
200
  return default
195
201
 
196
202
 
203
+ def default_max_output_tokens(model=None):
204
+ """The default reply budget for ``model``, in tokens.
205
+
206
+ Large models get :data:`DEFAULT_MAX_OUTPUT_TOKENS` (32k); a model with a
207
+ smaller published context window gets at most half of it, so a 32k reply
208
+ budget cannot consume a 8k window. Explicit ``--max-tokens`` always wins;
209
+ this only fills in the default when the user did not configure one.
210
+ """
211
+ window = context_window_for(model)
212
+ if not window:
213
+ return DEFAULT_MAX_OUTPUT_TOKENS
214
+ return max(1_024, min(DEFAULT_MAX_OUTPUT_TOKENS, int(window) // 2))
215
+
216
+
197
217
  def compaction_budget(model=None, explicit_limit=None, max_output_tokens=None):
198
218
  """Resolve the compaction budget for ``model``.
199
219
 
mini_code_cli/media.py ADDED
@@ -0,0 +1,194 @@
1
+ """Image attachments for chat messages.
2
+
3
+ The OpenAI-compatible endpoint accepts image input as a content list:
4
+
5
+ [{"type": "text", "text": "what is this?"},
6
+ {"type": "image_url", "image_url": {"url": "data:image/png;base64,..."}}]
7
+
8
+ Base64 in the persisted history would make every session file huge and resend
9
+ the bytes on every request. Instead, a message holds a small ``image_ref``
10
+ block naming a file in the session cache::
11
+
12
+ {"type": "image_ref", "path": "/cache/<session>/attachments/...",
13
+ "mime": "image/png", "name": "board.png"}
14
+
15
+ :func:`materialize_messages` resolves those refs into data URIs only when a
16
+ request is built. Text-only consumers (plan/review/compaction prompts, token
17
+ estimates, history views) use :func:`content_text`, which turns an image ref
18
+ into a short ``[image: name]`` marker.
19
+ """
20
+ import base64
21
+ import hashlib
22
+ import mimetypes
23
+ import os
24
+ import shutil
25
+
26
+ ATTACHMENT_DIRNAME = "attachments"
27
+ MAX_IMAGE_BYTES = 10 * 1024 * 1024
28
+ #: Rough prompt cost of one image for the context estimate. The server's real
29
+ #: count depends on dimensions; this is deliberately conservative and only
30
+ #: affects the local projection used for compaction.
31
+ IMAGE_TOKEN_ESTIMATE = 1000
32
+
33
+ IMAGE_MIMES = {
34
+ ".png": "image/png",
35
+ ".jpg": "image/jpeg",
36
+ ".jpeg": "image/jpeg",
37
+ ".webp": "image/webp",
38
+ ".gif": "image/gif",
39
+ }
40
+
41
+
42
+ def image_mime(path):
43
+ """Return the MIME type for a supported image path, or ``None``."""
44
+ return IMAGE_MIMES.get(os.path.splitext(str(path or ""))[1].lower())
45
+
46
+
47
+ def is_image_path(path):
48
+ return image_mime(path) is not None
49
+
50
+
51
+ def stage_image(path, session_dir, name=None):
52
+ """Copy an image into the session cache and return an ``image_ref`` block.
53
+
54
+ Raises ``ValueError`` for unsupported extensions, unreadable files and
55
+ oversized images. The copy is content-addressed so attaching the same image
56
+ twice reuses one file.
57
+ """
58
+ source = os.path.abspath(os.path.expanduser(str(path or "")))
59
+ mime = image_mime(source)
60
+ if not mime:
61
+ raise ValueError(
62
+ "unsupported image type; use PNG, JPEG, WEBP or GIF")
63
+ try:
64
+ size = os.path.getsize(source)
65
+ except OSError as exc:
66
+ raise ValueError(f"cannot read image: {exc}")
67
+ if size > MAX_IMAGE_BYTES:
68
+ raise ValueError(
69
+ f"image is too large ({size} bytes; limit {MAX_IMAGE_BYTES})")
70
+ try:
71
+ with open(source, "rb") as handle:
72
+ data = handle.read()
73
+ except OSError as exc:
74
+ raise ValueError(f"cannot read image: {exc}")
75
+
76
+ digest = hashlib.sha1(data).hexdigest()[:16]
77
+ base = _safe_name(name or os.path.basename(source))
78
+ directory = os.path.join(session_dir, ATTACHMENT_DIRNAME)
79
+ os.makedirs(directory, exist_ok=True)
80
+ target = os.path.join(directory, f"{digest}-{base}")
81
+ if not os.path.isfile(target):
82
+ tmp = target + ".tmp"
83
+ with open(tmp, "wb") as handle:
84
+ handle.write(data)
85
+ os.chmod(tmp, 0o600)
86
+ os.replace(tmp, target)
87
+ return {"type": "image_ref", "path": target, "mime": mime,
88
+ "name": os.path.basename(source), "bytes": len(data)}
89
+
90
+
91
+ def _safe_name(name):
92
+ name = os.path.basename(str(name or "image"))
93
+ cleaned = "".join(ch if ch.isalnum() or ch in "._-" else "_"
94
+ for ch in name)
95
+ return cleaned or "image"
96
+
97
+
98
+ def user_content(text, image_refs=()):
99
+ """Build a user message content value from text and image refs."""
100
+ text = str(text or "")
101
+ refs = [ref for ref in image_refs if isinstance(ref, dict)]
102
+ if not refs:
103
+ return text
104
+ return [{"type": "text", "text": text}] + refs
105
+
106
+
107
+ def content_text(content):
108
+ """Flatten a message content value to text for text-only consumers."""
109
+ if isinstance(content, str):
110
+ return content
111
+ if content is None:
112
+ return ""
113
+ if isinstance(content, list):
114
+ parts = []
115
+ for part in content:
116
+ if isinstance(part, str):
117
+ parts.append(part)
118
+ elif isinstance(part, dict):
119
+ kind = part.get("type")
120
+ if kind == "text":
121
+ parts.append(str(part.get("text") or ""))
122
+ elif kind in ("image_ref", "image_url"):
123
+ name = part.get("name")
124
+ if not name:
125
+ name = os.path.basename(str(part.get("path") or "image"))
126
+ parts.append(f"[image: {name}]")
127
+ elif kind:
128
+ parts.append(f"[{kind}]")
129
+ return "\n".join(part for part in parts if part)
130
+ return str(content)
131
+
132
+
133
+ def image_refs(content):
134
+ """Return the image-ref blocks in a content value."""
135
+ if not isinstance(content, list):
136
+ return []
137
+ return [part for part in content
138
+ if isinstance(part, dict) and part.get("type") == "image_ref"]
139
+
140
+
141
+ def materialize_messages(messages):
142
+ """Return messages with ``image_ref`` blocks resolved to data URIs.
143
+
144
+ The original list is not mutated: history keeps the small file references.
145
+ A missing attachment becomes a text marker rather than failing the request.
146
+ """
147
+ result = []
148
+ changed = False
149
+ for message in messages:
150
+ if not isinstance(message, dict):
151
+ result.append(message)
152
+ continue
153
+ content = message.get("content")
154
+ if not isinstance(content, list):
155
+ result.append(message)
156
+ continue
157
+ parts = []
158
+ for part in content:
159
+ if isinstance(part, dict) and part.get("type") == "image_ref":
160
+ changed = True
161
+ resolved = _materialize_ref(part)
162
+ parts.append(resolved)
163
+ else:
164
+ parts.append(part)
165
+ new_message = dict(message)
166
+ new_message["content"] = parts
167
+ result.append(new_message)
168
+ return result if changed else messages
169
+
170
+
171
+ def _materialize_ref(ref):
172
+ path = ref.get("path")
173
+ mime = ref.get("mime") or mimetypes.guess_type(str(path))[0]
174
+ try:
175
+ with open(str(path), "rb") as handle:
176
+ data = handle.read()
177
+ except OSError:
178
+ label = ref.get("name") or os.path.basename(str(path or "image"))
179
+ return {"type": "text",
180
+ "text": f"[image unavailable: {label}]"}
181
+ encoded = base64.b64encode(data).decode("ascii")
182
+ return {"type": "image_url",
183
+ "image_url": {"url": f"data:{mime};base64,{encoded}"}}
184
+
185
+
186
+ def copy_into_session(path, session_dir, name=None):
187
+ """Compatibility wrapper used by the session command."""
188
+ return stage_image(path, session_dir, name=name)
189
+
190
+
191
+ def remove_session_attachments(session_dir):
192
+ """Remove the attachment directory (used by explicit session cleanup)."""
193
+ shutil.rmtree(os.path.join(session_dir, ATTACHMENT_DIRNAME),
194
+ ignore_errors=True)
@@ -40,6 +40,7 @@ import time
40
40
 
41
41
  from . import ui
42
42
  from .config import DEFAULT_CACHE_LOCATION, SESSION_DIRNAME
43
+ from .utils import coerce_usage_int
43
44
 
44
45
 
45
46
  # ---------------------------------------------------------------------------
@@ -463,10 +464,7 @@ def _coerce_usage(saved):
463
464
  stats = empty_usage()
464
465
  if isinstance(saved, dict):
465
466
  for key in USAGE_KEYS:
466
- try:
467
- stats[key] = int(saved.get(key, 0) or 0)
468
- except (TypeError, ValueError):
469
- stats[key] = 0
467
+ stats[key] = coerce_usage_int(saved.get(key, 0))
470
468
  return stats
471
469
 
472
470
 
@@ -474,9 +472,10 @@ def accumulate_usage(token_stats, usage):
474
472
  """Add a single LLM call's token usage into the running totals."""
475
473
  if not usage:
476
474
  return
477
- token_stats["prompt_tokens"] += int(usage.get("prompt_tokens", 0) or 0)
478
- token_stats["completion_tokens"] += int(usage.get("completion_tokens", 0) or 0)
479
- token_stats["total_tokens"] += int(usage.get("total_tokens", 0) or 0)
475
+ token_stats["prompt_tokens"] += coerce_usage_int(usage.get("prompt_tokens"))
476
+ token_stats["completion_tokens"] += coerce_usage_int(
477
+ usage.get("completion_tokens"))
478
+ token_stats["total_tokens"] += coerce_usage_int(usage.get("total_tokens"))
480
479
  token_stats["llm_calls"] += 1
481
480
 
482
481
 
mini_code_cli/planning.py CHANGED
@@ -1,17 +1,23 @@
1
1
  """Planning strategies for ``--plan`` mode.
2
2
 
3
- The loop's built-in plan handling is :func:`plan_verify_step`, the original
4
- implementation:
3
+ The default is ``plan-verify2``, the machine-readable successor to the
4
+ ``plan-verify`` strategy that won the clean benchmark comparison:
5
5
 
6
6
  * the loop asks the model to author a plan;
7
- * after the work settles it asks the model to review the plan;
8
- * it runs one more step so the review can drive further work.
7
+ * after the work settles it asks for a short verdict ending in
8
+ ``STATUS: DONE`` / ``STATUS: INCOMPLETE`` / ``STATUS: IN PROGRESS``;
9
+ * a DONE verdict ends the turn immediately. An unfinished verdict injects
10
+ the outstanding work and lets the agent act; another verdict follows the
11
+ next time the work settles. If the agent makes no tool call after an
12
+ unfinished verdict, the turn ends instead of verifying forever.
9
13
 
10
14
  Alternative strategies:
11
15
 
12
- * ``plan-verify`` -- same plan + review, but the post-review step is only
13
- appended to the transcript when it calls a tool. A no-tool answer is shown
14
- to the user and ends the turn without being stored.
16
+ * ``plan-verify`` -- author a plan, review it once the work settles, then
17
+ keep the post-review step only when it calls a tool. A no-tool answer is
18
+ shown to the user and ends the turn without being stored.
19
+ * ``plan-verify-step`` -- the original behaviour: same plan + review, then
20
+ always run one extra step and keep whatever that step says.
15
21
  * ``open-plan`` -- the agent owns a plan document in ``--allowed-dir/.mini``
16
22
  and reads/writes it with the normal file tools; the loop neither authors
17
23
  nor reviews a plan.
@@ -20,10 +26,65 @@ Keeping the names here (rather than inline in ``agent_loop`` or ``argparse``)
20
26
  means a future strategy only has to be added in one place plus the loop branch
21
27
  that implements it.
22
28
  """
29
+ import re
23
30
 
24
31
  PLAN_VERIFY_STEP = "plan-verify-step"
25
32
  PLAN_VERIFY = "plan-verify"
33
+ PLAN_VERIFY2 = "plan-verify2"
26
34
  OPEN_PLAN = "open-plan"
27
35
 
28
- PLAN_STRATEGIES = (PLAN_VERIFY_STEP, PLAN_VERIFY, OPEN_PLAN)
29
- DEFAULT_PLAN_STRATEGY = PLAN_VERIFY_STEP
36
+ PLAN_STRATEGIES = (PLAN_VERIFY_STEP, PLAN_VERIFY, PLAN_VERIFY2, OPEN_PLAN)
37
+ DEFAULT_PLAN_STRATEGY = PLAN_VERIFY2
38
+
39
+ #: Outcomes returned by :func:`parse_verify_status`.
40
+ VERIFY_DONE = "done"
41
+ VERIFY_INCOMPLETE = "incomplete"
42
+
43
+ _STATUS_LINE_RE = re.compile(
44
+ r"(?im)^\s*(?:status|verdict|result)\s*[:\-]\s*(?P<state>[^\n]+?)\s*$")
45
+
46
+ _INCOMPLETE_RE = re.compile(
47
+ r"(?i)\b(?:incomplete|unfinished|in[\s_-]*progress|not[\s_-]*done|"
48
+ r"not[\s_-]*complete|todo|pending|blocked)\b")
49
+
50
+ _DONE_RE = re.compile(
51
+ r"(?i)\b(?:done|complete|completed|finished|resolved)\b")
52
+
53
+
54
+ def parse_verify_status(text):
55
+ """Extract the machine-readable completion verdict from a verify reply.
56
+
57
+ The loop asks the verifier to end with exactly one line such as
58
+ ``STATUS: DONE`` or ``STATUS: INCOMPLETE``. This turns that line into
59
+ :data:`VERIFY_DONE`, :data:`VERIFY_INCOMPLETE`, or ``None`` when the reply
60
+ did not state a usable verdict.
61
+
62
+ A ``STATUS:`` line wins over prose, and only the last one counts: the
63
+ verifier may discuss steps before stating its verdict. If there is no such
64
+ line, only the final non-empty line is considered, so an analysis sentence
65
+ ("the build is not complete") cannot flip the verdict of a later explicit
66
+ marker. Anything ambiguous returns ``None``; callers treat that as
67
+ unfinished but stop if the agent takes no action.
68
+ """
69
+ text = str(text or "")
70
+ matches = list(_STATUS_LINE_RE.finditer(text))
71
+ if matches:
72
+ return _status_from_state(matches[-1].group("state"))
73
+
74
+ lines = [line.strip() for line in text.splitlines() if line.strip()]
75
+ if lines:
76
+ return _status_from_state(lines[-1])
77
+ return None
78
+
79
+
80
+ def _status_from_state(state):
81
+ """Normalise one status phrase; ``None`` when it is not a known verdict."""
82
+ state = str(state or "").strip().strip(".:!*_`()[]")
83
+ if not state:
84
+ return None
85
+ # Check the unfinished spellings first: "INCOMPLETE" contains "COMPLETE".
86
+ if _INCOMPLETE_RE.search(state):
87
+ return VERIFY_INCOMPLETE
88
+ if _DONE_RE.search(state):
89
+ return VERIFY_DONE
90
+ return None