This commit is contained in:
2026-03-15 20:08:10 -04:00
parent 33768b748c
commit 55a8c9432e
26 changed files with 3449 additions and 0 deletions

5
plugin-agent-permissions/.gitignore vendored Normal file
View File

@@ -0,0 +1,5 @@
node_modules
dist
.pnpm-debug.log
*.log
.DS_Store

View File

@@ -0,0 +1,62 @@
# Agent Permissions Plugin - Subtasks
## Proposed Issue Breakdown
The following subtasks should be created under FRE-339 "Scope a plugin":
### FRE-XXX: Scaffold agent permissions plugin
**Description:** Create basic plugin structure with manifest, worker entry point, and UI entry point. Set up TypeScript/Vitest build configuration.
**Deliverables:**
- Plugin directory structure created
- `package.json` with dependencies
- `tsconfig.json` configured
- `esbuild.config.mjs` for bundling
- `src/manifest.ts` with plugin metadata and capabilities
- `src/worker.ts` entry point (stub)
- `src/ui/index.tsx` entry point (stub)
- `vitest.config.ts` for testing
---
### FRE-XXX: Implement worker data/action handlers
**Description:** Implement the worker logic for reading and writing agent permissions.
**Deliverables:**
- `agent-permissions` data handler - returns permissions for a single agent
- `toggle-agent-permission` action - enables/disables a permission for an agent
- `all-agents-permissions` data handler - returns all agents with their permissions
- Database queries against `principal_permission_grants` and `principals` tables
- Proper error handling and validation
---
### FRE-XXX: Build UI components
**Description:** Create React UI components for displaying and toggling agent permissions.
**Deliverables:**
- `AgentPermissionsTab.tsx` - Detail tab component shown on agent page
- Permission toggle controls with proper styling
- Loading states and error handling
- Integration with Paperclip UI design system
---
### FRE-XXX: Test plugin
**Description:** Write unit and integration tests for the plugin.
**Deliverables:**
- Unit tests for worker data handlers
- Unit tests for action handlers
- Integration tests for UI components
- Test coverage report
---
## Notes
- All subtasks should have `assigneeAgentId: d20f6f1c-1f24-4405-a122-2f93e0d6c94a` (Founding Engineer)
- All subtasks should have `projectId: 1c49333d-5ee2-41d7-b4c0-2ddfd577ba61` (Paperclip plugins)
- All subtasks should have `parentId: 2777d642-6a55-4ae9-950a-b115ad270e28` (FRE-339)
- Priority: medium
- Status: todo

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,48 @@
{
"name": "@paperclipai/plugin-agent-permissions",
"version": "0.1.0",
"type": "module",
"private": true,
"description": "Per-agent permission toggling for fine-grained access control",
"scripts": {
"build": "node ./esbuild.config.mjs",
"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",
"permissions",
"agent-management"
],
"author": "FrenoCorp",
"license": "MIT",
"pnpm": {
"overrides": {
"@paperclipai/shared": "file:.paperclip-sdk/paperclipai-shared-0.3.1.tgz"
}
},
"devDependencies": {
"@paperclipai/shared": "file:.paperclip-sdk/paperclipai-shared-0.3.1.tgz",
"@paperclipai/plugin-sdk": "file:.paperclip-sdk/paperclipai-plugin-sdk-1.0.0.tgz",
"@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"
}
}

1217
plugin-agent-permissions/pnpm-lock.yaml generated Normal file

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,39 @@
import type { PaperclipPluginManifestV1 } from "@paperclipai/plugin-sdk";
const manifest: PaperclipPluginManifestV1 = {
id: "paperclipai.plugin-agent-permissions",
apiVersion: 1,
version: "0.1.0",
displayName: "Agent Permissions",
description: "Per-agent permission toggling for fine-grained access control",
author: "FrenoCorp",
categories: ["ui", "automation"],
capabilities: [
"agents.read",
"ui.detailTab.register",
"ui.sidebar.register"
],
entrypoints: {
worker: "./dist/worker.js",
ui: "./dist/ui"
},
ui: {
slots: [
{
type: "detailTab",
id: "permissions",
displayName: "Permissions",
exportName: "AgentPermissionsTab",
entityTypes: ["agent"]
},
{
type: "sidebar",
id: "permissions-nav",
displayName: "Permissions",
exportName: "PermissionsNav"
}
]
}
};
export default manifest;

