feat(FN-3332): add droid runtime plugin with event bridge and process manag

The merge delivers a new `fusion-plugin-droid-runtime` plugin providing a full MCP server and runtime adapter for droid-based agents, with event bridging, process management, tool mapping, and a prompt builder. It also adds agent delegation and org hierarchy tools to the pi extension, while fixing a

Fusion-Task-Id: FN-3332
This commit is contained in:
Fusion
2026-05-04 03:04:33 -07:00
committed by gsxdsm
parent 79c4970739
commit 5be5da1938
36 changed files with 2947 additions and 214 deletions

View File

@@ -52,6 +52,7 @@
"@fusion-plugin-examples/dependency-graph": "workspace:*",
"@fusion-plugin-examples/hermes-runtime": "workspace:*",
"@fusion-plugin-examples/openclaw-runtime": "workspace:*",
"@fusion-plugin-examples/droid-runtime": "workspace:*",
"@fusion-plugin-examples/paperclip-runtime": "workspace:*",
"@fusion/core": "workspace:*",
"@fusion/engine": "workspace:*",

View File

@@ -1,43 +1,21 @@
import { describe, expect, it } from "vitest";
import { describe, expect, it, vi } from "vitest";
vi.mock("@fusion-plugin-examples/droid-runtime/probe", () => ({
probeDroidBinary: vi.fn(async () => ({
available: true,
authenticated: true,
version: "1.0.0",
binaryPath: "/usr/bin/droid",
probeDurationMs: 5,
})),
}));
import { probeDroidCli } from "../droid-cli-probe.js";
/**
* These tests exercise the real probe — we deliberately do NOT mock
* `spawn`. The probe's job is to tell the truth about the local system,
* and mocking defeats that. Instead we:
*
* 1. Assert the shape is sound regardless of binary availability
* 2. Assert timeouts fire when the binary hangs (we don't have a
* hanging binary fixture, so we cover the structural case only)
* 3. Let the suite pass whether or not `droid` is installed on the
* test runner — both outcomes are legitimate.
*
* If you need mocked probe behavior for a higher-level route test, spy
* on `probeDroidCli` at the import boundary rather than shimming spawn.
*/
describe("probeDroidCli", () => {
it("returns a well-formed result whether or not droid is installed", async () => {
it("delegates to plugin probe and returns shaped status", async () => {
const result = await probeDroidCli();
expect(typeof result.available).toBe("boolean");
expect(typeof result.probeDurationMs).toBe("number");
if (result.available) {
// When available: version string should come back populated.
expect(typeof result.version).toBe("string");
} else {
// When unavailable: reason must be populated so the UI can render.
expect(typeof result.reason).toBe("string");
}
});
it("respects a short timeout", async () => {
// Not a true hang test (we don't have a hanging binary), but
// confirms the timeoutMs option wires through and probe completes
// in a bounded window when using a very small timeout.
const result = await probeDroidCli({ timeoutMs: 50 });
expect(result.probeDurationMs).toBeLessThan(5000);
// Either it completed fast enough or hit the timeout — both fine.
if (!result.available && result.reason?.includes("timed out")) {
expect(result.reason).toContain("50ms");
}
expect(result.available).toBe(true);
expect(result.probeDurationMs).toBeTypeOf("number");
});
});

View File

@@ -1,148 +1,7 @@
/**
* Probe for the locally-installed Droid CLI binary.
*
* Used by GET /api/providers/droid-cli/status to power the "Factory AI —
* via Droid CLI" provider card. The card shows `authenticated=true` only
* when the binary is on PATH *and* the user has flipped on `useDroidCli`.
*
* Intentional design choices:
*
* - No caching. The user's PATH can change between requests (nvm switches,
* fresh terminal, etc.) — we'd rather pay one `spawn()` per poll than
* serve a stale "droid not installed" response. Droid's `--version`
* flag exits in ~40ms, so cost is negligible.
*
* - Short timeout. A misbehaving `droid` shim could hang indefinitely;
* we cap the probe at 2s and report `available: false` with a timeout
* reason rather than blocking the HTTP request.
*
* - No authorization. We never shell-interpolate PATH or user input.
* We spawn `droid --version` directly with argv, no shell.
*/
import { probeDroidBinary } from "@fusion-plugin-examples/droid-runtime/probe";
import { spawn } from "node:child_process";
export type DroidCliBinaryStatus = Awaited<ReturnType<typeof probeDroidBinary>>;
/** Result shape returned to the dashboard status endpoint. */
export interface DroidCliBinaryStatus {
/** True if the `droid` binary was found on PATH and ran to completion. */
available: boolean;
/** Trimmed stdout from `droid --version`, if available. */
version?: string;
/** Absolute path, if we could resolve it via `which`. */
binaryPath?: string;
/** Human-readable failure reason when `available === false`. */
reason?: string;
/** Wall-clock duration of the probe, useful for debugging slow paths. */
probeDurationMs: number;
}
/** Default probe timeout. Droid's --version is fast; 2s is generous. */
const PROBE_TIMEOUT_MS = 2000;
/**
* Spawn `droid --version` and return a structured status result.
*
* Never throws — any failure is captured as `available: false` with a reason
* so the caller (an HTTP handler) can render the provider card without
* try/catch.
*/
export async function probeDroidCli(
options: { timeoutMs?: number } = {},
): Promise<DroidCliBinaryStatus> {
const startedAt = Date.now();
const timeoutMs = options.timeoutMs ?? PROBE_TIMEOUT_MS;
const binaryPath = await tryResolveBinaryPath("droid");
return new Promise<DroidCliBinaryStatus>((resolvePromise) => {
const finish = (result: Omit<DroidCliBinaryStatus, "probeDurationMs">): void => {
resolvePromise({ ...result, probeDurationMs: Date.now() - startedAt });
};
let settled = false;
const child = spawn(binaryPath ?? "droid", ["--version"], {
stdio: ["ignore", "pipe", "pipe"],
});
const timer = setTimeout(() => {
if (settled) return;
settled = true;
try {
child.kill("SIGKILL");
} catch {
// Process already gone — nothing to do.
}
finish({
available: false,
binaryPath,
reason: `Probe timed out after ${timeoutMs}ms`,
});
}, timeoutMs);
let stdout = "";
let stderr = "";
child.stdout?.on("data", (chunk) => {
stdout += chunk.toString("utf-8");
});
child.stderr?.on("data", (chunk) => {
stderr += chunk.toString("utf-8");
});
child.on("error", (err) => {
if (settled) return;
settled = true;
clearTimeout(timer);
const isNotFound = (err as NodeJS.ErrnoException).code === "ENOENT";
finish({
available: false,
binaryPath,
reason: isNotFound ? "`droid` not found on PATH" : err.message,
});
});
child.on("close", (code) => {
if (settled) return;
settled = true;
clearTimeout(timer);
if (code === 0) {
finish({
available: true,
version: stdout.trim() || undefined,
binaryPath,
});
} else {
finish({
available: false,
binaryPath,
reason:
stderr.trim() || `droid --version exited with code ${String(code)}`,
});
}
});
});
}
/**
* Best-effort `which droid`. We don't fail probe on inability to resolve
* the path — the spawn above is the actual authority. This is just for
* surfacing a friendly "found at /opt/homebrew/bin/droid" in the UI.
*/
async function tryResolveBinaryPath(binary: string): Promise<string | undefined> {
return new Promise((resolvePromise) => {
const which = process.platform === "win32" ? "where" : "which";
const child = spawn(which, [binary], { stdio: ["ignore", "pipe", "ignore"] });
let out = "";
child.stdout?.on("data", (chunk) => {
out += chunk.toString("utf-8");
});
child.on("error", () => resolvePromise(undefined));
child.on("close", (code) => {
if (code === 0) {
const first = out.trim().split(/\r?\n/)[0];
resolvePromise(first?.length ? first : undefined);
} else {
resolvePromise(undefined);
}
});
});
export async function probeDroidCli(options: { timeoutMs?: number } = {}): Promise<DroidCliBinaryStatus> {
return probeDroidBinary({ timeoutMs: options.timeoutMs });
}

View File

@@ -1,25 +1,8 @@
# @fusion/droid-cli
First-party Fusion pi extension package that routes pi provider requests through the `droid` CLI subprocess using stream-json NDJSON.
Compatibility shim package for Fusion's Droid integration.
## Provider
Runtime/provider implementation now lives in:
- `@fusion-plugin-examples/droid-runtime` (`plugins/fusion-plugin-droid-runtime`)
- Provider ID: `droid-cli`
- Binary: `droid` (must be installed and authenticated on PATH)
- Registration: package extension entrypoint in `index.ts`
## Capabilities
- Subprocess streaming bridge for text/thinking/tool events
- Model auto-discovery from Droid CLI at provider startup with in-process caching
- Session resume support (`--resume` / `--session-id`) to avoid replaying prior turns
- MCP schema bridge for exposing pi custom tools as schema-only definitions
- Tool mapping and break-early control so pi remains the tool executor
- Thinking effort mapping from pi reasoning options to Droid CLI flags
## Development
```bash
pnpm --filter @fusion/droid-cli test
pnpm --filter @fusion/droid-cli exec tsc --noEmit
```
This package preserves the historical pi extension entrypoint and delegates to the plugin-owned implementation so existing imports continue to work.

View File

@@ -1,18 +1,18 @@
import type { ExtensionAPI } from "@mariozechner/pi-coding-agent";
import { streamViaCli } from "./src/provider.js";
import { streamViaCli } from "../../plugins/fusion-plugin-droid-runtime/src/provider.js";
import {
discoverDroidModels,
validateCliPresenceAsync,
validateCliAuthAsync,
killAllProcesses,
discoverDroidModels,
} from "./src/process-manager.js";
} from "../../plugins/fusion-plugin-droid-runtime/src/process-manager.js";
import { createHash } from "node:crypto";
import {
getCustomToolDefs,
toolsFromContext,
writeMcpConfig,
type McpToolDef,
} from "./src/mcp-config.js";
} from "../../plugins/fusion-plugin-droid-runtime/src/mcp-config.js";
process.on("exit", killAllProcesses);
@@ -117,7 +117,11 @@ export default function (pi: ExtensionAPI) {
pi,
(context as { tools?: ReadonlyArray<{ name: string; description: string; parameters: Record<string, unknown> }> }).tools,
);
return streamViaCli(model, context, { ...options, mcpConfigPath: configPath });
return streamViaCli(
model,
context as never,
{ ...(options ?? {}), mcpConfigPath: configPath } as never,
);
},
});
} catch (err) {

View File

@@ -25,6 +25,9 @@
"@mariozechner/pi-ai": "*",
"@mariozechner/pi-coding-agent": "*"
},
"dependencies": {
"@fusion-plugin-examples/droid-runtime": "workspace:*"
},
"devDependencies": {
"@types/node": "^22.0.0",
"typescript": "^5.7.0",

View File

@@ -71,16 +71,16 @@ import { streamViaCli } from "../provider";
describe("provider registration (default export)", () => {
it("registers provider id droid-cli with deduped discovered models", async () => {
vi.resetModules();
vi.doMock("../../src/provider.js", () => ({
vi.doMock("../../../../plugins/fusion-plugin-droid-runtime/src/provider.js", () => ({
streamViaCli: vi.fn(() => ({ mocked: true })),
}));
vi.doMock("../../src/process-manager.js", () => ({
vi.doMock("../../../../plugins/fusion-plugin-droid-runtime/src/process-manager.js", () => ({
validateCliPresenceAsync: vi.fn(async () => ({ ok: true })),
validateCliAuthAsync: vi.fn(async () => true),
killAllProcesses: vi.fn(),
discoverDroidModels: vi.fn(async () => ["droid-pro", "droid-max", "droid-pro"]),
}));
vi.doMock("../../src/mcp-config.js", () => ({
vi.doMock("../../../../plugins/fusion-plugin-droid-runtime/src/mcp-config.js", () => ({
getCustomToolDefs: vi.fn(() => []),
toolsFromContext: vi.fn(() => []),
writeMcpConfig: vi.fn(() => "/tmp/droid-mcp.json"),
@@ -105,9 +105,9 @@ describe("provider registration (default export)", () => {
"droid-pro",
"droid-max",
]);
vi.doUnmock("../../src/provider.js");
vi.doUnmock("../../src/process-manager.js");
vi.doUnmock("../../src/mcp-config.js");
vi.doUnmock("../../../../plugins/fusion-plugin-droid-runtime/src/provider.js");
vi.doUnmock("../../../../plugins/fusion-plugin-droid-runtime/src/process-manager.js");
vi.doUnmock("../../../../plugins/fusion-plugin-droid-runtime/src/mcp-config.js");
});
});