Clarify plugin authoring and external dev workflow

This commit is contained in:
Dotta
2026-03-14 10:40:21 -05:00
parent cb5d7e76fb
commit 30888759f2
36 changed files with 693 additions and 410 deletions

View File

@@ -0,0 +1,2 @@
dist
node_modules

View File

@@ -0,0 +1,23 @@
# Plugin Authoring Smoke Example
A Paperclip plugin
## Development
```bash
pnpm install
pnpm dev # watch builds
pnpm dev:ui # local dev server with hot-reload events
pnpm test
```
## Install Into Paperclip
```bash
pnpm paperclipai plugin install ./
```
## Build Options
- `pnpm build` uses esbuild presets from `@paperclipai/plugin-sdk/bundlers`.
- `pnpm build:rollup` uses rollup presets from the same SDK.

View File

@@ -0,0 +1,17 @@
import esbuild from "esbuild";
import { createPluginBundlerPresets } from "@paperclipai/plugin-sdk/bundlers";
const presets = createPluginBundlerPresets({ uiEntry: "src/ui/index.tsx" });
const watch = process.argv.includes("--watch");
const workerCtx = await esbuild.context(presets.esbuild.worker);
const manifestCtx = await esbuild.context(presets.esbuild.manifest);
const uiCtx = await esbuild.context(presets.esbuild.ui);
if (watch) {
await Promise.all([workerCtx.watch(), manifestCtx.watch(), uiCtx.watch()]);
console.log("esbuild watch mode enabled for worker, manifest, and ui");
} else {
await Promise.all([workerCtx.rebuild(), manifestCtx.rebuild(), uiCtx.rebuild()]);
await Promise.all([workerCtx.dispose(), manifestCtx.dispose(), uiCtx.dispose()]);
}

View File

@@ -0,0 +1,44 @@
{
"name": "@paperclipai/plugin-authoring-smoke-example",
"version": "0.1.0",
"type": "module",
"private": true,
"description": "A Paperclip plugin",
"scripts": {
"build": "node ./esbuild.config.mjs",
"build:rollup": "rollup -c",
"dev": "node ./esbuild.config.mjs --watch",
"dev:ui": "paperclip-plugin-dev-server --root . --ui-dir dist/ui --port 4177",
"test": "vitest run --config ./vitest.config.ts",
"typecheck": "tsc --noEmit"
},
"paperclipPlugin": {
"manifest": "./dist/manifest.js",
"worker": "./dist/worker.js",
"ui": "./dist/ui/"
},
"keywords": [
"paperclip",
"plugin",
"connector"
],
"author": "Plugin Author",
"license": "MIT",
"dependencies": {
"@paperclipai/plugin-sdk": "workspace:*"
},
"devDependencies": {
"@rollup/plugin-node-resolve": "^16.0.1",
"@rollup/plugin-typescript": "^12.1.2",
"@types/node": "^24.6.0",
"@types/react": "^19.0.8",
"esbuild": "^0.27.3",
"rollup": "^4.38.0",
"tslib": "^2.8.1",
"typescript": "^5.7.3",
"vitest": "^3.0.5"
},
"peerDependencies": {
"react": ">=18"
}
}

View File

@@ -0,0 +1,28 @@
import { nodeResolve } from "@rollup/plugin-node-resolve";
import typescript from "@rollup/plugin-typescript";
import { createPluginBundlerPresets } from "@paperclipai/plugin-sdk/bundlers";
const presets = createPluginBundlerPresets({ uiEntry: "src/ui/index.tsx" });
function withPlugins(config) {
if (!config) return null;
return {
...config,
plugins: [
nodeResolve({
extensions: [".ts", ".tsx", ".js", ".jsx", ".mjs"],
}),
typescript({
tsconfig: "./tsconfig.json",
declaration: false,
declarationMap: false,
}),
],
};
}
export default [
withPlugins(presets.rollup.manifest),
withPlugins(presets.rollup.worker),
withPlugins(presets.rollup.ui),
].filter(Boolean);

View File

@@ -0,0 +1,32 @@
import type { PaperclipPluginManifestV1 } from "@paperclipai/plugin-sdk";
const manifest: PaperclipPluginManifestV1 = {
id: "paperclipai.plugin-authoring-smoke-example",
apiVersion: 1,
version: "0.1.0",
displayName: "Plugin Authoring Smoke Example",
description: "A Paperclip plugin",
author: "Plugin Author",
categories: ["connector"],
capabilities: [
"events.subscribe",
"plugin.state.read",
"plugin.state.write"
],
entrypoints: {
worker: "./dist/worker.js",
ui: "./dist/ui"
},
ui: {
slots: [
{
type: "dashboardWidget",
id: "health-widget",
displayName: "Plugin Authoring Smoke Example Health",
exportName: "DashboardWidget"
}
]
}
};
export default manifest;