View File

@@ -0,0 +1,88 @@
import { useState } from "react";
import { usePluginData, usePluginAction } from "@paperclipai/plugin-sdk/ui";
import type { PluginDetailTabProps } from "@paperclipai/plugin-sdk/ui";
const PERMISSION_KEYS = [
"agents:create",
"users:invite",
"users:manage_permissions",
"tasks:assign",
"tasks:assign_scope",
"joins:approve"
] as const;
const PERMISSION_LABELS: Record<string, string> = {
"agents:create": "Create Agents",
"users:invite": "Invite Users",
"users:manage_permissions": "Manage Permissions",
"tasks:assign": "Assign Tasks",
"tasks:assign_scope": "Task Assignment Scope",
"joins:approve": "Approve Join Requests"
};
export function AgentPermissionsTab({ context }: PluginDetailTabProps) {
const { entityId: agentId } = context;
const { data, loading, error, refresh } = usePluginData<{
agentId: string;
permissions: Record<string, boolean>;
}>("agent-permissions", { agentId });
const togglePermission = usePluginAction("toggle-agent-permission");
const [updating, setUpdating] = useState<string | null>(null);
if (loading) return <div style={{ padding: "1rem" }}>Loading permissions...</div>;
if (error) return <div style={{ padding: "1rem", color: "#c00" }}>Error: {error.message}</div>;
if (!data) return <div style={{ padding: "1rem" }}>No permissions data available</div>;
async function handleToggle(permissionKey: string, currentEnabled: boolean) {
setUpdating(permissionKey);
try {
await togglePermission({ agentId, permissionKey, enabled: !currentEnabled });
await refresh();
} catch (err) {
console.error("Failed to toggle permission:", err);
} finally {
setUpdating(null);
}
}
return (
<div style={{ padding: "1rem", maxWidth: "600px" }}>
<h2 style={{ marginBottom: "1.5rem", fontSize: "1.25rem", fontWeight: 600 }}>Agent Permissions</h2>
<p style={{ color: "#666", marginBottom: "1.5rem" }}>
Control what actions this agent can perform.
</p>
<div style={{ display: "flex", flexDirection: "column", gap: "0.75rem" }}>
{PERMISSION_KEYS.map((key) => {
const enabled = data.permissions[key] ?? false;
const isUpdating = updating === key;
return (
<label key={key} style={{
display: "flex",
alignItems: "center",
gap: "0.75rem",
cursor: isUpdating ? "wait" : "pointer",
padding: "0.5rem",
borderRadius: "4px",
backgroundColor: isUpdating ? "#f5f5f5" : "transparent",
transition: "background-color 0.2s"
}}>
<input
type="checkbox"
checked={enabled}
onChange={() => handleToggle(key, enabled)}
disabled={updating !== null}
style={{ width: "18px", height: "18px", cursor: isUpdating ? "wait" : "pointer" }}
/>
<span style={{ fontWeight: 500 }}>{PERMISSION_LABELS[key] || key}</span>
{isUpdating && <span style={{ color: "#888", fontSize: "0.875rem" }}>updating...</span>}
</label>
);
})}
</div>
</div>
);
}

View File

