mini-code-cli 0.1.1.4__py3-none-any.whl → 0.2.0.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- mini_code_cli/agent_loop.py +443 -77
- mini_code_cli/background.py +494 -0
- mini_code_cli/persistence.py +14 -7
- mini_code_cli/runner.py +10 -2
- mini_code_cli/sandbox.py +1 -0
- mini_code_cli/subagents/__init__.py +4 -3
- mini_code_cli/subagents/base.py +3 -2
- mini_code_cli/tools.py +215 -23
- mini_code_cli/tui.py +1046 -0
- mini_code_cli/ui.py +114 -59
- mini_code_cli/utils.py +25 -10
- {mini_code_cli-0.1.1.4.dist-info → mini_code_cli-0.2.0.0.dist-info}/METADATA +60 -10
- mini_code_cli-0.2.0.0.dist-info/RECORD +30 -0
- mini_code_cli-0.1.1.4.dist-info/RECORD +0 -28
- {mini_code_cli-0.1.1.4.dist-info → mini_code_cli-0.2.0.0.dist-info}/WHEEL +0 -0
- {mini_code_cli-0.1.1.4.dist-info → mini_code_cli-0.2.0.0.dist-info}/entry_points.txt +0 -0
- {mini_code_cli-0.1.1.4.dist-info → mini_code_cli-0.2.0.0.dist-info}/licenses/LICENSE +0 -0
- {mini_code_cli-0.1.1.4.dist-info → mini_code_cli-0.2.0.0.dist-info}/top_level.txt +0 -0
|
@@ -0,0 +1,494 @@
|
|
|
1
|
+
"""Background shell commands and sub-agent tasks.
|
|
2
|
+
|
|
3
|
+
The foreground agent loop is synchronous: it blocks in ``subprocess.run`` or an
|
|
4
|
+
HTTP call. This module gives it a small, thread-safe registry so long-running
|
|
5
|
+
work can be started and inspected without blocking the current turn:
|
|
6
|
+
|
|
7
|
+
* ``shell`` tasks are real OS processes (their own process group, so cancel
|
|
8
|
+
kills the whole tree);
|
|
9
|
+
* ``subagent`` tasks run a nested :class:`~mini_code_cli.subagents.SubAgent`
|
|
10
|
+
in a worker thread and pass it a cancellation event.
|
|
11
|
+
|
|
12
|
+
Output is streamed to ``<session>/background/<id>.log`` and mirrored into a
|
|
13
|
+
bounded in-memory tail. The registry never writes to the terminal: the
|
|
14
|
+
``background`` tool and the ``/background`` command read consistent snapshots,
|
|
15
|
+
so a worker thread cannot corrupt the console.
|
|
16
|
+
|
|
17
|
+
Nothing survives a process restart. The log files do, which is useful for
|
|
18
|
+
post-mortems, but PIDs are never reattached.
|
|
19
|
+
"""
|
|
20
|
+
|
|
21
|
+
import os
|
|
22
|
+
import signal
|
|
23
|
+
import subprocess
|
|
24
|
+
import threading
|
|
25
|
+
import time
|
|
26
|
+
from collections import deque
|
|
27
|
+
|
|
28
|
+
MAX_TAIL_LINES = 2_000
|
|
29
|
+
DEFAULT_TAIL_LINES = 40
|
|
30
|
+
MAX_TOOL_TAIL_CHARS = 20_000
|
|
31
|
+
|
|
32
|
+
SHELL = "shell"
|
|
33
|
+
SUBAGENT = "subagent"
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def _truncate(text, limit=MAX_TOOL_TAIL_CHARS):
|
|
37
|
+
text = "" if text is None else str(text)
|
|
38
|
+
if len(text) <= limit:
|
|
39
|
+
return text
|
|
40
|
+
return text[-limit:]
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def _read_tail(path, lines=DEFAULT_TAIL_LINES):
|
|
44
|
+
"""Best-effort tail of a log file; never raises."""
|
|
45
|
+
try:
|
|
46
|
+
with open(path, "r", encoding="utf-8", errors="replace") as handle:
|
|
47
|
+
return "".join(deque(handle, maxlen=max(int(lines), 0)))
|
|
48
|
+
except OSError:
|
|
49
|
+
return ""
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
class BackgroundTask:
|
|
53
|
+
"""One task's state. Mutated by its worker and read through snapshots."""
|
|
54
|
+
|
|
55
|
+
def __init__(self, task_id, kind, label, log_path):
|
|
56
|
+
self.id = task_id
|
|
57
|
+
self.kind = kind
|
|
58
|
+
self.label = label
|
|
59
|
+
self.log_path = log_path
|
|
60
|
+
self.status = "running"
|
|
61
|
+
self.pid = None
|
|
62
|
+
self.started_at = time.time()
|
|
63
|
+
self.ended_at = None
|
|
64
|
+
self.exit_code = None
|
|
65
|
+
self.result = ""
|
|
66
|
+
self.error = ""
|
|
67
|
+
self.cancel_reason = ""
|
|
68
|
+
self.done = threading.Event()
|
|
69
|
+
self.cancel_event = threading.Event()
|
|
70
|
+
self._output = deque(maxlen=MAX_TAIL_LINES)
|
|
71
|
+
self._lock = threading.Lock()
|
|
72
|
+
self.thread = None
|
|
73
|
+
self.process = None
|
|
74
|
+
self.timer = None
|
|
75
|
+
|
|
76
|
+
def append_output(self, text):
|
|
77
|
+
if not text:
|
|
78
|
+
return
|
|
79
|
+
with self._lock:
|
|
80
|
+
self._output.append(str(text))
|
|
81
|
+
|
|
82
|
+
def output_tail(self, lines=DEFAULT_TAIL_LINES):
|
|
83
|
+
with self._lock:
|
|
84
|
+
text = "".join(self._output)
|
|
85
|
+
if not text:
|
|
86
|
+
text = _read_tail(self.log_path, lines)
|
|
87
|
+
return _truncate(text)
|
|
88
|
+
|
|
89
|
+
def snapshot(self):
|
|
90
|
+
with self._lock:
|
|
91
|
+
age = (self.ended_at or time.time()) - self.started_at
|
|
92
|
+
return {
|
|
93
|
+
"id": self.id,
|
|
94
|
+
"kind": self.kind,
|
|
95
|
+
"label": self.label,
|
|
96
|
+
"status": self.status,
|
|
97
|
+
"pid": self.pid,
|
|
98
|
+
"age_seconds": max(age, 0.0),
|
|
99
|
+
"exit_code": self.exit_code,
|
|
100
|
+
"log_path": self.log_path,
|
|
101
|
+
"result": self.result,
|
|
102
|
+
"error": self.error,
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
def finish(self, status, exit_code=None, result="", error=""):
|
|
106
|
+
with self._lock:
|
|
107
|
+
if self.ended_at is None:
|
|
108
|
+
self.ended_at = time.time()
|
|
109
|
+
self.status = status
|
|
110
|
+
self.exit_code = exit_code
|
|
111
|
+
if result:
|
|
112
|
+
self.result = str(result)
|
|
113
|
+
if error:
|
|
114
|
+
self.error = str(error)
|
|
115
|
+
self.done.set()
|
|
116
|
+
|
|
117
|
+
|
|
118
|
+
class BackgroundTaskManager:
|
|
119
|
+
"""Owns the tasks for one foreground session."""
|
|
120
|
+
|
|
121
|
+
def __init__(self, log_dir):
|
|
122
|
+
self.log_dir = str(log_dir)
|
|
123
|
+
self._tasks = {}
|
|
124
|
+
self._next_id = 0
|
|
125
|
+
self._lock = threading.Lock()
|
|
126
|
+
|
|
127
|
+
# -- lifecycle ---------------------------------------------------------
|
|
128
|
+
|
|
129
|
+
def set_log_dir(self, log_dir):
|
|
130
|
+
"""Point future tasks at another directory (used on a restore)."""
|
|
131
|
+
self.log_dir = str(log_dir)
|
|
132
|
+
|
|
133
|
+
def _new_task(self, kind, label):
|
|
134
|
+
with self._lock:
|
|
135
|
+
self._next_id += 1
|
|
136
|
+
task_id = f"bg-{self._next_id}"
|
|
137
|
+
os.makedirs(self.log_dir, exist_ok=True)
|
|
138
|
+
log_path = os.path.join(self.log_dir, f"{task_id}.log")
|
|
139
|
+
task = BackgroundTask(task_id, kind, label, log_path)
|
|
140
|
+
self._tasks[task_id] = task
|
|
141
|
+
return task
|
|
142
|
+
|
|
143
|
+
def get(self, task_id):
|
|
144
|
+
with self._lock:
|
|
145
|
+
return self._tasks.get(str(task_id))
|
|
146
|
+
|
|
147
|
+
def list(self):
|
|
148
|
+
with self._lock:
|
|
149
|
+
return [task.snapshot() for task in self._tasks.values()]
|
|
150
|
+
|
|
151
|
+
def running(self):
|
|
152
|
+
return [snapshot for snapshot in self.list()
|
|
153
|
+
if snapshot["status"] in ("running", "cancelling")]
|
|
154
|
+
|
|
155
|
+
def shutdown(self):
|
|
156
|
+
"""Cancel everything still running; called when the session exits."""
|
|
157
|
+
for snapshot in self.running():
|
|
158
|
+
self.cancel(snapshot["id"])
|
|
159
|
+
for task in list(self._tasks.values()):
|
|
160
|
+
if task.thread is not None:
|
|
161
|
+
task.thread.join(timeout=2.0)
|
|
162
|
+
|
|
163
|
+
# -- starting ----------------------------------------------------------
|
|
164
|
+
|
|
165
|
+
def start_shell(self, command, cwd=None, max_seconds=None):
|
|
166
|
+
"""Start ``command`` in its own process group and return the task."""
|
|
167
|
+
command = str(command or "").strip()
|
|
168
|
+
if not command:
|
|
169
|
+
raise ValueError("command must not be empty")
|
|
170
|
+
task = self._new_task(SHELL, command)
|
|
171
|
+
try:
|
|
172
|
+
env = os.environ.copy()
|
|
173
|
+
kwargs = {}
|
|
174
|
+
if os.name == "posix":
|
|
175
|
+
# Give the task its own group so cancel kills its children too.
|
|
176
|
+
kwargs["start_new_session"] = True
|
|
177
|
+
process = subprocess.Popen(
|
|
178
|
+
command, shell=True, cwd=cwd or None,
|
|
179
|
+
stdout=subprocess.PIPE, stderr=subprocess.STDOUT,
|
|
180
|
+
text=True, bufsize=1, env=env, **kwargs)
|
|
181
|
+
except OSError as exc:
|
|
182
|
+
task.finish("failed", error=str(exc))
|
|
183
|
+
return task
|
|
184
|
+
task.process = process
|
|
185
|
+
task.pid = process.pid
|
|
186
|
+
task.thread = threading.Thread(
|
|
187
|
+
target=self._monitor_shell, args=(task, process), daemon=True)
|
|
188
|
+
task.thread.start()
|
|
189
|
+
if max_seconds:
|
|
190
|
+
task.timer = threading.Timer(
|
|
191
|
+
float(max_seconds), self._cancel_task,
|
|
192
|
+
args=(task,), kwargs={"reason": "timeout"})
|
|
193
|
+
task.timer.daemon = True
|
|
194
|
+
task.timer.start()
|
|
195
|
+
return task
|
|
196
|
+
|
|
197
|
+
def start_callable(self, label, func, max_seconds=None):
|
|
198
|
+
"""Run ``func(should_stop)`` in a worker thread and track it."""
|
|
199
|
+
task = self._new_task(SUBAGENT, label)
|
|
200
|
+
task.thread = threading.Thread(
|
|
201
|
+
target=self._monitor_callable, args=(task, func), daemon=True)
|
|
202
|
+
task.thread.start()
|
|
203
|
+
if max_seconds:
|
|
204
|
+
task.timer = threading.Timer(
|
|
205
|
+
float(max_seconds), self._cancel_task,
|
|
206
|
+
args=(task,), kwargs={"reason": "timeout"})
|
|
207
|
+
task.timer.daemon = True
|
|
208
|
+
task.timer.start()
|
|
209
|
+
return task
|
|
210
|
+
|
|
211
|
+
# -- workers -----------------------------------------------------------
|
|
212
|
+
|
|
213
|
+
def _monitor_shell(self, task, process):
|
|
214
|
+
status, error = "failed", ""
|
|
215
|
+
try:
|
|
216
|
+
with open(task.log_path, "w", encoding="utf-8",
|
|
217
|
+
errors="replace") as log:
|
|
218
|
+
stream = process.stdout
|
|
219
|
+
while stream is not None:
|
|
220
|
+
chunk = stream.readline()
|
|
221
|
+
if not chunk:
|
|
222
|
+
break
|
|
223
|
+
log.write(chunk)
|
|
224
|
+
log.flush()
|
|
225
|
+
task.append_output(chunk)
|
|
226
|
+
code = process.wait()
|
|
227
|
+
except Exception as exc: # noqa: BLE001 - a worker must never escape
|
|
228
|
+
code, error = None, str(exc)
|
|
229
|
+
finally:
|
|
230
|
+
if process.stdout is not None:
|
|
231
|
+
try:
|
|
232
|
+
process.stdout.close()
|
|
233
|
+
except OSError:
|
|
234
|
+
pass
|
|
235
|
+
if task.cancel_reason:
|
|
236
|
+
status = "cancelled"
|
|
237
|
+
elif code == 0:
|
|
238
|
+
status = "done"
|
|
239
|
+
elif code is not None:
|
|
240
|
+
status = "failed"
|
|
241
|
+
task.finish(status, exit_code=code, error=error)
|
|
242
|
+
|
|
243
|
+
def _monitor_callable(self, task, func):
|
|
244
|
+
status, result, error = "done", "", ""
|
|
245
|
+
try:
|
|
246
|
+
result = func(task.cancel_event.is_set)
|
|
247
|
+
except Exception as exc: # noqa: BLE001
|
|
248
|
+
status, error = "failed", str(exc)
|
|
249
|
+
if task.cancel_event.is_set():
|
|
250
|
+
status = "cancelled"
|
|
251
|
+
if not error:
|
|
252
|
+
error = task.cancel_reason or "cancelled"
|
|
253
|
+
task.finish(status, result=result, error=error)
|
|
254
|
+
|
|
255
|
+
# -- inspection / control ---------------------------------------------
|
|
256
|
+
|
|
257
|
+
def tail(self, task_id, lines=DEFAULT_TAIL_LINES):
|
|
258
|
+
task = self.get(task_id)
|
|
259
|
+
if task is None:
|
|
260
|
+
return None
|
|
261
|
+
return task.output_tail(lines)
|
|
262
|
+
|
|
263
|
+
def wait(self, task_id, timeout=None):
|
|
264
|
+
task = self.get(task_id)
|
|
265
|
+
if task is None:
|
|
266
|
+
return None
|
|
267
|
+
task.done.wait(None if timeout is None else max(float(timeout), 0.0))
|
|
268
|
+
return task.snapshot()
|
|
269
|
+
|
|
270
|
+
def cancel(self, task_id):
|
|
271
|
+
task = self.get(task_id)
|
|
272
|
+
if task is None:
|
|
273
|
+
return None
|
|
274
|
+
self._cancel_task(task)
|
|
275
|
+
return task.snapshot()
|
|
276
|
+
|
|
277
|
+
def _cancel_task(self, task, reason="cancelled"):
|
|
278
|
+
if task.done.is_set():
|
|
279
|
+
return
|
|
280
|
+
task.cancel_reason = task.cancel_reason or reason
|
|
281
|
+
task.cancel_event.set()
|
|
282
|
+
if task.kind == SHELL and task.pid:
|
|
283
|
+
with task._lock:
|
|
284
|
+
task.status = "cancelling"
|
|
285
|
+
self._kill_group(task, signal.SIGTERM)
|
|
286
|
+
if not task.done.wait(2.0):
|
|
287
|
+
self._kill_group(task, getattr(signal, "SIGKILL", signal.SIGTERM))
|
|
288
|
+
else:
|
|
289
|
+
with task._lock:
|
|
290
|
+
task.status = "cancelling"
|
|
291
|
+
|
|
292
|
+
@staticmethod
|
|
293
|
+
def _kill_group(task, sig):
|
|
294
|
+
pid = task.pid
|
|
295
|
+
if os.name == "posix" and hasattr(os, "killpg"):
|
|
296
|
+
try:
|
|
297
|
+
os.killpg(os.getpgid(pid), sig)
|
|
298
|
+
return
|
|
299
|
+
except (ProcessLookupError, PermissionError, OSError):
|
|
300
|
+
pass
|
|
301
|
+
process = task.process
|
|
302
|
+
if process is not None:
|
|
303
|
+
try:
|
|
304
|
+
process.terminate() if sig == signal.SIGTERM else process.kill()
|
|
305
|
+
except OSError:
|
|
306
|
+
pass
|
|
307
|
+
|
|
308
|
+
|
|
309
|
+
# ---------------------------------------------------------------------------
|
|
310
|
+
# the `background` tool
|
|
311
|
+
# ---------------------------------------------------------------------------
|
|
312
|
+
|
|
313
|
+
_TOOL_DESCRIPTION = """Start, inspect, wait for, or cancel background tasks.
|
|
314
|
+
|
|
315
|
+
Use `start` for long-running work you do not want to block on (a full test
|
|
316
|
+
suite, a build, a download, a sub-agent). Shell tasks run in the background
|
|
317
|
+
with their output stored in a log; sub-agent tasks run a nested agent.
|
|
318
|
+
Poll with `list`/`output`, wait with `wait`, and stop with `cancel`.
|
|
319
|
+
"""
|
|
320
|
+
|
|
321
|
+
_TOOL_SCHEMA = {
|
|
322
|
+
"type": "function",
|
|
323
|
+
"function": {
|
|
324
|
+
"name": "background",
|
|
325
|
+
"description": _TOOL_DESCRIPTION,
|
|
326
|
+
"parameters": {
|
|
327
|
+
"type": "object",
|
|
328
|
+
"properties": {
|
|
329
|
+
"action": {
|
|
330
|
+
"type": "string",
|
|
331
|
+
"enum": ["start", "list", "output", "wait", "cancel"],
|
|
332
|
+
"description": "What to do.",
|
|
333
|
+
},
|
|
334
|
+
"kind": {
|
|
335
|
+
"type": "string",
|
|
336
|
+
"enum": [SHELL, SUBAGENT],
|
|
337
|
+
"description": "Task kind for action=start (default shell).",
|
|
338
|
+
},
|
|
339
|
+
"command": {
|
|
340
|
+
"type": "string",
|
|
341
|
+
"description": "Shell command for kind=shell, action=start.",
|
|
342
|
+
},
|
|
343
|
+
"cwd": {
|
|
344
|
+
"type": "string",
|
|
345
|
+
"description": "Working directory for a shell task.",
|
|
346
|
+
},
|
|
347
|
+
"subagent": {
|
|
348
|
+
"type": "string",
|
|
349
|
+
"description": "Sub-agent name for kind=subagent.",
|
|
350
|
+
},
|
|
351
|
+
"task": {
|
|
352
|
+
"type": "string",
|
|
353
|
+
"description": "Task text for kind=subagent.",
|
|
354
|
+
},
|
|
355
|
+
"max_steps": {
|
|
356
|
+
"type": "integer",
|
|
357
|
+
"description": "Optional step cap for a sub-agent task.",
|
|
358
|
+
},
|
|
359
|
+
"task_id": {
|
|
360
|
+
"type": "string",
|
|
361
|
+
"description": "Task id (bg-1, ...) for output/wait/cancel.",
|
|
362
|
+
},
|
|
363
|
+
"tail": {
|
|
364
|
+
"type": "integer",
|
|
365
|
+
"description": "Lines of output to return (default 40).",
|
|
366
|
+
},
|
|
367
|
+
"timeout": {
|
|
368
|
+
"type": "number",
|
|
369
|
+
"description": "Seconds to wait (0 = return immediately).",
|
|
370
|
+
},
|
|
371
|
+
},
|
|
372
|
+
"required": ["action"],
|
|
373
|
+
},
|
|
374
|
+
},
|
|
375
|
+
}
|
|
376
|
+
|
|
377
|
+
|
|
378
|
+
def _format_task(snapshot):
|
|
379
|
+
state = snapshot.get("status", "?")
|
|
380
|
+
age = snapshot.get("age_seconds", 0.0)
|
|
381
|
+
label = (snapshot.get("label") or "").replace("\n", " ")
|
|
382
|
+
if len(label) > 100:
|
|
383
|
+
label = label[:97] + "..."
|
|
384
|
+
extra = ""
|
|
385
|
+
if snapshot.get("exit_code") is not None:
|
|
386
|
+
extra = f" exit={snapshot['exit_code']}"
|
|
387
|
+
elif snapshot.get("error"):
|
|
388
|
+
extra = f" error={snapshot['error'][:100]}"
|
|
389
|
+
return f"{snapshot['id']} {state} {age:6.1f}s{extra}: {label}"
|
|
390
|
+
|
|
391
|
+
|
|
392
|
+
def background_tool(manager, subagent_runner, action, kind=SHELL, command=None,
|
|
393
|
+
cwd=None, subagent=None, task=None, max_steps=None,
|
|
394
|
+
task_id=None, tail=DEFAULT_TAIL_LINES, timeout=0):
|
|
395
|
+
"""Tool entry point; ``manager`` and ``subagent_runner`` are bound by the session."""
|
|
396
|
+
action = str(action or "").strip().lower()
|
|
397
|
+
kind = str(kind or SHELL).strip().lower()
|
|
398
|
+
try:
|
|
399
|
+
tail = max(0, min(int(tail or 0), 500))
|
|
400
|
+
except (TypeError, ValueError):
|
|
401
|
+
tail = DEFAULT_TAIL_LINES
|
|
402
|
+
try:
|
|
403
|
+
timeout = max(0.0, float(timeout or 0))
|
|
404
|
+
except (TypeError, ValueError):
|
|
405
|
+
timeout = 0.0
|
|
406
|
+
|
|
407
|
+
if action == "list":
|
|
408
|
+
snapshots = manager.list()
|
|
409
|
+
if not snapshots:
|
|
410
|
+
return "No background tasks."
|
|
411
|
+
return "\n".join(_format_task(snapshot) for snapshot in snapshots)
|
|
412
|
+
|
|
413
|
+
if action == "start":
|
|
414
|
+
if kind not in (SHELL, SUBAGENT):
|
|
415
|
+
return f"Error: kind must be {SHELL!r} or {SUBAGENT!r}."
|
|
416
|
+
if kind == SUBAGENT:
|
|
417
|
+
if not subagent or not task:
|
|
418
|
+
return "Error: kind=subagent requires `subagent` and `task`."
|
|
419
|
+
if subagent_runner is None:
|
|
420
|
+
return "Error: no sub-agents are enabled in this session."
|
|
421
|
+
return _start_subagent(manager, subagent_runner, subagent, task,
|
|
422
|
+
max_steps)
|
|
423
|
+
if not command:
|
|
424
|
+
return "Error: kind=shell requires `command`."
|
|
425
|
+
try:
|
|
426
|
+
started = manager.start_shell(command, cwd=cwd)
|
|
427
|
+
except Exception as exc: # noqa: BLE001
|
|
428
|
+
return f"Error: could not start background task: {exc}"
|
|
429
|
+
return (f"Started {started.id} ({started.kind}): {started.label}\n"
|
|
430
|
+
f"Use background(action='output', task_id='{started.id}') "
|
|
431
|
+
f"to read its output.")
|
|
432
|
+
|
|
433
|
+
if action == "output":
|
|
434
|
+
if not task_id:
|
|
435
|
+
return "Error: output requires `task_id`."
|
|
436
|
+
text = manager.tail(task_id, tail)
|
|
437
|
+
if text is None:
|
|
438
|
+
return f"Error: no background task {task_id!r}."
|
|
439
|
+
snapshot = manager.get(task_id).snapshot()
|
|
440
|
+
header = _format_task(snapshot)
|
|
441
|
+
return (header + ("\n" + text if text else "\n(no output yet)"))
|
|
442
|
+
|
|
443
|
+
if action == "wait":
|
|
444
|
+
if not task_id:
|
|
445
|
+
return "Error: wait requires `task_id`."
|
|
446
|
+
snapshot = manager.wait(task_id, timeout)
|
|
447
|
+
if snapshot is None:
|
|
448
|
+
return f"Error: no background task {task_id!r}."
|
|
449
|
+
text = manager.tail(task_id, tail)
|
|
450
|
+
header = _format_task(snapshot)
|
|
451
|
+
return (header + ("\n" + text if text else "\n(no output)"))
|
|
452
|
+
|
|
453
|
+
if action == "cancel":
|
|
454
|
+
if not task_id:
|
|
455
|
+
return "Error: cancel requires `task_id`."
|
|
456
|
+
snapshot = manager.cancel(task_id)
|
|
457
|
+
if snapshot is None:
|
|
458
|
+
return f"Error: no background task {task_id!r}."
|
|
459
|
+
return _format_task(snapshot)
|
|
460
|
+
|
|
461
|
+
return ("Error: unknown action. Use start, list, output, wait or cancel.")
|
|
462
|
+
|
|
463
|
+
|
|
464
|
+
def _start_subagent(manager, subagent_runner, subagent, task, max_steps):
|
|
465
|
+
label = f"subagent {subagent}: {str(task).replace(chr(10), ' ')}"
|
|
466
|
+
|
|
467
|
+
def worker(should_stop):
|
|
468
|
+
return subagent_runner(subagent, task, max_steps, should_stop)
|
|
469
|
+
|
|
470
|
+
try:
|
|
471
|
+
started = manager.start_callable(label, worker)
|
|
472
|
+
except Exception as exc: # noqa: BLE001
|
|
473
|
+
return f"Error: could not start sub-agent task: {exc}"
|
|
474
|
+
return (f"Started {started.id} ({started.kind}): {started.label}\n"
|
|
475
|
+
f"Use background(action='output', task_id='{started.id}') "
|
|
476
|
+
f"to read its result.")
|
|
477
|
+
|
|
478
|
+
|
|
479
|
+
def background_tools():
|
|
480
|
+
"""The OpenAI-style tool schema contributed by this module."""
|
|
481
|
+
return [dict(_TOOL_SCHEMA)]
|
|
482
|
+
|
|
483
|
+
|
|
484
|
+
def background_tools_dict(manager, subagent_runner=None):
|
|
485
|
+
"""The dispatch entry, with the session's manager and sub-agent runner bound."""
|
|
486
|
+
import functools
|
|
487
|
+
|
|
488
|
+
return {
|
|
489
|
+
"background": {
|
|
490
|
+
"function": functools.partial(
|
|
491
|
+
background_tool, manager, subagent_runner),
|
|
492
|
+
"description": _TOOL_DESCRIPTION,
|
|
493
|
+
}
|
|
494
|
+
}
|
mini_code_cli/persistence.py
CHANGED
|
@@ -131,7 +131,7 @@ def pointer_dir(allowed_dir):
|
|
|
131
131
|
return os.path.join(os.path.abspath(allowed_dir), SESSION_DIRNAME)
|
|
132
132
|
|
|
133
133
|
|
|
134
|
-
def _last_session_dir_store(allowed_dir):
|
|
134
|
+
def _last_session_dir_store(allowed_dir, console=None):
|
|
135
135
|
"""Return the pointer directory for ``allowed_dir`` (creating it if needed).
|
|
136
136
|
|
|
137
137
|
Best-effort: never raises. Returns None if the directory cannot be ensured,
|
|
@@ -144,11 +144,13 @@ def _last_session_dir_store(allowed_dir):
|
|
|
144
144
|
os.makedirs(store, exist_ok=True)
|
|
145
145
|
return store
|
|
146
146
|
except OSError as e:
|
|
147
|
-
ui.console.note(
|
|
147
|
+
(console or ui.console).note(
|
|
148
|
+
f"Could not use {store} for the latest-session pointer: {e}",
|
|
149
|
+
"warn")
|
|
148
150
|
return None
|
|
149
151
|
|
|
150
152
|
|
|
151
|
-
def save_last_session_pointer(allowed_dir, session_dir):
|
|
153
|
+
def save_last_session_pointer(allowed_dir, session_dir, console=None):
|
|
152
154
|
"""Record ``session_dir`` as the latest session in ``<allowed_dir>/.mini``.
|
|
153
155
|
|
|
154
156
|
Writes a tiny JSON file (the absolute path plus a timestamp) so a later
|
|
@@ -160,10 +162,13 @@ def save_last_session_pointer(allowed_dir, session_dir):
|
|
|
160
162
|
Written atomically (temp file + ``os.replace``) so a reader never observes a
|
|
161
163
|
half-written pointer. Best-effort: never raises, returns the written path or
|
|
162
164
|
None.
|
|
165
|
+
|
|
166
|
+
``console`` defaults to the module-level renderer; the agent loop passes its
|
|
167
|
+
own so a sub-agent's failure is not printed onto the parent's screen.
|
|
163
168
|
"""
|
|
164
169
|
if not session_dir:
|
|
165
170
|
return None
|
|
166
|
-
store = _last_session_dir_store(allowed_dir)
|
|
171
|
+
store = _last_session_dir_store(allowed_dir, console=console)
|
|
167
172
|
if store is None:
|
|
168
173
|
return None
|
|
169
174
|
path = os.path.join(store, LAST_SESSION_FILENAME)
|
|
@@ -178,7 +183,8 @@ def save_last_session_pointer(allowed_dir, session_dir):
|
|
|
178
183
|
os.replace(tmp_path, path)
|
|
179
184
|
return path
|
|
180
185
|
except OSError as e:
|
|
181
|
-
ui.console.note(
|
|
186
|
+
(console or ui.console).note(
|
|
187
|
+
f"Could not record latest-session pointer: {e}", "warn")
|
|
182
188
|
try:
|
|
183
189
|
os.unlink(tmp_path)
|
|
184
190
|
except OSError:
|
|
@@ -292,7 +298,7 @@ def _segment_indices(directory, pattern):
|
|
|
292
298
|
return sorted(indices)
|
|
293
299
|
|
|
294
300
|
|
|
295
|
-
def delete_segments_above(directory, keep_index):
|
|
301
|
+
def delete_segments_above(directory, keep_index, console=None):
|
|
296
302
|
"""Delete every history/usage segment whose index is above ``keep_index``.
|
|
297
303
|
|
|
298
304
|
A ``/reset`` that lands on an *earlier* segment must not leave the segments
|
|
@@ -324,7 +330,8 @@ def delete_segments_above(directory, keep_index):
|
|
|
324
330
|
os.unlink(path)
|
|
325
331
|
removed.append(path)
|
|
326
332
|
except OSError as e:
|
|
327
|
-
ui.console.note(
|
|
333
|
+
(console or ui.console).note(
|
|
334
|
+
f"Could not remove {name}: {e}", "warn")
|
|
328
335
|
return removed
|
|
329
336
|
|
|
330
337
|
|
mini_code_cli/runner.py
CHANGED
|
@@ -14,8 +14,16 @@ from .config import DEFAULT_TOOL_TIMEOUT
|
|
|
14
14
|
# mistaken for our wall-clock timeout. The old implementation redefined a local
|
|
15
15
|
# ``TimeoutError`` class, which shadowed the stdlib one and meant any tool that
|
|
16
16
|
# legitimately raised ``TimeoutError`` was silently reported as "timed out".
|
|
17
|
-
class _TimedOut(
|
|
18
|
-
|
|
17
|
+
class _TimedOut(BaseException):
|
|
18
|
+
"""Sentinel raised by SIGALRM.
|
|
19
|
+
|
|
20
|
+
It deliberately subclasses ``BaseException``, not ``Exception``: tools
|
|
21
|
+
often wrap their work in a broad ``except Exception`` (``run_shell_command``
|
|
22
|
+
does), and an ``Exception`` sentinel was swallowed there, returning a bare
|
|
23
|
+
``"Error: "`` instead of the proper timeout message. ``call_function_with_timeout``
|
|
24
|
+
catches this type explicitly before anything else.
|
|
25
|
+
"""
|
|
26
|
+
|
|
19
27
|
|
|
20
28
|
|
|
21
29
|
def call_function_with_timeout(func, tool_params, name, timeout_seconds=DEFAULT_TOOL_TIMEOUT,
|
mini_code_cli/sandbox.py
CHANGED
|
@@ -4,9 +4,10 @@ Sub-agents are pluggable: each one is a :class:`~mini_code_cli.subagents.base.Su
|
|
|
4
4
|
instance. :func:`register` adds one; :func:`get_registry` returns the live dict
|
|
5
5
|
that the agent loop turns into extra tools when ``--enable-subagents`` is set.
|
|
6
6
|
|
|
7
|
-
|
|
8
|
-
(:class:`ResearchSubAgent`, :class:`PlanSubAgent
|
|
9
|
-
|
|
7
|
+
The worked examples live in :mod:`mini_code_cli.subagents.builtin`
|
|
8
|
+
(:class:`ResearchSubAgent`, :class:`PlanSubAgent`,
|
|
9
|
+
:class:`SoftwareEngineeringSubAgent`, :class:`GenericSubAgent`); import one or
|
|
10
|
+
write your own and register it.
|
|
10
11
|
"""
|
|
11
12
|
from .base import SubAgent # noqa: F401 (public re-export)
|
|
12
13
|
|
mini_code_cli/subagents/base.py
CHANGED
|
@@ -211,7 +211,7 @@ class SubAgent:
|
|
|
211
211
|
"""Location the nested agent should write its report to."""
|
|
212
212
|
return os.path.join(self._child_cache_dir(parent), "report.md")
|
|
213
213
|
|
|
214
|
-
def run(self, task, parent, max_steps=None, **options):
|
|
214
|
+
def run(self, task, parent, max_steps=None, should_stop=None, **options):
|
|
215
215
|
"""Run the nested agent for ``task`` inside ``parent`` and return text.
|
|
216
216
|
|
|
217
217
|
Spins up a child :class:`AgentSession` (reusing all the normal loop
|
|
@@ -282,7 +282,8 @@ class SubAgent:
|
|
|
282
282
|
# path the system prompt (built at system_prompt() time) told the
|
|
283
283
|
# child to write to, so the two always agree.
|
|
284
284
|
report_path = self._report_path(parent)
|
|
285
|
-
final_text = child._drive_auto(
|
|
285
|
+
final_text = child._drive_auto(
|
|
286
|
+
task, max_steps=max_steps, should_stop=should_stop)
|
|
286
287
|
return self._build_result(child, final_text, report_path)
|
|
287
288
|
except Exception as e:
|
|
288
289
|
# Turn any failure into an Error string the parent loop feeds back
|