Skip to content

Personal AI, On Personal Devices

Python

fix(agents): repair Claude Agent SDK runner (#865)

Elliot Slusky90c37afe2cab
diff --git a/.gitignore b/.gitignore
index 75e2da3b..258b8fe3 100644
--- a/.gitignore
+++ b/.gitignore
@@ -102,6 +102,7 @@ CLAUDE.md
research_mining_*
.python-version
src/openjarvis/channels/whatsapp_baileys_bridge/node_modules/
+src/openjarvis/agents/claude_code_runner/node_modules/
# SQLite in-memory artifacts
:memory:
diff --git a/docs/architecture/agents.md b/docs/architecture/agents.md
index 80af8b75..280b7b57 100644
--- a/docs/architecture/agents.md
+++ b/docs/architecture/agents.md
@@ -368,13 +368,13 @@ result = agent.run("Fix the failing test in test_utils.py")
**Registry key:** `claude_code`
-Wraps the `@anthropic-ai/claude-code` SDK via a bundled Node.js subprocess bridge. Unlike every other agent, inference is handled entirely by the Claude Agent SDK -- the OpenJarvis inference engine is not used. This makes `ClaudeCodeAgent` a true external agent, similar in spirit to `OpenHandsAgent` but implemented via subprocess rather than an importable Python SDK.
+Wraps the `@anthropic-ai/claude-agent-sdk` package via a bundled Node.js subprocess bridge. Unlike every other agent, inference is handled entirely by the Claude Agent SDK -- the OpenJarvis inference engine is not used. This makes `ClaudeCodeAgent` a true external agent, similar in spirit to `OpenHandsAgent` but implemented via subprocess rather than an importable Python SDK.
```mermaid
graph LR
Q["User Query"] --> PY["Python: build JSON request"]
- PY --> SPAWN["Spawn: node dist/index.js"]
- SPAWN --> NODE["Node.js runner<br/>@anthropic-ai/claude-code SDK"]
+ PY --> SPAWN["Spawn: node index.mjs"]
+ SPAWN --> NODE["Node.js runner<br/>@anthropic-ai/claude-agent-sdk"]
NODE --> SDK["Claude Agent SDK<br/>(cloud inference)"]
SDK --> NODE
NODE --> JSON["Sentinel-delimited JSON<br/>on stdout"]
@@ -384,14 +384,14 @@ graph LR
How it works:
-1. On first call, copies the bundled `claude_code_runner/` to `~/.openjarvis/claude_code_runner/` and runs `npm install --production` if `node_modules` is absent
+1. On first call, copies the bundled `claude_code_runner/` to `~/.openjarvis/claude_code_runner/` and installs the pinned Agent SDK if it is missing or outdated
2. Builds a JSON request with `prompt`, `api_key`, `workspace`, `allowed_tools`, `system_prompt`, and `session_id`
-3. Spawns `node dist/index.js` and writes the request to stdin
+3. Spawns `node index.mjs` and writes the request to stdin
4. Reads stdout and extracts the JSON payload between `---OPENJARVIS_OUTPUT_START---` and `---OPENJARVIS_OUTPUT_END---` sentinels
5. Falls back to treating all stdout as plain text content if sentinels are absent
!!! warning "Requires Node.js 22+"
- `ClaudeCodeAgent` raises `RuntimeError` at `run()` time if `node` is not found on `PATH`. An `ANTHROPIC_API_KEY` environment variable is required for the Claude Agent SDK to authenticate.
+ `ClaudeCodeAgent` raises `RuntimeError` at `run()` time if `node` or npm is not found on `PATH`. An `ANTHROPIC_API_KEY` environment variable is required for the Claude Agent SDK to authenticate.
```python
from openjarvis.agents.claude_code import ClaudeCodeAgent
diff --git a/docs/user-guide/agents.md b/docs/user-guide/agents.md
index 6758193a..3eeb13fb 100644
--- a/docs/user-guide/agents.md
+++ b/docs/user-guide/agents.md
@@ -394,15 +394,15 @@ j.close()
## ClaudeCodeAgent
-The `ClaudeCodeAgent` wraps the `@anthropic-ai/claude-code` SDK via a bundled Node.js subprocess bridge. Unlike the other agents, inference is handled entirely by the Claude Agent SDK -- the `engine` parameter is accepted only for `BaseAgent` interface conformance and is not used.
+The `ClaudeCodeAgent` wraps the `@anthropic-ai/claude-agent-sdk` package via a bundled Node.js subprocess bridge. Unlike the other agents, inference is handled entirely by the Claude Agent SDK -- the `engine` parameter is accepted only for `BaseAgent` interface conformance and is not used.
!!! warning "Requirements"
- Requires Node.js 22+ on `PATH` and an `ANTHROPIC_API_KEY` environment variable (or pass `api_key=` directly). The bundled runner is auto-installed to `~/.openjarvis/claude_code_runner/` on first use via `npm install`.
+ Requires Node.js 22+ with npm on `PATH` and an `ANTHROPIC_API_KEY` environment variable (or pass `api_key=` directly). The bundled runner is auto-installed to `~/.openjarvis/claude_code_runner/` on first use.
**How it works:**
-1. On first call, copies the bundled `claude_code_runner/` to `~/.openjarvis/claude_code_runner/` and runs `npm install --production` if `node_modules` is missing.
-2. Builds a JSON request payload (prompt, API key, workspace, allowed tools, system prompt, session ID) and sends it to `stdin` of a `node dist/index.js` subprocess.
+1. On first call, copies the bundled `claude_code_runner/` to `~/.openjarvis/claude_code_runner/` and installs the pinned Agent SDK if it is missing or outdated.
+2. Builds a JSON request payload (prompt, API key, workspace, allowed tools, system prompt, session ID) and sends it to `stdin` of a `node index.mjs` subprocess.
3. The Node.js runner calls the Claude Agent SDK and writes sentinel-delimited JSON to `stdout`.
4. The Python side parses the output between `---OPENJARVIS_OUTPUT_START---` and `---OPENJARVIS_OUTPUT_END---` markers, extracting content, tool results, and metadata.
5. Returns an `AgentResult` with `turns=1`.
diff --git a/pyproject.toml b/pyproject.toml
index 382282ed..e4da3b68 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -201,9 +201,13 @@ openjarvis-rust = { path = "rust/crates/openjarvis-python" }
[tool.hatch.build.targets.wheel]
packages = ["src/openjarvis"]
+exclude = [
+ "/src/openjarvis/agents/claude_code_runner",
+]
[tool.hatch.build.targets.wheel.force-include]
-"src/openjarvis/agents/claude_code_runner" = "_node_modules/claude_code_runner"
+"src/openjarvis/agents/claude_code_runner/index.mjs" = "_node_modules/claude_code_runner/index.mjs"
+"src/openjarvis/agents/claude_code_runner/package.json" = "_node_modules/claude_code_runner/package.json"
"src/openjarvis/channels/whatsapp_baileys_bridge" = "_node_modules/whatsapp_baileys_bridge"
"scripts/install" = "_install_scripts"
"deploy/windows" = "_deploy/windows"
diff --git a/src/openjarvis/agents/claude_code.py b/src/openjarvis/agents/claude_code.py
index fdece7f0..4b69205f 100644
--- a/src/openjarvis/agents/claude_code.py
+++ b/src/openjarvis/agents/claude_code.py
@@ -1,7 +1,8 @@
"""ClaudeCodeAgent -- wraps the Claude Agent SDK via Node.js subprocess bridge.
-Spawns a Node.js runner process that calls the ``@anthropic-ai/claude-code``
-SDK, communicating via JSON over stdin/stdout with sentinel-delimited output.
+Spawns a Node.js runner process that calls the
+``@anthropic-ai/claude-agent-sdk`` package, communicating via JSON over
+stdin/stdout with sentinel-delimited output.
The engine parameter is accepted for interface conformance with BaseAgent but
is not used -- inference is handled entirely by the Claude Agent SDK.
@@ -44,8 +45,8 @@ if not _RUNNER_SRC.exists():
class ClaudeCodeAgent(BaseAgent):
"""Agent that wraps the Claude Agent SDK via a Node.js subprocess.
- Spawns a Node.js process running ``dist/index.js`` which imports
- ``@anthropic-ai/claude-code`` and streams agentic responses. Results
+ Spawns a Node.js process running ``index.mjs`` which imports
+ ``@anthropic-ai/claude-agent-sdk`` and streams agentic responses. Results
are communicated back via sentinel-delimited JSON on stdout.
The ``engine`` parameter is accepted for BaseAgent interface conformance
@@ -85,6 +86,7 @@ class ClaudeCodeAgent(BaseAgent):
self._allowed_tools = allowed_tools
self._system_prompt = system_prompt
self._timeout = timeout
+ self._node_executable = "node"
# ------------------------------------------------------------------
# Runner management
@@ -92,38 +94,53 @@ class ClaudeCodeAgent(BaseAgent):
def _ensure_runner(self) -> Path:
"""Copy the bundled runner to ``~/.openjarvis/claude_code_runner/``
- and run ``npm install`` if ``node_modules`` is missing.
+ and install the Agent SDK when it is missing or outdated.
Returns the path to the runner directory.
- Raises :class:`RuntimeError` if Node.js is not available.
+ Raises :class:`RuntimeError` if Node.js or npm is not available.
"""
- if shutil.which("node") is None:
+ node_path = shutil.which("node")
+ if node_path is None:
raise RuntimeError(
"ClaudeCodeAgent requires Node.js (>=22). "
"Install it from https://nodejs.org/ or via your package manager."
)
+ npm_path = shutil.which("npm")
+ if npm_path is None:
+ raise RuntimeError(
+ "ClaudeCodeAgent requires npm. Install Node.js (>=22) with npm."
+ )
+ self._node_executable = node_path
dest = get_config_dir() / "claude_code_runner"
dest.mkdir(parents=True, exist_ok=True)
- # Copy runner files if missing or outdated
- for sub in ("package.json", "dist"):
- src = _RUNNER_SRC / sub
- dst = dest / sub
- if src.is_file():
- shutil.copy2(src, dst)
- elif src.is_dir():
- if dst.exists():
- shutil.rmtree(dst)
- shutil.copytree(src, dst)
-
- # Install npm dependencies if node_modules missing
- node_modules = dest / "node_modules"
- if not node_modules.exists():
+ for name in ("package.json", "index.mjs"):
+ shutil.copy2(_RUNNER_SRC / name, dest / name)
+
+ package = json.loads((dest / "package.json").read_text(encoding="utf-8"))
+ expected_sdk = package["dependencies"]["@anthropic-ai/claude-agent-sdk"]
+ installed_package = (
+ dest
+ / "node_modules"
+ / "@anthropic-ai"
+ / "claude-agent-sdk"
+ / "package.json"
+ )
+ try:
+ installed_sdk = json.loads(
+ installed_package.read_text(encoding="utf-8")
+ ).get("version")
+ except (OSError, json.JSONDecodeError):
+ installed_sdk = None
+
+ # Existing caches contain the old CLI-only package, so validate the
+ # installed SDK instead of trusting that node_modules merely exists.
+ if installed_sdk != expected_sdk:
logger.info("Installing claude_code_runner dependencies...")
subprocess.run(
- ["npm", "install", "--production"],
+ [npm_path, "install", "--omit=dev", "--include=optional"],
cwd=str(dest),
check=True,
capture_output=True,
@@ -144,7 +161,7 @@ class ClaudeCodeAgent(BaseAgent):
) -> AgentResult:
"""Execute a query via the Claude Agent SDK subprocess.
- Spawns ``node dist/index.js``, writes a JSON request to stdin, and
+ Spawns ``node index.mjs``, writes a JSON request to stdin, and
reads sentinel-delimited JSON output from stdout.
"""
self._emit_turn_start(input)
@@ -163,7 +180,7 @@ class ClaudeCodeAgent(BaseAgent):
try:
proc = subprocess.run(
- ["node", "dist/index.js"],
+ [self._node_executable, "index.mjs"],
cwd=str(runner_dir),
input=json.dumps(request),
capture_output=True,
diff --git a/src/openjarvis/agents/claude_code_runner/index.mjs b/src/openjarvis/agents/claude_code_runner/index.mjs
new file mode 100644
index 00000000..ff196f30
--- /dev/null
+++ b/src/openjarvis/agents/claude_code_runner/index.mjs
@@ -0,0 +1,131 @@
+/**
+ * OpenJarvis Claude Agent SDK runner.
+ *
+ * Reads one JSON request from stdin and writes one sentinel-delimited JSON
+ * response to stdout.
+ */
+
+import { query } from "@anthropic-ai/claude-agent-sdk";
+
+const OUTPUT_START = "---OPENJARVIS_OUTPUT_START---";
+const OUTPUT_END = "---OPENJARVIS_OUTPUT_END---";
+
+function emitResult(response) {
+ console.log(OUTPUT_START);
+ console.log(JSON.stringify(response));
+ console.log(OUTPUT_END);
+}
+
+function emitError(message) {
+ emitResult({ content: message, tool_results: [], metadata: { error: true } });
+ console.error(message);
+}
+
+async function readStdin() {
+ let data = "";
+ process.stdin.setEncoding("utf-8");
+ for await (const chunk of process.stdin) {
+ data += chunk;
+ }
+ return data;
+}
+
+function serializeContent(content) {
+ return typeof content === "string" ? content : JSON.stringify(content ?? "");
+}
+
+async function main() {
+ let request;
+ try {
+ request = JSON.parse(await readStdin());
+ } catch (error) {
+ emitError(`Failed to parse input: ${error}`);
+ process.exitCode = 1;
+ return;
+ }
+
+ if (request.api_key) {
+ process.env.ANTHROPIC_API_KEY = request.api_key;
+ }
+
+ const options = { maxTurns: 30 };
+ if (request.workspace) {
+ options.cwd = request.workspace;
+ }
+ if (request.system_prompt) {
+ options.systemPrompt = request.system_prompt;
+ }
+ if (request.allowed_tools?.length) {
+ options.allowedTools = request.allowed_tools;
+ }
+ if (request.session_id) {
+ options.sessionId = request.session_id;
+ }
+
+ let content = "";
+ let messageCount = 0;
+ const toolResults = [];
+ const toolUseIndexes = new Map();
+
+ try {
+ for await (const message of query({ prompt: request.prompt, options })) {
+ messageCount += 1;
+
+ if (message.type === "assistant") {
+ const blocks = Array.isArray(message.message?.content)
+ ? message.message.content
+ : [];
+ for (const block of blocks) {
+ if (block.type === "text") {
+ content = block.text;
+ } else if (block.type === "tool_use") {
+ toolUseIndexes.set(block.id, toolResults.length);
+ toolResults.push({
+ tool_name: block.name,
+ content: serializeContent(block.input),
+ success: true,
+ });
+ }
+ }
+ } else if (message.type === "user") {
+ const blocks = Array.isArray(message.message?.content)
+ ? message.message.content
+ : [];
+ for (const block of blocks) {
+ if (block.type !== "tool_result") {
+ continue;
+ }
+ const index = toolUseIndexes.get(block.tool_use_id);
+ if (index !== undefined) {
+ toolResults[index].content = serializeContent(block.content);
+ toolResults[index].success = !block.is_error;
+ }
+ }
+ } else if (message.type === "result") {
+ if (message.is_error || message.subtype !== "success") {
+ const errorMessage =
+ message.subtype === "success"
+ ? message.result
+ : message.errors?.join("\n");
+ throw new Error(errorMessage || "Claude query failed");
+ }
+ content = message.result || content;
+ }
+ }
+
+ emitResult({
+ content,
+ tool_results: toolResults,
+ metadata: {
+ message_count: messageCount,
+ session_id: request.session_id || undefined,
+ },
+ });
+ } catch (error) {
+ const message = error instanceof Error ? error.message : String(error);
+ emitError(`Claude Agent SDK error: ${message}`);
+ process.exitCode = 1;
+ }
+}
+
+await main();
diff --git a/src/openjarvis/agents/claude_code_runner/package.json b/src/openjarvis/agents/claude_code_runner/package.json
index 019a6338..bb7bc78d 100644
--- a/src/openjarvis/agents/claude_code_runner/package.json
+++ b/src/openjarvis/agents/claude_code_runner/package.json
@@ -1,8 +1,8 @@
{
"name": "openjarvis-claude-code-runner",
"version": "0.1.0",
- "main": "dist/index.js",
+ "main": "index.mjs",
"dependencies": {
- "@anthropic-ai/claude-code": "^0.2"
+ "@anthropic-ai/claude-agent-sdk": "0.3.237"
}
}
diff --git a/src/openjarvis/agents/claude_code_runner/src/index.ts b/src/openjarvis/agents/claude_code_runner/src/index.ts
deleted file mode 100644
index 216fbf26..00000000
--- a/src/openjarvis/agents/claude_code_runner/src/index.ts
+++ /dev/null
@@ -1,157 +0,0 @@
-/**
- * OpenJarvis Claude Code Runner
- *
- * Reads a JSON request from stdin, invokes the Claude Agent SDK,
- * and writes sentinel-wrapped JSON output to stdout.
- *
- * Input (JSON on stdin):
- * { prompt, api_key, workspace, allowed_tools, system_prompt, session_id }
- *
- * Output (on stdout, between sentinels):
- * ---OPENJARVIS_OUTPUT_START---
- * { content, tool_results, metadata }
- * ---OPENJARVIS_OUTPUT_END---
- */
-
-import { query, type Tool } from "@anthropic-ai/claude-code";
-
-const OUTPUT_START = "---OPENJARVIS_OUTPUT_START---";
-const OUTPUT_END = "---OPENJARVIS_OUTPUT_END---";
-
-interface RunnerRequest {
- prompt: string;
- api_key: string;
- workspace: string;
- allowed_tools: string[];
- system_prompt: string;
- session_id: string;
-}
-
-interface ToolResultEntry {
- tool_name: string;
- content: string;
- success: boolean;
-}
-
-interface RunnerResponse {
- content: string;
- tool_results: ToolResultEntry[];
- metadata: Record<string, unknown>;
-}
-
-function emitResult(response: RunnerResponse): void {
- console.log(OUTPUT_START);
- console.log(JSON.stringify(response));
- console.log(OUTPUT_END);
-}
-
-function emitError(message: string): void {
- emitResult({
- content: message,
- tool_results: [],
- metadata: { error: true },
- });
-}
-
-async function readStdin(): Promise<string> {
- return new Promise((resolve, reject) => {
- let data = "";
- process.stdin.setEncoding("utf-8");
- process.stdin.on("data", (chunk: string) => {
- data += chunk;
- });
- process.stdin.on("end", () => {
- resolve(data);
- });
- process.stdin.on("error", (err: Error) => {
- reject(err);
- });
- });
-}
-
-async function main(): Promise<void> {
- let request: RunnerRequest;
-
- try {
- const raw = await readStdin();
- request = JSON.parse(raw) as RunnerRequest;
- } catch (err) {
- emitError(`Failed to parse input: ${err}`);
- process.exit(1);
- }
-
- // Set the API key in the environment for the SDK
- if (request.api_key) {
- process.env.ANTHROPIC_API_KEY = request.api_key;
- }
-
- try {
- // Build options for the claude-code SDK query
- const options: Parameters<typeof query>[0] = {
- prompt: request.prompt,
- options: {
- maxTurns: 30,
- },
- };
-
- if (request.workspace) {
- options.options!.cwd = request.workspace;
- }
-
- if (request.system_prompt) {
- options.options!.systemPrompt = request.system_prompt;
- }
-
- if (request.allowed_tools && request.allowed_tools.length > 0) {
- options.options!.allowedTools = request.allowed_tools as Tool[];
- }
-
- if (request.session_id) {
- options.options!.sessionId = request.session_id;
- }
-
- // Execute the query
- const messages = await query(options);
-
- // Extract the final assistant text and any tool results
- let content = "";
- const toolResults: ToolResultEntry[] = [];
-
- for (const msg of messages) {
- if (msg.type === "text") {
- content = msg.text;
- } else if (msg.type === "tool_use") {
- toolResults.push({
- tool_name: msg.name,
- content: JSON.stringify(msg.input),
- success: true,
- });
- } else if (msg.type === "tool_result") {
- // Update last tool result with actual output
- if (toolResults.length > 0) {
- const last = toolResults[toolResults.length - 1];
- last.content =
- typeof msg.content === "string"
- ? msg.content
- : JSON.stringify(msg.content);
- last.success = !msg.is_error;
- }
- }
- }
-
- emitResult({
- content,
- tool_results: toolResults,
- metadata: {
- message_count: messages.length,
- session_id: request.session_id || undefined,
- },
- });
- } catch (err) {
- const message = err instanceof Error ? err.message : String(err);
- emitError(`Claude Code SDK error: ${message}`);
- process.exit(1);
- }
-}
-
-main();
diff --git a/tests/agents/test_claude_code.py b/tests/agents/test_claude_code.py
index 6597fe10..8056d848 100644
--- a/tests/agents/test_claude_code.py
+++ b/tests/agents/test_claude_code.py
@@ -13,6 +13,7 @@ from openjarvis.agents._stubs import AgentResult
from openjarvis.agents.claude_code import (
_OUTPUT_END,
_OUTPUT_START,
+ _RUNNER_SRC,
ClaudeCodeAgent,
)
from openjarvis.core.events import EventBus, EventType
@@ -40,7 +41,7 @@ def _mock_proc(
returncode: int = 0,
) -> subprocess.CompletedProcess:
return subprocess.CompletedProcess(
- args=["node", "dist/index.js"],
+ args=["node", "index.mjs"],
returncode=returncode,
stdout=stdout,
stderr=stderr,
@@ -83,6 +84,14 @@ class TestEnsureRunner:
with pytest.raises(RuntimeError, match="Node.js"):
agent._ensure_runner()
+ def test_bundled_runner_is_runnable(self):
+ package = json.loads((_RUNNER_SRC / "package.json").read_text())
+
+ assert package["main"] == "index.mjs"
+ assert (_RUNNER_SRC / package["main"]).is_file()
+ assert package["dependencies"]["@anthropic-ai/claude-agent-sdk"] == "0.3.237"
+ assert "@anthropic-ai/claude-code" not in package["dependencies"]
+
def test_creates_runner_dir(self, tmp_path, monkeypatch):
engine = MagicMock()
engine.engine_id = "mock"
@@ -98,36 +107,76 @@ class TestEnsureRunner:
home_dir.mkdir()
monkeypatch.setenv("OPENJARVIS_HOME", str(home_dir))
+ def which(executable):
+ return f"/usr/bin/{executable}"
+
with (
- patch("shutil.which", return_value="/usr/bin/node"),
+ patch("shutil.which", side_effect=which),
patch("subprocess.run") as mock_run,
):
mock_run.return_value = _mock_proc()
dest = home_dir / "claude_code_runner"
result = agent._ensure_runner()
assert result == dest
- mock_run.assert_called_once()
- call_args = mock_run.call_args
- assert "npm" in call_args[0][0][0]
-
- def test_skips_npm_install_when_node_modules_exists(self, tmp_path, monkeypatch):
+ assert (dest / "index.mjs").is_file()
+ assert (dest / "package.json").is_file()
+ assert mock_run.call_args.args[0] == [
+ "/usr/bin/npm",
+ "install",
+ "--omit=dev",
+ "--include=optional",
+ ]
+
+ def test_skips_npm_install_when_sdk_version_matches(self, tmp_path, monkeypatch):
engine = MagicMock()
engine.engine_id = "mock"
agent = ClaudeCodeAgent(engine, "test-model")
home_dir = tmp_path / "home"
dest = home_dir / "claude_code_runner"
- dest.mkdir(parents=True)
- (dest / "node_modules").mkdir()
+ installed = (
+ dest
+ / "node_modules"
+ / "@anthropic-ai"
+ / "claude-agent-sdk"
+ / "package.json"
+ )
+ installed.parent.mkdir(parents=True)
+ installed.write_text('{"version":"0.3.237"}')
monkeypatch.setenv("OPENJARVIS_HOME", str(home_dir))
with (
- patch("shutil.which", return_value="/usr/bin/node"),
+ patch("shutil.which", side_effect=lambda name: f"/usr/bin/{name}"),
patch("subprocess.run") as mock_run,
):
agent._ensure_runner()
mock_run.assert_not_called()
+ def test_reinstalls_legacy_cache(self, tmp_path, monkeypatch):
+ engine = MagicMock()
+ engine.engine_id = "mock"
+ agent = ClaudeCodeAgent(engine, "test-model")
+ home_dir = tmp_path / "home"
+ old_package = (
+ home_dir
+ / "claude_code_runner"
+ / "node_modules"
+ / "@anthropic-ai"
+ / "claude-code"
+ / "package.json"
+ )
+ old_package.parent.mkdir(parents=True)
+ old_package.write_text('{"version":"0.2.126"}')
+ monkeypatch.setenv("OPENJARVIS_HOME", str(home_dir))
+
+ with (
+ patch("shutil.which", side_effect=lambda name: f"/usr/bin/{name}"),
+ patch("subprocess.run") as mock_run,
+ ):
+ agent._ensure_runner()
+
+ assert mock_run.call_count == 1
+
# ---------------------------------------------------------------------------
# run() tests
@@ -162,7 +211,7 @@ class TestClaudeCodeRun:
"_ensure_runner",
return_value="/fake/runner",
),
- patch("subprocess.run", return_value=proc),
+ patch("subprocess.run", return_value=proc) as mock_run,
):
result = agent.run("Say hello")
@@ -171,6 +220,7 @@ class TestClaudeCodeRun:
assert result.turns == 1
assert result.tool_results == []
assert result.metadata["message_count"] == 3
+ assert mock_run.call_args.args[0] == ["node", "index.mjs"]
def test_run_with_tool_results(self):
agent = self._make_agent()
diff --git a/tests/deployment/test_packaging.py b/tests/deployment/test_packaging.py
index 3368bf85..99c06abc 100644
--- a/tests/deployment/test_packaging.py
+++ b/tests/deployment/test_packaging.py
@@ -19,6 +19,7 @@ PYPROJECT = ROOT / "pyproject.toml"
DESKTOP_LIB_RS = ROOT / "frontend" / "src-tauri" / "src" / "lib.rs"
WINDOWS_INSTALL_PS1 = ROOT / "deploy" / "windows" / "install.ps1"
QUICKSTART_SH = ROOT / "scripts" / "quickstart.sh"
+CLAUDE_RUNNER = ROOT / "src" / "openjarvis" / "agents" / "claude_code_runner"
def _pyproject() -> dict:
@@ -66,3 +67,17 @@ def test_quickstart_installs_web_search_dependencies() -> None:
quickstart = QUICKSTART_SH.read_text()
assert "--extra tools-search" in quickstart
assert "already running on port 8000" in quickstart
+
+
+def test_claude_runner_wheel_maps_only_runtime_files() -> None:
+ wheel = _pyproject()["tool"]["hatch"]["build"]["targets"]["wheel"]
+ force_include = wheel["force-include"]
+ source = "src/openjarvis/agents/claude_code_runner"
+
+ assert source not in force_include
+ for filename in ("index.mjs", "package.json"):
+ assert force_include[f"{source}/{filename}"] == (
+ f"_node_modules/claude_code_runner/{filename}"
+ )
+ assert (CLAUDE_RUNNER / filename).is_file()
+ assert f"/{source}" in wheel["exclude"]