@@ -0,0 +1,54 @@
import { usePluginData } from "@paperclipai/plugin-sdk/ui";
import type { PluginSidebarProps } from "@paperclipai/plugin-sdk/ui";
interface AgentPermissionsSummary {
agentId: string;
agentName: string;
permissions: Record<string, boolean>;
}
export function PermissionsNav({ context }: PluginSidebarProps) {
const { data: agentsData, loading, error } = usePluginData<AgentPermissionsSummary[]>("all-agents-permissions");
if (loading) return <div style={{ padding: "1rem" }}>Loading...</div>;
if (error) return <div style={{ padding: "1rem", color: "#c00" }}>Error: {error.message}</div>;
if (!agentsData || agentsData.length === 0) {
return (
<div style={{ padding: "1rem" }}>
<h3 style={{ fontSize: "1rem", fontWeight: 600, marginBottom: "0.5rem" }}>Permissions</h3>
<p style={{ color: "#666", fontSize: "0.875rem" }}>No agents found</p>
</div>
);
}
const agentsWithPermissions = agentsData.filter(a =>
Object.values(a.permissions).some(v => v)
);
return (
<div style={{ padding: "1rem" }}>
<h3 style={{ fontSize: "1rem", fontWeight: 600, marginBottom: "0.75rem" }}>Permissions</h3>
<p style={{ color: "#666", fontSize: "0.75rem", marginBottom: "1rem" }}>
{agentsWithPermissions.length} agent(s) with custom permissions
</p>
<div style={{ display: "flex", flexDirection: "column", gap: "0.5rem" }}>
{agentsData.slice(0, 5).map(agent => {
const permCount = Object.values(agent.permissions).filter(Boolean).length;
return (
<div key={agent.agentId} style={{
fontSize: "0.875rem",
padding: "0.5rem",
backgroundColor: "#f9f9f9",
borderRadius: "4px"
}}>
<div style={{ fontWeight: 500 }}>{agent.agentName}</div>
<div style={{ color: "#888", fontSize: "0.75rem" }}>
{permCount} permission(s) granted
</div>
</div>
);
})}
</div>
</div>
);
}

View File

@@ -0,0 +1,2 @@
export { AgentPermissionsTab } from './AgentPermissionsTab';
export { PermissionsNav } from './PermissionsNav';

View File

@@ -0,0 +1,99 @@
import { definePlugin, runWorker } from "@paperclipai/plugin-sdk";
const PERMISSION_KEYS = [
"agents:create",
"users:invite",
"users:manage_permissions",
"tasks:assign",
"tasks:assign_scope",
"joins:approve"
] as const;
type PermissionKey = typeof PERMISSION_KEYS[number];
interface AgentPermissions {
agentId: string;
permissions: Record<PermissionKey, boolean>;
}
interface AllAgentsPermissions {
agentId: string;
agentName: string;
permissions: Record<PermissionKey, boolean>;
}
type AgentPermissionsMap = Record<string, Record<PermissionKey, boolean>>;
const plugin = definePlugin({
async setup(ctx) {
ctx.data.register("agent-permissions", async (params) => {
const { agentId } = params as { agentId: string };
const allPerms = (await ctx.state.get(
{ scopeKind: "instance", stateKey: "agent_permissions" }
) as AgentPermissionsMap) ?? {};
const agentPerms = allPerms[agentId] ?? {};
return {
agentId,
permissions: PERMISSION_KEYS.reduce((acc, key) => ({
...acc,
[key]: agentPerms[key] ?? false
}), {} as Record<PermissionKey, boolean>)
};
});
ctx.actions.register("toggle-agent-permission", async (params) => {
const { agentId, permissionKey, enabled } = params as {
agentId: string;
permissionKey: PermissionKey;
enabled: boolean;
};
const allPerms = (await ctx.state.get(
{ scopeKind: "instance", stateKey: "agent_permissions" }
) as AgentPermissionsMap) ?? {};
const agentPerms = allPerms[agentId] ?? {};
const updated = { ...agentPerms, [permissionKey]: enabled };
await ctx.state.set(
{ scopeKind: "instance", stateKey: "agent_permissions" },
{ ...allPerms, [agentId]: updated }
);
return { success: true };
});
ctx.data.register("all-agents-permissions", async (params) => {
const companyId = typeof params.companyId === "string" ? params.companyId : "";
const agents = companyId
? await ctx.agents.list({ companyId, limit: 100, offset: 0 })
: [];
const allPerms = (await ctx.state.get(
{ scopeKind: "instance", stateKey: "agent_permissions" }
) as AgentPermissionsMap) ?? {};
const result: AllAgentsPermissions[] = agents.map(agent => ({
agentId: agent.id,
agentName: agent.name,
permissions: PERMISSION_KEYS.reduce((acc, key) => ({
...acc,
[key]: allPerms[agent.id]?.[key] ?? false
}), {} as Record<PermissionKey, boolean>)
}));
return result;
});
},
async onHealth() {
return { status: "ok", message: "Agent permissions plugin running" };
}
});
export default plugin;
runWorker(plugin, import.meta.url);

View File

