@@ -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+ )