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 1158144c52
commit d3711cd449
16 changed files with 1060 additions and 251 deletions

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.