@@ -0,0 +1,23 @@
{
"compilerOptions": {
"target": "ES2022",
"module": "ESNext",
"moduleResolution": "bundler",
"lib": ["ES2022", "DOM", "DOM.Iterable"],
"jsx": "react-jsx",
"strict": true,
"esModuleInterop": true,
"skipLibCheck": true,
"forceConsistentCasingInFileNames": true,
"resolveJsonModule": true,
"declaration": true,
"declarationMap": true,
"noEmit": true,
"isolatedModules": true,
"allowSyntheticDefaultImports": true,
"outDir": "dist",
"rootDir": "src"
},
"include": ["src/**/*", "tests/**/*"],
"exclude": ["node_modules", "dist"]
}

View File

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

3
plugin-log-viewer/.gitignore vendored Normal file
View File

@@ -0,0 +1,3 @@
dist
node_modules
.paperclip-sdk

View File

@@ -0,0 +1,41 @@
# Log Viewer Plugin
A Paperclip plugin that monitors and displays agent run logs and activity in real-time.
## Features
- **Dashboard Widget**: Shows recent log activity on the main dashboard
- **Full Log Page**: View all captured events with filtering
- **Event Tracking**: Captures:
- Agent run started/finished/failed
- Issue created/updated
- Goal created
- Agent created
## Development
```bash
pnpm install
pnpm dev # watch builds
pnpm dev:ui # local dev server with hot-reload events
pnpm test
```
This scaffold snapshots `@paperclipai/plugin-sdk` and `@paperclipai/shared` from a local Paperclip checkout at:
`/home/mike/code/paperclip/packages/plugins/sdk`
The packed tarballs live in `.paperclip-sdk/` for local development. Before publishing this plugin, switch those dependencies to published package versions once they are available on npm.
## Install Into Paperclip
```bash
curl -X POST http://127.0.0.1:3100/api/plugins/install \
-H "Content-Type: application/json" \
-d '{"packageName":"/home/mike/code/paperclip_plugins/plugin-log-viewer","isLocalPath":true}'
```
## 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,48 @@
{
"name": "@paperclipai/plugin-log-viewer",
"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",
"pnpm": {
"overrides": {
"@paperclipai/shared": "file:.paperclip-sdk/paperclipai-shared-0.3.1.tgz"
}
},
"devDependencies": {
"@paperclipai/shared": "file:.paperclip-sdk/paperclipai-shared-0.3.1.tgz",
"@paperclipai/plugin-sdk": "file:.paperclip-sdk/paperclipai-plugin-sdk-1.0.0.tgz",
"@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"
}
}

1217
plugin-log-viewer/pnpm-lock.yaml generated Normal file

File diff suppressed because it is too large Load Diff

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,53 @@
import type { PaperclipPluginManifestV1 } from "@paperclipai/plugin-sdk";
const manifest: PaperclipPluginManifestV1 = {
id: "paperclipai.plugin-log-viewer",
apiVersion: 1,
version: "0.1.0",
displayName: "Log Viewer",
description: "Monitor and view agent run logs and activity in real-time",
author: "FrenoCorp",
categories: ["automation", "ui"],
capabilities: [
"events.subscribe",
"plugin.state.read",
"plugin.state.write",
"activity.read"
],
entrypoints: {
worker: "./dist/worker.js",
ui: "./dist/ui"
},
ui: {
slots: [
{
type: "dashboardWidget",
id: "log-viewer-widget",
displayName: "Log Activity",
exportName: "DashboardWidget"
},
{
type: "page",
id: "logs",
displayName: "Log Viewer",
exportName: "LogsPage"
}
],
launchers: [
{
id: "open-logs",
displayName: "View Logs",
placementZone: "globalToolbarButton",
action: {
type: "navigate",
target: "/plugins/log-viewer"
},
render: {
environment: "hostRoute"
}
}
]
}
};
export default manifest;

View File

