xonecas.io
64875
Mc

mini-coder / commit d15d14c

feat: abort, clear input, and quit updates

xonecas2026-04-24 d15d14cd8ab94934960da9b2644115aee1108bbe parent e3055c5

11 files changed

.gitignore+1−0
@@ -2,3 +2,4 @@
22 node_modules
33 __pycache__
44 *.pyc
5+benchmarks/jobs
benchmarks/break-filter-js-from-html.sh+9−0
@@ -0,0 +1,9 @@
1+PYTHONPATH="$PWD" harbor run -y \
2+ --job-name "break-filter-js-from-html-$(date +%F__%H-%M-%S)" \
3+ --jobs-dir "$PWD/benchmarks/jobs" \
4+ --dataset terminal-bench/terminal-bench-2 \
5+ --include-task-name terminal-bench/break-filter-js-from-html \
6+ --agent-import-path benchmarks.local-harbor-agent:LocalMiniCoderAgent \
7+ --n-attempts 4 \
8+ --n-concurrent 2 \
9+ --max-retries 0
benchmarks/filter-js-from-html.sh+9−0
@@ -0,0 +1,9 @@
1+PYTHONPATH="$PWD" harbor run -y \
2+ --job-name "filter-js-from-html-$(date +%F__%H-%M-%S)" \
3+ --jobs-dir "$PWD/benchmarks/jobs" \
4+ --dataset terminal-bench/terminal-bench-2 \
5+ --include-task-name terminal-bench/filter-js-from-html \
6+ --agent-import-path benchmarks.local-harbor-agent:LocalMiniCoderAgent \
7+ --n-attempts 4 \
8+ --n-concurrent 2 \
9+ --max-retries 0
benchmarks/fix-git.sh+9−0
@@ -0,0 +1,9 @@
1+PYTHONPATH="$PWD" harbor run -y \
2+ --job-name "fix-git-$(date +%F__%H-%M-%S)" \
3+ --jobs-dir "$PWD/benchmarks/jobs" \
4+ --dataset terminal-bench/terminal-bench-2 \
5+ --include-task-name terminal-bench/fix-git \
6+ --agent-import-path benchmarks.local-harbor-agent:LocalMiniCoderAgent \
7+ --n-attempts 4 \
8+ --n-concurrent 2 \
9+ --max-retries 0
benchmarks/local-harbor-agent.py+177−2
@@ -1,2 +1,177 @@
1-# TODO: Implement the harbor agent that runs the local checkout of mini-coder
2-# Use the current environments auth from `~/.config/mini-coder/auth.json`
1+from __future__ import annotations
2+
3+import shlex
4+import subprocess
5+from pathlib import Path
6+from tempfile import TemporaryDirectory
7+
8+from harbor.agents.installed.base import BaseInstalledAgent, with_prompt_template
9+from harbor.environments.base import BaseEnvironment
10+from harbor.models.agent.context import AgentContext
11+from harbor.models.trial.paths import EnvironmentPaths
12+
13+
14+class LocalMiniCoderAgent(BaseInstalledAgent):
15+ """Harbor installed-agent wrapper for this local mini-coder checkout."""
16+
17+ def __init__(self, *args, version: str = "local", **kwargs):
18+ super().__init__(*args, version=version, **kwargs)
19+ self._host_repo_root = Path(__file__).resolve().parents[1]
20+ self._host_auth_path = Path.home() / ".config" / "mini-coder" / "auth.json"
21+
22+ @staticmethod
23+ def name() -> str:
24+ return "mini-coder-local"
25+
26+ async def install(self, environment: BaseEnvironment) -> None:
27+ self._require_host_checkout()
28+ await self._install_system_dependencies(environment)
29+ await self._install_bun(environment)
30+
31+ with TemporaryDirectory(prefix="mini-coder-harbor-") as temp_dir:
32+ tarball_path = self._package_local_checkout(Path(temp_dir))
33+ container_tarball_path = f"/tmp/{tarball_path.name}"
34+ await environment.upload_file(tarball_path, container_tarball_path)
35+ await self._install_global_package(environment, container_tarball_path)
36+
37+ def populate_context_post_run(self, context: AgentContext) -> None:
38+ del context
39+
40+ def _require_host_checkout(self) -> None:
41+ missing = [
42+ path
43+ for path in (
44+ self._host_repo_root / "package.json",
45+ self._host_repo_root / "bin" / "mc.ts",
46+ self._host_repo_root / "src",
47+ )
48+ if not path.exists()
49+ ]
50+ if missing:
51+ raise FileNotFoundError(
52+ "Missing local mini-coder checkout files required for Harbor: "
53+ + ", ".join(str(path) for path in missing)
54+ )
55+
56+ def _require_host_auth(self) -> None:
57+ if not self._host_auth_path.is_file():
58+ raise FileNotFoundError(
59+ f"Missing mini-coder auth file required for Harbor: {self._host_auth_path}"
60+ )
61+
62+ def _package_local_checkout(self, target_dir: Path) -> Path:
63+ target_dir.mkdir(parents=True, exist_ok=True)
64+ tarball_path = target_dir / "mini-coder-local.tgz"
65+
66+ try:
67+ result = subprocess.run(
68+ [
69+ "bun",
70+ "pm",
71+ "pack",
72+ "--ignore-scripts",
73+ "--filename",
74+ str(tarball_path),
75+ ],
76+ cwd=self._host_repo_root,
77+ capture_output=True,
78+ text=True,
79+ check=False,
80+ )
81+ except FileNotFoundError as exc:
82+ raise RuntimeError("bun is required on the host to package mini-coder") from exc
83+
84+ if result.returncode != 0:
85+ details = result.stderr.strip() or result.stdout.strip() or "unknown error"
86+ raise RuntimeError(f"Failed to package mini-coder: {details}")
87+ if not tarball_path.is_file():
88+ raise RuntimeError(f"Expected mini-coder package at {tarball_path}")
89+
90+ return tarball_path
91+
92+ async def _install_system_dependencies(self, environment: BaseEnvironment) -> None:
93+ await self.exec_as_root(
94+ environment,
95+ command=(
96+ "if command -v apt-get >/dev/null 2>&1; then "
97+ "apt-get update && apt-get install -y curl unzip ca-certificates bash; "
98+ "elif command -v apk >/dev/null 2>&1; then "
99+ "apk add --no-cache curl unzip ca-certificates bash; "
100+ "elif command -v yum >/dev/null 2>&1; then "
101+ "yum install -y curl unzip ca-certificates bash; "
102+ "else echo 'Unsupported package manager for mini-coder install' >&2; exit 1; fi"
103+ ),
104+ env={"DEBIAN_FRONTEND": "noninteractive"},
105+ )
106+
107+ async def _install_bun(self, environment: BaseEnvironment) -> None:
108+ await self.exec_as_agent(
109+ environment,
110+ command=(
111+ "if ! command -v bun >/dev/null 2>&1; then "
112+ "curl -fsSL https://bun.sh/install | bash; fi; "
113+ "export PATH=\"$HOME/.bun/bin:$PATH\"; "
114+ "test -x \"$(command -v bun)\""
115+ ),
116+ )
117+
118+ async def _install_global_package(
119+ self, environment: BaseEnvironment, package_spec: str
120+ ) -> None:
121+ await self.exec_as_agent(
122+ environment,
123+ command=(
124+ "export PATH=\"$HOME/.bun/bin:$PATH\"; "
125+ f"bun add -g --ignore-scripts {shlex.quote(package_spec)}; "
126+ "test -x ~/.bun/bin/mc || command -v mc >/dev/null"
127+ ),
128+ )
129+
130+ async def _container_config_dir(self, environment: BaseEnvironment) -> str:
131+ result = await self.exec_as_agent(environment, command='printf %s "$HOME"')
132+ home_dir = (result.stdout or "").strip()
133+ if not home_dir:
134+ raise RuntimeError("Failed to determine the agent home directory")
135+
136+ config_dir = f"{home_dir}/.config/mini-coder"
137+ await self.exec_as_agent(environment, command=f"mkdir -p {shlex.quote(config_dir)}")
138+ return config_dir
139+
140+ async def _upload_host_auth(
141+ self, environment: BaseEnvironment, config_dir: str
142+ ) -> None:
143+ tmp_auth_path = "/tmp/mini-coder-auth.json"
144+ auth_target = f"{config_dir}/auth.json"
145+ await environment.upload_file(self._host_auth_path, tmp_auth_path)
146+ await self.exec_as_root(environment, command=f"chmod 644 {tmp_auth_path}")
147+ await self.exec_as_agent(
148+ environment,
149+ command=(
150+ f"cp {shlex.quote(tmp_auth_path)} {shlex.quote(auth_target)} && "
151+ f"chmod 600 {shlex.quote(auth_target)}"
152+ ),
153+ )
154+
155+ @with_prompt_template
156+ async def run(
157+ self,
158+ instruction: str,
159+ environment: BaseEnvironment,
160+ context: AgentContext,
161+ ) -> None:
162+ del context
163+ self._require_host_auth()
164+ config_dir = await self._container_config_dir(environment)
165+ await self._upload_host_auth(environment, config_dir)
166+
167+ stdout_path = (EnvironmentPaths.agent_dir / "mini-coder.json").as_posix()
168+ stderr_path = (EnvironmentPaths.agent_dir / "mini-coder.stderr.txt").as_posix()
169+ await self.exec_as_agent(
170+ environment,
171+ command=(
172+ "export PATH=\"$HOME/.bun/bin:$PATH\"; "
173+ f"mc --json -p {shlex.quote(instruction)} </dev/null "
174+ f">{shlex.quote(stdout_path)} "
175+ f"2>{shlex.quote(stderr_path)}"
176+ ),
177+ )
src/agent.ts+13−3
@@ -22,8 +22,8 @@ Behaviour guidelines:
2222 - Once you've gathered enough information to complete the request, stop exploring and complete the task.
2323 - When completing a task, ensure that you fulfill the contract **exactly**.
2424 - Use temp directory for temp files, scripts or anything that doesn't match the requested output.
25-- Be careful with existing changes and destructive commands, they could be your user's changes.
26-- Tone: use a jovial but motivated colleague persona. Be less verbose and more concise. You are working with software engineers, act appropriate, no fluff, only direct talk.
25+- Be careful with existing changes and destructive commands, they could harm your user's changes.
26+- 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.
2727 `;
2828
2929 // `AGENTS.md` support: find it in current folder (./AGENTS.md) and a global one. (`.agents/AGENTS.md`)
@@ -122,6 +122,7 @@ export async function streamAgent(
122122 systemPrompt: string,
123123 messages: Message[],
124124 options: CliOptions,
125+ abortController?: AbortController,
125126 streamFn?: (ev: AssistantMessageEvent) => void,
126127 toolsFn?: (tool: ToolResultMessage) => void,
127128 completeFn?: (msg: AssistantMessage, context: Context) => void,
@@ -132,10 +133,17 @@ export async function streamAgent(
132133 tools: tools.map((t) => t.tool),
133134 };
134135
136+ let controller: AbortController
137+ const onAbort = () => { controller?.abort(); }
138+ // Wire the global abort signal to each turn http requests
139+ abortController?.signal.addEventListener('abort', onAbort)
140+
135141 while (true) {
142+ controller = new AbortController()
136143 const s = streamSimple(options.model, context, {
137144 apiKey,
138145 reasoning: options.effort,
146+ signal: controller.signal
139147 });
140148
141149 for await (const ev of s) {
@@ -163,17 +171,19 @@ export async function streamAgent(
163171 toolsFn?.(msg);
164172 }
165173
166- if (toolCalls.length > 0) {
174+ if (toolCalls.length > 0 && !["error", "aborted"].includes(finalMessage.stopReason)) {
167175 // TODO: Investigate why we get an error: `No output for tool call id XXXX...` when
168176 // we add { apiKey } in this call. And how does it work without it?
169177 const cont = await completeSimple(options.model, context, {
170178 reasoning: options.effort,
179+ signal: controller.signal
171180 });
172181 context.messages.push(cont);
173182 }
174183
175184 if (["stop", "error", "aborted"].includes(finalMessage.stopReason)) {
176185 completeFn?.(finalMessage, context);
186+ abortController?.signal.removeEventListener('abort', onAbort)
177187 return;
178188 }
179189 }
src/headless.ts+1−0
@@ -33,6 +33,7 @@ export async function streamHeadless(
3333 TASK_PROMPT,
3434 messages,
3535 options,
36+ undefined,
3637 (ev) => {
3738 switch (ev.type) {
3839 case "text_start":
src/index.ts+4−0
@@ -16,6 +16,9 @@ export async function main(): Promise<void> {
1616 process.exit(0);
1717 }
1818
19+
20+ const abortController = new AbortController();
21+
1922 const state: TUIState = {
2023 options,
2124 prompt: "",
@@ -24,6 +27,7 @@ export async function main(): Promise<void> {
2427 streaming: false,
2528 stickToBottom: true,
2629 scrollOffset: 0,
30+ abortController
2731 };
2832
2933 initTUI(state, leave);
src/tui-components.ts+14−0
@@ -1,5 +1,6 @@
11 import { type Color, HStack, Text } from "@cel-tui/core";
22 import { onceEvery } from "./shared";
3+import { TUIState } from "./types";
34
45 export const theme = {
56 black: "color00" as Color,
@@ -88,3 +89,16 @@ export function Spinner() {
8889
8990 return { spinnerEvery, currentSpinner };
9091 }
92+
93+export function ActivityPill(state: TUIState, spinnerFrame: string) {
94+ let label = state.activeState.replaceAll("_", " ");
95+ const fg = state.streaming ? theme.bblack : theme.bwhite;
96+ const bg = state.streaming ? theme.bwhite : theme.bblack;
97+ const frame = state.streaming ? spinnerFrame : ""
98+
99+ if (frame) {
100+ label += ` ${frame}`
101+ }
102+
103+ return TextPill(label, fg, bg)
104+}
src/tui.ts+26−6
@@ -1,17 +1,30 @@
11 import { basename } from "node:path";
2-import { cel, HStack, ProcessTerminal, VStack } from "@cel-tui/core";
2+import { cel, HStack, ProcessTerminal, Text, VStack } from "@cel-tui/core";
33 import type { Message } from "@mariozechner/pi-ai";
44 import { streamAgent, TASK_PROMPT } from "./agent";
55 import { getApiKey } from "./oauth";
66 import { secureRandomString } from "./shared";
77 import { bash, runBashTool } from "./tool-bash";
88 import { edit, runEditTool } from "./tool-edit";
9-import { Spinner, TextPill, theme } from "./tui-components";
9+import { ActivityPill, Spinner, TextPill, theme } from "./tui-components";
1010 import { Conversation } from "./tui-conversation";
1111 import { Editor } from "./tui-editor";
1212 import { createTUIToolMessage } from "./tui-state";
1313 import type { ToolAndRunner, TUIMessage, TUIState } from "./types";
1414
15+function clearOrAbort(state: TUIState) {
16+ // Are we mid stream? Abort it.
17+ if (state.streaming) {
18+ state.abortController.abort()
19+ state.abortController = new AbortController();
20+ }
21+
22+ // Is the user clearing a state prompt?
23+ if (state.prompt?.length) {
24+ state.prompt = ""
25+ }
26+}
27+
1528 export function initTUI(state: TUIState, leave: (s: string) => void) {
1629 const cwd = basename(process.cwd());
1730 const { spinnerEvery, currentSpinner } = Spinner();
@@ -37,9 +50,13 @@ export function initTUI(state: TUIState, leave: (s: string) => void) {
3750 padding: { x: 1, y: 1 },
3851 onKeyPress: (key) => {
3952 if (key === "ctrl+q" || key === "ctrl+c" || key === "ctrl+d") {
53+ // Quit
4054 clearInterval(baseFramerateIntervalId);
4155 cel.stop();
4256 leave("Done.");
57+ } else if (key === 'escape') {
58+ // Abort or clear prompt
59+ clearOrAbort(state)
4360 }
4461 },
4562 },
@@ -50,10 +67,7 @@ export function initTUI(state: TUIState, leave: (s: string) => void) {
5067 TextPill(state.options.model.name, theme.bblack, theme.bwhite),
5168 TextPill(`../${cwd}`, theme.bwhite, theme.bblack),
5269 VStack({ flex: 1 }, []),
53- TextPill(state.activeState, theme.bwhite, theme.bblack),
54- state.streaming
55- ? TextPill(currentSpinner(), theme.black, theme.white)
56- : TextPill(currentSpinner(), theme.bwhite, theme.bblack),
70+ ActivityPill(state, currentSpinner())
5771 ]),
5872
5973 Editor(
@@ -66,6 +80,11 @@ export function initTUI(state: TUIState, leave: (s: string) => void) {
6680 (key: string) => {
6781 // onKeyPress
6882 if (key === "enter") {
83+ if (state.prompt === ':q') {
84+ clearInterval(baseFramerateIntervalId)
85+ cel.stop()
86+ leave("Done. I like vim too.")
87+ }
6988 const submit = async () => {
7089 await streamTUI(state);
7190 };
@@ -109,6 +128,7 @@ export async function streamTUI(state: TUIState) {
109128 TASK_PROMPT,
110129 messages,
111130 state.options,
131+ state.abortController,
112132 (ev) => {
113133 switch (ev.type) {
114134 case "text_start":
src/types.ts+1−0
@@ -29,6 +29,7 @@ export type TUIState = {
2929 streaming: boolean;
3030 stickToBottom: boolean;
3131 scrollOffset: number;
32+ abortController: AbortController;
3233 };
3334
3435 export type SavedOAuthAuth = OAuthCredentials & {