feat(FN-2262): merge fusion/fn-2262 (auto-resolved)

- feat(FN-2262): document Paperclip runtime configuration and constraints
- docs(FN-2261): update README with implementation details
- feat(FN-2261): add paperclip runtime resolution compatibility tests
- feat(FN-2261): add runtime adapter and registration tests
- feat(FN-2261): integrate adapter into plugin entrypoint
- feat(FN-2261): implement PaperclipRuntimeAdapter
- fix(FN-2261): remove pi-coding-agent re-exports from types.ts
- feat(FN-2261): define runtime types for Paperclip plugin
- feat(FN-2260): merge fusion/fn-2260
This commit is contained in:
Fusion
2026-04-22 14:33:02 -07:00
committed by gsxdsm
parent acceca7fe5
commit b0b492ed6d
16 changed files with 1060 additions and 251 deletions

View File

@@ -1,57 +1,252 @@
# Paperclip Runtime Plugin
A Fusion plugin that provides the Paperclip runtime for AI agents. Paperclip enables AI agents to browse web pages and extract content through a headless browser interface.
A Fusion plugin that provides the **Paperclip runtime** for AI agents, using the existing pi backend for session management.
## Status
## Overview
> **Note:** This plugin is currently a scaffold with a placeholder runtime. Full Paperclip runtime implementation is deferred to FN-2261.
This plugin provides a runtime adapter that wraps the existing `createFnAgent` and `promptWithFallback` functions from `@fusion/engine`, making the pi-based agent session available through Fusion's plugin runtime system.
## Runtime ID
| Property | Value |
|----------|-------|
| **Runtime ID** | `paperclip` |
| **Name** | `Paperclip Runtime` |
| **Version** | `1.0.0` |
## Installation
This plugin is installed as a local plugin:
### Prerequisites
1. Install pi globally:
```bash
npm i -g @mariozechner/pi-coding-agent
```
2. Authenticate pi with your AI provider:
```bash
pi
# Follow the login flow for your provider
```
### Install the Plugin
Install the plugin as a local plugin:
```bash
fn plugin add ./plugins/fusion-plugin-paperclip-runtime
```
## Runtime Capabilities
Verify installation:
When fully implemented, this runtime will provide:
```bash
fn plugin list
# Should show fusion-plugin-paperclip-runtime
```
- **Web Page Browsing**: Navigate to URLs and retrieve page content
- **Content Extraction**: Extract specific information from web pages using CSS selectors or XPath
- **Form Interaction**: Fill and submit web forms
- **JavaScript Rendering**: Execute JavaScript to render dynamic content
## Configuration
### Plugin Discovery
After installation, the Paperclip runtime is automatically discovered by Fusion's plugin system when the plugin is loaded. No additional configuration is required to make the runtime available.
### Selecting the Paperclip Runtime
Once the plugin is installed, you can select the Paperclip runtime for agents by setting `runtimeHint` in the agent's `runtimeConfig`.
#### Via Agent Configuration
Set the runtime hint in an agent's `runtimeConfig`:
```json
{
"name": "Paperclip Executor",
"role": "executor",
"runtimeConfig": {
"runtimeHint": "paperclip"
}
}
```
When an agent with `runtimeHint: "paperclip"` is assigned to a task, the task's executor session will use the Paperclip Runtime Adapter.
#### How Runtime Selection Works
1. When an agent session is created, Fusion checks the agent's `runtimeConfig.runtimeHint`
2. If `runtimeHint` is set to `"paperclip"`, Fusion resolves the Paperclip Runtime from the plugin
3. If the plugin is not installed or unavailable, Fusion falls back to the default `pi` runtime
4. If `runtimeHint` is not set, Fusion uses the default `pi` runtime
### Fallback Behavior
If the Paperclip runtime is unavailable (plugin not installed, not enabled, or factory error), Fusion automatically falls back to the default `pi` runtime with a warning log:
```
[runtime-resolver] Runtime "paperclip" unavailable (not_found), falling back to default pi runtime
```
The fallback behavior ensures tasks continue executing even if the plugin is misconfigured.
## Runtime Resolution Order
When resolving a runtime, Fusion follows this order:
1. **No runtime hint** → Use default `pi` runtime
2. **Hint is `"pi"` or `"default"`** → Use default `pi` runtime
3. **Hint is a plugin runtime ID** (e.g., `"paperclip"`) → Look up and instantiate the plugin runtime
4. **Plugin runtime unavailable** → Fall back to default `pi` runtime
## Supported Session Purposes
The Paperclip runtime supports all Fusion agent session purposes:
- `executor` — Task implementation
- `triage` — Task specification
- `reviewer` — Code/plan review
- `merger` — Merge operations
- `heartbeat` — Health monitoring
- `validation` — Workflow step validation
## Interface Implementation
The Paperclip Runtime Adapter implements the `AgentRuntime` interface:
| Method | Description |
|--------|-------------|
| `id` | Returns `"paperclip"` |
| `name` | Returns `"Paperclip Runtime"` |
| `createSession(options)` | Creates a session using `createFnAgent` from `@fusion/engine` |
| `promptWithFallback(session, prompt, options?)` | Delegates to pi's `promptWithFallback` with automatic retry and compaction |
| `describeModel(session)` | Returns `"<provider>/<modelId>"` or `"unknown model"` |
| `dispose(session)` | Calls `session.dispose()` if available |
## Credentials
The Paperclip runtime uses the user's existing pi configuration:
- **No additional credentials required** — Reuses pi's authenticated provider
- **Provider/model** — Sourced from pi's configured default
- **Fallback provider/model** — Uses pi's configured fallback if set
If pi is not authenticated, session creation will fail and fall back to the default `pi` runtime.
## Constraints
### Prerequisites
- `pi` must be installed globally (`npm i -g @mariozechner/pi-coding-agent`)
- `pi` must be authenticated with at least one AI provider
- The plugin must be installed and enabled in Fusion
- The agent must have `runtimeConfig.runtimeHint` set to `"paperclip"` to use this runtime
### Limitations
- **No task-level runtime selection**: Runtime selection is configured at the agent level via `runtimeConfig.runtimeHint`, not at the task level. Tasks inherit the runtime from their assigned agent.
- **Session persistence**: The Paperclip runtime uses pi's session management. Sessions are persisted to disk according to pi's configuration.
- **Tool selection**: Tool availability is controlled by the `skills` parameter passed to `createSession`, not by the runtime itself.
- **Model selection**: Model selection is determined by pi's configuration, not by the runtime adapter.
### Compatibility
The Paperclip runtime is compatible with all Fusion session purposes. It wraps the same underlying implementation used by the default `pi` runtime, ensuring feature parity.
## Verification
### Check Plugin Status
```bash
fn plugin list
```
### Verify Agent Configuration
Check that the agent has the correct `runtimeConfig`:
```bash
fn agent list
# Look for agents with runtimeHint: "paperclip" in their runtimeConfig
```
### Verify Runtime Resolution
Enable debug logging and look for runtime resolution messages:
```
[runtime-resolver] [executor] Using configured plugin runtime "paperclip" from "fusion-plugin-paperclip-runtime"
```
Or fallback warnings (when plugin is unavailable):
```
[runtime-resolver] [executor] Runtime "paperclip" unavailable (not_found), falling back to default pi runtime
```
## Development
### Build
```bash
pnpm --filter ./plugins/fusion-plugin-paperclip-runtime build
cd plugins/fusion-plugin-paperclip-runtime
pnpm build
```
### Test
```bash
pnpm --filter ./plugins/fusion-plugin-paperclip-runtime test
cd plugins/fusion-plugin-paperclip-runtime
pnpm test
```
### Project Structure
```
fusion-plugin-paperclip-runtime/
├── manifest.json # Plugin metadata with runtime declaration
├── src/
│ ├── index.ts # Plugin entry point with runtime registration
│ ├── runtime-adapter.ts # PaperclipRuntimeAdapter implementation
│ └── types.ts # Type re-exports
├── README.md
└── package.json
```
## Architecture
This plugin follows the Fusion plugin runtime contract defined in FN-2256. It registers a runtime factory that creates Paperclip runtime instances on demand.
This plugin follows the Fusion plugin runtime contract defined in [FN-2256](https://github.com/gsxdsm/fusion/issues/FN-2256).
### Runtime Contract
### Runtime Registration
- **Runtime ID**: `paperclip`
- **Factory**: `PluginRuntimeFactory` from `@fusion/plugin-sdk`
Runtimes are registered via the plugin's `runtime` field:
## Deferred Work
```typescript
const plugin = definePlugin({
manifest: { /* ... */ },
runtime: {
metadata: {
runtimeId: "paperclip",
name: "Paperclip Runtime",
description: "Paperclip-backed AI session using the user's configured pi provider and model",
version: "1.0.0",
},
factory: paperclipRuntimeFactory,
},
});
```
Full runtime implementation including:
- Browser automation setup
- Content extraction logic
- Session management
- Error handling and retry logic
### Runtime Factory
These are tracked in [FN-2261](https://github.com/gsxdsm/fusion/issues/FN-2261).
The factory function creates a new `PaperclipRuntimeAdapter` instance when the runtime is resolved:
```typescript
async function paperclipRuntimeFactory(): Promise<PaperclipRuntimeAdapter> {
return new PaperclipRuntimeAdapter();
}
```
## Related
- [FN-2256](https://github.com/gsxdsm/fusion/issues/FN-2256) — Runtime contract definition
- [FN-2260](https://github.com/gsxdsm/fusion/issues/FN-2260) — Plugin scaffold
- [Runtime Resolution](../packages/engine/src/runtime-resolution.ts) — Engine runtime resolution implementation

View File

@@ -1,15 +1,15 @@
{
"id": "fusion-plugin-paperclip-runtime",
"name": "Paperclip Runtime Plugin",
"version": "0.1.0",
"description": "Provides Paperclip web access runtime for Fusion AI agents",
"version": "1.0.0",
"description": "Provides Paperclip runtime for Fusion AI agents",
"author": "Fusion Team",
"homepage": "https://github.com/gsxdsm/fusion",
"fusionVersion": ">=0.1.0",
"runtime": {
"runtimeId": "paperclip",
"name": "Paperclip Runtime",
"description": "Web access runtime for AI agents — browse pages and extract content",
"version": "0.1.0"
"description": "Paperclip-backed AI session using the user's configured pi provider and model",
"version": "1.0.0"
}
}

View File

@@ -18,6 +18,7 @@
"test": "vitest run --silent=passed-only --reporter=dot"
},
"dependencies": {
"@fusion/engine": "workspace:*",
"@fusion/plugin-sdk": "workspace:*"
},
"devDependencies": {

View File

@@ -1,5 +1,6 @@
import { describe, it, expect } from "vitest";
import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";
import plugin from "../index.js";
import { PaperclipRuntimeAdapter } from "../runtime-adapter.js";
// ── Test Suite ─────────────────────────────────────────────────────────────────
@@ -8,9 +9,9 @@ describe("paperclip-runtime plugin", () => {
it("should export a valid FusionPlugin with correct manifest fields", () => {
expect(plugin.manifest.id).toBe("fusion-plugin-paperclip-runtime");
expect(plugin.manifest.name).toBe("Paperclip Runtime Plugin");
expect(plugin.manifest.version).toBe("0.1.0");
expect(plugin.manifest.version).toBe("1.0.0");
expect(plugin.manifest.description).toBe(
"Provides Paperclip web access runtime for Fusion AI agents",
"Provides Paperclip runtime for Fusion AI agents",
);
expect(plugin.manifest.author).toBe("Fusion Team");
expect(plugin.state).toBe("installed");
@@ -20,7 +21,7 @@ describe("paperclip-runtime plugin", () => {
expect(plugin.manifest.runtime).toBeDefined();
expect(plugin.manifest.runtime!.runtimeId).toBe("paperclip");
expect(plugin.manifest.runtime!.name).toBe("Paperclip Runtime");
expect(plugin.manifest.runtime!.version).toBe("0.1.0");
expect(plugin.manifest.runtime!.version).toBe("1.0.0");
});
it("should have fusionVersion requirement", () => {
@@ -28,7 +29,7 @@ describe("paperclip-runtime plugin", () => {
});
});
describe("runtime placeholder registration", () => {
describe("runtime registration", () => {
it("should have runtime registration", () => {
expect(plugin.runtime).toBeDefined();
});
@@ -37,7 +38,10 @@ describe("paperclip-runtime plugin", () => {
const runtime = plugin.runtime!;
expect(runtime.metadata.runtimeId).toBe("paperclip");
expect(runtime.metadata.name).toBe("Paperclip Runtime");
expect(runtime.metadata.version).toBe("0.1.0");
expect(runtime.metadata.description).toBe(
"Paperclip-backed AI session using the user's configured pi provider and model",
);
expect(runtime.metadata.version).toBe("1.0.0");
});
it("should have a factory function", () => {
@@ -46,25 +50,32 @@ describe("paperclip-runtime plugin", () => {
});
});
describe("runtime placeholder invocation", () => {
it("should throw deterministic error with FN-2261 reference when factory is invoked", async () => {
const factory = plugin.runtime!.factory;
await expect(factory({} as any)).rejects.toThrow(
"Paperclip runtime implementation is deferred to FN-2261",
);
describe("runtime factory invocation", () => {
beforeEach(() => {
// Mock @fusion/engine for createFnAgent
vi.mock("@fusion/engine", () => ({
createFnAgent: vi.fn().mockResolvedValue({ session: {} }),
promptWithFallback: vi.fn(),
}));
// Mock describeModel
vi.mock("../../engine/src/pi.js", () => ({
describeModel: vi.fn().mockReturnValue("mock/model"),
}));
});
it("should throw error with placeholder message in the error text", async () => {
const factory = plugin.runtime!.factory;
afterEach(() => {
vi.restoreAllMocks();
});
try {
await factory({} as any);
expect.fail("Expected factory to throw an error");
} catch (error) {
expect((error as Error).message).toContain("placeholder");
expect((error as Error).message).toContain("FN-2261");
}
it("should return a PaperclipRuntimeAdapter instance when factory is invoked", async () => {
const runtime = await plugin.runtime!.factory({} as any);
expect(runtime).toBeInstanceOf(PaperclipRuntimeAdapter);
});
it("should return an adapter with correct id and name", async () => {
const runtime = await plugin.runtime!.factory({} as any);
expect(runtime.id).toBe("paperclip");
expect(runtime.name).toBe("Paperclip Runtime");
});
});
@@ -91,5 +102,25 @@ describe("paperclip-runtime plugin", () => {
expect(() => plugin.hooks.onLoad!(mockCtx as any)).not.toThrow();
});
it("onLoad should call logger.info", () => {
const mockLogger = {
info: vi.fn(),
warn: vi.fn(),
error: vi.fn(),
debug: vi.fn(),
};
const mockCtx = {
pluginId: "fusion-plugin-paperclip-runtime",
settings: {},
logger: mockLogger,
emitEvent: () => {},
taskStore: {},
};
plugin.hooks.onLoad!(mockCtx as any);
expect(mockLogger.info).toHaveBeenCalledWith("Paperclip Runtime Plugin loaded");
});
});
});

View File

@@ -0,0 +1,206 @@
/**
* Runtime Adapter Tests
*
* Tests for the PaperclipRuntimeAdapter class.
*/
import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";
import { PaperclipRuntimeAdapter } from "../runtime-adapter.js";
// ── Mock Modules ────────────────────────────────────────────────────────────────
// Mock @fusion/engine for createFnAgent and promptWithFallback
const mockCreateFnAgent = vi.fn();
const mockPromptWithFallback = vi.fn();
vi.mock("@fusion/engine", () => ({
createFnAgent: mockCreateFnAgent,
promptWithFallback: mockPromptWithFallback,
}));
// Mock the relative import of describeModel from pi.ts
// This uses require() in the adapter, so we mock the entire module
vi.mock("../../engine/src/pi.js", () => ({
describeModel: vi.fn().mockReturnValue("mock/anthropic-claude"),
}));
// ── Test Suite ─────────────────────────────────────────────────────────────────
describe("PaperclipRuntimeAdapter", () => {
let adapter: PaperclipRuntimeAdapter;
beforeEach(() => {
vi.clearAllMocks();
adapter = new PaperclipRuntimeAdapter();
});
afterEach(() => {
vi.restoreAllMocks();
});
describe("runtime identity", () => {
it("should have id 'paperclip'", () => {
expect(adapter.id).toBe("paperclip");
});
it("should have name 'Paperclip Runtime'", () => {
expect(adapter.name).toBe("Paperclip Runtime");
});
});
describe("createSession", () => {
it("should call createFnAgent with correct options", async () => {
const mockSession = { dispose: vi.fn() };
const mockResult = { session: mockSession, sessionFile: "/path/to/session.json" };
mockCreateFnAgent.mockResolvedValue(mockResult);
const options = {
cwd: "/project",
systemPrompt: "You are helpful",
skills: ["bash", "read"],
};
const result = await adapter.createSession(options);
expect(mockCreateFnAgent).toHaveBeenCalledTimes(1);
expect(mockCreateFnAgent).toHaveBeenCalledWith({
cwd: "/project",
systemPrompt: "You are helpful",
tools: undefined,
customTools: undefined,
onText: undefined,
onThinking: undefined,
onToolStart: undefined,
onToolEnd: undefined,
defaultProvider: undefined,
defaultModelId: undefined,
fallbackProvider: undefined,
fallbackModelId: undefined,
defaultThinkingLevel: undefined,
sessionManager: undefined,
skillSelection: undefined,
skills: ["bash", "read"],
});
expect(result.session).toBe(mockSession);
expect(result.sessionFile).toBe("/path/to/session.json");
});
it("should pass through model options", async () => {
mockCreateFnAgent.mockResolvedValue({ session: {} });
await adapter.createSession({
cwd: "/project",
systemPrompt: "Test",
defaultProvider: "anthropic",
defaultModelId: "claude-sonnet-4-5",
fallbackProvider: "openai",
fallbackModelId: "gpt-4o",
});
expect(mockCreateFnAgent).toHaveBeenCalledWith(
expect.objectContaining({
defaultProvider: "anthropic",
defaultModelId: "claude-sonnet-4-5",
fallbackProvider: "openai",
fallbackModelId: "gpt-4o",
}),
);
});
it("should pass through custom tools", async () => {
mockCreateFnAgent.mockResolvedValue({ session: {} });
const customTools = [{ name: "custom_tool", execute: vi.fn() }];
await adapter.createSession({
cwd: "/project",
systemPrompt: "Test",
customTools,
});
expect(mockCreateFnAgent).toHaveBeenCalledWith(
expect.objectContaining({
customTools,
}),
);
});
it("should pass through skill selection context", async () => {
mockCreateFnAgent.mockResolvedValue({ session: {} });
const skillSelection = {
projectRootDir: "/project",
requestedSkillNames: ["bash"],
sessionPurpose: "executor" as const,
};
await adapter.createSession({
cwd: "/project",
systemPrompt: "Test",
skillSelection,
});
expect(mockCreateFnAgent).toHaveBeenCalledWith(
expect.objectContaining({
skillSelection,
}),
);
});
});
describe("promptWithFallback", () => {
it("should delegate to promptWithFallback from engine", async () => {
const mockSession = { id: "test-session" };
mockPromptWithFallback.mockResolvedValue(undefined);
await adapter.promptWithFallback(mockSession as any, "Hello", { images: [] });
expect(mockPromptWithFallback).toHaveBeenCalledTimes(1);
expect(mockPromptWithFallback).toHaveBeenCalledWith(mockSession, "Hello", { images: [] });
});
it("should work without options", async () => {
mockPromptWithFallback.mockResolvedValue(undefined);
await adapter.promptWithFallback({} as any, "Hello");
expect(mockPromptWithFallback).toHaveBeenCalledWith({}, "Hello", undefined);
});
});
describe("describeModel", () => {
it("should return model description from pi describeModel", () => {
// eslint-disable-next-line @typescript-eslint/no-require-imports
const { describeModel } = require("../../engine/src/pi.js");
const mockSession = { model: { provider: "anthropic", id: "claude-sonnet-4-5" } };
const result = adapter.describeModel(mockSession as any);
expect(describeModel).toHaveBeenCalledWith(mockSession);
expect(result).toBe("mock/anthropic-claude"); // from mock
});
});
describe("dispose", () => {
it("should call session.dispose() when available", async () => {
const disposeMock = vi.fn().mockResolvedValue(undefined);
const mockSession = { dispose: disposeMock } as any;
await adapter.dispose(mockSession);
expect(disposeMock).toHaveBeenCalledTimes(1);
});
it("should be a no-op when session has no dispose method", async () => {
const mockSession = { id: "test" } as any;
// Should not throw
await expect(adapter.dispose(mockSession)).resolves.toBeUndefined();
});
it("should handle dispose that throws", async () => {
const disposeMock = vi.fn().mockRejectedValue(new Error("Dispose failed"));
const mockSession = { dispose: disposeMock } as any;
await expect(adapter.dispose(mockSession)).rejects.toThrow("Dispose failed");
});
});
});

View File

@@ -1,37 +1,36 @@
/**
* Paperclip Runtime Plugin
*
* Provides the Paperclip web access runtime for Fusion AI agents.
* This is a placeholder implementation — full runtime behavior is deferred to FN-2261.
* Provides the Paperclip runtime for Fusion AI agents, backed by the user's
* configured pi provider and model.
*
* ## Runtime Capabilities
*
* This plugin implements the AgentRuntime interface, providing:
* - Session creation via createFnAgent
* - Prompt with automatic retry and compaction
* - Model description extraction
* - Session disposal support
*/
import { definePlugin } from "@fusion/plugin-sdk";
import { PaperclipRuntimeAdapter } from "./runtime-adapter.js";
import type {
FusionPlugin,
PluginRuntimeRegistration,
} from "@fusion/plugin-sdk";
// ── Runtime Placeholder ────────────────────────────────────────────────────────
// ── Runtime Registration ─────────────────────────────────────────────────────
/**
* Deferred implementation error message for Paperclip runtime.
* This message is thrown when the runtime factory is invoked before
* full implementation is complete (FN-2261).
*/
const DEFERRED_ERROR_MESSAGE =
"Paperclip runtime implementation is deferred to FN-2261. " +
"This is a placeholder plugin — runtime creation is not yet available.";
/**
* Paperclip runtime factory placeholder.
* Paperclip runtime factory.
*
* Throws a deterministic error indicating that the full Paperclip runtime
* implementation has not been completed yet.
* Creates a new PaperclipRuntimeAdapter instance when the runtime is resolved.
*
* @throws Error with DEFERRED_ERROR_MESSAGE when invoked
* @returns Promise resolving to a PaperclipRuntimeAdapter instance
*/
async function paperclipRuntimeFactory(): Promise<never> {
throw new Error(DEFERRED_ERROR_MESSAGE);
async function paperclipRuntimeFactory(): Promise<PaperclipRuntimeAdapter> {
return new PaperclipRuntimeAdapter();
}
/**
@@ -43,8 +42,8 @@ const paperclipRuntime: PluginRuntimeRegistration = {
runtimeId: "paperclip",
name: "Paperclip Runtime",
description:
"Web access runtime for AI agents — browse pages and extract content using headless browser automation",
version: "0.1.0",
"Paperclip-backed AI session using the user's configured pi provider and model",
version: "1.0.0",
},
factory: paperclipRuntimeFactory,
};
@@ -55,8 +54,8 @@ const plugin: FusionPlugin = definePlugin({
manifest: {
id: "fusion-plugin-paperclip-runtime",
name: "Paperclip Runtime Plugin",
version: "0.1.0",
description: "Provides Paperclip web access runtime for Fusion AI agents",
version: "1.0.0",
description: "Provides Paperclip runtime for Fusion AI agents",
author: "Fusion Team",
homepage: "https://github.com/gsxdsm/fusion",
fusionVersion: ">=0.1.0",
@@ -64,17 +63,15 @@ const plugin: FusionPlugin = definePlugin({
runtimeId: "paperclip",
name: "Paperclip Runtime",
description:
"Web access runtime for AI agents — browse pages and extract content",
version: "0.1.0",
"Paperclip-backed AI session using the user's configured pi provider and model",
version: "1.0.0",
},
},
state: "installed",
runtime: paperclipRuntime,
hooks: {
onLoad: (ctx) => {
ctx.logger.info(
"Paperclip Runtime Plugin loaded (placeholder — implementation deferred to FN-2261)",
);
ctx.logger.info("Paperclip Runtime Plugin loaded");
},
},
});

View File

@@ -0,0 +1,137 @@
/**
* Paperclip Runtime Adapter
*
* Implements the AgentRuntime interface for Fusion's plugin system, providing
* AI agent sessions backed by the user's configured pi provider and model.
*
* ## Responsibilities
*
* - Wraps `createFnAgent` from the engine's pi module
* - Delegates `promptWithFallback` to the pi implementation
* - Provides model description via pi's `describeModel`
* - Handles session disposal when explicitly requested
*
* ## Usage
*
* ```typescript
* import { PaperclipRuntimeAdapter } from "./runtime-adapter.js";
*
* const adapter = new PaperclipRuntimeAdapter();
* const { session } = await adapter.createSession({
* cwd: process.cwd(),
* systemPrompt: "You are a helpful assistant",
* skills: ["bash", "read"],
* });
*
* await adapter.promptWithFallback(session, "Hello, world!");
* console.log(adapter.describeModel(session)); // e.g., "anthropic/claude-sonnet-4-5"
*
* await adapter.dispose(session);
* ```
*/
import type { AgentRuntime, AgentRuntimeOptions, AgentSessionResult } from "./types.js";
import type { AgentSession } from "@mariozechner/pi-coding-agent";
// ── describeModel (from pi.ts, not re-exported from @fusion/engine) ─────────────
//
// describeModel is defined in packages/engine/src/pi.ts but is NOT exported from
// the @fusion/engine public API. We import it via relative path for use in the adapter.
// This is acceptable within the monorepo workspace. External plugins would need a
// different approach (e.g., the engine could export it publicly in the future).
//
// eslint-disable-next-line @typescript-eslint/no-require-imports
const { describeModel: getModelDescription } = require("../../engine/src/pi.js");
/**
* Paperclip runtime adapter implementing the Fusion AgentRuntime interface.
*
* This adapter wraps the existing pi agent creation and session management,
* making it available through Fusion's plugin runtime system.
*
* ## Disposal Semantics
*
* The `dispose()` method is provided as an extension to the AgentRuntime interface.
* Engine session consumers may call `dispose()` to clean up sessions when done.
* If the session doesn't support disposal, this is a no-op.
*/
export class PaperclipRuntimeAdapter implements AgentRuntime {
/** Unique runtime identifier */
readonly id = "paperclip";
/** Human-readable runtime name */
readonly name = "Paperclip Runtime";
/**
* Create a new agent session using the pi backend.
*
* @param options - Session creation options including cwd, systemPrompt, model selection, and skills
* @returns Promise resolving to the session result with session and optional sessionFile
*/
async createSession(options: AgentRuntimeOptions): Promise<AgentSessionResult> {
const { createFnAgent } = await import("@fusion/engine");
return createFnAgent({
cwd: options.cwd,
systemPrompt: options.systemPrompt,
tools: options.tools,
customTools: options.customTools,
onText: options.onText,
onThinking: options.onThinking,
onToolStart: options.onToolStart,
onToolEnd: options.onToolEnd,
defaultProvider: options.defaultProvider,
defaultModelId: options.defaultModelId,
fallbackProvider: options.fallbackProvider,
fallbackModelId: options.fallbackModelId,
defaultThinkingLevel: options.defaultThinkingLevel,
sessionManager: options.sessionManager,
skillSelection: options.skillSelection,
skills: options.skills,
});
}
/**
* Prompt the session with user input, with automatic retry and compaction.
*
* Delegates to the pi backend's promptWithFallback implementation which handles:
* - Automatic retry on transient errors
* - Context compaction on context limit errors
* - Model fallback on retryable model selection errors
*
* @param session - The agent session to prompt
* @param prompt - The prompt text
* @param options - Optional prompt options (e.g., images for vision)
*/
async promptWithFallback(session: AgentSession, prompt: string, options?: unknown): Promise<void> {
const { promptWithFallback: pwf } = await import("@fusion/engine");
return pwf(session, prompt, options);
}
/**
* Get a human-readable model description from a session.
*
* Returns the model in the format `"<provider>/<modelId>"`
* or `"unknown model"` when the session has no model set.
*
* @param session - The agent session to describe
* @returns Model description string
*/
describeModel(session: AgentSession): string {
return getModelDescription(session);
}
/**
* Dispose of an agent session.
*
* Calls `session.dispose()` if the session supports disposal,
* otherwise this is a no-op. This extension method provides
* explicit cleanup semantics expected by engine session consumers.
*
* @param session - The agent session to dispose
*/
async dispose(session: AgentSession): Promise<void> {
if (typeof (session as { dispose?: () => Promise<void> }).dispose === "function") {
await (session as { dispose: () => Promise<void> }).dispose();
}
}
}

View File

@@ -0,0 +1,74 @@
/**
* Paperclip Runtime Plugin - Type Definitions
*
* Re-exports runtime contract types from @fusion/engine and plugin types from @fusion/plugin-sdk.
* These types define the interface that the Paperclip runtime adapter must implement.
*
* ## Type Sources
*
* - `AgentRuntime`, `AgentRuntimeOptions`, `AgentSessionResult`: from @fusion/engine (FN-2256 contract)
* - `PluginRuntimeRegistration`, `PluginRuntimeManifestMetadata`, `FusionPlugin`: from @fusion/plugin-sdk
*
* ## Internal Types
*
* `AgentSession` and `ToolDefinition` are used internally in the adapter implementation
* but are NOT re-exported here since they come from @mariozechner/pi-coding-agent,
* which is not a direct dependency of this plugin. They are accessible via
* `AgentSessionResult.session` and `AgentRuntimeOptions.customTools` respectively.
*/
// ── Agent Runtime Contract (from @fusion/engine) ──────────────────────────────
export type {
/**
* Agent runtime adapter interface.
*
* All session runtimes (default pi runtime, plugin-provided runtimes) must
* implement this interface to ensure consistent behavior across engine subsystems.
*/
AgentRuntime,
/**
* Options for creating an agent session.
* Mirrors the options accepted by createFnAgent.
*/
AgentRuntimeOptions,
/**
* Result of creating an agent session.
*/
AgentSessionResult,
} from "@fusion/engine";
// ── Plugin Registration Types (from @fusion/plugin-sdk) ───────────────────────
export type {
/**
* Plugin runtime registration metadata.
* Contains identity and versioning information for a runtime.
*/
PluginRuntimeManifestMetadata,
/**
* Plugin runtime factory function.
* Creates a runtime instance when the plugin is loaded.
*/
PluginRuntimeFactory,
/**
* Plugin runtime registration with metadata and factory.
* The primary registration format used by Fusion's plugin system.
*/
PluginRuntimeRegistration,
/**
* Fusion plugin definition.
* The main export type for all Fusion plugins.
*/
FusionPlugin,
} from "@fusion/plugin-sdk";
// ── Note on describeModel ──────────────────────────────────────────────────────
//
// describeModel is NOT exported from @fusion/engine's public API.
// It is defined in packages/engine/src/pi.ts but only used internally.
// Plugin adapters should import describeModel directly from the relative path:
// import { describeModel } from "../../engine/src/pi.js";
//
// This relative import is only valid within the monorepo workspace.
// External plugins would need a different approach.