@@ -0,0 +1,187 @@
import { usePluginData, usePluginAction, type PluginWidgetProps, type PluginPageProps } from "@paperclipai/plugin-sdk/ui";
interface LogEntry {
id: string;
eventType: string;
entityId: string;
entityType: string;
timestamp: string;
data?: Record<string, unknown>;
}
interface HealthData {
status: "ok" | "degraded" | "error";
checkedAt: string;
logCount: number;
}
export function DashboardWidget(_props: PluginWidgetProps) {
const { data, loading, error, refresh } = usePluginData<HealthData>("health");
const { data: logs } = usePluginData<LogEntry[]>("logs");
if (loading) return <div>Loading...</div>;
if (error) return <div>Error: {error.message}</div>;
const recentLogs = logs?.slice(0, 3) ?? [];
return (
<div style={{ display: "grid", gap: "0.5rem", padding: "0.5rem" }}>
<div style={{ display: "flex", justifyContent: "space-between", alignItems: "center" }}>
<strong>Log Activity</strong>
<span style={{ fontSize: "0.75rem", color: "#666" }}>
{data?.logCount ?? 0} events
</span>
</div>
{recentLogs.length === 0 ? (
<div style={{ fontSize: "0.875rem", color: "#888" }}>No recent activity</div>
) : (
<div style={{ display: "grid", gap: "0.25rem" }}>
{recentLogs.map((log) => (
<div
key={log.id}
style={{
fontSize: "0.75rem",
padding: "0.25rem",
backgroundColor: "#f5f5f5",
borderRadius: "4px",
display: "grid",
gridTemplateColumns: "1fr auto",
gap: "0.5rem"
}}
>
<span style={{ fontWeight: 500 }}>{formatEventType(log.eventType)}</span>
<span style={{ color: "#888" }}>{formatTime(log.timestamp)}</span>
</div>
))}
</div>
)}
<button
onClick={() => void refresh()}
style={{
fontSize: "0.75rem",
padding: "0.25rem 0.5rem",
marginTop: "0.25rem"
}}
>
Refresh
</button>
</div>
);
}
export function LogsPage(_props: PluginPageProps) {
const { data: logs, loading, error, refresh } = usePluginData<LogEntry[]>("logs");
const clearLogs = usePluginAction("clear-logs");
const handleClear = async () => {
await clearLogs();
void refresh();
};
if (loading) return <div>Loading logs...</div>;
if (error) return <div>Error: {error.message}</div>;
return (
<div style={{ padding: "1rem", maxWidth: "800px", margin: "0 auto" }}>
<div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: "1rem" }}>
<h1 style={{ fontSize: "1.5rem", fontWeight: 600 }}>Log Viewer</h1>
<div style={{ display: "flex", gap: "0.5rem" }}>
<button
onClick={() => void refresh()}
style={{
padding: "0.5rem 1rem",
backgroundColor: "#f5f5f5",
border: "1px solid #ddd",
borderRadius: "4px",
cursor: "pointer"
}}
>
Refresh
</button>
<button
onClick={() => void handleClear()}
style={{
padding: "0.5rem 1rem",
backgroundColor: "#fee",
border: "1px solid #fcc",
borderRadius: "4px",
cursor: "pointer",
color: "#c00"
}}
>
Clear Logs
</button>
</div>
</div>
<div style={{ display: "grid", gap: "0.5rem" }}>
{!logs || logs.length === 0 ? (
<div style={{ padding: "2rem", textAlign: "center", color: "#888" }}>
No log entries yet. Activity will appear here as events occur.
</div>
) : (
logs.map((log) => (
<div
key={log.id}
style={{
padding: "0.75rem",
backgroundColor: "#fff",
border: "1px solid #eee",
borderRadius: "6px",
display: "grid",
gridTemplateColumns: "auto 1fr auto",
gap: "1rem",
alignItems: "center"
}}
>
<span
style={{
padding: "0.25rem 0.5rem",
borderRadius: "4px",
fontSize: "0.75rem",
fontWeight: 500,
backgroundColor: getEventColor(log.eventType),
color: "#fff"
}}
>
{formatEventType(log.eventType)}
</span>
<div style={{ display: "grid", gap: "0.25rem" }}>
<div style={{ fontSize: "0.875rem", fontWeight: 500 }}>
{log.entityType}: {log.entityId.slice(0, 8)}...
</div>
{log.data?.companyId ? (
<div style={{ fontSize: "0.75rem", color: "#888" }}>
Company: {String(log.data.companyId as string).slice(0, 8)}...
</div>
) : null}
</div>
<span style={{ fontSize: "0.75rem", color: "#888" }}>
{formatTime(log.timestamp)}
</span>
</div>
))
)}
</div>
</div>
);
}
function formatEventType(eventType: string): string {
const parts = eventType.split(".");
return parts[parts.length - 1] ?? eventType;
}
function formatTime(timestamp: string): string {
const date = new Date(timestamp);
return date.toLocaleTimeString([], { hour: "2-digit", minute: "2-digit" });
}
function getEventColor(eventType: string): string {
if (eventType.includes("failed")) return "#c00";
if (eventType.includes("finished")) return "#4a4";
if (eventType.includes("started")) return "#48a";
if (eventType.includes("created")) return "#4a8";
if (eventType.includes("updated")) return "#888";
return "#666";
}