View File

@@ -0,0 +1,23 @@
import { usePluginAction, usePluginData, type PluginWidgetProps } from "@paperclipai/plugin-sdk/ui";
type HealthData = {
status: "ok" | "degraded" | "error";
checkedAt: string;
};
export function DashboardWidget(_props: PluginWidgetProps) {
const { data, loading, error } = usePluginData<HealthData>("health");
const ping = usePluginAction("ping");
if (loading) return <div>Loading plugin health...</div>;
if (error) return <div>Plugin error: {error.message}</div>;
return (
<div style={{ display: "grid", gap: "0.5rem" }}>
<strong>Plugin Authoring Smoke Example</strong>
<div>Health: {data?.status ?? "unknown"}</div>
<div>Checked: {data?.checkedAt ?? "never"}</div>
<button onClick={() => void ping()}>Ping Worker</button>
</div>
);
}

View File

@@ -0,0 +1,27 @@
import { definePlugin, runWorker } from "@paperclipai/plugin-sdk";
const plugin = definePlugin({
async setup(ctx) {
ctx.events.on("issue.created", async (event) => {
const issueId = event.entityId ?? "unknown";
await ctx.state.set({ scopeKind: "issue", scopeId: issueId, stateKey: "seen" }, true);
ctx.logger.info("Observed issue.created", { issueId });
});
ctx.data.register("health", async () => {
return { status: "ok", checkedAt: new Date().toISOString() };
});
ctx.actions.register("ping", async () => {
ctx.logger.info("Ping action invoked");
return { pong: true, at: new Date().toISOString() };
});
},
async onHealth() {
return { status: "ok", message: "Plugin worker is running" };
}
});
export default plugin;
runWorker(plugin, import.meta.url);

View File

@@ -0,0 +1,20 @@
import { describe, expect, it } from "vitest";
import { createTestHarness } from "@paperclipai/plugin-sdk/testing";
import manifest from "../src/manifest.js";
import plugin from "../src/worker.js";
describe("plugin scaffold", () => {
it("registers data + actions and handles events", async () => {
const harness = createTestHarness({ manifest, capabilities: [...manifest.capabilities, "events.emit"] });
await plugin.definition.setup(harness.ctx);
await harness.emit("issue.created", { issueId: "iss_1" }, { entityId: "iss_1", entityType: "issue" });
expect(harness.getState({ scopeKind: "issue", scopeId: "iss_1", stateKey: "seen" })).toBe(true);
const data = await harness.getData<{ status: string }>("health");
expect(data.status).toBe("ok");
const action = await harness.performAction<{ pong: boolean }>("ping");
expect(action.pong).toBe(true);
});
});

View File

@@ -0,0 +1,27 @@
{
"compilerOptions": {
"target": "ES2022",
"module": "NodeNext",
"moduleResolution": "NodeNext",
"lib": [
"ES2022",
"DOM"
],
"jsx": "react-jsx",
"strict": true,
"skipLibCheck": true,
"declaration": true,
"declarationMap": true,
"sourceMap": true,
"outDir": "dist",
"rootDir": "."
},
"include": [
"src",
"tests"
],
"exclude": [
"dist",
"node_modules"
]
}

View File

@@ -0,0 +1,8 @@
import { defineConfig } from "vitest/config";
export default defineConfig({
test: {
include: ["tests/**/*.spec.ts"],
environment: "node",
},
});

View File

