xonecas.io
64875
Mc

mini-coder / commit a9089ea

feat: headless cleanup and bugfixes

xonecas2026-04-25 a9089ea2ee6d0b4ccac68a93de584749b794804e parent ed699fb

12 files changed

This diff is too big to show in full. The first 1000 lines are below, and every file is listed with its counts.

.npmignore+7−0
@@ -0,0 +1,7 @@
1+.agents
2+benchmarks
3+AGENTS.md
4+BENCHMARK.md
5+biome.json
6+skills-lock.json
7+TODO.md
TODO.md+3−5
@@ -2,9 +2,7 @@
22
33 > This file is managed by the user, only edit if asked to.
44
5-- [ ] Use this `https://github.com/steveukx/git-js/blob/main/simple-git/typings/response.d.ts#L326`
5+- [ ] Write a minimal python harbor agent, we removed the overcomplicated last one since we change our
6+ json output format. Which is now more like a ndjson output.
67
7-- `src/tui.ts:248` tool timing is still cumulative for later tool calls\*\*
8- The new duration is computed from `msg.timestamp`, which is set when the tool call is first shown, not when that specific tool
9- runner starts. Since `streamAgent` executes tool calls serially, the second/third tool in one assistant turn will show a duration
10- that includes time spent waiting on earlier tools, so the displayed `Took ...` is inaccurate.
8+- [ ] `Took XXXX` label in the TUI are all wrong ahah, need to be revised.
benchmarks/local-harbor-agent.py+146−427
@@ -1,16 +1,14 @@
1+# TODO: `LocalMiniCoderAgent` so we can run terminal bench with our current local modified code.
2+
13 from __future__ import annotations
24
35 import json
46 import shlex
5-import shutil
6-import subprocess
7+import tarfile
78 from pathlib import Path
89 from tempfile import TemporaryDirectory
910 from typing import Any
1011
11-
12-_FINAL_STOP_REASONS = frozenset({"stop", "error", "aborted"})
13-
1412 from harbor.agents.installed.base import BaseInstalledAgent, with_prompt_template
1513 from harbor.environments.base import BaseEnvironment
1614 from harbor.models.agent.context import AgentContext
@@ -18,476 +16,197 @@ from harbor.models.trial.paths import EnvironmentPaths
1816
1917
2018 class LocalMiniCoderAgent(BaseInstalledAgent):
21- """Harbor installed-agent wrapper for this local mini-coder checkout."""
22-
23- _JSON_LOG_FILENAME = "mini-coder.json"
24- _STDERR_LOG_FILENAME = "mini-coder.stderr.txt"
25- _PACKAGE_PATHS = ("bin/mc.ts", "src")
26- _PACKAGE_MANIFEST_KEYS = (
27- "name",
28- "version",
29- "type",
30- "bin",
31- "dependencies",
32- "packageManager",
33- )
34-
35- def __init__(self, *args, version: str = "local", **kwargs):
36- super().__init__(*args, version=version, **kwargs)
37- self._host_repo_root = Path(__file__).resolve().parents[1]
38- host_config_dir = Path.home() / ".config" / "mini-coder"
39- self._host_auth_path = host_config_dir / "auth.json"
40- self._host_settings_path = host_config_dir / "settings.json"
19+ """Minimal Harbor installed-agent wrapper for the local mini-coder checkout."""
20+
21+ CONTAINER_ROOT = "/tmp/mini-coder-next"
22+ STDOUT_LOG = "mini-coder.ndjson"
23+ STDERR_LOG = "mini-coder.stderr.txt"
4124
4225 @staticmethod
4326 def name() -> str:
4427 return "mini-coder-local"
4528
46- async def install(self, environment: BaseEnvironment) -> None:
47- self._require_host_checkout()
48- await self._install_system_dependencies(environment)
49- await self._install_bun(environment)
50-
51- with TemporaryDirectory(prefix="mini-coder-harbor-") as temp_dir:
52- tarball_path = self._package_local_checkout(Path(temp_dir))
53- container_tarball_path = f"/tmp/{tarball_path.name}"
54- await environment.upload_file(tarball_path, container_tarball_path)
55- await self._install_global_package(environment, container_tarball_path)
56-
57- def populate_context_post_run(self, context: AgentContext) -> None:
58- output_path = self.logs_dir / self._JSON_LOG_FILENAME
59- stderr_path = self.logs_dir / self._STDERR_LOG_FILENAME
60- metadata: dict[str, Any] = {
61- "json_log_path": str(output_path),
62- "stderr_log_path": str(stderr_path),
63- }
64-
65- if stderr_path.is_file():
66- stderr_text = stderr_path.read_text(
67- encoding="utf-8", errors="replace"
68- ).strip()
69- if stderr_text:
70- metadata["stderr_excerpt"] = self._truncate_metadata_text(stderr_text)
71-
72- try:
73- with output_path.open(encoding="utf-8") as handle:
74- result = json.load(handle)
75- except FileNotFoundError:
76- metadata["parse_error"] = f"Missing mini-coder JSON log: {output_path}"
77- self._merge_context_metadata(context, metadata)
78- return
79- except json.JSONDecodeError as exc:
80- metadata["parse_error"] = f"Invalid mini-coder JSON log: {exc}"
81- metadata["stdout_excerpt"] = self._read_text_excerpt(output_path)
82- self._merge_context_metadata(context, metadata)
83- return
84- except OSError as exc:
85- metadata["parse_error"] = f"Failed to read mini-coder JSON log: {exc}"
86- self._merge_context_metadata(context, metadata)
87- return
88-
89- parsed_result = self._extract_result_from_json_log(result)
90- metadata.update(parsed_result["metadata"])
91- result_message = parsed_result.get("message")
92- if not isinstance(result_message, dict):
93- self._merge_context_metadata(context, metadata)
94- return
95-
96- usage = result_message.get("usage")
97- usage_data = usage if isinstance(usage, dict) else {}
98-
99- context.n_input_tokens = self._optional_int(usage_data.get("input"))
100- context.n_output_tokens = self._optional_int(usage_data.get("output"))
101-
102- cache_read = self._optional_int(usage_data.get("cacheRead"))
103- cache_write = self._optional_int(usage_data.get("cacheWrite"))
104- if cache_read is not None or cache_write is not None:
105- context.n_cache_tokens = (cache_read or 0) + (cache_write or 0)
106-
107- cost = usage_data.get("cost")
108- if isinstance(cost, dict):
109- context.cost_usd = self._optional_float(cost.get("total"))
110-
111- for source_key, metadata_key in (
112- ("api", "api"),
113- ("provider", "provider"),
114- ("model", "model"),
115- ("responseId", "response_id"),
116- ("stopReason", "stop_reason"),
117- ("errorMessage", "error_message"),
118- ):
119- value = result_message.get(source_key)
120- if isinstance(value, str) and value:
121- metadata[metadata_key] = value
122-
123- if usage:
124- metadata["usage"] = usage
125-
126- self._merge_context_metadata(context, metadata)
127-
128- @classmethod
129- def _extract_result_from_json_log(
130- cls, result: Any
131- ) -> dict[str, dict[str, Any] | dict[str, Any] | None]:
132- if isinstance(result, dict):
133- return {"message": result, "metadata": {"json_log_shape": "object"}}
134-
135- if not isinstance(result, list):
136- return {
137- "message": None,
138- "metadata": {
139- "json_log_shape": type(result).__name__,
140- "parse_error": "mini-coder JSON log was neither an object nor an array",
141- },
142- }
143-
144- assistant_messages = [
145- item
146- for item in result
147- if isinstance(item, dict) and item.get("role") == "assistant"
148- ]
149- if not assistant_messages:
150- return {
151- "message": None,
152- "metadata": {
153- "json_log_shape": "array",
154- "event_count": len(result),
155- "assistant_message_count": 0,
156- "parse_error": "mini-coder JSON log array had no assistant messages",
157- },
158- }
159-
160- final_message = next(
161- (
162- item
163- for item in reversed(assistant_messages)
164- if item.get("stopReason") in _FINAL_STOP_REASONS
165- ),
166- assistant_messages[-1],
167- )
168- return {
169- "message": final_message,
170- "metadata": {
171- "json_log_shape": "array",
172- "event_count": len(result),
173- "assistant_message_count": len(assistant_messages),
174- },
175- }
176-
177- @staticmethod
178- def _optional_int(value: Any) -> int | None:
179- if isinstance(value, bool):
180- return None
181- if isinstance(value, int):
182- return value
183- if isinstance(value, float) and value.is_integer():
184- return int(value)
185- return None
186-
187- @staticmethod
188- def _optional_float(value: Any) -> float | None:
189- if isinstance(value, bool):
190- return None
191- if isinstance(value, (int, float)):
192- return float(value)
193- return None
194-
195- @staticmethod
196- def _truncate_metadata_text(text: str, max_chars: int = 4000) -> str:
197- if len(text) <= max_chars:
198- return text
199- return text[:max_chars] + " ... [truncated]"
200-
201- def _read_text_excerpt(self, path: Path) -> str:
202- try:
203- return self._truncate_metadata_text(
204- path.read_text(encoding="utf-8", errors="replace").strip()
205- )
206- except OSError as exc:
207- return f"<failed to read {path}: {exc}>"
208-
209- @staticmethod
210- def _merge_context_metadata(
211- context: AgentContext, metadata: dict[str, Any]
212- ) -> None:
213- existing = context.metadata or {}
214- context.metadata = {**existing, **metadata}
215-
216- def _require_host_checkout(self) -> None:
217- missing = [
218- path
219- for path in (
220- self._host_repo_root / "package.json",
221- self._host_repo_root / "bin" / "mc.ts",
222- self._host_repo_root / "src",
223- )
224- if not path.exists()
225- ]
226- if missing:
227- raise FileNotFoundError(
228- "Missing local mini-coder checkout files required for Harbor: "
229- + ", ".join(str(path) for path in missing)
230- )
231-
232- def _require_host_auth(self) -> None:
233- if not self._host_auth_path.is_file():
234- raise FileNotFoundError(
235- f"Missing mini-coder auth file required for Harbor: {self._host_auth_path}"
236- )
237-
238- def _package_local_checkout(self, target_dir: Path) -> Path:
239- target_dir.mkdir(parents=True, exist_ok=True)
240- package_root = target_dir / "mini-coder-package"
241- tarball_path = target_dir / "mini-coder-local.tgz"
242- self._stage_minimal_package(package_root)
243-
244- try:
245- result = subprocess.run(
246- [
247- "bun",
248- "pm",
249- "pack",
250- "--ignore-scripts",
251- "--filename",
252- str(tarball_path),
253- ],
254- cwd=package_root,
255- capture_output=True,
256- text=True,
257- check=False,
258- )
259- except FileNotFoundError as exc:
260- raise RuntimeError("bun is required on the host to package mini-coder") from exc
261-
262- if result.returncode != 0:
263- details = result.stderr.strip() or result.stdout.strip() or "unknown error"
264- raise RuntimeError(f"Failed to package mini-coder: {details}")
265- if not tarball_path.is_file():
266- raise RuntimeError(f"Expected mini-coder package at {tarball_path}")
267-
268- return tarball_path
269-
270- def _stage_minimal_package(self, package_root: Path) -> None:
271- if package_root.exists():
272- shutil.rmtree(package_root)
273- package_root.mkdir(parents=True)
274-
275- package_manifest = self._minimal_package_manifest()
276- (package_root / "package.json").write_text(
277- json.dumps(package_manifest, indent=2) + "\n", encoding="utf-8"
278- )
279-
280- for relative_path in self._PACKAGE_PATHS:
281- source_path = self._host_repo_root / relative_path
282- target_path = package_root / relative_path
283- if source_path.is_dir():
284- shutil.copytree(source_path, target_path)
285- else:
286- target_path.parent.mkdir(parents=True, exist_ok=True)
287- shutil.copy2(source_path, target_path)
288-
289- def _minimal_package_manifest(self) -> dict[str, Any]:
290- manifest_path = self._host_repo_root / "package.json"
291- source_manifest = json.loads(manifest_path.read_text(encoding="utf-8"))
292- if not isinstance(source_manifest, dict):
293- raise RuntimeError(f"Invalid package manifest at {manifest_path}")
294-
295- package_manifest = {
296- key: source_manifest[key]
297- for key in self._PACKAGE_MANIFEST_KEYS
298- if key in source_manifest
299- }
300- missing = [
301- key
302- for key in ("name", "version", "type", "bin")
303- if key not in package_manifest
304- ]
305- if missing:
306- raise RuntimeError(
307- f"Missing required package manifest keys: {', '.join(missing)}"
308- )
309-
310- return package_manifest
311-
312- @staticmethod
313- def _pinned_bun_version(package_manager: Any) -> str | None:
314- if not isinstance(package_manager, str):
315- return None
316- tool_name, _, version = package_manager.partition("@")
317- if tool_name != "bun" or not version:
318- return None
319- if any(not part.isdigit() for part in version.split(".")):
320- return None
321- return version
322-
323- def _expected_bun_version(self) -> str | None:
324- manifest_path = self._host_repo_root / "package.json"
325- source_manifest = json.loads(manifest_path.read_text(encoding="utf-8"))
326- if not isinstance(source_manifest, dict):
327- return None
328- return self._pinned_bun_version(source_manifest.get("packageManager"))
29+ def __init__(self, *args: Any, version: str = "local", **kwargs: Any) -> None:
30+ super().__init__(*args, version=version, **kwargs)
31+ self.repo_root = Path(__file__).resolve().parents[1]
32+ self.host_config_dir = Path.home() / ".config" / "mini-coder"
32933
330- async def _install_system_dependencies(self, environment: BaseEnvironment) -> None:
34+ async def install(self, environment: BaseEnvironment) -> None:
33135 await self.exec_as_root(
33236 environment,
33337 command=(
334- "if command -v apt-get >/dev/null 2>&1; then "
335- "apt-get update && apt-get install -y curl unzip ca-certificates bash; "
336- "elif command -v apk >/dev/null 2>&1; then "
337- "apk add --no-cache curl unzip ca-certificates bash; "
338- "elif command -v yum >/dev/null 2>&1; then "
339- "yum install -y curl unzip ca-certificates bash; "
340- "else echo 'Unsupported package manager for mini-coder install' >&2; exit 1; fi"
38+ "apt-get update && "
39+ "apt-get install -y curl unzip ca-certificates bash"
34140 ),
34241 env={"DEBIAN_FRONTEND": "noninteractive"},
34342 )
34443
345- async def _install_bun(self, environment: BaseEnvironment) -> None:
346- expected_version = self._expected_bun_version()
347- install_command = "curl -fsSL https://bun.sh/install | bash"
348- if expected_version is not None:
349- install_command = (
350- f"curl -fsSL https://bun.sh/install | bash -s -- bun-v{expected_version}"
351- )
352- await self.exec_as_agent(
353- environment,
354- command=(
355- f"expected_version={shlex.quote(expected_version)}; "
356- "current_version=''; "
357- "if command -v bun >/dev/null 2>&1; then "
358- "current_version=$(bun --version 2>/dev/null || true); "
359- "fi; "
360- "if [ -z \"$current_version\" ] || [ \"$current_version\" != \"$expected_version\" ]; then "
361- f"{install_command}; "
362- "fi; "
363- "export PATH=\"$HOME/.bun/bin:$PATH\"; "
364- "test -x \"$(command -v bun)\" && "
365- "[ \"$(bun --version)\" = \"$expected_version\" ]"
366- ),
367- )
368- return
369-
370- await self.exec_as_agent(
371- environment,
372- command=(
373- "if ! command -v bun >/dev/null 2>&1; then "
374- f"{install_command}; fi; "
375- "export PATH=\"$HOME/.bun/bin:$PATH\"; "
376- "test -x \"$(command -v bun)\""
377- ),
378- )
379-
380- async def _install_global_package(
381- self, environment: BaseEnvironment, package_spec: str
382- ) -> None:
38344 await self.exec_as_agent(
38445 environment,
38546 command=(
386- "export PATH=\"$HOME/.bun/bin:$PATH\"; "
387- f"bun add -g --ignore-scripts {shlex.quote(package_spec)} && "
388- "test -x ~/.bun/bin/mc"
47+ 'if ! command -v bun >/dev/null 2>&1; then '
48+ "curl -fsSL https://bun.sh/install | bash; "
49+ "fi"
38950 ),
39051 )
39152
392- async def _container_home(self, environment: BaseEnvironment) -> str:
393- result = await self.exec_as_agent(environment, command='printf %s "$HOME"')
394- home_dir = (result.stdout or "").strip()
395- if not home_dir:
396- raise RuntimeError("Failed to determine the agent home directory")
397- return home_dir
53+ with TemporaryDirectory(prefix="mini-coder-harbor-") as tmp:
54+ tarball = Path(tmp) / "mini-coder-next.tgz"
55+ self._make_source_tarball(tarball)
56+ await environment.upload_file(tarball, "/tmp/mini-coder-next.tgz")
39857
399- async def _container_config_dir(self, environment: BaseEnvironment, home_dir: str) -> str:
400- config_dir = f"{home_dir}/.config/mini-coder"
40158 await self.exec_as_agent(
40259 environment,
40360 command=(
404- f"export HOME={shlex.quote(home_dir)}; "
405- f"mkdir -p {shlex.quote(config_dir)}"
61+ f"rm -rf {shlex.quote(self.CONTAINER_ROOT)} && "
62+ f"mkdir -p {shlex.quote(self.CONTAINER_ROOT)} && "
63+ f"tar -xzf /tmp/mini-coder-next.tgz -C {shlex.quote(self.CONTAINER_ROOT)} && "
64+ 'export PATH="$HOME/.bun/bin:$PATH"; '
65+ f"cd {shlex.quote(self.CONTAINER_ROOT)} && "
66+ "bun install --frozen-lockfile"
40667 ),
40768 )
408- return config_dir
40969
410- async def _upload_host_config_file(
70+ @with_prompt_template
71+ async def run(
41172 self,
73+ instruction: str,
41274 environment: BaseEnvironment,
413- host_path: Path,
414- container_tmp_path: str,
415- target_path: str,
416- *,
417- required: bool,
75+ context: AgentContext,
41876 ) -> None:
419- if not host_path.is_file():
420- if required:
421- raise FileNotFoundError(
422- f"Missing mini-coder config file required for Harbor: {host_path}"
423- )
424- return
77+ del context
78+
79+ home = await self._container_home(environment)
80+ config_dir = f"{home}/.config/mini-coder"
42581
426- await environment.upload_file(host_path, container_tmp_path)
427- await self.exec_as_root(
428- environment, command=f"chmod 644 {shlex.quote(container_tmp_path)}"
429- )
43082 await self.exec_as_agent(
43183 environment,
432- command=(
433- f"cp {shlex.quote(container_tmp_path)} {shlex.quote(target_path)} && "
434- f"chmod 600 {shlex.quote(target_path)}"
435- ),
436- )
437- await self.exec_as_root(
438- environment, command=f"rm -f {shlex.quote(container_tmp_path)}"
84+ command=f"mkdir -p {shlex.quote(config_dir)}",
43985 )
44086
441- async def _upload_host_auth(
442- self, environment: BaseEnvironment, config_dir: str
443- ) -> None:
444- await self._upload_host_config_file(
87+ await self._upload_config_file(
44588 environment,
446- self._host_auth_path,
447- "/tmp/mini-coder-auth.json",
89+ self.host_config_dir / "auth.json",
44890 f"{config_dir}/auth.json",
44991 required=True,
45092 )
451-
452- async def _upload_host_settings(
453- self, environment: BaseEnvironment, config_dir: str
454- ) -> None:
455- await self._upload_host_config_file(
93+ await self._upload_config_file(
45694 environment,
457- self._host_settings_path,
458- "/tmp/mini-coder-settings.json",
95+ self.host_config_dir / "settings.json",
45996 f"{config_dir}/settings.json",
46097 required=False,
46198 )
46299
463- @with_prompt_template
464- async def run(
100+ stdout_path = (EnvironmentPaths.agent_dir / self.STDOUT_LOG).as_posix()
101+ stderr_path = (EnvironmentPaths.agent_dir / self.STDERR_LOG).as_posix()
102+
103+ await self.exec_as_agent(
104+ environment,
105+ command=(
106+ f"export HOME={shlex.quote(home)}; "
107+ f'export PATH="{home}/.bun/bin:$PATH"; '
108+ f"bun {shlex.quote(self.CONTAINER_ROOT + '/bin/mc.ts')} "
109+ f"--json -p {shlex.quote(instruction)} "
110+ f"</dev/null >{shlex.quote(stdout_path)} 2>{shlex.quote(stderr_path)}"
111+ ),
112+ )
113+
114+ def populate_context_post_run(self, context: AgentContext) -> None:
115+ stdout_path = self.logs_dir / self.STDOUT_LOG
116+ stderr_path = self.logs_dir / self.STDERR_LOG
117+
118+ metadata = {
119+ "mini_coder_stdout": str(stdout_path),
120+ "mini_coder_stderr": str(stderr_path),
121+ }
122+
123+ usage = self._extract_usage(stdout_path)
124+ if usage:
125+ context.n_input_tokens = self._as_int(usage.get("input"))
126+ context.n_output_tokens = self._as_int(usage.get("output"))
127+
128+ cost = usage.get("cost")
129+ if isinstance(cost, dict):
130+ context.cost_usd = self._as_float(cost.get("total"))
131+
132+ metadata["usage"] = usage
133+
134+ context.metadata = {**(context.metadata or {}), **metadata}
135+
136+ def _make_source_tarball(self, tarball: Path) -> None:
137+ required = ["package.json", "bun.lock", "bin", "src"]
138+
139+ for name in required:
140+ path = self.repo_root / name
141+ if not path.exists():
142+ raise FileNotFoundError(f"Missing required mini-coder file: {path}")
143+
144+ with tarfile.open(tarball, "w:gz") as tf:
145+ for name in required:
146+ tf.add(self.repo_root / name, arcname=name)
147+
148+ tsconfig = self.repo_root / "tsconfig.json"
149+ if tsconfig.exists():
150+ tf.add(tsconfig, arcname="tsconfig.json")
151+
152+ async def _container_home(self, environment: BaseEnvironment) -> str:
153+ result = await self.exec_as_agent(environment, command='printf %s "$HOME"')
154+ home = (result.stdout or "").strip()
155+ if not home:
156+ raise RuntimeError("Could not determine container HOME")
157+ return home
158+
159+ async def _upload_config_file(
465160 self,
466- instruction: str,
467161 environment: BaseEnvironment,
468- context: AgentContext,
162+ host_path: Path,
163+ container_path: str,
164+ *,
165+ required: bool,
469166 ) -> None:
470- del context
471- self._require_host_auth()
472- home_dir = await self._container_home(environment)
473- config_dir = await self._container_config_dir(environment, home_dir)
474- await self._upload_host_auth(environment, config_dir)
475- await self._upload_host_settings(environment, config_dir)
476-
477- stdout_path = (
478- EnvironmentPaths.agent_dir / self._JSON_LOG_FILENAME
479- ).as_posix()
480- stderr_path = (
481- EnvironmentPaths.agent_dir / self._STDERR_LOG_FILENAME
482- ).as_posix()
483- mc_path = f"{home_dir}/.bun/bin/mc"
167+ if not host_path.exists():
168+ if required:
169+ raise FileNotFoundError(f"Missing mini-coder config file: {host_path}")
170+ return
171+
172+ tmp_path = f"/tmp/{host_path.name}"
173+ await environment.upload_file(host_path, tmp_path)
484174 await self.exec_as_agent(
485175 environment,
486176 command=(
487- f"export HOME={shlex.quote(home_dir)}; "
488- f"export PATH={shlex.quote(f'{home_dir}/.bun/bin')}:$PATH; "
489- f"{shlex.quote(mc_path)} --json -p {shlex.quote(instruction)} </dev/null "
490- f">{shlex.quote(stdout_path)} "
491- f"2>{shlex.quote(stderr_path)}"
177+ f"cp {shlex.quote(tmp_path)} {shlex.quote(container_path)} && "
178+ f"chmod 600 {shlex.quote(container_path)}"
492179 ),
493180 )
181+
182+ @staticmethod
183+ def _extract_usage(path: Path) -> dict[str, Any] | None:
184+ if not path.exists():
185+ return None
186+
187+ # mini-coder --json currently emits newline-delimited JSON events.
188+ for line in reversed(path.read_text(encoding="utf-8", errors="replace").splitlines()):
189+ try:
190+ event = json.loads(line)
191+ except json.JSONDecodeError:
192+ continue
193+
194+ if not isinstance(event, dict):
195+ continue
196+
197+ message = event.get("message")
198+ if isinstance(message, dict) and isinstance(message.get("usage"), dict):
199+ return message["usage"]
200+
201+ if isinstance(event.get("usage"), dict):
202+ return event["usage"]
203+
204+ return None
205+
206+ @staticmethod
207+ def _as_int(value: Any) -> int | None:
208+ return value if isinstance(value, int) and not isinstance(value, bool) else None
209+
210+ @staticmethod
211+ def _as_float(value: Any) -> float | None:
212+ return float(value) if isinstance(value, int | float) and not isinstance(value, bool) else None
biome.json+1−1
@@ -1,5 +1,5 @@
11 {
2- "$schema": "https://biomejs.dev/schemas/2.4.12/schema.json",
2+ "$schema": "https://biomejs.dev/schemas/2.4.13/schema.json",
33 "assist": {
44 "actions": {
55 "source": {
bun.lock+13−2
@@ -7,12 +7,13 @@
77 "dependencies": {
88 "@cel-tui/components": "^0.8.1",
99 "@cel-tui/core": "^0.8.1",
10- "@mariozechner/pi-ai": "^0.70.0",
10+ "@mariozechner/pi-ai": "^0.70.2",
1111 "diff": "^9.0.0",
12+ "simple-git": "^3.36.0",
1213 "yaml": "^2.8.3",
1314 },
1415 "devDependencies": {
15- "@biomejs/biome": "^2.4.12",
16+ "@biomejs/biome": "^2.4.13",
1617 "@types/bun": "^1.3.13",
1718 "prettier": "^3.8.3",
1819 "typescript": "^6.0.3",
@@ -124,6 +125,10 @@
124125
125126 "@google/genai": ["@google/genai@1.50.1", "", { "dependencies": { "google-auth-library": "^10.3.0", "p-retry": "^4.6.2", "protobufjs": "^7.5.4", "ws": "^8.18.0" }, "peerDependencies": { "@modelcontextprotocol/sdk": "^1.25.2" }, "optionalPeers": ["@modelcontextprotocol/sdk"] }, "sha512-YbkX7H9+1Pt8wOt7DDREy8XSoiL6fRDzZQRyaVBarFf8MR3zHGqVdvM4cLbDXqPhxqvegZShgfxb8kw9C7YhAQ=="],
126127
128+ "@kwsites/file-exists": ["@kwsites/file-exists@1.1.1", "", { "dependencies": { "debug": "^4.1.1" } }, "sha512-m9/5YGR18lIwxSFDwfE3oA7bWuq9kdau6ugN4H2rJeyhFQZcG9AgSHkQtSD15a8WvTgfz9aikZMrKPHvbpqFiw=="],
129+
130+ "@kwsites/promise-deferred": ["@kwsites/promise-deferred@1.1.1", "", {}, "sha512-GaHYm+c0O9MjZRu0ongGBRbinu8gVAMd2UZjji6jVmqKtZluZnptXGWhz1E8j8D2HJ3f/yMxKAUC0b+57wncIw=="],
131+
127132 "@mariozechner/pi-ai": ["@mariozechner/pi-ai@0.70.2", "", { "dependencies": { "@anthropic-ai/sdk": "^0.90.0", "@aws-sdk/client-bedrock-runtime": "^3.1030.0", "@google/genai": "^1.40.0", "@mistralai/mistralai": "^2.2.0", "chalk": "^5.6.2", "openai": "6.26.0", "partial-json": "^0.1.7", "proxy-agent": "^6.5.0", "typebox": "^1.1.24", "undici": "^7.19.1", "zod-to-json-schema": "^3.24.6" }, "bin": { "pi-ai": "dist/cli.js" } }, "sha512-+30LRPjXsXF+oI96DvGWMbdPGeqoLJvadh6UPev7wx2DzhC9FEqXkQcoMZ0usbC …
128133
129134 "@mistralai/mistralai": ["@mistralai/mistralai@2.2.0", "", { "dependencies": { "ws": "^8.18.0", "zod": "^3.25.0 || ^4.0.0", "zod-to-json-schema": "^3.25.0" } }, "sha512-JQUGIXjFWnw/J9LpTSf/ZXwVW3Sh8FBAcfTo5QvAHqkl4CfSiIwnjRJhMoAFcP6ncCe84YPU1ncDGX+p3OXnfg=="],
@@ -148,6 +153,10 @@
148153
149154 "@protobufjs/utf8": ["@protobufjs/utf8@1.1.0", "", {}, "sha512-Vvn3zZrhQZkkBE8LSuW3em98c0FwgO4nxzv6OdSxPKJIEKY2bGbHn+mhGIPerzI4twdxaP8/0+06HBpwf345Lw=="],
150155
156+ "@simple-git/args-pathspec": ["@simple-git/args-pathspec@1.0.3", "", {}, "sha512-ngJMaHlsWDTfjyq9F3VIQ8b7NXbBLq5j9i5bJ6XLYtD6qlDXT7fdKY2KscWWUF8t18xx052Y/PUO1K1TRc9yKA=="],
157+
158+ "@simple-git/argv-parser": ["@simple-git/argv-parser@1.1.1", "", { "dependencies": { "@simple-git/args-pathspec": "^1.0.3" } }, "sha512-Q9lBcfQ+VQCpQqGJFHe5yooOS5hGdLFFbJ5R+R5aDsnkPCahtn1hSkMcORX65J2Z5lxSkD0lQorMsncuBQxYUw=="],
159+
151160 "@smithy/config-resolver": ["@smithy/config-resolver@4.4.17", "", { "dependencies": { "@smithy/node-config-provider": "^4.3.14", "@smithy/types": "^4.14.1", "@smithy/util-config-provider": "^4.2.2", "@smithy/util-endpoints": "^3.4.2", "@smithy/util-middleware": "^4.2.14", "tslib": "^2.6.2" } }, "sha512-TzDZcAnhTyAHbXVxWZo7/tEcrIeFq20IBk8So3OLOetWpR8EwY/yEqBMBFaJMeyEiREDq4NfEl+qO3OAUD+vbQ=="],
152161
153162 "@smithy/core": ["@smithy/core@3.23.16", "", { "dependencies": { "@smithy/protocol-http": "^5.3.14", "@smithy/types": "^4.14.1", "@smithy/url-parser": "^4.2.14", "@smithy/util-base64": "^4.3.2", "@smithy/util-body-length-browser": "^4.2.2", "@smithy/util-middleware": "^4.2.14", "@smithy/util-stream": "^4.5.24", "@smithy/util-utf8": "^4.2.2", "@smithy/uuid": "^1.1.2", "tslib": "^2.6.2" } }, "sha512-JStomOrINQA1VqNEopLsgcdgwd42au7mykKqVr30XFw89wLt9sDxJDi4djVPRwQmmzyTGy/uOvTc2ultMpFi1w=="],
@@ -354,6 +363,8 @@
354363
355364 "safe-buffer": ["safe-buffer@5.2.1", "", {}, "sha512-rp3So07KcdmmKbGvgaNxQSJr7bGVSVk5S9Eq1F+ppbRo70+YeaDxkw5Dd8NPN+GD6bjnYm2VuPuCXmpuYvmCXQ=="],
356365
366+ "simple-git": ["simple-git@3.36.0", "", { "dependencies": { "@kwsites/file-exists": "^1.1.1", "@kwsites/promise-deferred": "^1.1.1", "@simple-git/args-pathspec": "^1.0.3", "@simple-git/argv-parser": "^1.1.0", "debug": "^4.4.0" } }, "sha512-cGQjLjK8bxJw4QuYT7gxHw3/IouVESbhahSsHrX97MzCL1gu2u7oy38W6L2ZIGECEfIBG4BabsWDPjBxJENv9Q=="],
367+
357368 "smart-buffer": ["smart-buffer@4.2.0", "", {}, "sha512-94hK0Hh8rPqQl2xXc3HsaBoOXKV20MToPkcXvwbISWLEs+64sBq5kFgn2kJDHb1Pry9yrP0dxrCI9RRci7RXKg=="],
358369
359370 "socks": ["socks@2.8.7", "", { "dependencies": { "ip-address": "^10.0.1", "smart-buffer": "^4.2.0" } }, "sha512-HLpt+uLy/pxB+bum/9DzAgiKS8CX1EvbWxI4zlmgGCExImLdiad2iCwXT5Z4c9c3Eq8rP2318mPW2c+QbtjK8A=="],
package.json+1−0
@@ -24,6 +24,7 @@
2424 "@cel-tui/core": "^0.8.1",
2525 "@mariozechner/pi-ai": "^0.70.2",
2626 "diff": "^9.0.0",
27+ "simple-git": "^3.36.0",
2728 "yaml": "^2.8.3"
2829 }
2930 }
src/agent.ts+138−65
@@ -1,5 +1,5 @@
11 import { readdir } from "node:fs/promises";
2-import { homedir } from "node:os";
2+import { homedir, platform } from "node:os";
33 import { join } from "node:path";
44 import {
55 type AssistantMessage,
@@ -10,36 +10,98 @@ import {
1010 streamSimple,
1111 type ToolResultMessage,
1212 } from "@mariozechner/pi-ai";
13+import { simpleGit, type StatusResult } from "simple-git";
1314 import { parseSkillFrontmatter } from "./shared";
1415 import type { CliOptions, ToolAndRunner } from "./types";
1516
16-// TODO: Add environment information section (including git status)
17-const IDENTITY_PROMPT = `# You are "mini-coder", an elite coding agent.
17+const IDENTITY_PROMPT = `# You are "mini-coder", an efficient, elite coding agent.
1818
19-Behaviour guidelines:
19+## Behaviour rules:
2020
21-- Summaries must match the diff.
22-- Do not overstate what changed or what was verified.
23-- Do not over-scope your work, focus on the requirements to answer only.
24-- Once you've gathered enough information to complete the request, stop exploring and complete it.
21+**IMPORTANT**: This is your default behaviour, breaking these rules is unacceptable.
22+
23+- Answer all user requests without guessing, or assuming.
24+- Use recent online information, the current environment, and your training data combined for a complete answer.
2525 - Be defensive with existing changes and destructive commands, they could harm your user's changes.
26+- Be efficient, don't get lost with tangents or satisfying your curiosity, root yourself on the user request.
27+- Narrate your edits with small commentary messages during long tasks.
28+- Do not over-scope your work, or add more scope during implementation.
29+- Focus on the user's request requirements to answer accurately and efficiently.
30+- Once you've gathered enough information to complete the request, stop exploring and complete it.
31+- Ensure that you fulfill the user's expectation, requirements and contract **exactly**.
32+- Use temp directory for temp files, scripts, plan files, or anything that doesn't match the requested output.
33+- Always verify your changes using compilation, testing, and manual verification when possible.
34+- Do not overstate what changed or what was verified. Never make unverified claims.
35+- Summaries must match the diff.
2636 - Tone: use a jovial but motivated colleague persona. Be less verbose and more concise. You are working with software engineers, act appropriately, no fluff, only direct talk.`;
2737
2838 export const MAIN_PROMPT = `${IDENTITY_PROMPT}
29-- Answer all user questions without guessing, or assuming.
30-- Use recent online information, the current environment, and your training data combined for a complete answer.
31-- **Use the \`task()\` tool to do most your work**. Define a plan with the user, break it down into tasks, and use the tool.
32-- If a task requires more than 1 or 2 other tool calls, or follow up calls, **always** use the \`task()\` tool instead.
39+
40+## Workflow:
41+
42+- Use this if the user did not specify a workflow.
43+
44+1. Read the user's message, understand the request.
45+2. Gather context from the local environment, local code, docs and online related references to the request as needed.
46+3. Plan your changes by breaking down the request into small tasks, resolve open questions with the user to complete your plan with accuracy and detail.
47+4. Use the appropriate tools to execute the plan. Keep the plan up to date and follow it accurately.
48+5. Validate your changes without adding more scope to your work.
49+6. Summarize your changes and completed plan in your final message.
50+
51+## Tool selection heuristic:
52+
53+**Always** follow this logic when deciding your tool usage:
54+
55+- You have limitted context size, the task tool compresses tool loops for you, keeping your context pressure low.
56+- Before **every tool call** consider if you are doing too much in your context window, and favor using the task tool.
57+- If the user's request requires **less** than 3 to 4 shell/edit/read tool calls, use them and complete the request.
58+- Else, the request requires **more** than 4 shell/edit tool calls, use the \`task()\` tool.
59+- This is not optional, if you fill your context with exploration, excessive tool calls, then you have none left to help the user. This is unacceptable.
60+
61+**IMPORTANT: Always make sure you are not falling into a shell tool calling loop!**
62+
63+- This is a clear sign you should be using the task tool. Stop the loop and use the task tool.
3364 `;
3465
3566 export const TASK_PROMPT = `${IDENTITY_PROMPT}
36-- Use recent online information, the current environment, and your training data combined for a complete answer.
37-- When completing a task, ensure that you fulfill the contract **exactly**.
38-- Always verify your changes using compilation, testing, and manual verification when possible.
39-- Use temp directory for temp files, scripts or anything that doesn't match the requested output.
40-- Your final message should include a summary of your actions and any diffs from your edits.
67+
68+## Workflow:
69+
70+1. Read the user message, understand the request. Gather context as needed to complete the request.
71+2. Plan your changes by breaking down the request into smaller tasks as needed.
72+3. Execute your plan with the appropriate tools.
73+4. Validate your changes without adding scope, and ensuring the user's request is met **exactly** with no deviations.
74+5. Your final message should include a summary of your actions and any diffs from your edits.
4175 `;
4276
77+async function getEnvPrompt() {
78+ // TODO: What else do the agents always check before answering every time?
79+ let gitStatus: StatusResult | {nogit: string};
80+ try {
81+ gitStatus = await simpleGit().status();
82+ } catch (_) {
83+ gitStatus = {nogit: "No git repo in this folder."};
84+ }
85+ const envStatus = JSON.stringify(
86+ {
87+ cwd: process.cwd(),
88+ os: platform(),
89+ git: gitStatus,
90+ },
91+ null,
92+ 4,
93+ );
94+
95+ const text = `### Environment status and information
96+
97+\`\`\`json
98+ ${envStatus}
99+\`\`\`
100+`;
101+
102+ return text;
103+}
104+
43105 // `AGENTS.md` support: find it in current folder (./AGENTS.md) and a global one. (`.agents/AGENTS.md`)
44106 export async function getAGENTSFiles() {
45107 const content: string[] = [];
@@ -94,7 +156,7 @@ export async function getSkills(): Promise<string> {
94156
95157 skillsBlock += `## ${parsed.name}
96158
97-> File: ${path}
159+> Absolute file path to read: ${path}
98160
99161 ${parsed.description}
100162
@@ -106,8 +168,10 @@ ${parsed.description}
106168
107169 const skills = `# Skills
108170
109-The following skills provide specialized instructions for specific tasks.
110-Use the shell tool to read a skill's file when the task matches its description.
171+- The following skills provide specialized instructions for specific tasks.
172+- Use the shell tool to read a skill's file when the task matches its description.
173+- Use the skill provided absolute file path instead of guessing or constructing one.
174+- Skills can be global (in ~/.agents/skills) or locat to the directory (./agents/skills)
111175
112176 ${skillsBlock}`;
113177
@@ -117,7 +181,8 @@ ${skillsBlock}`;
117181 export async function buildSystemPrompt(systemPrompt: string) {
118182 const agentsContent = await getAGENTSFiles();
119183 const skillsContent = await getSkills();
120- let complete = systemPrompt;
184+ const envStatus = await getEnvPrompt();
185+ let complete = systemPrompt + envStatus;
121186
122187 if (skillsContent) {
123188 complete += `\n${skillsContent}`;
@@ -154,55 +219,63 @@ export async function streamAgent(
154219 // Wire the global abort signal to each turn http requests
155220 abortController?.signal.addEventListener("abort", onAbort);
156221
157- while (true) {
158- controller = new AbortController();
159- const s = streamSimple(options.model, context, {
160- apiKey,
161- reasoning: options.effort,
162- signal: controller.signal,
163- });
222+ try {
223+ while (true) {
224+ controller = new AbortController();
225+ const s = streamSimple(options.model, context, {
226+ apiKey,
227+ reasoning: options.effort,
228+ signal: controller.signal,
229+ });
164230
165- for await (const ev of s) {
166- streamFn?.(ev, context);
167- }
231+ for await (const ev of s) {
232+ streamFn?.(ev, context);
233+ }
168234
169- const finalMessage = await s.result();
170- context.messages.push(finalMessage);
235+ const finalMessage = await s.result();
236+ context.messages.push(finalMessage);
171237
172- if (["stop", "error", "aborted"].includes(finalMessage.stopReason)) {
173- completeFn?.(finalMessage, context);
174- abortController?.signal.removeEventListener("abort", onAbort);
175- return;
176- }
238+ // Check if the agent is done, or an error/abort happened before moving
239+ // on towards tool calling.
240+ if (["stop", "error", "aborted"].includes(finalMessage.stopReason)) {
241+ // Agent is done, send the final message, and current context.
242+ completeFn?.(finalMessage, context);
243+ abortController?.signal.removeEventListener("abort", onAbort);
244+ return;
245+ }
177246
178- const toolCalls = finalMessage.content.filter(
179- (msg) => msg.type === "toolCall",
180- );
181-
182- for (const call of toolCalls) {
183- const toolDef = tools.find((i) => i.tool.name === call.name);
184- const result = (await toolDef?.runner(call.arguments)) || "";
185- const msg: ToolResultMessage = {
186- role: "toolResult",
187- toolCallId: call.id,
188- toolName: call.name,
189- content: [{ type: "text", text: result }],
190- isError: false,
191- timestamp: Date.now(),
192- };
193- context.messages.push(msg);
194- toolsFn?.(msg, context);
195- }
247+ // Call tolls and per tool result callback.
248+ const toolCalls = finalMessage.content.filter(
249+ (msg) => msg.type === "toolCall",
250+ );
251+
252+ for (const call of toolCalls) {
253+ const toolDef = tools.find((i) => i.tool.name === call.name);
254+ const result = (await toolDef?.runner(call.arguments)) || "";
255+ const msg: ToolResultMessage = {
256+ role: "toolResult",
257+ toolCallId: call.id,
258+ toolName: call.name,
259+ content: [{ type: "text", text: result }],
260+ isError: false,
261+ timestamp: Date.now(),
262+ };
263+ context.messages.push(msg);
264+
265+ // Update with tool results.
266+ toolsFn?.(msg, context);
267+ }
196268
197- if (toolCalls.length > 0) {
198- // TODO: Investigate why we get an error: `No output for tool call id XXXX...` when
199- // we add { apiKey } in this call. And how does it work without it?
200- const cont = await completeSimple(options.model, context, {
201- apiKey,
202- reasoning: options.effort,
203- signal: controller.signal,
204- });
205- context.messages.push(cont);
269+ if (toolCalls.length > 0) {
270+ const cont = await completeSimple(options.model, context, {
271+ apiKey,
272+ reasoning: options.effort,
273+ signal: controller.signal,
274+ });
275+ context.messages.push(cont);
276+ }
206277 }
278+ } finally {
279+ abortController?.signal.removeEventListener("abort", onAbort);
207280 }
208281 }
src/headless.ts+69−47
@@ -1,4 +1,9 @@
1-import type { Message } from "@mariozechner/pi-ai";
1+import type {
2+ AssistantMessage,
3+ AssistantMessageEvent,
4+ Message,
5+ ToolResultMessage,
6+} from "@mariozechner/pi-ai";
27 import { MAIN_PROMPT, streamAgent } from "./agent";
38 import { getApiKey } from "./oauth";
49 import { bash, runBashTool } from "./tool-bash";
@@ -21,13 +26,68 @@ export async function streamHeadless(
2126 { role: "user", content: options.prompt || "", timestamp: Date.now() },
2227 ];
2328
Cut short: this commit's diff is over 1000 lines.
src/tool-bash.ts+2−2
Cut short: this commit's diff is over 1000 lines.
src/tool-edit.ts+8−2
Cut short: this commit's diff is over 1000 lines.
src/tool-task.ts+32−19
Cut short: this commit's diff is over 1000 lines.
src/tui.ts+124−111
Cut short: this commit's diff is over 1000 lines.