View File

@@ -0,0 +1,130 @@
import { definePlugin, runWorker } from "@paperclipai/plugin-sdk";
interface LogEntry {
id: string;
eventType: string;
entityId: string;
entityType: string;
timestamp: string;
data?: Record<string, unknown>;
}
const MAX_LOG_ENTRIES = 100;
const plugin = definePlugin({
async setup(ctx) {
const recentLogs: LogEntry[] = [];
async function addLogEntry(eventType: string, entityId: string, entityType: string, data?: Record<string, unknown>) {
const entry: LogEntry = {
id: `log_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`,
eventType,
entityId,
entityType,
timestamp: new Date().toISOString(),
data
};
recentLogs.unshift(entry);
if (recentLogs.length > MAX_LOG_ENTRIES) {
recentLogs.pop();
}
await ctx.state.set(
{ scopeKind: "instance", stateKey: "recent_logs" },
recentLogs
);
}
ctx.events.on("agent.run.started", async (event) => {
const runId = event.entityId ?? "unknown";
await addLogEntry("agent.run.started", runId, "run", {
companyId: event.companyId
});
ctx.logger.info("Agent run started", { runId });
});
ctx.events.on("agent.run.finished", async (event) => {
const runId = event.entityId ?? "unknown";
await addLogEntry("agent.run.finished", runId, "run", {
companyId: event.companyId
});
ctx.logger.info("Agent run finished", { runId });
});
ctx.events.on("agent.run.failed", async (event) => {
const runId = event.entityId ?? "unknown";
await addLogEntry("agent.run.failed", runId, "run", {
companyId: event.companyId
});
ctx.logger.info("Agent run failed", { runId });
});
ctx.events.on("issue.created", async (event) => {
const issueId = event.entityId ?? "unknown";
await addLogEntry("issue.created", issueId, "issue", {
companyId: event.companyId
});
ctx.logger.info("Issue created", { issueId });
});
ctx.events.on("issue.updated", async (event) => {
const issueId = event.entityId ?? "unknown";
await addLogEntry("issue.updated", issueId, "issue", {
companyId: event.companyId
});
ctx.logger.info("Issue updated", { issueId });
});
ctx.events.on("goal.created", async (event) => {
const goalId = event.entityId ?? "unknown";
await addLogEntry("goal.created", goalId, "goal", {
companyId: event.companyId
});
ctx.logger.info("Goal created", { goalId });
});
ctx.events.on("agent.created", async (event) => {
const agentId = event.entityId ?? "unknown";
await addLogEntry("agent.created", agentId, "agent", {
companyId: event.companyId
});
ctx.logger.info("Agent created", { agentId });
});
ctx.data.register("logs", async () => {
const stored = await ctx.state.get(
{ scopeKind: "instance", stateKey: "recent_logs" }
);
return (stored as LogEntry[] | null) ?? recentLogs;
});
ctx.data.register("health", async () => {
return {
status: "ok",
checkedAt: new Date().toISOString(),
logCount: recentLogs.length
};
});
ctx.actions.register("clear-logs", async () => {
recentLogs.length = 0;
await ctx.state.set(
{ scopeKind: "instance", stateKey: "recent_logs" },
[]
);
ctx.logger.info("Logs cleared");
return { success: true };
});
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,26 @@
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 log viewer", () => {
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", { companyId: "comp_1" }, { entityId: "iss_1", entityType: "issue", companyId: "comp_1" });
const logs = await harness.getData<Array<{ eventType: string; entityId: string }>>("logs");
expect(logs).toBeDefined();
expect(logs.length).toBeGreaterThan(0);
expect(logs[0].eventType).toBe("issue.created");
expect(logs[0].entityId).toBe("iss_1");
const health = await harness.getData<{ status: string; logCount: number }>("health");
expect(health.status).toBe("ok");
expect(health.logCount).toBe(1);
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",
},
});