@@ -39,8 +39,6 @@ const manifest: PaperclipPluginManifestV1 = {
"goals.read",
"goals.create",
"goals.update",
"assets.write",
"assets.read",
"activity.log.write",
"metrics.write",
"plugin.state.read",

View File

@@ -71,7 +71,6 @@ type OverviewData = {
};
lastJob: unknown;
lastWebhook: unknown;
lastAsset: unknown;
lastProcessResult: unknown;
streamChannels: Record<string, string>;
safeCommands: Array<{ key: string; label: string; description: string }>;
@@ -766,7 +765,6 @@ function KitchenSinkPageWidgets({ context }: { context: PluginPageProps["context
value={{
lastJob: overview.data?.lastJob ?? null,
lastWebhook: overview.data?.lastWebhook ?? null,
lastAsset: overview.data?.lastAsset ?? null,
lastProcessResult: overview.data?.lastProcessResult ?? null,
}}
/>
@@ -1340,7 +1338,6 @@ function KitchenSinkConsole({ context }: { context: { companyId: string | null;
const [secretRef, setSecretRef] = useState("");
const [metricName, setMetricName] = useState("manual");
const [metricValue, setMetricValue] = useState("1");
const [assetContent, setAssetContent] = useState("Kitchen Sink asset demo");
const [workspaceId, setWorkspaceId] = useState("");
const [workspacePath, setWorkspacePath] = useState<string>(DEFAULT_CONFIG.workspaceScratchFile);
const [workspaceContent, setWorkspaceContent] = useState("Kitchen Sink wrote this file.");
@@ -1388,7 +1385,6 @@ function KitchenSinkConsole({ context }: { context: { companyId: string | null;
const writeMetric = usePluginAction("write-metric");
const httpFetch = usePluginAction("http-fetch");
const resolveSecret = usePluginAction("resolve-secret");
const createAsset = usePluginAction("create-asset");
const runProcess = usePluginAction("run-process");
const readWorkspaceFile = usePluginAction("read-workspace-file");
const writeWorkspaceScratch = usePluginAction("write-workspace-scratch");
@@ -1808,7 +1804,7 @@ function KitchenSinkConsole({ context }: { context: { companyId: string | null;
</div>
</Section>
<Section title="HTTP + Secrets + Assets + Activity + Metrics">
<Section title="HTTP + Secrets + Activity + Metrics">
<div style={{ display: "grid", gap: "12px", gridTemplateColumns: "repeat(auto-fit, minmax(240px, 1fr))" }}>
<form
style={layoutStack}
@@ -1836,22 +1832,6 @@ function KitchenSinkConsole({ context }: { context: { companyId: string | null;
<input style={inputStyle} value={secretRef} onChange={(event) => setSecretRef(event.target.value)} placeholder="MY_SECRET_REF" />
<button type="submit" style={buttonStyle}>Resolve secret ref</button>
</form>
<form
style={layoutStack}
onSubmit={(event) => {
event.preventDefault();
void createAsset({ filename: "kitchen-sink-demo.txt", content: assetContent })
.then((next) => {
setResult(next);
overview.refresh();
})
.catch((error) => setResult({ error: error instanceof Error ? error.message : String(error) }));
}}
>
<strong>Assets</strong>
<textarea style={{ ...inputStyle, minHeight: "88px" }} value={assetContent} onChange={(event) => setAssetContent(event.target.value)} />
<button type="submit" style={buttonStyle}>Upload text asset</button>
</form>
<form
style={layoutStack}
onSubmit={(event) => {

View File

@@ -262,7 +262,6 @@ async function registerDataHandlers(ctx: PluginContext): Promise<void> {
const agents = companyId ? await ctx.agents.list({ companyId, limit: 200, offset: 0 }) : [];
const lastJob = await readInstanceState(ctx, "last-job-run");
const lastWebhook = await readInstanceState(ctx, "last-webhook");
const lastAsset = await readInstanceState(ctx, "last-asset");
const entityRecords = await ctx.entities.list({ limit: 10 } satisfies PluginEntityQuery);
return {
pluginId: PLUGIN_ID,
@@ -281,7 +280,6 @@ async function registerDataHandlers(ctx: PluginContext): Promise<void> {
},
lastJob,
lastWebhook,
lastAsset,
lastProcessResult,
streamChannels: STREAM_CHANNELS,
safeCommands: SAFE_COMMANDS,
@@ -619,24 +617,6 @@ async function registerActionHandlers(ctx: PluginContext): Promise<void> {
};
});
ctx.actions.register("create-asset", async (params) => {
const filename = typeof params.filename === "string" && params.filename.length > 0
? params.filename
: `kitchen-sink-${Date.now()}.txt`;
const content = typeof params.content === "string" ? params.content : "Kitchen Sink example asset";
const uploaded = await ctx.assets.upload(filename, "text/plain", Buffer.from(content, "utf8"));
const url = await ctx.assets.getUrl(uploaded.assetId);
const result = { ...uploaded, url };
await writeInstanceState(ctx, "last-asset", result);
pushRecord({
level: "info",
source: "assets",
message: `Uploaded asset ${filename}`,
data: { assetId: uploaded.assetId },
});
return result;
});
ctx.actions.register("run-process", async (params) => {
const config = await getConfig(ctx);
const companyId = getCurrentCompanyId(params);