The open-source app everyone uses to manage agents at work
TypeScript acpxagent-orchestrationagent-skillsagentic-aiai-agentsai-engineeringai-governanceai-toolsautonomous-agentsclaudeclaude-codeclaude-skillscodexhermesllmmcpmulti-agentopenclawproject-managementworkflow-automation
Add kitchen sink plugin example
Dotta6fa1dd21974a
diff --git a/doc/plans/2026-03-13-plugin-kitchen-sink-example.md b/doc/plans/2026-03-13-plugin-kitchen-sink-example.mdnew file mode 100644index 0000000000..6a81c5cd5c--- /dev/null+++ b/doc/plans/2026-03-13-plugin-kitchen-sink-example.md@@ -0,0 +1,699 @@+# Kitchen Sink Plugin Plan++## Goal++Add a new first-party example plugin, `Kitchen Sink (Example)`, that demonstrates every currently implemented Paperclip plugin API surface in one place.++This plugin is meant to be:++- a living reference implementation for contributors+- a manual test harness for the plugin runtime+- a discoverable demo of what plugins can actually do today++It is not meant to be a polished end-user product plugin.++## Why++The current plugin system has a real API surface, but it is spread across:++- SDK docs+- SDK types+- plugin spec prose+- two example plugins that each show only a narrow slice++That makes it hard to answer basic questions like:++- what can plugins render?+- what can plugin workers actually do?+- which surfaces are real versus aspirational?+- how should a new plugin be structured in this repo?++The kitchen-sink plugin should answer those questions by example.++## Success Criteria++The plugin is successful if a contributor can install it and, without reading the SDK first, discover and exercise the current plugin runtime surface area from inside Paperclip.++Concretely:++- it installs from the bundled examples list+- it exposes at least one demo for every implemented worker API surface+- it exposes at least one demo for every host-mounted UI surface+- it clearly labels local-only / trusted-only demos+- it is safe enough for local development by default+- it doubles as a regression harness for plugin runtime changes++## Constraints++- Keep it instance-installed, not company-installed.+- Treat this as a trusted/local example plugin.+- Do not rely on cloud-safe runtime assumptions.+- Avoid destructive defaults.+- Avoid irreversible mutations unless they are clearly labeled and easy to undo.++## Source Of Truth For This Plan++This plan is based on the currently implemented SDK/types/runtime, not only the long-horizon spec.++Primary references:++- `packages/plugins/sdk/README.md`+- `packages/plugins/sdk/src/types.ts`+- `packages/plugins/sdk/src/ui/types.ts`+- `packages/shared/src/constants.ts`+- `packages/shared/src/types/plugin.ts`++## Current Surface Inventory++### Worker/runtime APIs to demonstrate++These are the concrete `ctx` clients currently exposed by the SDK:++- `ctx.config`+- `ctx.events`+- `ctx.jobs`+- `ctx.launchers`+- `ctx.http`+- `ctx.secrets`+- `ctx.assets`+- `ctx.activity`+- `ctx.state`+- `ctx.entities`+- `ctx.projects`+- `ctx.companies`+- `ctx.issues`+- `ctx.agents`+- `ctx.goals`+- `ctx.data`+- `ctx.actions`+- `ctx.streams`+- `ctx.tools`+- `ctx.metrics`+- `ctx.logger`++### UI surfaces to demonstrate++Surfaces defined in the SDK:++- `page`+- `settingsPage`+- `dashboardWidget`+- `sidebar`+- `sidebarPanel`+- `detailTab`+- `taskDetailView`+- `projectSidebarItem`+- `toolbarButton`+- `contextMenuItem`+- `commentAnnotation`+- `commentContextMenuItem`++### Current host confidence++Confirmed or strongly indicated as mounted in the current app:++- `page`+- `settingsPage`+- `dashboardWidget`+- `detailTab`+- `projectSidebarItem`+- comment surfaces+- launcher infrastructure++Need explicit validation before claiming full demo coverage:++- `sidebar`+- `sidebarPanel`+- `taskDetailView`+- `toolbarButton` as direct slot, distinct from launcher placement+- `contextMenuItem` as direct slot, distinct from comment menu and launcher placement++The implementation should keep a small validation checklist for these before we call the plugin "complete".++## Plugin Concept++The plugin should be named:++- display name: `Kitchen Sink (Example)`+- package: `@paperclipai/plugin-kitchen-sink-example`+- plugin id: `paperclip.kitchen-sink-example` or `paperclip-kitchen-sink-example`++Recommendation: use `paperclip-kitchen-sink-example` to match current in-repo example naming style.++Category mix:++- `ui`+- `automation`+- `workspace`+- `connector`++That is intentionally broad because the point is coverage.++## UX Shape++The plugin should have one main full-page demo console plus smaller satellites on other surfaces.++### 1. Plugin page++Primary route: the plugin `page` surface should be the central dashboard for all demos.++Recommended page sections:++- `Overview`+ - what this plugin demonstrates+ - current capabilities granted+ - current host context+- `UI Surfaces`+ - links explaining where each other surface should appear+- `Data + Actions`+ - buttons and forms for bridge-driven worker demos+- `Events + Streams`+ - emit event+ - watch event log+ - stream demo output+- `Paperclip Domain APIs`+ - companies+ - projects/workspaces+ - issues+ - goals+ - agents+- `Local Workspace + Process`+ - file listing+ - file read/write scratch area+ - child process demo+- `Jobs + Webhooks + Tools`+ - job status+ - webhook URL and recent deliveries+ - declared tools+- `State + Entities + Assets`+ - scoped state editor+ - plugin entity inspector+ - upload/generated asset demo+- `Observability`+ - metrics written+ - activity log samples+ - latest worker logs++### 2. Dashboard widget++A compact widget on the main dashboard should show:++- plugin health+- count of demos exercised+- recent event/stream activity+- shortcut to the full plugin page++### 3. Project sidebar item++Add a `Kitchen Sink` link under each project that deep-links into a project-scoped plugin tab.++### 4. Detail tabs++Use detail tabs to demonstrate entity-context rendering on:++- `project`+- `issue`+- `agent`+- `goal`++Each tab should show:++- the host context it received+- the relevant entity fetch via worker bridge+- one small action scoped to that entity++### 5. Comment surfaces++Use issue comment demos to prove comment-specific extension points:++- `commentAnnotation`+ - render parsed metadata below each comment+ - show comment id, issue id, and a small derived status+- `commentContextMenuItem`+ - add a menu action like `Copy Context To Kitchen Sink`+ - action writes a plugin entity or state record for later inspection++### 6. Settings page++Custom `settingsPage` should be intentionally simple and operational:++- `About`+- `Danger / Trust Model`+- demo toggles+- local process defaults+- workspace scratch-path behavior+- secret reference inputs+- event/job/webhook sample config++This plugin should also keep the generic plugin settings `Status` tab useful by writing health, logs, and metrics.++## Feature Matrix++Each implemented worker API should have a visible demo.++### `ctx.config`++Demo:++- read live config+- show config JSON+- react to config changes without restart where possible++### `ctx.events`++Demos:++- emit a plugin event+- subscribe to plugin events+- subscribe to a core Paperclip event such as `issue.created`+- show recent received events in a timeline++### `ctx.jobs`++Demos:++- one scheduled heartbeat-style demo job+- one manual run button from the UI if host supports manual job trigger+- show last run result and timestamps++### `ctx.launchers`++Demos:++- declare launchers in manifest+- optionally register one runtime launcher from the worker+- show launcher metadata on the plugin page++### `ctx.http`++Demo:++- make a simple outbound GET request to a safe endpoint+- show status code, latency, and JSON result++Recommendation: default to a Paperclip-local endpoint or a stable public echo endpoint to avoid flaky docs.++### `ctx.secrets`++Demo:++- operator enters a secret reference in config+- plugin resolves it on demand+- UI only shows masked result length / success status, never raw secret++### `ctx.assets`++Demos:++- generate a text asset from the UI+- optionally upload a tiny JSON blob or screenshot-like text file+- show returned asset URL++### `ctx.activity`++Demo:++- button to write a plugin activity log entry against current company/entity++### `ctx.state`++Demos:++- instance-scoped state+- company-scoped state+- project-scoped state+- issue-scoped state+- delete/reset controls++Use a small state inspector/editor on the plugin page.++### `ctx.entities`++Demos:++- create plugin-owned sample records+- list/filter them+- show one realistic use case such as "copied comments" or "demo sync records"++### `ctx.projects`++Demos:++- list projects+- list project workspaces+- resolve primary workspace+- resolve workspace for issue++### `ctx.companies`++Demo:++- list companies and show current selected company++### `ctx.issues`++Demos:++- list issues in current company+- create issue+- update issue status/title+- list comments+- create comment++### `ctx.agents`++Demos:++- list agents+- invoke one agent with a test prompt+- pause/resume where safe++Agent mutation controls should be behind an explicit warning.++### `ctx.agents.sessions`++Demos:++- create agent chat session+- send message+- stream events back to the UI+- close session++This is a strong candidate for the best "wow" demo on the plugin page.++### `ctx.goals`++Demos:++- list goals+- create goal+- update status/title++### `ctx.data`++Use throughout the plugin for all read-side bridge demos.++### `ctx.actions`++Use throughout the plugin for all mutation-side bridge demos.++### `ctx.streams`++Demos:++- live event log stream+- token-style stream from an agent session relay+- fake progress stream for a long-running action++### `ctx.tools`++Demos:++- declare 2-3 simple agent tools+- tool 1: echo/diagnostics+- tool 2: project/workspace summary+- tool 3: create issue or write plugin state++The plugin page should list declared tools and show example input payloads.++### `ctx.metrics`++Demo:++- write a sample metric on each major demo action+- surface a small recent metrics table in the plugin page++### `ctx.logger`++Demo:++- every action logs structured entries+- plugin settings `Status` page then doubles as the log viewer++## Local Workspace And Process Demos++The plugin SDK intentionally leaves file/process operations to the plugin itself once it has workspace metadata.++The kitchen-sink plugin should demonstrate that explicitly.++### Workspace demos++- list files from a selected workspace+- read a file+- write to a plugin-owned scratch file+- optionally search files with `rg` if available++### Process demos++- run a short-lived command like `pwd`, `ls`, or `git status`+- stream stdout/stderr back to UI+- show exit code and timing++Important safeguards:++- default commands must be read-only+- no shell interpolation from arbitrary free-form input in v1+- provide a curated command list or a strongly validated command form+- clearly label this area as local-only and trusted-only++## Proposed Manifest Coverage++The plugin should aim to declare:++- `page`+- `settingsPage`+- `dashboardWidget`+- `detailTab` for `project`, `issue`, `agent`, `goal`+- `projectSidebarItem`+- `commentAnnotation`+- `commentContextMenuItem`++Then, after host validation, add if supported:++- `sidebar`+- `sidebarPanel`+- `taskDetailView`+- `toolbarButton`+- `contextMenuItem`++It should also declare one or more `ui.launchers` entries to exercise launcher behavior independently of slot rendering.++## Proposed Package Layout++New package:++- `packages/plugins/examples/plugin-kitchen-sink-example/`++Expected files:++- `package.json`+- `README.md`+- `tsconfig.json`+- `src/index.ts`+- `src/manifest.ts`+- `src/worker.ts`+- `src/ui/index.tsx`+- `src/ui/components/...`+- `src/ui/hooks/...`+- `src/lib/...`+- optional `scripts/build-ui.mjs` if UI bundling needs esbuild++## Proposed Internal Architecture++### Worker modules++Recommended split:++- `src/worker.ts`+ - plugin definition and wiring+- `src/worker/data.ts`+ - `ctx.data.register(...)`+- `src/worker/actions.ts`+ - `ctx.actions.register(...)`+- `src/worker/events.ts`+ - event subscriptions and event log buffer+- `src/worker/jobs.ts`+ - scheduled job handlers+- `src/worker/tools.ts`+ - tool declarations and handlers+- `src/worker/local-runtime.ts`+ - file/process demos+- `src/worker/demo-store.ts`+ - helpers for state/entities/assets/metrics++### UI modules++Recommended split:++- `src/ui/index.tsx`+ - exported slot components+- `src/ui/page/KitchenSinkPage.tsx`+- `src/ui/settings/KitchenSinkSettingsPage.tsx`+- `src/ui/widgets/KitchenSinkDashboardWidget.tsx`+- `src/ui/tabs/ProjectKitchenSinkTab.tsx`+- `src/ui/tabs/IssueKitchenSinkTab.tsx`+- `src/ui/tabs/AgentKitchenSinkTab.tsx`+- `src/ui/tabs/GoalKitchenSinkTab.tsx`+- `src/ui/comments/KitchenSinkCommentAnnotation.tsx`+- `src/ui/comments/KitchenSinkCommentMenuItem.tsx`+- `src/ui/shared/...`++## Configuration Schema++The plugin should have a substantial but understandable `instanceConfigSchema`.++Recommended config fields:++- `enableDangerousDemos`+- `enableWorkspaceDemos`+- `enableProcessDemos`+- `showSidebarEntry`+- `showSidebarPanel`+- `showProjectSidebarItem`+- `showCommentAnnotation`+- `showCommentContextMenuItem`+- `showToolbarLauncher`+- `defaultDemoCompanyId` optional+- `secretRefExample`+- `httpDemoUrl`+- `processAllowedCommands`+- `workspaceScratchSubdir`++Defaults should keep risky behavior off.++## Safety Defaults++Default posture:++- UI and read-only demos on+- mutating domain demos on but explicitly labeled+- process demos off by default+- no arbitrary shell input by default+- no raw secret rendering ever++## Phased Build Plan++### Phase 1: Core plugin skeleton++- scaffold package+- add manifest, worker, UI entrypoints+- add README+- make it appear in bundled examples list++### Phase 2: Core, confirmed UI surfaces++- plugin page+- settings page+- dashboard widget+- project sidebar item+- detail tabs++### Phase 3: Core worker APIs++- config+- state+- entities+- companies/projects/issues/goals+- data/actions+- metrics/logger/activity++### Phase 4: Real-time and automation APIs++- streams+- events+- jobs+- webhooks+- agent sessions+- tools++### Phase 5: Local trusted runtime demos++- workspace file demos+- child process demos+- guarded by config++### Phase 6: Secondary UI surfaces++- comment annotation+- comment context menu item+- launchers++### Phase 7: Validation-only surfaces++Validate whether the current host truly mounts:++- `sidebar`+- `sidebarPanel`+- `taskDetailView`+- direct-slot `toolbarButton`+- direct-slot `contextMenuItem`++If mounted, add demos.+If not mounted, document them as SDK-defined but host-pending.++## Documentation Deliverables++The plugin should ship with a README that includes:++- what it demonstrates+- which surfaces are local-only+- how to install it+- where each UI surface should appear+- a mapping from demo card to SDK API++It should also be referenced from plugin docs as the "reference everything plugin".++## Testing And Verification++Minimum verification:++- package typecheck/build+- install from bundled example list+- page loads+- widget appears+- project tab appears+- comment surfaces render+- settings page loads+- key actions succeed++Recommended manual checklist:++- create issue from plugin+- create goal from plugin+- emit and receive plugin event+- stream action output+- open agent session and receive streamed reply+- upload an asset+- write plugin activity log+- run a safe local process demo++## Open Questions++1. Should the process demo remain curated-command-only in the first pass?+ Recommendation: yes.++2. Should the plugin create throwaway "kitchen sink demo" issues/goals automatically?+ Recommendation: no. Make creation explicit.++3. Should we expose unsupported-but-typed surfaces in the UI even if host mounting is not wired?+ Recommendation: yes, but label them as `SDK-defined / host validation pending`.++4. Should agent mutation demos include pause/resume by default?+ Recommendation: probably yes, but behind a warning block.++5. Should this plugin be treated as a supported regression harness in CI later?+ Recommendation: yes. Long term, this should be the plugin-runtime smoke test package.++## Recommended Next Step++If this plan looks right, the next implementation pass should start by building only:++- package skeleton+- page+- settings page+- dashboard widget+- one project detail tab+- one issue detail tab+- the basic worker/action/data/state/event scaffolding++That is enough to lock the architecture before filling in every demo surface.diff --git a/packages/plugins/examples/plugin-kitchen-sink-example/README.md b/packages/plugins/examples/plugin-kitchen-sink-example/README.mdnew file mode 100644index 0000000000..bfa4ec5268--- /dev/null+++ b/packages/plugins/examples/plugin-kitchen-sink-example/README.md@@ -0,0 +1,33 @@+# @paperclipai/plugin-kitchen-sink-example++Kitchen Sink is the first-party reference plugin that demonstrates nearly the full currently implemented Paperclip plugin surface in one package.++It is intentionally broad:++- full plugin page+- dashboard widget+- project and issue surfaces+- comment surfaces+- sidebar surfaces+- settings page+- worker bridge data/actions+- events, jobs, webhooks, tools, streams+- state, entities, assets, metrics, activity+- local workspace and process demos++This plugin is for local development, contributor onboarding, and runtime regression testing. It is not meant as a production plugin template to ship unchanged.++## Install++```sh+pnpm --filter @paperclipai/plugin-kitchen-sink-example build+pnpm paperclipai plugin install ./packages/plugins/examples/plugin-kitchen-sink-example+```++Or install it from the Paperclip plugin manager as a bundled example once this repo is built.++## Notes++- Local workspace and process demos are trusted-only and default to safe, curated commands.+- The plugin settings page lets you toggle optional demo surfaces and local runtime behavior.+- Some SDK-defined host surfaces still depend on the Paperclip host wiring them visibly; this package aims to exercise the currently mounted ones and make the rest obvious.diff --git a/packages/plugins/examples/plugin-kitchen-sink-example/package.json b/packages/plugins/examples/plugin-kitchen-sink-example/package.jsonnew file mode 100644index 0000000000..467ff03996--- /dev/null+++ b/packages/plugins/examples/plugin-kitchen-sink-example/package.json@@ -0,0 +1,37 @@+{+ "name": "@paperclipai/plugin-kitchen-sink-example",+ "version": "0.1.0",+ "description": "Reference plugin that demonstrates the full Paperclip plugin surface area in one package",+ "type": "module",+ "private": true,+ "exports": {+ ".": "./src/index.ts"+ },+ "paperclipPlugin": {+ "manifest": "./dist/manifest.js",+ "worker": "./dist/worker.js",+ "ui": "./dist/ui/"+ },+ "scripts": {+ "prebuild": "node ../../../../scripts/ensure-plugin-build-deps.mjs",+ "build": "tsc && node ./scripts/build-ui.mjs",+ "clean": "rm -rf dist",+ "typecheck": "pnpm --filter @paperclipai/plugin-sdk build && tsc --noEmit"+ },+ "dependencies": {+ "@paperclipai/plugin-sdk": "workspace:*",+ "@paperclipai/shared": "workspace:*"+ },+ "devDependencies": {+ "esbuild": "^0.27.3",+ "@types/node": "^24.6.0",+ "@types/react": "^19.0.8",+ "@types/react-dom": "^19.0.3",+ "react": "^19.0.0",+ "react-dom": "^19.0.0",+ "typescript": "^5.7.3"+ },+ "peerDependencies": {+ "react": ">=18"+ }+}diff --git a/packages/plugins/examples/plugin-kitchen-sink-example/scripts/build-ui.mjs b/packages/plugins/examples/plugin-kitchen-sink-example/scripts/build-ui.mjsnew file mode 100644index 0000000000..5cd75637cf--- /dev/null+++ b/packages/plugins/examples/plugin-kitchen-sink-example/scripts/build-ui.mjs@@ -0,0 +1,24 @@+import esbuild from "esbuild";+import path from "node:path";+import { fileURLToPath } from "node:url";++const __filename = fileURLToPath(import.meta.url);+const __dirname = path.dirname(__filename);+const packageRoot = path.resolve(__dirname, "..");++await esbuild.build({+ entryPoints: [path.join(packageRoot, "src/ui/index.tsx")],+ outfile: path.join(packageRoot, "dist/ui/index.js"),+ bundle: true,+ format: "esm",+ platform: "browser",+ target: ["es2022"],+ sourcemap: true,+ external: [+ "react",+ "react-dom",+ "react/jsx-runtime",+ "@paperclipai/plugin-sdk/ui",+ ],+ logLevel: "info",+});diff --git a/packages/plugins/examples/plugin-kitchen-sink-example/src/constants.ts b/packages/plugins/examples/plugin-kitchen-sink-example/src/constants.tsnew file mode 100644index 0000000000..4479d4a57b--- /dev/null+++ b/packages/plugins/examples/plugin-kitchen-sink-example/src/constants.ts@@ -0,0 +1,112 @@+import type { PluginLauncherRegistration } from "@paperclipai/plugin-sdk";++export const PLUGIN_ID = "paperclip-kitchen-sink-example";+export const PLUGIN_VERSION = "0.1.0";++export const SLOT_IDS = {+ page: "kitchen-sink-page",+ settingsPage: "kitchen-sink-settings-page",+ dashboardWidget: "kitchen-sink-dashboard-widget",+ sidebar: "kitchen-sink-sidebar-link",+ sidebarPanel: "kitchen-sink-sidebar-panel",+ projectSidebarItem: "kitchen-sink-project-link",+ projectTab: "kitchen-sink-project-tab",+ issueTab: "kitchen-sink-issue-tab",+ taskDetailView: "kitchen-sink-task-detail",+ toolbarButton: "kitchen-sink-toolbar-action",+ contextMenuItem: "kitchen-sink-context-action",+ commentAnnotation: "kitchen-sink-comment-annotation",+ commentContextMenuItem: "kitchen-sink-comment-action",+} as const;++export const EXPORT_NAMES = {+ page: "KitchenSinkPage",+ settingsPage: "KitchenSinkSettingsPage",+ dashboardWidget: "KitchenSinkDashboardWidget",+ sidebar: "KitchenSinkSidebarLink",+ sidebarPanel: "KitchenSinkSidebarPanel",+ projectSidebarItem: "KitchenSinkProjectSidebarItem",+ projectTab: "KitchenSinkProjectTab",+ issueTab: "KitchenSinkIssueTab",+ taskDetailView: "KitchenSinkTaskDetailView",+ toolbarButton: "KitchenSinkToolbarButton",+ contextMenuItem: "KitchenSinkContextMenuItem",+ commentAnnotation: "KitchenSinkCommentAnnotation",+ commentContextMenuItem: "KitchenSinkCommentContextMenuItem",+ launcherModal: "KitchenSinkLauncherModal",+} as const;++export const JOB_KEYS = {+ heartbeat: "demo-heartbeat",+} as const;++export const WEBHOOK_KEYS = {+ demo: "demo-ingest",+} as const;++export const TOOL_NAMES = {+ echo: "echo",+ companySummary: "company-summary",+ createIssue: "create-issue",+} as const;++export const STREAM_CHANNELS = {+ progress: "progress",+ agentChat: "agent-chat",+} as const;++export const SAFE_COMMANDS = [+ {+ key: "pwd",+ label: "Print workspace path",+ command: "pwd",+ args: [] as string[],+ description: "Prints the current workspace directory.",+ },+ {+ key: "ls",+ label: "List workspace files",+ command: "ls",+ args: ["-la"] as string[],+ description: "Lists files in the selected workspace.",+ },+ {+ key: "git-status",+ label: "Git status",+ command: "git",+ args: ["status", "--short", "--branch"] as string[],+ description: "Shows git status for the selected workspace.",+ },+] as const;++export type SafeCommandKey = (typeof SAFE_COMMANDS)[number]["key"];++export const DEFAULT_CONFIG = {+ showSidebarEntry: true,+ showSidebarPanel: true,+ showProjectSidebarItem: true,+ showCommentAnnotation: true,+ showCommentContextMenuItem: true,+ enableWorkspaceDemos: true,+ enableProcessDemos: false,+ secretRefExample: "",+ httpDemoUrl: "https://httpbin.org/anything",+ allowedCommands: SAFE_COMMANDS.map((command) => command.key),+ workspaceScratchFile: ".paperclip-kitchen-sink-demo.txt",+} as const;++export const RUNTIME_LAUNCHER: PluginLauncherRegistration = {+ id: "kitchen-sink-runtime-launcher",+ displayName: "Kitchen Sink Modal",+ description: "Demonstrates runtime launcher registration from the worker.",+ placementZone: "toolbarButton",+ entityTypes: ["project", "issue"],+ action: {+ type: "openModal",+ target: EXPORT_NAMES.launcherModal,+ },+ render: {+ environment: "hostOverlay",+ bounds: "wide",+ },+};diff --git a/packages/plugins/examples/plugin-kitchen-sink-example/src/index.ts b/packages/plugins/examples/plugin-kitchen-sink-example/src/index.tsnew file mode 100644index 0000000000..f301da5d92--- /dev/null+++ b/packages/plugins/examples/plugin-kitchen-sink-example/src/index.ts@@ -0,0 +1,2 @@+export { default as manifest } from "./manifest.js";+export { default as worker } from "./worker.js";diff --git a/packages/plugins/examples/plugin-kitchen-sink-example/src/manifest.ts b/packages/plugins/examples/plugin-kitchen-sink-example/src/manifest.tsnew file mode 100644index 0000000000..c7c761095f--- /dev/null+++ b/packages/plugins/examples/plugin-kitchen-sink-example/src/manifest.ts@@ -0,0 +1,290 @@+import type { PaperclipPluginManifestV1 } from "@paperclipai/plugin-sdk";+import {+ DEFAULT_CONFIG,+ EXPORT_NAMES,+ JOB_KEYS,+ PLUGIN_ID,+ PLUGIN_VERSION,+ SLOT_IDS,+ TOOL_NAMES,+ WEBHOOK_KEYS,+} from "./constants.js";++const manifest: PaperclipPluginManifestV1 = {+ id: PLUGIN_ID,+ apiVersion: 1,+ version: PLUGIN_VERSION,+ displayName: "Kitchen Sink (Example)",+ description: "Reference plugin that demonstrates the current Paperclip plugin API surface, UI surfaces, bridge actions, events, jobs, webhooks, tools, local workspace access, and runtime diagnostics in one place.",+ author: "Paperclip",+ categories: ["ui", "automation", "workspace", "connector"],+ capabilities: [+ "companies.read",+ "projects.read",+ "project.workspaces.read",+ "issues.read",+ "issues.create",+ "issues.update",+ "issue.comments.read",+ "issue.comments.create",+ "agents.read",+ "agents.pause",+ "agents.resume",+ "agents.invoke",+ "agent.sessions.create",+ "agent.sessions.list",+ "agent.sessions.send",+ "agent.sessions.close",+ "goals.read",+ "goals.create",+ "goals.update",+ "assets.write",+ "assets.read",+ "activity.log.write",+ "metrics.write",+ "plugin.state.read",+ "plugin.state.write",+ "events.subscribe",+ "events.emit",+ "jobs.schedule",+ "webhooks.receive",+ "http.outbound",+ "secrets.read-ref",+ "agent.tools.register",+ "instance.settings.register",+ "ui.sidebar.register",+ "ui.page.register",+ "ui.detailTab.register",+ "ui.dashboardWidget.register",+ "ui.commentAnnotation.register",+ "ui.action.register",+ ],+ entrypoints: {+ worker: "./dist/worker.js",+ ui: "./dist/ui",+ },+ instanceConfigSchema: {+ type: "object",+ properties: {+ showSidebarEntry: {+ type: "boolean",+ title: "Show Sidebar Entry",+ default: DEFAULT_CONFIG.showSidebarEntry,+ },+ showSidebarPanel: {+ type: "boolean",+ title: "Show Sidebar Panel",+ default: DEFAULT_CONFIG.showSidebarPanel,+ },+ showProjectSidebarItem: {+ type: "boolean",+ title: "Show Project Sidebar Item",+ default: DEFAULT_CONFIG.showProjectSidebarItem,+ },+ showCommentAnnotation: {+ type: "boolean",+ title: "Show Comment Annotation",+ default: DEFAULT_CONFIG.showCommentAnnotation,+ },+ showCommentContextMenuItem: {+ type: "boolean",+ title: "Show Comment Action",+ default: DEFAULT_CONFIG.showCommentContextMenuItem,+ },+ enableWorkspaceDemos: {+ type: "boolean",+ title: "Enable Workspace Demos",+ default: DEFAULT_CONFIG.enableWorkspaceDemos,+ },+ enableProcessDemos: {+ type: "boolean",+ title: "Enable Process Demos",+ default: DEFAULT_CONFIG.enableProcessDemos,+ description: "Allows curated local child-process demos in project workspaces.",+ },+ secretRefExample: {+ type: "string",+ title: "Secret Reference Example",+ default: DEFAULT_CONFIG.secretRefExample,+ },+ httpDemoUrl: {+ type: "string",+ title: "HTTP Demo URL",+ default: DEFAULT_CONFIG.httpDemoUrl,+ },+ allowedCommands: {+ type: "array",+ title: "Allowed Process Commands",+ items: {+ type: "string",+ enum: DEFAULT_CONFIG.allowedCommands,+ },+ default: DEFAULT_CONFIG.allowedCommands,+ },+ workspaceScratchFile: {+ type: "string",+ title: "Workspace Scratch File",+ default: DEFAULT_CONFIG.workspaceScratchFile,+ },+ },+ },+ jobs: [+ {+ jobKey: JOB_KEYS.heartbeat,+ displayName: "Demo Heartbeat",+ description: "Periodic demo job that records plugin runtime activity.",+ schedule: "*/15 * * * *",+ },+ ],+ webhooks: [+ {+ endpointKey: WEBHOOK_KEYS.demo,+ displayName: "Demo Ingest",+ description: "Accepts arbitrary webhook payloads and records the latest delivery in plugin state.",+ },+ ],+ tools: [+ {+ name: TOOL_NAMES.echo,+ displayName: "Kitchen Sink Echo",+ description: "Returns the provided message and the current run context.",+ parametersSchema: {+ type: "object",+ properties: {+ message: { type: "string" },+ },+ required: ["message"],+ },+ },+ {+ name: TOOL_NAMES.companySummary,+ displayName: "Kitchen Sink Company Summary",+ description: "Summarizes the current company using the Paperclip domain APIs.",+ parametersSchema: {+ type: "object",+ properties: {},+ },+ },+ {+ name: TOOL_NAMES.createIssue,+ displayName: "Kitchen Sink Create Issue",+ description: "Creates an issue in the current project from an agent tool call.",+ parametersSchema: {+ type: "object",+ properties: {+ title: { type: "string" },+ description: { type: "string" },+ },+ required: ["title"],+ },+ },+ ],+ ui: {+ slots: [+ {+ type: "page",+ id: SLOT_IDS.page,+ displayName: "Kitchen Sink",+ exportName: EXPORT_NAMES.page,+ },+ {+ type: "settingsPage",+ id: SLOT_IDS.settingsPage,+ displayName: "Kitchen Sink Settings",+ exportName: EXPORT_NAMES.settingsPage,+ },+ {+ type: "dashboardWidget",+ id: SLOT_IDS.dashboardWidget,+ displayName: "Kitchen Sink",+ exportName: EXPORT_NAMES.dashboardWidget,+ },+ {+ type: "sidebar",+ id: SLOT_IDS.sidebar,+ displayName: "Kitchen Sink",+ exportName: EXPORT_NAMES.sidebar,+ },+ {+ type: "sidebarPanel",+ id: SLOT_IDS.sidebarPanel,+ displayName: "Kitchen Sink Panel",+ exportName: EXPORT_NAMES.sidebarPanel,+ },+ {+ type: "projectSidebarItem",+ id: SLOT_IDS.projectSidebarItem,+ displayName: "Kitchen Sink",+ exportName: EXPORT_NAMES.projectSidebarItem,+ entityTypes: ["project"],+ },+ {+ type: "detailTab",+ id: SLOT_IDS.projectTab,+ displayName: "Kitchen Sink",+ exportName: EXPORT_NAMES.projectTab,+ entityTypes: ["project"],+ },+ {+ type: "detailTab",+ id: SLOT_IDS.issueTab,+ displayName: "Kitchen Sink",+ exportName: EXPORT_NAMES.issueTab,+ entityTypes: ["issue"],+ },+ {+ type: "taskDetailView",+ id: SLOT_IDS.taskDetailView,+ displayName: "Kitchen Sink Task View",+ exportName: EXPORT_NAMES.taskDetailView,+ entityTypes: ["issue"],+ },+ {+ type: "toolbarButton",+ id: SLOT_IDS.toolbarButton,+ displayName: "Kitchen Sink Action",+ exportName: EXPORT_NAMES.toolbarButton,+ entityTypes: ["project", "issue"],+ },+ {+ type: "contextMenuItem",+ id: SLOT_IDS.contextMenuItem,+ displayName: "Kitchen Sink Context",+ exportName: EXPORT_NAMES.contextMenuItem,+ entityTypes: ["project", "issue"],+ },+ {+ type: "commentAnnotation",+ id: SLOT_IDS.commentAnnotation,+ displayName: "Kitchen Sink Comment Annotation",+ exportName: EXPORT_NAMES.commentAnnotation,+ entityTypes: ["comment"],+ },+ {+ type: "commentContextMenuItem",+ id: SLOT_IDS.commentContextMenuItem,+ displayName: "Kitchen Sink Comment Action",+ exportName: EXPORT_NAMES.commentContextMenuItem,+ entityTypes: ["comment"],+ },+ ],+ launchers: [+ {+ id: "kitchen-sink-launcher",+ displayName: "Kitchen Sink Modal",+ placementZone: "toolbarButton",+ entityTypes: ["project", "issue"],+ action: {+ type: "openModal",+ target: EXPORT_NAMES.launcherModal,+ },+ render: {+ environment: "hostOverlay",+ bounds: "wide",+ },+ },+ ],+ },+};++export default manifest;diff --git a/packages/plugins/examples/plugin-kitchen-sink-example/src/ui/index.tsx b/packages/plugins/examples/plugin-kitchen-sink-example/src/ui/index.tsxnew file mode 100644index 0000000000..b8fc914ccf--- /dev/null+++ b/packages/plugins/examples/plugin-kitchen-sink-example/src/ui/index.tsx@@ -0,0 +1,1625 @@+import { useEffect, useMemo, useState, type CSSProperties, type FormEvent, type ReactNode } from "react";+import {+ useHostContext,+ usePluginAction,+ usePluginData,+ usePluginStream,+ type PluginCommentAnnotationProps,+ type PluginCommentContextMenuItemProps,+ type PluginDetailTabProps,+ type PluginPageProps,+ type PluginProjectSidebarItemProps,+ type PluginSettingsPageProps,+ type PluginSidebarProps,+ type PluginWidgetProps,+} from "@paperclipai/plugin-sdk/ui";+import {+ DEFAULT_CONFIG,+ JOB_KEYS,+ PLUGIN_ID,+ SAFE_COMMANDS,+ SLOT_IDS,+ STREAM_CHANNELS,+ TOOL_NAMES,+ WEBHOOK_KEYS,+} from "../constants.js";++type CompanyRecord = { id: string; name: string; issuePrefix?: string | null };+type ProjectRecord = { id: string; name: string; status?: string; path?: string | null };+type IssueRecord = { id: string; title: string; status: string; projectId?: string | null };+type GoalRecord = { id: string; title: string; status: string };+type AgentRecord = { id: string; name: string; status: string };++type OverviewData = {+ pluginId: string;+ version: string;+ capabilities: string[];+ config: Record<string, unknown>;+ runtimeLaunchers: Array<{ id: string; displayName: string; placementZone: string }>;+ recentRecords: Array<{ id: string; source: string; message: string; createdAt: string; level: string; data?: unknown }>;+ counts: {+ companies: number;+ projects: number;+ issues: number;+ goals: number;+ agents: number;+ entities: number;+ };+ lastJob: unknown;+ lastWebhook: unknown;+ lastAsset: unknown;+ lastProcessResult: unknown;+ streamChannels: Record<string, string>;+ safeCommands: Array<{ key: string; label: string; description: string }>;+ manifest: {+ jobs: Array<{ jobKey: string; displayName: string; schedule?: string }>;+ webhooks: Array<{ endpointKey: string; displayName: string }>;+ tools: Array<{ name: string; displayName: string; description: string }>;+ };+};++type EntityRecord = {+ id: string;+ entityType: string;+ title: string | null;+ status: string | null;+ scopeKind: string;+ scopeId: string | null;+ externalId: string | null;+ data: unknown;+};++type StateValueData = {+ scope: {+ scopeKind: string;+ scopeId?: string;+ namespace?: string;+ stateKey: string;+ };+ value: unknown;+};++type PluginConfigData = {+ showSidebarEntry?: boolean;+ showSidebarPanel?: boolean;+ showProjectSidebarItem?: boolean;+ showCommentAnnotation?: boolean;+ showCommentContextMenuItem?: boolean;+ enableWorkspaceDemos?: boolean;+ enableProcessDemos?: boolean;+};++type CommentContextData = {+ commentId: string;+ issueId: string;+ preview: string;+ length: number;+ copiedCount: number;+} | null;++type ProcessResult = {+ commandKey: string;+ cwd: string;+ code: number | null;+ stdout: string;+ stderr: string;+ startedAt: string;+ finishedAt: string;+};++const layoutStack: CSSProperties = {+ display: "grid",+ gap: "12px",+};++const cardStyle: CSSProperties = {+ border: "1px solid var(--border)",+ borderRadius: "12px",+ padding: "14px",+ background: "var(--card, transparent)",+};++const subtleCardStyle: CSSProperties = {+ border: "1px solid color-mix(in srgb, var(--border) 75%, transparent)",+ borderRadius: "10px",+ padding: "12px",+};++const rowStyle: CSSProperties = {+ display: "flex",+ flexWrap: "wrap",+ alignItems: "center",+ gap: "8px",+};++const sectionHeaderStyle: CSSProperties = {+ display: "flex",+ alignItems: "center",+ justifyContent: "space-between",+ gap: "8px",+ marginBottom: "10px",+};++const buttonStyle: CSSProperties = {+ appearance: "none",+ border: "1px solid var(--border)",+ borderRadius: "999px",+ background: "transparent",+ color: "inherit",+ padding: "6px 12px",+ fontSize: "12px",+ cursor: "pointer",+};++const primaryButtonStyle: CSSProperties = {+ ...buttonStyle,+ background: "var(--foreground)",+ color: "var(--background)",+ borderColor: "var(--foreground)",+};++const inputStyle: CSSProperties = {+ width: "100%",+ border: "1px solid var(--border)",+ borderRadius: "8px",+ padding: "8px 10px",+ background: "transparent",+ color: "inherit",+ fontSize: "12px",+};++const codeStyle: CSSProperties = {+ margin: 0,+ padding: "10px",+ borderRadius: "8px",+ border: "1px solid var(--border)",+ background: "color-mix(in srgb, var(--muted, #888) 16%, transparent)",+ overflowX: "auto",+ fontSize: "11px",+ lineHeight: 1.45,+};++const widgetGridStyle: CSSProperties = {+ display: "grid",+ gap: "12px",+ gridTemplateColumns: "repeat(auto-fit, minmax(220px, 1fr))",+};++const widgetStyle: CSSProperties = {+ border: "1px solid var(--border)",+ borderRadius: "14px",+ padding: "14px",+ display: "grid",+ gap: "8px",+ background: "color-mix(in srgb, var(--card, transparent) 72%, transparent)",+};++const mutedTextStyle: CSSProperties = {+ fontSize: "12px",+ opacity: 0.72,+ lineHeight: 1.45,+};++function hostPath(companyPrefix: string | null | undefined, suffix: string): string {+ return companyPrefix ? `/${companyPrefix}${suffix}` : suffix;+}++function JsonBlock({ value }: { value: unknown }) {+ return <pre style={codeStyle}>{JSON.stringify(value, null, 2)}</pre>;+}++function Section({+ title,+ action,+ children,+}: {+ title: string;+ action?: ReactNode;+ children: ReactNode;+}) {+ return (+ <section style={cardStyle}>+ <div style={sectionHeaderStyle}>+ <strong>{title}</strong>+ {action}+ </div>+ <div style={layoutStack}>{children}</div>+ </section>+ );+}++function Pill({ label }: { label: string }) {+ return (+ <span+ style={{+ display: "inline-flex",+ alignItems: "center",+ gap: "6px",+ borderRadius: "999px",+ border: "1px solid var(--border)",+ padding: "2px 8px",+ fontSize: "11px",+ }}+ >+ {label}+ </span>+ );+}++function MiniWidget({+ title,+ eyebrow,+ children,+}: {+ title: string;+ eyebrow?: string;+ children: ReactNode;+}) {+ return (+ <section style={widgetStyle}>+ {eyebrow ? <div style={{ fontSize: "11px", opacity: 0.65, textTransform: "uppercase", letterSpacing: "0.06em" }}>{eyebrow}</div> : null}+ <strong>{title}</strong>+ <div style={layoutStack}>{children}</div>+ </section>+ );+}++function MiniList({+ items,+ render,+ empty,+}: {+ items: unknown[];+ render: (item: unknown, index: number) => ReactNode;+ empty: string;+}) {+ if (items.length === 0) return <div style={{ fontSize: "12px", opacity: 0.7 }}>{empty}</div>;+ return (+ <div style={{ display: "grid", gap: "8px" }}>+ {items.map((item, index) => (+ <div key={index} style={subtleCardStyle}>+ {render(item, index)}+ </div>+ ))}+ </div>+ );+}++function StatusLine({ label, value }: { label: string; value: ReactNode }) {+ return (+ <div style={{ display: "grid", gap: "4px" }}>+ <span style={{ fontSize: "11px", opacity: 0.65, textTransform: "uppercase", letterSpacing: "0.06em" }}>{label}</span>+ <div style={{ fontSize: "12px" }}>{value}</div>+ </div>+ );+}++function usePluginOverview(companyId: string | null) {+ return usePluginData<OverviewData>("overview", companyId ? { companyId } : {});+}++function usePluginConfigData() {+ return usePluginData<PluginConfigData>("plugin-config");+}++function hostFetchJson<T>(path: string, init?: RequestInit): Promise<T> {+ return fetch(path, {+ credentials: "include",+ headers: {+ "content-type": "application/json",+ ...(init?.headers ?? {}),+ },+ ...init,+ }).then(async (response) => {+ if (!response.ok) {+ const text = await response.text();+ throw new Error(text || `Request failed: ${response.status}`);+ }+ return await response.json() as T;+ });+}++function useSettingsConfig() {+ const [configJson, setConfigJson] = useState<Record<string, unknown>>({ ...DEFAULT_CONFIG });+ const [loading, setLoading] = useState(true);+ const [saving, setSaving] = useState(false);+ const [error, setError] = useState<string | null>(null);++ useEffect(() => {+ let cancelled = false;+ setLoading(true);+ hostFetchJson<{ configJson?: Record<string, unknown> | null } | null>(`/api/plugins/${PLUGIN_ID}/config`)+ .then((result) => {+ if (cancelled) return;+ setConfigJson({ ...DEFAULT_CONFIG, ...(result?.configJson ?? {}) });+ setError(null);+ })+ .catch((nextError) => {+ if (cancelled) return;+ setError(nextError instanceof Error ? nextError.message : String(nextError));+ })+ .finally(() => {+ if (!cancelled) setLoading(false);+ });+ return () => {+ cancelled = true;+ };+ }, []);++ async function save(nextConfig: Record<string, unknown>) {+ setSaving(true);+ try {+ await hostFetchJson(`/api/plugins/${PLUGIN_ID}/config`, {+ method: "POST",+ body: JSON.stringify({ configJson: nextConfig }),+ });+ setConfigJson(nextConfig);+ setError(null);+ } catch (nextError) {+ setError(nextError instanceof Error ? nextError.message : String(nextError));+ throw nextError;+ } finally {+ setSaving(false);+ }+ }++ return {+ configJson,+ setConfigJson,+ loading,+ saving,+ error,+ save,+ };+}++function CompactSurfaceSummary({ label, entityType }: { label: string; entityType?: string | null }) {+ const context = useHostContext();+ const companyId = context.companyId;+ const entityId = context.entityId;+ const resolvedEntityType = entityType ?? context.entityType ?? null;+ const entityQuery = usePluginData(+ "entity-context",+ companyId && entityId && resolvedEntityType+ ? { companyId, entityId, entityType: resolvedEntityType }+ : {},+ );+ const writeMetric = usePluginAction("write-metric");++ return (+ <div style={layoutStack}>+ <div style={rowStyle}>+ <strong>{label}</strong>+ {resolvedEntityType ? <Pill label={resolvedEntityType} /> : null}+ </div>+ <JsonBlock value={context} />+ <button+ type="button"+ style={buttonStyle}+ onClick={() => {+ if (!companyId) return;+ void writeMetric({ name: "surface_click", value: 1, companyId }).catch(console.error);+ }}+ >+ Write surface metric+ </button>+ {entityQuery.data ? <JsonBlock value={entityQuery.data} /> : null}+ </div>+ );+}++function KitchenSinkPageWidgets({ context }: { context: PluginPageProps["context"] }) {+ const overview = usePluginOverview(context.companyId);+ const emitDemoEvent = usePluginAction("emit-demo-event");+ const startProgressStream = usePluginAction("start-progress-stream");+ const writeMetric = usePluginAction("write-metric");+ const progressStream = usePluginStream<{ step?: number; message?: string }>(+ STREAM_CHANNELS.progress,+ { companyId: context.companyId ?? undefined },+ );++ const companyPath = hostPath(context.companyPrefix, `/plugins/${PLUGIN_ID}`);++ return (+ <div style={widgetGridStyle}>+ <MiniWidget title="Runtime Summary" eyebrow="Overview">+ <div style={{ display: "grid", gap: "4px", fontSize: "12px" }}>+ <div>Companies: {overview.data?.counts.companies ?? 0}</div>+ <div>Projects: {overview.data?.counts.projects ?? 0}</div>+ <div>Issues: {overview.data?.counts.issues ?? 0}</div>+ <div>Agents: {overview.data?.counts.agents ?? 0}</div>+ </div>+ </MiniWidget>++ <MiniWidget title="Quick Actions" eyebrow="Try It">+ <div style={rowStyle}>+ <button+ type="button"+ style={buttonStyle}+ onClick={() => {+ if (!context.companyId) return;+ void emitDemoEvent({ companyId: context.companyId, message: "Triggered from Kitchen Sink page" }).catch(console.error);+ }}+ >+ Emit event+ </button>+ <button+ type="button"+ style={buttonStyle}+ onClick={() => {+ if (!context.companyId) return;+ void startProgressStream({ companyId: context.companyId, steps: 4 }).catch(console.error);+ }}+ >+ Start stream+ </button>+ <button+ type="button"+ style={buttonStyle}+ onClick={() => {+ if (!context.companyId) return;+ void writeMetric({ companyId: context.companyId, name: "page_quick_action", value: 1 }).catch(console.error);+ }}+ >+ Write metric+ </button>+ </div>+ <div style={mutedTextStyle}>+ Recent progress events: {progressStream.events.length}+ </div>+ </MiniWidget>++ <MiniWidget title="Surface Map" eyebrow="UI">+ <div style={{ display: "grid", gap: "4px", fontSize: "12px" }}>+ <div>Sidebar link and panel</div>+ <div>Dashboard widget</div>+ <div>Project link, tab, toolbar button, launcher</div>+ <div>Issue tab, task view, toolbar button, launcher</div>+ <div>Comment annotation and comment action</div>+ </div>+ </MiniWidget>++ <MiniWidget title="Manifest Coverage" eyebrow="Worker">+ <div style={{ display: "grid", gap: "4px", fontSize: "12px" }}>+ <div>Jobs: {overview.data?.manifest.jobs.length ?? 0}</div>+ <div>Webhooks: {overview.data?.manifest.webhooks.length ?? 0}</div>+ <div>Tools: {overview.data?.manifest.tools.length ?? 0}</div>+ <div>Launchers: {overview.data?.runtimeLaunchers.length ?? 0}</div>+ </div>+ </MiniWidget>++ <MiniWidget title="Latest Runtime State" eyebrow="Diagnostics">+ <div style={mutedTextStyle}>+ This updates as you use the worker demos below.+ </div>+ <JsonBlock+ value={{+ lastJob: overview.data?.lastJob ?? null,+ lastWebhook: overview.data?.lastWebhook ?? null,+ lastAsset: overview.data?.lastAsset ?? null,+ lastProcessResult: overview.data?.lastProcessResult ?? null,+ }}+ />+ </MiniWidget>++ <MiniWidget title="Plugin Page Route" eyebrow="Navigation">+ <div style={mutedTextStyle}>+ The sidebar entry opens this page directly. Use it as the main kitchen-sink control surface.+ </div>+ <a href={companyPath} style={{ fontSize: "12px" }}>+ {companyPath}+ </a>+ </MiniWidget>+ </div>+ );+}++function KitchenSinkConsole({ context }: { context: { companyId: string | null; companyPrefix?: string | null; projectId?: string | null; entityId?: string | null; entityType?: string | null } }) {+ const companyId = context.companyId;+ const overview = usePluginOverview(companyId);+ const companies = usePluginData<CompanyRecord[]>("companies");+ const projects = usePluginData<ProjectRecord[]>("projects", companyId ? { companyId } : {});+ const issues = usePluginData<IssueRecord[]>("issues", companyId ? { companyId } : {});+ const goals = usePluginData<GoalRecord[]>("goals", companyId ? { companyId } : {});+ const agents = usePluginData<AgentRecord[]>("agents", companyId ? { companyId } : {});++ const [issueTitle, setIssueTitle] = useState("Kitchen Sink demo issue");+ const [goalTitle, setGoalTitle] = useState("Kitchen Sink demo goal");+ const [stateScopeKind, setStateScopeKind] = useState("instance");+ const [stateScopeId, setStateScopeId] = useState("");+ const [stateNamespace, setStateNamespace] = useState("");+ const [stateKey, setStateKey] = useState("demo");+ const [stateValue, setStateValue] = useState("{\"hello\":\"world\"}");+ const [entityType, setEntityType] = useState("demo-record");+ const [entityTitle, setEntityTitle] = useState("Kitchen Sink Entity");+ const [entityScopeKind, setEntityScopeKind] = useState("instance");+ const [entityScopeId, setEntityScopeId] = useState("");+ const [selectedProjectId, setSelectedProjectId] = useState("");+ const [selectedIssueId, setSelectedIssueId] = useState("");+ const [selectedGoalId, setSelectedGoalId] = useState("");+ const [selectedAgentId, setSelectedAgentId] = useState("");+ const [httpUrl, setHttpUrl] = useState<string>(DEFAULT_CONFIG.httpDemoUrl);+ 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.");+ const [commandKey, setCommandKey] = useState<string>(SAFE_COMMANDS[0]?.key ?? "pwd");+ const [toolMessage, setToolMessage] = useState("Hello from the Kitchen Sink tool");+ const [toolOutput, setToolOutput] = useState<unknown>(null);+ const [jobOutput, setJobOutput] = useState<unknown>(null);+ const [webhookOutput, setWebhookOutput] = useState<unknown>(null);+ const [result, setResult] = useState<unknown>(null);++ const stateQuery = usePluginData<StateValueData>("state-value", {+ scopeKind: stateScopeKind,+ scopeId: stateScopeId || undefined,+ namespace: stateNamespace || undefined,+ stateKey,+ });+ const entityQuery = usePluginData<EntityRecord[]>("entities", {+ entityType,+ scopeKind: entityScopeKind,+ scopeId: entityScopeId || undefined,+ limit: 25,+ });+ const workspaceQuery = usePluginData<Array<{ id: string; name: string; path: string }>>(+ "workspaces",+ companyId && selectedProjectId ? { companyId, projectId: selectedProjectId } : {},+ );+ const progressStream = usePluginStream<{ step: number; total: number; message: string }>(+ STREAM_CHANNELS.progress,+ companyId ? { companyId } : undefined,+ );+ const agentStream = usePluginStream<{ eventType: string; message: string | null }>(+ STREAM_CHANNELS.agentChat,+ companyId ? { companyId } : undefined,+ );++ const emitDemoEvent = usePluginAction("emit-demo-event");+ const createIssue = usePluginAction("create-issue");+ const advanceIssueStatus = usePluginAction("advance-issue-status");+ const createGoal = usePluginAction("create-goal");+ const advanceGoalStatus = usePluginAction("advance-goal-status");+ const writeScopedState = usePluginAction("write-scoped-state");+ const deleteScopedState = usePluginAction("delete-scoped-state");+ const upsertEntity = usePluginAction("upsert-entity");+ const writeActivity = usePluginAction("write-activity");+ 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");+ const startProgressStream = usePluginAction("start-progress-stream");+ const invokeAgent = usePluginAction("invoke-agent");+ const pauseAgent = usePluginAction("pause-agent");+ const resumeAgent = usePluginAction("resume-agent");+ const askAgent = usePluginAction("ask-agent");++ useEffect(() => {+ if (!selectedProjectId && projects.data?.[0]?.id) setSelectedProjectId(projects.data[0].id);+ }, [projects.data, selectedProjectId]);++ useEffect(() => {+ if (!selectedIssueId && issues.data?.[0]?.id) setSelectedIssueId(issues.data[0].id);+ }, [issues.data, selectedIssueId]);++ useEffect(() => {+ if (!selectedGoalId && goals.data?.[0]?.id) setSelectedGoalId(goals.data[0].id);+ }, [goals.data, selectedGoalId]);++ useEffect(() => {+ if (!selectedAgentId && agents.data?.[0]?.id) setSelectedAgentId(agents.data[0].id);+ }, [agents.data, selectedAgentId]);++ useEffect(() => {+ if (!workspaceId && workspaceQuery.data?.[0]?.id) setWorkspaceId(workspaceQuery.data[0].id);+ }, [workspaceId, workspaceQuery.data]);++ const projectRef = selectedProjectId || context.projectId || "";++ async function refreshAll() {+ overview.refresh();+ projects.refresh();+ issues.refresh();+ goals.refresh();+ agents.refresh();+ stateQuery.refresh();+ entityQuery.refresh();+ workspaceQuery.refresh();+ }++ async function executeTool(name: string) {+ if (!companyId || !selectedAgentId || !projectRef) {+ setToolOutput({ error: "Select a company, project, and agent first." });+ return;+ }+ try {+ const toolName = `${PLUGIN_ID}:${name}`;+ const body =+ name === TOOL_NAMES.echo+ ? { message: toolMessage }+ : name === TOOL_NAMES.createIssue+ ? { title: issueTitle, description: "Created through the tool dispatcher demo." }+ : {};+ const response = await hostFetchJson(`/api/plugins/tools/execute`, {+ method: "POST",+ body: JSON.stringify({+ tool: toolName,+ parameters: body,+ runContext: {+ agentId: selectedAgentId,+ runId: `kitchen-sink-${Date.now()}`,+ companyId,+ projectId: projectRef,+ },+ }),+ });+ setToolOutput(response);+ await refreshAll();+ } catch (error) {+ setToolOutput({ error: error instanceof Error ? error.message : String(error) });+ }+ }++ async function fetchJobsAndTrigger() {+ try {+ const jobsResponse = await hostFetchJson<Array<{ id: string; jobKey: string }>>(`/api/plugins/${PLUGIN_ID}/jobs`);+ const job = jobsResponse.find((entry) => entry.jobKey === JOB_KEYS.heartbeat) ?? jobsResponse[0];+ if (!job) {+ setJobOutput({ error: "No plugin jobs returned by the host." });+ return;+ }+ const triggerResult = await hostFetchJson(`/api/plugins/${PLUGIN_ID}/jobs/${job.id}/trigger`, {+ method: "POST",+ });+ setJobOutput({ jobs: jobsResponse, triggerResult });+ overview.refresh();+ } catch (error) {+ setJobOutput({ error: error instanceof Error ? error.message : String(error) });+ }+ }++ async function sendWebhook() {+ try {+ const response = await hostFetchJson(`/api/plugins/${PLUGIN_ID}/webhooks/${WEBHOOK_KEYS.demo}`, {+ method: "POST",+ body: JSON.stringify({+ source: "kitchen-sink-ui",+ sentAt: new Date().toISOString(),+ }),+ });+ setWebhookOutput(response);+ overview.refresh();+ } catch (error) {+ setWebhookOutput({ error: error instanceof Error ? error.message : String(error) });+ }+ }++ return (+ <div style={{ display: "grid", gap: "14px" }}>+ <Section+ title="Overview"+ action={<button type="button" style={buttonStyle} onClick={() => refreshAll()}>Refresh</button>}+ >+ <div style={rowStyle}>+ <Pill label={`Plugin: ${overview.data?.pluginId ?? PLUGIN_ID}`} />+ <Pill label={`Version: ${overview.data?.version ?? "loading"}`} />+ <Pill label={`Company: ${companyId ?? "none"}`} />+ {context.entityType ? <Pill label={`Entity: ${context.entityType}`} /> : null}+ </div>+ {overview.data ? (+ <>+ <div style={{ display: "grid", gap: "8px", gridTemplateColumns: "repeat(auto-fit, minmax(160px, 1fr))" }}>+ <StatusLine label="Companies" value={overview.data.counts.companies} />+ <StatusLine label="Projects" value={overview.data.counts.projects} />+ <StatusLine label="Issues" value={overview.data.counts.issues} />+ <StatusLine label="Goals" value={overview.data.counts.goals} />+ <StatusLine label="Agents" value={overview.data.counts.agents} />+ <StatusLine label="Entities" value={overview.data.counts.entities} />+ </div>+ <JsonBlock value={overview.data.config} />+ </>+ ) : (+ <div style={{ fontSize: "12px", opacity: 0.7 }}>Loading overview…</div>+ )}+ </Section>++ <Section title="UI Surfaces">+ <div style={rowStyle}>+ <a href={hostPath(context.companyPrefix, `/plugins/${PLUGIN_ID}`)} style={{ fontSize: "12px" }}>Open plugin page</a>+ {projectRef ? (+ <a+ href={hostPath(context.companyPrefix, `/projects/${projectRef}?tab=plugin:${PLUGIN_ID}:${SLOT_IDS.projectTab}`)}+ style={{ fontSize: "12px" }}+ >+ Open project tab+ </a>+ ) : null}+ {selectedIssueId ? (+ <a+ href={hostPath(context.companyPrefix, `/issues/${selectedIssueId}`)}+ style={{ fontSize: "12px" }}+ >+ Open selected issue+ </a>+ ) : null}+ </div>+ <JsonBlock value={overview.data?.runtimeLaunchers ?? []} />+ </Section>++ <Section title="Paperclip Domain APIs">+ <div style={{ display: "grid", gap: "12px", gridTemplateColumns: "repeat(auto-fit, minmax(220px, 1fr))" }}>+ <div style={subtleCardStyle}>+ <strong>Companies</strong>+ <MiniList+ items={companies.data ?? []}+ empty="No companies."+ render={(item) => {+ const company = item as CompanyRecord;+ return <div>{company.name} <span style={{ opacity: 0.6 }}>({company.id.slice(0, 8)})</span></div>;+ }}+ />+ </div>+ <div style={subtleCardStyle}>+ <strong>Projects</strong>+ <MiniList+ items={projects.data ?? []}+ empty="No projects."+ render={(item) => {+ const project = item as ProjectRecord;+ return <div>{project.name} <span style={{ opacity: 0.6 }}>({project.status ?? "unknown"})</span></div>;+ }}+ />+ </div>+ <div style={subtleCardStyle}>+ <strong>Issues</strong>+ <MiniList+ items={issues.data ?? []}+ empty="No issues."+ render={(item) => {+ const issue = item as IssueRecord;+ return <div>{issue.title} <span style={{ opacity: 0.6 }}>({issue.status})</span></div>;+ }}+ />+ </div>+ <div style={subtleCardStyle}>+ <strong>Goals</strong>+ <MiniList+ items={goals.data ?? []}+ empty="No goals."+ render={(item) => {+ const goal = item as GoalRecord;+ return <div>{goal.title} <span style={{ opacity: 0.6 }}>({goal.status})</span></div>;+ }}+ />+ </div>+ </div>+ </Section>++ <Section title="Issue + Goal Actions">+ <div style={{ display: "grid", gap: "10px", gridTemplateColumns: "repeat(auto-fit, minmax(240px, 1fr))" }}>+ <form+ style={layoutStack}+ onSubmit={(event) => {+ event.preventDefault();+ if (!companyId) return;+ void createIssue({ companyId, projectId: selectedProjectId || undefined, title: issueTitle })+ .then((next) => {+ setResult(next);+ return refreshAll();+ })+ .catch((error) => setResult({ error: error instanceof Error ? error.message : String(error) }));+ }}+ >+ <strong>Create issue</strong>+ <input style={inputStyle} value={issueTitle} onChange={(event) => setIssueTitle(event.target.value)} />+ <button type="submit" style={primaryButtonStyle} disabled={!companyId}>Create issue</button>+ </form>+ <form+ style={layoutStack}+ onSubmit={(event) => {+ event.preventDefault();+ if (!companyId || !selectedIssueId) return;+ void advanceIssueStatus({ companyId, issueId: selectedIssueId, status: "in_review" })+ .then((next) => {+ setResult(next);+ return refreshAll();+ })+ .catch((error) => setResult({ error: error instanceof Error ? error.message : String(error) }));+ }}+ >+ <strong>Advance selected issue</strong>+ <select style={inputStyle} value={selectedIssueId} onChange={(event) => setSelectedIssueId(event.target.value)}>+ {(issues.data ?? []).map((issue) => (+ <option key={issue.id} value={issue.id}>{issue.title}</option>+ ))}+ </select>+ <button type="submit" style={buttonStyle} disabled={!companyId || !selectedIssueId}>Move to in_review</button>+ </form>+ <form+ style={layoutStack}+ onSubmit={(event) => {+ event.preventDefault();+ if (!companyId) return;+ void createGoal({ companyId, title: goalTitle })+ .then((next) => {+ setResult(next);+ return refreshAll();+ })+ .catch((error) => setResult({ error: error instanceof Error ? error.message : String(error) }));+ }}+ >+ <strong>Create goal</strong>+ <input style={inputStyle} value={goalTitle} onChange={(event) => setGoalTitle(event.target.value)} />+ <button type="submit" style={primaryButtonStyle} disabled={!companyId}>Create goal</button>+ </form>+ <form+ style={layoutStack}+ onSubmit={(event) => {+ event.preventDefault();+ if (!companyId || !selectedGoalId) return;+ void advanceGoalStatus({ companyId, goalId: selectedGoalId, status: "active" })+ .then((next) => {+ setResult(next);+ return refreshAll();+ })+ .catch((error) => setResult({ error: error instanceof Error ? error.message : String(error) }));+ }}+ >+ <strong>Advance selected goal</strong>+ <select style={inputStyle} value={selectedGoalId} onChange={(event) => setSelectedGoalId(event.target.value)}>+ {(goals.data ?? []).map((goal) => (+ <option key={goal.id} value={goal.id}>{goal.title}</option>+ ))}+ </select>+ <button type="submit" style={buttonStyle} disabled={!companyId || !selectedGoalId}>Move to active</button>+ </form>+ </div>+ </Section>++ <Section title="State + Entities">+ <div style={{ display: "grid", gap: "12px", gridTemplateColumns: "repeat(auto-fit, minmax(260px, 1fr))" }}>+ <form+ style={layoutStack}+ onSubmit={(event) => {+ event.preventDefault();+ void writeScopedState({+ scopeKind: stateScopeKind,+ scopeId: stateScopeId || undefined,+ namespace: stateNamespace || undefined,+ stateKey,+ value: stateValue,+ })+ .then((next) => {+ setResult(next);+ stateQuery.refresh();+ })+ .catch((error) => setResult({ error: error instanceof Error ? error.message : String(error) }));+ }}+ >+ <strong>State</strong>+ <input style={inputStyle} value={stateScopeKind} onChange={(event) => setStateScopeKind(event.target.value)} placeholder="scopeKind" />+ <input style={inputStyle} value={stateScopeId} onChange={(event) => setStateScopeId(event.target.value)} placeholder="scopeId (optional)" />+ <input style={inputStyle} value={stateNamespace} onChange={(event) => setStateNamespace(event.target.value)} placeholder="namespace (optional)" />+ <input style={inputStyle} value={stateKey} onChange={(event) => setStateKey(event.target.value)} placeholder="stateKey" />+ <textarea style={{ ...inputStyle, minHeight: "88px" }} value={stateValue} onChange={(event) => setStateValue(event.target.value)} />+ <div style={rowStyle}>+ <button type="submit" style={primaryButtonStyle}>Write state</button>+ <button+ type="button"+ style={buttonStyle}+ onClick={() => {+ void deleteScopedState({+ scopeKind: stateScopeKind,+ scopeId: stateScopeId || undefined,+ namespace: stateNamespace || undefined,+ stateKey,+ })+ .then((next) => {+ setResult(next);+ stateQuery.refresh();+ })+ .catch((error) => setResult({ error: error instanceof Error ? error.message : String(error) }));+ }}+ >+ Delete state+ </button>+ </div>+ <JsonBlock value={stateQuery.data ?? { loading: true }} />+ </form>+ <form+ style={layoutStack}+ onSubmit={(event) => {+ event.preventDefault();+ void upsertEntity({+ entityType,+ title: entityTitle,+ scopeKind: entityScopeKind,+ scopeId: entityScopeId || undefined,+ data: JSON.stringify({ createdAt: new Date().toISOString() }),+ })+ .then((next) => {+ setResult(next);+ entityQuery.refresh();+ overview.refresh();+ })+ .catch((error) => setResult({ error: error instanceof Error ? error.message : String(error) }));+ }}+ >+ <strong>Entities</strong>+ <input style={inputStyle} value={entityType} onChange={(event) => setEntityType(event.target.value)} placeholder="entityType" />+ <input style={inputStyle} value={entityTitle} onChange={(event) => setEntityTitle(event.target.value)} placeholder="title" />+ <input style={inputStyle} value={entityScopeKind} onChange={(event) => setEntityScopeKind(event.target.value)} placeholder="scopeKind" />+ <input style={inputStyle} value={entityScopeId} onChange={(event) => setEntityScopeId(event.target.value)} placeholder="scopeId (optional)" />+ <button type="submit" style={primaryButtonStyle}>Upsert entity</button>+ <JsonBlock value={entityQuery.data ?? []} />+ </form>+ </div>+ </Section>++ <Section title="Events + Streams">+ <div style={rowStyle}>+ <button+ type="button"+ style={primaryButtonStyle}+ onClick={() => {+ if (!companyId) return;+ void emitDemoEvent({ companyId, message: "Kitchen Sink manual event" })+ .then((next) => {+ setResult(next);+ overview.refresh();+ })+ .catch((error) => setResult({ error: error instanceof Error ? error.message : String(error) }));+ }}+ >+ Emit demo event+ </button>+ <button+ type="button"+ style={buttonStyle}+ onClick={() => {+ if (!companyId) return;+ void startProgressStream({ companyId, steps: 5 })+ .then((next) => setResult(next))+ .catch((error) => setResult({ error: error instanceof Error ? error.message : String(error) }));+ }}+ >+ Start progress stream+ </button>+ </div>+ <div style={{ display: "grid", gap: "12px", gridTemplateColumns: "repeat(auto-fit, minmax(240px, 1fr))" }}>+ <div style={subtleCardStyle}>+ <strong>Progress stream</strong>+ <JsonBlock value={progressStream.events.slice(-8)} />+ </div>+ <div style={subtleCardStyle}>+ <strong>Recent records</strong>+ <JsonBlock value={overview.data?.recentRecords ?? []} />+ </div>+ </div>+ </Section>++ <Section title="HTTP + Secrets + Assets + Activity + Metrics">+ <div style={{ display: "grid", gap: "12px", gridTemplateColumns: "repeat(auto-fit, minmax(240px, 1fr))" }}>+ <form+ style={layoutStack}+ onSubmit={(event) => {+ event.preventDefault();+ void httpFetch({ url: httpUrl })+ .then((next) => setResult(next))+ .catch((error) => setResult({ error: error instanceof Error ? error.message : String(error) }));+ }}+ >+ <strong>HTTP</strong>+ <input style={inputStyle} value={httpUrl} onChange={(event) => setHttpUrl(event.target.value)} />+ <button type="submit" style={buttonStyle}>Fetch URL</button>+ </form>+ <form+ style={layoutStack}+ onSubmit={(event) => {+ event.preventDefault();+ void resolveSecret({ secretRef })+ .then((next) => setResult(next))+ .catch((error) => setResult({ error: error instanceof Error ? error.message : String(error) }));+ }}+ >+ <strong>Secrets</strong>+ <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) => {+ event.preventDefault();+ if (!companyId) return;+ void writeActivity({ companyId, entityType: context.entityType ?? undefined, entityId: context.entityId ?? undefined })+ .then((next) => setResult(next))+ .catch((error) => setResult({ error: error instanceof Error ? error.message : String(error) }));+ }}+ >+ <strong>Activity + Metrics</strong>+ <input style={inputStyle} value={metricName} onChange={(event) => setMetricName(event.target.value)} placeholder="metric name" />+ <input style={inputStyle} value={metricValue} onChange={(event) => setMetricValue(event.target.value)} placeholder="metric value" />+ <div style={rowStyle}>+ <button+ type="button"+ style={buttonStyle}+ onClick={() => {+ if (!companyId) return;+ void writeMetric({ companyId, name: metricName, value: Number(metricValue || "1") })+ .then((next) => setResult(next))+ .catch((error) => setResult({ error: error instanceof Error ? error.message : String(error) }));+ }}+ >+ Write metric+ </button>+ <button type="submit" style={buttonStyle} disabled={!companyId}>Write activity</button>+ </div>+ </form>+ </div>+ </Section>++ <Section title="Workspace + Process">+ <div style={{ display: "grid", gap: "10px", gridTemplateColumns: "repeat(auto-fit, minmax(240px, 1fr))" }}>+ <div style={layoutStack}>+ <strong>Select project/workspace</strong>+ <select style={inputStyle} value={selectedProjectId} onChange={(event) => setSelectedProjectId(event.target.value)}>+ <option value="">Select project</option>+ {(projects.data ?? []).map((project) => (+ <option key={project.id} value={project.id}>{project.name}</option>+ ))}+ </select>+ <select style={inputStyle} value={workspaceId} onChange={(event) => setWorkspaceId(event.target.value)}>+ <option value="">Select workspace</option>+ {(workspaceQuery.data ?? []).map((workspace) => (+ <option key={workspace.id} value={workspace.id}>{workspace.name}</option>+ ))}+ </select>+ <JsonBlock value={workspaceQuery.data ?? []} />+ </div>+ <form+ style={layoutStack}+ onSubmit={(event) => {+ event.preventDefault();+ if (!companyId || !selectedProjectId) return;+ void writeWorkspaceScratch({+ companyId,+ projectId: selectedProjectId,+ workspaceId: workspaceId || undefined,+ relativePath: workspacePath,+ content: workspaceContent,+ })+ .then((next) => setResult(next))+ .catch((error) => setResult({ error: error instanceof Error ? error.message : String(error) }));+ }}+ >+ <strong>Workspace file</strong>+ <input style={inputStyle} value={workspacePath} onChange={(event) => setWorkspacePath(event.target.value)} />+ <textarea style={{ ...inputStyle, minHeight: "88px" }} value={workspaceContent} onChange={(event) => setWorkspaceContent(event.target.value)} />+ <div style={rowStyle}>+ <button type="submit" style={buttonStyle} disabled={!companyId || !selectedProjectId}>Write scratch file</button>+ <button+ type="button"+ style={buttonStyle}+ onClick={() => {+ if (!companyId || !selectedProjectId) return;+ void readWorkspaceFile({+ companyId,+ projectId: selectedProjectId,+ workspaceId: workspaceId || undefined,+ relativePath: workspacePath,+ })+ .then((next) => setResult(next))+ .catch((error) => setResult({ error: error instanceof Error ? error.message : String(error) }));+ }}+ >+ Read file+ </button>+ </div>+ </form>+ <form+ style={layoutStack}+ onSubmit={(event) => {+ event.preventDefault();+ if (!companyId || !selectedProjectId) return;+ void runProcess({+ companyId,+ projectId: selectedProjectId,+ workspaceId: workspaceId || undefined,+ commandKey,+ })+ .then((next) => {+ setResult(next);+ overview.refresh();+ })+ .catch((error) => setResult({ error: error instanceof Error ? error.message : String(error) }));+ }}+ >+ <strong>Curated process demo</strong>+ <select style={inputStyle} value={commandKey} onChange={(event) => setCommandKey(event.target.value)}>+ {SAFE_COMMANDS.map((command) => (+ <option key={command.key} value={command.key}>{command.label}</option>+ ))}+ </select>+ <button type="submit" style={buttonStyle} disabled={!companyId || !selectedProjectId}>Run command</button>+ <JsonBlock value={overview.data?.lastProcessResult ?? { note: "No process run yet." }} />+ </form>+ </div>+ </Section>++ <Section title="Agents + Sessions">+ <div style={{ display: "grid", gap: "12px", gridTemplateColumns: "repeat(auto-fit, minmax(240px, 1fr))" }}>+ <form+ style={layoutStack}+ onSubmit={(event) => {+ event.preventDefault();+ if (!companyId || !selectedAgentId) return;+ void invokeAgent({ companyId, agentId: selectedAgentId, prompt: "Kitchen Sink invoke demo" })+ .then((next) => setResult(next))+ .catch((error) => setResult({ error: error instanceof Error ? error.message : String(error) }));+ }}+ >+ <strong>Agent controls</strong>+ <select style={inputStyle} value={selectedAgentId} onChange={(event) => setSelectedAgentId(event.target.value)}>+ {(agents.data ?? []).map((agent) => (+ <option key={agent.id} value={agent.id}>{agent.name}</option>+ ))}+ </select>+ <div style={rowStyle}>+ <button type="submit" style={primaryButtonStyle} disabled={!companyId || !selectedAgentId}>Invoke</button>+ <button+ type="button"+ style={buttonStyle}+ onClick={() => {+ if (!companyId || !selectedAgentId) return;+ void pauseAgent({ companyId, agentId: selectedAgentId })+ .then((next) => {+ setResult(next);+ agents.refresh();+ })+ .catch((error) => setResult({ error: error instanceof Error ? error.message : String(error) }));+ }}+ >+ Pause+ </button>+ <button+ type="button"+ style={buttonStyle}+ onClick={() => {+ if (!companyId || !selectedAgentId) return;+ void resumeAgent({ companyId, agentId: selectedAgentId })+ .then((next) => {+ setResult(next);+ agents.refresh();+ })+ .catch((error) => setResult({ error: error instanceof Error ? error.message : String(error) }));+ }}+ >+ Resume+ </button>+ </div>+ </form>+ <form+ style={layoutStack}+ onSubmit={(event) => {+ event.preventDefault();+ if (!companyId || !selectedAgentId) return;+ void askAgent({ companyId, agentId: selectedAgentId, prompt: "Give a short greeting from the Kitchen Sink plugin." })+ .then((next) => setResult(next))+ .catch((error) => setResult({ error: error instanceof Error ? error.message : String(error) }));+ }}+ >+ <strong>Agent chat stream</strong>+ <button type="submit" style={buttonStyle} disabled={!companyId || !selectedAgentId}>Start chat demo</button>+ <JsonBlock value={agentStream.events.slice(-12)} />+ </form>+ </div>+ </Section>++ <Section title="Jobs + Webhooks + Tools">+ <div style={{ display: "grid", gap: "12px", gridTemplateColumns: "repeat(auto-fit, minmax(240px, 1fr))" }}>+ <div style={layoutStack}>+ <strong>Job demo</strong>+ <button type="button" style={buttonStyle} onClick={() => void fetchJobsAndTrigger()}>Trigger demo job</button>+ <JsonBlock value={jobOutput ?? overview.data?.lastJob ?? { note: "No job output yet." }} />+ </div>+ <div style={layoutStack}>+ <strong>Webhook demo</strong>+ <button type="button" style={buttonStyle} onClick={() => void sendWebhook()}>Send demo webhook</button>+ <JsonBlock value={webhookOutput ?? overview.data?.lastWebhook ?? { note: "No webhook yet." }} />+ </div>+ <div style={layoutStack}>+ <strong>Tool dispatcher demo</strong>+ <input style={inputStyle} value={toolMessage} onChange={(event) => setToolMessage(event.target.value)} />+ <div style={rowStyle}>+ <button type="button" style={buttonStyle} onClick={() => void executeTool(TOOL_NAMES.echo)}>Run echo tool</button>+ <button type="button" style={buttonStyle} onClick={() => void executeTool(TOOL_NAMES.companySummary)}>Run summary tool</button>+ <button type="button" style={buttonStyle} onClick={() => void executeTool(TOOL_NAMES.createIssue)}>Run create-issue tool</button>+ </div>+ <JsonBlock value={toolOutput ?? { note: "No tool output yet." }} />+ </div>+ </div>+ </Section>++ <Section title="Latest Result">+ <JsonBlock value={result ?? { note: "Run an action to see results here." }} />+ </Section>+ </div>+ );+}++export function KitchenSinkPage({ context }: PluginPageProps) {+ return (+ <div style={layoutStack}>+ <Section title="Kitchen Sink Plugin Page">+ <div style={{ fontSize: "13px", lineHeight: 1.5 }}>+ This page is the primary demo console for the Kitchen Sink example plugin. It is intentionally broad and exposes the current Paperclip plugin surface area in one place.+ </div>+ </Section>+ <KitchenSinkPageWidgets context={context} />+ <KitchenSinkConsole context={context} />+ </div>+ );+}++export function KitchenSinkSettingsPage({ context }: PluginSettingsPageProps) {+ const { configJson, setConfigJson, loading, saving, error, save } = useSettingsConfig();+ const [savedMessage, setSavedMessage] = useState<string | null>(null);++ function setField(key: string, value: unknown) {+ setConfigJson((current) => ({ ...current, [key]: value }));+ }++ async function onSubmit(event: FormEvent) {+ event.preventDefault();+ await save(configJson);+ setSavedMessage("Saved");+ window.setTimeout(() => setSavedMessage(null), 1500);+ }++ if (loading) {+ return <div style={{ fontSize: "12px", opacity: 0.7 }}>Loading plugin config…</div>;+ }++ return (+ <form onSubmit={onSubmit} style={{ display: "grid", gap: "18px" }}>+ <div style={{ display: "grid", gap: "12px", gridTemplateColumns: "minmax(0, 1.8fr) minmax(220px, 1fr)" }}>+ <div style={{ display: "grid", gap: "8px" }}>+ <strong>About</strong>+ <div style={{ fontSize: "13px", lineHeight: 1.5 }}>+ Kitchen Sink demonstrates the current Paperclip plugin API surface in one local, trusted example. It intentionally includes domain mutations, event handling, streams, tools, jobs, webhooks, and local workspace/process demos.+ </div>+ <div style={{ fontSize: "12px", opacity: 0.7 }}>+ Current company context: {context.companyId ?? "none"}+ </div>+ </div>+ <div style={{ display: "grid", gap: "8px" }}>+ <strong>Danger / Trust Model</strong>+ <div style={{ fontSize: "12px", lineHeight: 1.5 }}>+ Workspace and process demos run as trusted local code. Keep process demos off unless you explicitly want to exercise local child process behavior.+ </div>+ </div>+ </div>++ <div style={{ display: "grid", gap: "12px" }}>+ <strong>Settings</strong>+ <label style={rowStyle}>+ <input+ type="checkbox"+ checked={configJson.showSidebarEntry !== false}+ onChange={(event) => setField("showSidebarEntry", event.target.checked)}+ />+ <span>Show sidebar entry</span>+ </label>+ <label style={rowStyle}>+ <input+ type="checkbox"+ checked={configJson.showSidebarPanel !== false}+ onChange={(event) => setField("showSidebarPanel", event.target.checked)}+ />+ <span>Show sidebar panel</span>+ </label>+ <label style={rowStyle}>+ <input+ type="checkbox"+ checked={configJson.showProjectSidebarItem !== false}+ onChange={(event) => setField("showProjectSidebarItem", event.target.checked)}+ />+ <span>Show project sidebar item</span>+ </label>+ <label style={rowStyle}>+ <input+ type="checkbox"+ checked={configJson.showCommentAnnotation !== false}+ onChange={(event) => setField("showCommentAnnotation", event.target.checked)}+ />+ <span>Show comment annotation</span>+ </label>+ <label style={rowStyle}>+ <input+ type="checkbox"+ checked={configJson.showCommentContextMenuItem !== false}+ onChange={(event) => setField("showCommentContextMenuItem", event.target.checked)}+ />+ <span>Show comment context action</span>+ </label>+ <label style={rowStyle}>+ <input+ type="checkbox"+ checked={configJson.enableWorkspaceDemos !== false}+ onChange={(event) => setField("enableWorkspaceDemos", event.target.checked)}+ />+ <span>Enable workspace demos</span>+ </label>+ <label style={rowStyle}>+ <input+ type="checkbox"+ checked={configJson.enableProcessDemos === true}+ onChange={(event) => setField("enableProcessDemos", event.target.checked)}+ />+ <span>Enable curated process demos</span>+ </label>+ <label style={{ display: "grid", gap: "6px" }}>+ <span style={{ fontSize: "12px" }}>HTTP demo URL</span>+ <input+ style={inputStyle}+ value={String(configJson.httpDemoUrl ?? DEFAULT_CONFIG.httpDemoUrl)}+ onChange={(event) => setField("httpDemoUrl", event.target.value)}+ />+ </label>+ <label style={{ display: "grid", gap: "6px" }}>+ <span style={{ fontSize: "12px" }}>Secret reference example</span>+ <input+ style={inputStyle}+ value={String(configJson.secretRefExample ?? "")}+ onChange={(event) => setField("secretRefExample", event.target.value)}+ />+ </label>+ <label style={{ display: "grid", gap: "6px" }}>+ <span style={{ fontSize: "12px" }}>Workspace scratch file</span>+ <input+ style={inputStyle}+ value={String(configJson.workspaceScratchFile ?? DEFAULT_CONFIG.workspaceScratchFile)}+ onChange={(event) => setField("workspaceScratchFile", event.target.value)}+ />+ </label>+ </div>++ {error ? <div style={{ color: "var(--destructive, #c00)", fontSize: "12px" }}>{error}</div> : null}++ <div style={rowStyle}>+ <button type="submit" style={primaryButtonStyle} disabled={saving}>+ {saving ? "Saving…" : "Save settings"}+ </button>+ {savedMessage ? <span style={{ fontSize: "12px", opacity: 0.7 }}>{savedMessage}</span> : null}+ </div>+ </form>+ );+}++export function KitchenSinkDashboardWidget({ context }: PluginWidgetProps) {+ const overview = usePluginOverview(context.companyId);+ const writeMetric = usePluginAction("write-metric");++ return (+ <div style={layoutStack}>+ <div style={rowStyle}>+ <strong>Kitchen Sink</strong>+ <Pill label="dashboardWidget" />+ </div>+ <div style={{ fontSize: "12px", opacity: 0.7 }}>+ Plugin runtime surface demo for the current company.+ </div>+ <div style={{ display: "grid", gap: "4px", fontSize: "12px" }}>+ <div>Recent records: {overview.data?.recentRecords.length ?? 0}</div>+ <div>Projects: {overview.data?.counts.projects ?? 0}</div>+ <div>Issues: {overview.data?.counts.issues ?? 0}</div>+ </div>+ <div style={rowStyle}>+ <a href={hostPath(context.companyPrefix, `/plugins/${PLUGIN_ID}`)} style={{ fontSize: "12px" }}>Open page</a>+ <button+ type="button"+ style={buttonStyle}+ onClick={() => {+ if (!context.companyId) return;+ void writeMetric({ companyId: context.companyId, name: "dashboard_click", value: 1 }).catch(console.error);+ }}+ >+ Write metric+ </button>+ </div>+ </div>+ );+}++export function KitchenSinkSidebarLink({ context }: PluginSidebarProps) {+ const config = usePluginConfigData();+ if (config.data && config.data.showSidebarEntry === false) return null;+ const href = hostPath(context.companyPrefix, `/plugins/${PLUGIN_ID}`);+ const isActive = typeof window !== "undefined" && window.location.pathname === href;+ return (+ <a+ href={href}+ aria-current={isActive ? "page" : undefined}+ className={[+ "flex items-center gap-2.5 px-3 py-2 text-[13px] font-medium transition-colors",+ isActive+ ? "bg-accent text-foreground"+ : "text-foreground/80 hover:bg-accent/50 hover:text-foreground",+ ].join(" ")}+ >+ <span className="relative shrink-0">+ <svg viewBox="0 0 24 24" className="h-4 w-4" fill="none" stroke="currentColor" strokeWidth="1.9" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">+ <rect x="4" y="4" width="7" height="7" rx="1.5" />+ <rect x="13" y="4" width="7" height="7" rx="1.5" />+ <rect x="4" y="13" width="7" height="7" rx="1.5" />+ <path d="M13 16.5h7" />+ <path d="M16.5 13v7" />+ </svg>+ </span>+ <span className="flex-1 truncate">+ Kitchen Sink+ </span>+ </a>+ );+}++export function KitchenSinkSidebarPanel() {+ const context = useHostContext();+ const config = usePluginConfigData();+ const overview = usePluginOverview(context.companyId);+ if (config.data && config.data.showSidebarPanel === false) return null;+ return (+ <div style={{ ...layoutStack, ...subtleCardStyle, fontSize: "12px" }}>+ <strong>Kitchen Sink Panel</strong>+ <div>Recent plugin records: {overview.data?.recentRecords.length ?? 0}</div>+ <a href={hostPath(context.companyPrefix, `/plugins/${PLUGIN_ID}`)}>Open plugin page</a>+ </div>+ );+}++export function KitchenSinkProjectSidebarItem({ context }: PluginProjectSidebarItemProps) {+ const config = usePluginConfigData();+ if (config.data && config.data.showProjectSidebarItem === false) return null;+ return (+ <a+ href={hostPath(context.companyPrefix, `/projects/${context.entityId}?tab=plugin:${PLUGIN_ID}:${SLOT_IDS.projectTab}`)}+ style={{ fontSize: "12px", textDecoration: "none" }}+ >+ Kitchen Sink+ </a>+ );+}++export function KitchenSinkProjectTab({ context }: PluginDetailTabProps) {+ return <CompactSurfaceSummary label="Project Detail Tab" entityType="project" />;+}++export function KitchenSinkIssueTab({ context }: PluginDetailTabProps) {+ return <CompactSurfaceSummary label="Issue Detail Tab" entityType="issue" />;+}++export function KitchenSinkTaskDetailView() {+ return <CompactSurfaceSummary label="Task Detail View" entityType="issue" />;+}++export function KitchenSinkToolbarButton() {+ const context = useHostContext();+ const startProgress = usePluginAction("start-progress-stream");+ return (+ <button+ type="button"+ style={buttonStyle}+ onClick={() => {+ if (!context.companyId) return;+ void startProgress({ companyId: context.companyId, steps: 3 }).catch(console.error);+ }}+ >+ Kitchen Sink Action+ </button>+ );+}++export function KitchenSinkContextMenuItem() {+ const context = useHostContext();+ const writeActivity = usePluginAction("write-activity");+ return (+ <button+ type="button"+ style={buttonStyle}+ onClick={() => {+ if (!context.companyId) return;+ void writeActivity({+ companyId: context.companyId,+ entityType: context.entityType ?? undefined,+ entityId: context.entityId ?? undefined,+ message: "Kitchen Sink context action clicked",+ }).catch(console.error);+ }}+ >+ Kitchen Sink Context+ </button>+ );+}++export function KitchenSinkCommentAnnotation({ context }: PluginCommentAnnotationProps) {+ const config = usePluginConfigData();+ const data = usePluginData<CommentContextData>(+ "comment-context",+ context.companyId+ ? { companyId: context.companyId, issueId: context.parentEntityId, commentId: context.entityId }+ : {},+ );+ if (config.data && config.data.showCommentAnnotation === false) return null;+ if (!data.data) return null;+ return (+ <div style={{ ...subtleCardStyle, fontSize: "11px" }}>+ <strong>Kitchen Sink</strong>+ <div>Comment length: {data.data.length}</div>+ <div>Copied count: {data.data.copiedCount}</div>+ <div style={{ opacity: 0.75 }}>{data.data.preview}</div>+ </div>+ );+}++export function KitchenSinkCommentContextMenuItem({ context }: PluginCommentContextMenuItemProps) {+ const config = usePluginConfigData();+ const copyCommentContext = usePluginAction("copy-comment-context");+ const [status, setStatus] = useState<string | null>(null);+ if (config.data && config.data.showCommentContextMenuItem === false) return null;+ return (+ <div style={rowStyle}>+ <button+ type="button"+ style={buttonStyle}+ onClick={() => {+ if (!context.companyId) return;+ void copyCommentContext({+ companyId: context.companyId,+ issueId: context.parentEntityId,+ commentId: context.entityId,+ })+ .then(() => setStatus("Copied"))+ .catch((error) => setStatus(error instanceof Error ? error.message : String(error)));+ }}+ >+ Copy To Kitchen Sink+ </button>+ {status ? <span style={{ fontSize: "11px", opacity: 0.7 }}>{status}</span> : null}+ </div>+ );+}++export function KitchenSinkLauncherModal() {+ const context = useHostContext();+ return (+ <div style={{ display: "grid", gap: "10px" }}>+ <strong>Kitchen Sink Launcher Modal</strong>+ <div style={{ fontSize: "12px", opacity: 0.7 }}>+ This export exists so launcher infrastructure has a concrete modal target.+ </div>+ <JsonBlock value={context.renderEnvironment ?? { note: "No render environment metadata." }} />+ </div>+ );+}diff --git a/packages/plugins/examples/plugin-kitchen-sink-example/src/worker.ts b/packages/plugins/examples/plugin-kitchen-sink-example/src/worker.tsnew file mode 100644index 0000000000..fd0e9eff9d--- /dev/null+++ b/packages/plugins/examples/plugin-kitchen-sink-example/src/worker.ts@@ -0,0 +1,1055 @@+import { Buffer } from "node:buffer";+import { spawn } from "node:child_process";+import { randomUUID } from "node:crypto";+import { promises as fs } from "node:fs";+import path from "node:path";+import {+ PLUGIN_STATE_SCOPE_KINDS,+ definePlugin,+ runWorker,+ type PaperclipPlugin,+ type PluginContext,+ type PluginEntityQuery,+ type PluginEvent,+ type PluginHealthDiagnostics,+ type PluginJobContext,+ type PluginLauncherRegistration,+ type PluginWebhookInput,+ type PluginWorkspace,+ type PluginStateScopeKind,+ type ScopeKey,+ type ToolResult,+ type ToolRunContext,+} from "@paperclipai/plugin-sdk";+import type { Goal, Issue } from "@paperclipai/shared";+import {+ DEFAULT_CONFIG,+ JOB_KEYS,+ PLUGIN_ID,+ RUNTIME_LAUNCHER,+ SAFE_COMMANDS,+ STREAM_CHANNELS,+ TOOL_NAMES,+ WEBHOOK_KEYS,+} from "./constants.js";++type KitchenSinkConfig = {+ showSidebarEntry?: boolean;+ showSidebarPanel?: boolean;+ showProjectSidebarItem?: boolean;+ showCommentAnnotation?: boolean;+ showCommentContextMenuItem?: boolean;+ enableWorkspaceDemos?: boolean;+ enableProcessDemos?: boolean;+ secretRefExample?: string;+ httpDemoUrl?: string;+ allowedCommands?: string[];+ workspaceScratchFile?: string;+};++type DemoRecord = {+ id: string;+ level: "info" | "warning" | "error";+ source: string;+ message: string;+ createdAt: string;+ data?: unknown;+};++type ProcessResult = {+ commandKey: string;+ cwd: string;+ code: number | null;+ stdout: string;+ stderr: string;+ startedAt: string;+ finishedAt: string;+};++const recentRecords: DemoRecord[] = [];+const runtimeLaunchers = new Map<string, PluginLauncherRegistration>();+let currentContext: PluginContext | null = null;+let lastProcessResult: ProcessResult | null = null;++function isScopeKind(value: unknown): value is PluginStateScopeKind {+ return typeof value === "string" && PLUGIN_STATE_SCOPE_KINDS.includes(value as PluginStateScopeKind);+}++function summarizeError(error: unknown): string {+ if (error instanceof Error) return error.message;+ return String(error);+}++function pushRecord(record: Omit<DemoRecord, "id" | "createdAt">): DemoRecord {+ const next: DemoRecord = {+ id: randomUUID(),+ createdAt: new Date().toISOString(),+ ...record,+ };+ recentRecords.unshift(next);+ if (recentRecords.length > 50) recentRecords.length = 50;+ return next;+}++async function getConfig(ctx: PluginContext): Promise<KitchenSinkConfig> {+ const config = await ctx.config.get();+ return {+ ...DEFAULT_CONFIG,+ ...(config as KitchenSinkConfig),+ };+}++async function writeInstanceState(ctx: PluginContext, stateKey: string, value: unknown): Promise<void> {+ await ctx.state.set({ scopeKind: "instance", stateKey }, value);+}++async function readInstanceState<T = unknown>(ctx: PluginContext, stateKey: string): Promise<T | null> {+ return await ctx.state.get({ scopeKind: "instance", stateKey }) as T | null;+}++async function resolveWorkspace(+ ctx: PluginContext,+ companyId: string,+ projectId: string,+ workspaceId?: string,+): Promise<PluginWorkspace> {+ const workspaces = await ctx.projects.listWorkspaces(projectId, companyId);+ if (workspaces.length === 0) {+ throw new Error("No workspaces configured for this project");+ }+ if (!workspaceId) return workspaces[0]!;+ const workspace = workspaces.find((entry) => entry.id === workspaceId);+ if (!workspace) {+ throw new Error("Workspace not found");+ }+ return workspace;+}++function ensureInsideWorkspace(workspacePath: string, relativePath: string): string {+ const root = path.resolve(workspacePath);+ const resolved = path.resolve(root, relativePath);+ const relative = path.relative(root, resolved);+ if (relative.startsWith("..") || path.isAbsolute(relative)) {+ throw new Error("Requested path escapes the selected workspace");+ }+ return resolved;+}++function parseJsonish(value: string): unknown {+ const trimmed = value.trim();+ if (trimmed.length === 0) return "";+ try {+ return JSON.parse(trimmed) as unknown;+ } catch {+ return value;+ }+}++function parseScopeKey(params: Record<string, unknown>): ScopeKey {+ const scopeKind = isScopeKind(params.scopeKind) ? params.scopeKind : "instance";+ const scopeId = typeof params.scopeId === "string" && params.scopeId.length > 0 ? params.scopeId : undefined;+ const namespace = typeof params.namespace === "string" && params.namespace.length > 0 ? params.namespace : undefined;+ const stateKey = typeof params.stateKey === "string" && params.stateKey.length > 0+ ? params.stateKey+ : "demo";+ return { scopeKind, scopeId, namespace, stateKey };+}++async function runCuratedCommand(+ ctx: PluginContext,+ config: KitchenSinkConfig,+ companyId: string,+ projectId: string,+ workspaceId: string | undefined,+ commandKey: string,+): Promise<ProcessResult> {+ if (!config.enableProcessDemos) {+ throw new Error("Process demos are disabled in plugin settings");+ }+ const allowedCommands = new Set(config.allowedCommands ?? DEFAULT_CONFIG.allowedCommands);+ if (!allowedCommands.has(commandKey)) {+ throw new Error(`Command "${commandKey}" is not allowed by plugin settings`);+ }+ const definition = SAFE_COMMANDS.find((entry) => entry.key === commandKey);+ if (!definition) {+ throw new Error(`Unknown curated command "${commandKey}"`);+ }+ const workspace = await resolveWorkspace(ctx, companyId, projectId, workspaceId);+ const cwd = workspace.path;+ const startedAt = new Date().toISOString();+ const child = spawn(definition.command, definition.args, {+ cwd,+ stdio: ["ignore", "pipe", "pipe"],+ });++ let stdout = "";+ let stderr = "";++ child.stdout.on("data", (chunk) => {+ stdout += String(chunk);+ });+ child.stderr.on("data", (chunk) => {+ stderr += String(chunk);+ });++ const code = await new Promise<number | null>((resolve, reject) => {+ child.on("error", reject);+ child.on("close", resolve);+ });++ const result: ProcessResult = {+ commandKey,+ cwd,+ code,+ stdout: stdout.trim(),+ stderr: stderr.trim(),+ startedAt,+ finishedAt: new Date().toISOString(),+ };+ lastProcessResult = result;+ pushRecord({+ level: code === 0 ? "info" : "warning",+ source: "process",+ message: `Ran curated command "${commandKey}"`,+ data: { code, cwd },+ });+ await ctx.metrics.write("process.run", 1, { command: commandKey, exit_code: String(code ?? -1) });+ return result;+}++function getCurrentCompanyId(params: Record<string, unknown>): string {+ const companyId = typeof params.companyId === "string" ? params.companyId : "";+ if (!companyId) {+ throw new Error("companyId is required");+ }+ return companyId;+}++async function listIssuesForCompany(ctx: PluginContext, companyId: string): Promise<Issue[]> {+ return await ctx.issues.list({ companyId, limit: 20, offset: 0 });+}++async function listGoalsForCompany(ctx: PluginContext, companyId: string): Promise<Goal[]> {+ return await ctx.goals.list({ companyId, limit: 20, offset: 0 });+}++function recentRecordsSnapshot(): DemoRecord[] {+ return recentRecords.slice(0, 20);+}++function runtimeLaunchersSnapshot(): PluginLauncherRegistration[] {+ return [...runtimeLaunchers.values()];+}++async function registerDataHandlers(ctx: PluginContext): Promise<void> {+ ctx.data.register("plugin-config", async () => {+ return await getConfig(ctx);+ });++ ctx.data.register("overview", async (params) => {+ const companyId = typeof params.companyId === "string" ? params.companyId : "";+ const config = await getConfig(ctx);+ const companies = await ctx.companies.list({ limit: 20, offset: 0 });+ const projects = companyId ? await ctx.projects.list({ companyId, limit: 20, offset: 0 }) : [];+ const issues = companyId ? await listIssuesForCompany(ctx, companyId) : [];+ const goals = companyId ? await listGoalsForCompany(ctx, companyId) : [];+ const agents = companyId ? await ctx.agents.list({ companyId, limit: 20, 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,+ version: ctx.manifest.version,+ capabilities: ctx.manifest.capabilities,+ config,+ runtimeLaunchers: runtimeLaunchersSnapshot(),+ recentRecords: recentRecordsSnapshot(),+ counts: {+ companies: companies.length,+ projects: projects.length,+ issues: issues.length,+ goals: goals.length,+ agents: agents.length,+ entities: entityRecords.length,+ },+ lastJob,+ lastWebhook,+ lastAsset,+ lastProcessResult,+ streamChannels: STREAM_CHANNELS,+ safeCommands: SAFE_COMMANDS,+ manifest: {+ jobs: ctx.manifest.jobs ?? [],+ webhooks: ctx.manifest.webhooks ?? [],+ tools: ctx.manifest.tools ?? [],+ },+ };+ });++ ctx.data.register("companies", async () => {+ return await ctx.companies.list({ limit: 50, offset: 0 });+ });++ ctx.data.register("projects", async (params) => {+ const companyId = getCurrentCompanyId(params);+ return await ctx.projects.list({ companyId, limit: 50, offset: 0 });+ });++ ctx.data.register("issues", async (params) => {+ const companyId = getCurrentCompanyId(params);+ return await listIssuesForCompany(ctx, companyId);+ });++ ctx.data.register("goals", async (params) => {+ const companyId = getCurrentCompanyId(params);+ return await listGoalsForCompany(ctx, companyId);+ });++ ctx.data.register("agents", async (params) => {+ const companyId = getCurrentCompanyId(params);+ return await ctx.agents.list({ companyId, limit: 50, offset: 0 });+ });++ ctx.data.register("workspaces", async (params) => {+ const companyId = getCurrentCompanyId(params);+ const projectId = typeof params.projectId === "string" ? params.projectId : "";+ if (!projectId) return [];+ return await ctx.projects.listWorkspaces(projectId, companyId);+ });++ ctx.data.register("state-value", async (params) => {+ const input = parseScopeKey(params);+ const value = await ctx.state.get(input);+ return {+ scope: input,+ value,+ };+ });++ ctx.data.register("entities", async (params) => {+ const query: PluginEntityQuery = {+ entityType: typeof params.entityType === "string" && params.entityType.length > 0 ? params.entityType : undefined,+ scopeKind: isScopeKind(params.scopeKind) ? params.scopeKind : undefined,+ scopeId: typeof params.scopeId === "string" && params.scopeId.length > 0 ? params.scopeId : undefined,+ limit: typeof params.limit === "number" ? params.limit : 25,+ offset: 0,+ };+ return await ctx.entities.list(query);+ });++ ctx.data.register("comment-context", async (params) => {+ const companyId = getCurrentCompanyId(params);+ const issueId = typeof params.issueId === "string" ? params.issueId : "";+ const commentId = typeof params.commentId === "string" ? params.commentId : "";+ if (!issueId || !commentId) return null;+ const comments = await ctx.issues.listComments(issueId, companyId);+ const comment = comments.find((entry) => entry.id === commentId) ?? null;+ if (!comment) return null;+ return {+ commentId: comment.id,+ issueId,+ preview: comment.body.slice(0, 160),+ length: comment.body.length,+ copiedCount: (await ctx.entities.list({+ entityType: "copied-comment",+ scopeKind: "issue",+ scopeId: issueId,+ limit: 100,+ offset: 0,+ })).filter((entry) => entry.externalId === commentId).length,+ };+ });++ ctx.data.register("entity-context", async (params) => {+ const companyId = typeof params.companyId === "string" ? params.companyId : "";+ const entityId = typeof params.entityId === "string" ? params.entityId : "";+ const entityType = typeof params.entityType === "string" ? params.entityType : "";+ if (!companyId || !entityId || !entityType) return null;++ if (entityType === "project") {+ return await ctx.projects.get(entityId, companyId);+ }+ if (entityType === "issue") {+ return await ctx.issues.get(entityId, companyId);+ }+ if (entityType === "goal") {+ return await ctx.goals.get(entityId, companyId);+ }+ if (entityType === "agent") {+ return await ctx.agents.get(entityId, companyId);+ }+ return { entityId, entityType, companyId };+ });+}++async function registerActionHandlers(ctx: PluginContext): Promise<void> {+ ctx.actions.register("emit-demo-event", async (params) => {+ const companyId = getCurrentCompanyId(params);+ const message = typeof params.message === "string" && params.message.trim().length > 0+ ? params.message.trim()+ : "Kitchen Sink demo event";+ await ctx.events.emit("demo-event", companyId, {+ message,+ source: "kitchen-sink",+ emittedAt: new Date().toISOString(),+ });+ pushRecord({+ level: "info",+ source: "events.emit",+ message,+ data: { companyId },+ });+ await ctx.metrics.write("demo.events.emitted", 1, { source: "manual" });+ return { ok: true, message };+ });++ ctx.actions.register("write-scoped-state", async (params) => {+ const input = parseScopeKey(params);+ const valueInput = typeof params.value === "string" ? params.value : JSON.stringify(params.value ?? "");+ const value = parseJsonish(valueInput);+ await ctx.state.set(input, value);+ pushRecord({+ level: "info",+ source: "state",+ message: `Wrote state key ${input.stateKey}`,+ data: input,+ });+ await ctx.metrics.write("demo.state.write", 1, { scope: input.scopeKind });+ return { ok: true, scope: input, value };+ });++ ctx.actions.register("delete-scoped-state", async (params) => {+ const input = parseScopeKey(params);+ await ctx.state.delete(input);+ pushRecord({+ level: "warning",+ source: "state",+ message: `Deleted state key ${input.stateKey}`,+ data: input,+ });+ return { ok: true, scope: input };+ });++ ctx.actions.register("upsert-entity", async (params) => {+ const title = typeof params.title === "string" && params.title.length > 0 ? params.title : "Kitchen Sink Entity";+ const entityType = typeof params.entityType === "string" && params.entityType.length > 0+ ? params.entityType+ : "demo-record";+ const scopeKind = isScopeKind(params.scopeKind)+ ? params.scopeKind+ : "instance";+ const scopeId = typeof params.scopeId === "string" && params.scopeId.length > 0 ? params.scopeId : undefined;+ const status = typeof params.status === "string" && params.status.length > 0 ? params.status : "active";+ const data = typeof params.data === "string" ? parseJsonish(params.data) : params.data;+ const record = await ctx.entities.upsert({+ entityType,+ scopeKind,+ scopeId,+ externalId: typeof params.externalId === "string" && params.externalId.length > 0 ? params.externalId : randomUUID(),+ title,+ status,+ data: typeof data === "object" && data !== null ? data as Record<string, unknown> : { value: data },+ });+ pushRecord({+ level: "info",+ source: "entities",+ message: `Upserted entity ${record.entityType}`,+ data: { id: record.id, scopeKind: record.scopeKind },+ });+ return record;+ });++ ctx.actions.register("create-issue", async (params) => {+ const companyId = getCurrentCompanyId(params);+ const title = typeof params.title === "string" && params.title.trim().length > 0+ ? params.title.trim()+ : "Kitchen Sink demo issue";+ const description = typeof params.description === "string" ? params.description : undefined;+ const projectId = typeof params.projectId === "string" && params.projectId.length > 0 ? params.projectId : undefined;+ const issue = await ctx.issues.create({ companyId, projectId, title, description });+ pushRecord({+ level: "info",+ source: "issues.create",+ message: `Created issue ${issue.title}`,+ data: { issueId: issue.id },+ });+ await ctx.activity.log({+ companyId,+ entityType: "issue",+ entityId: issue.id,+ message: `Kitchen Sink created issue "${issue.title}"`,+ metadata: { plugin: PLUGIN_ID },+ });+ return issue;+ });++ ctx.actions.register("advance-issue-status", async (params) => {+ const companyId = getCurrentCompanyId(params);+ const issueId = typeof params.issueId === "string" ? params.issueId : "";+ const status = typeof params.status === "string" ? params.status : "";+ if (!issueId || !status) {+ throw new Error("issueId and status are required");+ }+ const issue = await ctx.issues.update(issueId, { status: status as Issue["status"] }, companyId);+ pushRecord({+ level: "info",+ source: "issues.update",+ message: `Updated issue ${issue.id} to ${issue.status}`,+ });+ return issue;+ });++ ctx.actions.register("create-goal", async (params) => {+ const companyId = getCurrentCompanyId(params);+ const title = typeof params.title === "string" && params.title.trim().length > 0+ ? params.title.trim()+ : "Kitchen Sink demo goal";+ const description = typeof params.description === "string" ? params.description : undefined;+ const goal = await ctx.goals.create({ companyId, title, description, level: "team", status: "planned" });+ pushRecord({+ level: "info",+ source: "goals.create",+ message: `Created goal ${goal.title}`,+ data: { goalId: goal.id },+ });+ return goal;+ });++ ctx.actions.register("advance-goal-status", async (params) => {+ const companyId = getCurrentCompanyId(params);+ const goalId = typeof params.goalId === "string" ? params.goalId : "";+ const status = typeof params.status === "string" ? params.status : "";+ if (!goalId || !status) {+ throw new Error("goalId and status are required");+ }+ const goal = await ctx.goals.update(goalId, { status: status as Goal["status"] }, companyId);+ pushRecord({+ level: "info",+ source: "goals.update",+ message: `Updated goal ${goal.id} to ${goal.status}`,+ });+ return goal;+ });++ ctx.actions.register("write-activity", async (params) => {+ const companyId = getCurrentCompanyId(params);+ const entityType = typeof params.entityType === "string" ? params.entityType : undefined;+ const entityId = typeof params.entityId === "string" ? params.entityId : undefined;+ const message = typeof params.message === "string" && params.message.length > 0+ ? params.message+ : "Kitchen Sink wrote an activity entry";+ await ctx.activity.log({+ companyId,+ entityType,+ entityId,+ message,+ metadata: { plugin: PLUGIN_ID },+ });+ pushRecord({+ level: "info",+ source: "activity",+ message,+ data: { entityType, entityId },+ });+ return { ok: true };+ });++ ctx.actions.register("write-metric", async (params) => {+ const value = typeof params.value === "number" ? params.value : Number(params.value ?? 1);+ const name = typeof params.name === "string" && params.name.length > 0 ? params.name : "manual";+ await ctx.metrics.write(`demo.${name}`, Number.isFinite(value) ? value : 1, { source: "manual" });+ pushRecord({+ level: "info",+ source: "metrics",+ message: `Wrote metric demo.${name}`,+ data: { value },+ });+ return { ok: true, value };+ });++ ctx.actions.register("http-fetch", async (params) => {+ const config = await getConfig(ctx);+ const url = typeof params.url === "string" && params.url.length > 0+ ? params.url+ : config.httpDemoUrl || DEFAULT_CONFIG.httpDemoUrl;+ const started = Date.now();+ const response = await ctx.http.fetch(url, { method: "GET" });+ const body = await response.text();+ const result = {+ ok: response.ok,+ status: response.status,+ url,+ durationMs: Date.now() - started,+ body: body.slice(0, 2000),+ };+ pushRecord({+ level: response.ok ? "info" : "warning",+ source: "http",+ message: `Fetched ${url}`,+ data: { status: response.status },+ });+ return result;+ });++ ctx.actions.register("resolve-secret", async (params) => {+ const config = await getConfig(ctx);+ const secretRef = typeof params.secretRef === "string" && params.secretRef.length > 0+ ? params.secretRef+ : config.secretRefExample || "";+ if (!secretRef) {+ throw new Error("No secret reference configured");+ }+ const resolved = await ctx.secrets.resolve(secretRef);+ pushRecord({+ level: "info",+ source: "secrets",+ message: `Resolved secret reference ${secretRef}`,+ });+ return {+ secretRef,+ resolvedLength: resolved.length,+ preview: resolved.length > 0 ? `${resolved.slice(0, 2)}***` : "",+ };+ });++ 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);+ const projectId = typeof params.projectId === "string" ? params.projectId : "";+ const workspaceId = typeof params.workspaceId === "string" && params.workspaceId.length > 0 ? params.workspaceId : undefined;+ const commandKey = typeof params.commandKey === "string" ? params.commandKey : "pwd";+ if (!projectId) throw new Error("projectId is required");+ return await runCuratedCommand(ctx, config, companyId, projectId, workspaceId, commandKey);+ });++ ctx.actions.register("read-workspace-file", async (params) => {+ const config = await getConfig(ctx);+ if (!config.enableWorkspaceDemos) {+ throw new Error("Workspace demos are disabled in plugin settings");+ }+ const companyId = getCurrentCompanyId(params);+ const projectId = typeof params.projectId === "string" ? params.projectId : "";+ const workspaceId = typeof params.workspaceId === "string" && params.workspaceId.length > 0 ? params.workspaceId : undefined;+ const relativePath = typeof params.relativePath === "string" && params.relativePath.length > 0+ ? params.relativePath+ : config.workspaceScratchFile || DEFAULT_CONFIG.workspaceScratchFile;+ if (!projectId) throw new Error("projectId is required");+ const workspace = await resolveWorkspace(ctx, companyId, projectId, workspaceId);+ const fullPath = ensureInsideWorkspace(workspace.path, relativePath);+ const content = await fs.readFile(fullPath, "utf8");+ return {+ workspaceId: workspace.id,+ relativePath,+ content,+ };+ });++ ctx.actions.register("write-workspace-scratch", async (params) => {+ const config = await getConfig(ctx);+ if (!config.enableWorkspaceDemos) {+ throw new Error("Workspace demos are disabled in plugin settings");+ }+ const companyId = getCurrentCompanyId(params);+ const projectId = typeof params.projectId === "string" ? params.projectId : "";+ const workspaceId = typeof params.workspaceId === "string" && params.workspaceId.length > 0 ? params.workspaceId : undefined;+ const relativePath = typeof params.relativePath === "string" && params.relativePath.length > 0+ ? params.relativePath+ : config.workspaceScratchFile || DEFAULT_CONFIG.workspaceScratchFile;+ const content = typeof params.content === "string" ? params.content : "Kitchen Sink workspace demo";+ if (!projectId) throw new Error("projectId is required");+ const workspace = await resolveWorkspace(ctx, companyId, projectId, workspaceId);+ const fullPath = ensureInsideWorkspace(workspace.path, relativePath);+ await fs.writeFile(fullPath, content, "utf8");+ pushRecord({+ level: "info",+ source: "workspace",+ message: `Wrote scratch file ${relativePath}`,+ data: { workspaceId: workspace.id },+ });+ return {+ workspaceId: workspace.id,+ relativePath,+ bytes: Buffer.byteLength(content, "utf8"),+ };+ });++ ctx.actions.register("start-progress-stream", async (params) => {+ const companyId = getCurrentCompanyId(params);+ const steps = typeof params.steps === "number" ? params.steps : 5;+ void (async () => {+ ctx.streams.open(STREAM_CHANNELS.progress, companyId);+ try {+ for (let index = 1; index <= steps; index += 1) {+ ctx.streams.emit(STREAM_CHANNELS.progress, {+ step: index,+ total: steps,+ message: `Progress step ${index}/${steps}`,+ });+ await new Promise((resolve) => setTimeout(resolve, 350));+ }+ } finally {+ ctx.streams.close(STREAM_CHANNELS.progress);+ }+ })();+ return { ok: true, channel: STREAM_CHANNELS.progress };+ });++ ctx.actions.register("invoke-agent", async (params) => {+ const companyId = getCurrentCompanyId(params);+ const agentId = typeof params.agentId === "string" ? params.agentId : "";+ const prompt = typeof params.prompt === "string" && params.prompt.length > 0+ ? params.prompt+ : "Kitchen Sink test invocation";+ if (!agentId) throw new Error("agentId is required");+ const result = await ctx.agents.invoke(agentId, companyId, { prompt, reason: "Kitchen Sink plugin demo" });+ pushRecord({+ level: "info",+ source: "agents.invoke",+ message: `Invoked agent ${agentId}`,+ data: result,+ });+ return result;+ });++ ctx.actions.register("pause-agent", async (params) => {+ const companyId = getCurrentCompanyId(params);+ const agentId = typeof params.agentId === "string" ? params.agentId : "";+ if (!agentId) throw new Error("agentId is required");+ return await ctx.agents.pause(agentId, companyId);+ });++ ctx.actions.register("resume-agent", async (params) => {+ const companyId = getCurrentCompanyId(params);+ const agentId = typeof params.agentId === "string" ? params.agentId : "";+ if (!agentId) throw new Error("agentId is required");+ return await ctx.agents.resume(agentId, companyId);+ });++ ctx.actions.register("ask-agent", async (params) => {+ const companyId = getCurrentCompanyId(params);+ const agentId = typeof params.agentId === "string" ? params.agentId : "";+ const prompt = typeof params.prompt === "string" && params.prompt.length > 0+ ? params.prompt+ : "Say hello from the Kitchen Sink plugin.";+ if (!agentId) throw new Error("agentId is required");++ ctx.streams.open(STREAM_CHANNELS.agentChat, companyId);+ const session = await ctx.agents.sessions.create(agentId, companyId, {+ reason: "Kitchen Sink plugin chat demo",+ });++ await ctx.agents.sessions.sendMessage(session.sessionId, companyId, {+ prompt,+ reason: "Kitchen Sink demo",+ onEvent: (event) => {+ ctx.streams.emit(STREAM_CHANNELS.agentChat, {+ eventType: event.eventType,+ stream: event.stream,+ message: event.message,+ payload: event.payload,+ });+ if (event.eventType === "done" || event.eventType === "error") {+ ctx.streams.close(STREAM_CHANNELS.agentChat);+ }+ },+ });++ pushRecord({+ level: "info",+ source: "agent.sessions",+ message: `Started agent session ${session.sessionId}`,+ data: { agentId, sessionId: session.sessionId },+ });+ return { channel: STREAM_CHANNELS.agentChat, sessionId: session.sessionId };+ });++ ctx.actions.register("copy-comment-context", async (params) => {+ const companyId = getCurrentCompanyId(params);+ const issueId = typeof params.issueId === "string" ? params.issueId : "";+ const commentId = typeof params.commentId === "string" ? params.commentId : "";+ if (!issueId || !commentId) {+ throw new Error("issueId and commentId are required");+ }+ const comments = await ctx.issues.listComments(issueId, companyId);+ const comment = comments.find((entry) => entry.id === commentId);+ if (!comment) {+ throw new Error("Comment not found");+ }+ const record = await ctx.entities.upsert({+ entityType: "copied-comment",+ scopeKind: "issue",+ scopeId: issueId,+ externalId: comment.id,+ title: `Copied comment ${comment.id.slice(0, 8)}`,+ status: "captured",+ data: {+ commentId: comment.id,+ issueId,+ body: comment.body,+ },+ });+ pushRecord({+ level: "info",+ source: "comments",+ message: `Copied comment ${comment.id} into plugin entities`,+ data: { recordId: record.id },+ });+ return record;+ });+}++async function registerToolHandlers(ctx: PluginContext): Promise<void> {+ ctx.tools.register(+ TOOL_NAMES.echo,+ {+ displayName: "Kitchen Sink Echo",+ description: "Echoes the provided message back to the caller.",+ parametersSchema: {+ type: "object",+ properties: {+ message: { type: "string" },+ },+ required: ["message"],+ },+ },+ async (params, runCtx): Promise<ToolResult> => {+ const payload = params as { message?: string };+ return {+ content: payload.message ?? "No message provided",+ data: {+ runCtx,+ message: payload.message ?? "",+ },+ };+ },+ );++ ctx.tools.register(+ TOOL_NAMES.companySummary,+ {+ displayName: "Kitchen Sink Company Summary",+ description: "Summarizes current company counts from the Paperclip APIs.",+ parametersSchema: { type: "object", properties: {} },+ },+ async (_params, runCtx): Promise<ToolResult> => {+ const projects = await ctx.projects.list({ companyId: runCtx.companyId, limit: 50, offset: 0 });+ const issues = await ctx.issues.list({ companyId: runCtx.companyId, limit: 50, offset: 0 });+ const goals = await ctx.goals.list({ companyId: runCtx.companyId, limit: 50, offset: 0 });+ const agents = await ctx.agents.list({ companyId: runCtx.companyId, limit: 50, offset: 0 });+ return {+ content: `Company has ${projects.length} projects, ${issues.length} issues, ${goals.length} goals, and ${agents.length} agents.`,+ data: {+ companyId: runCtx.companyId,+ projects: projects.length,+ issues: issues.length,+ goals: goals.length,+ agents: agents.length,+ },+ };+ },+ );++ ctx.tools.register(+ TOOL_NAMES.createIssue,+ {+ displayName: "Kitchen Sink Create Issue",+ description: "Creates an issue in the current run context.",+ parametersSchema: {+ type: "object",+ properties: {+ title: { type: "string" },+ description: { type: "string" },+ },+ required: ["title"],+ },+ },+ async (params, runCtx): Promise<ToolResult> => {+ const payload = params as { title?: string; description?: string };+ if (!payload.title) {+ return { error: "title is required" };+ }+ const issue = await ctx.issues.create({+ companyId: runCtx.companyId,+ projectId: runCtx.projectId,+ title: payload.title,+ description: payload.description,+ });+ return {+ content: `Created issue ${issue.title}`,+ data: issue,+ };+ },+ );+}++async function registerEventHandlers(ctx: PluginContext): Promise<void> {+ ctx.events.on("issue.created", async (event: PluginEvent) => {+ pushRecord({+ level: "info",+ source: "events.subscribe",+ message: "Observed issue.created",+ data: event,+ });+ });++ ctx.events.on("issue.updated", async (event: PluginEvent) => {+ pushRecord({+ level: "info",+ source: "events.subscribe",+ message: "Observed issue.updated",+ data: event,+ });+ });++ ctx.events.on(`plugin.${PLUGIN_ID}.demo-event`, async (event: PluginEvent) => {+ pushRecord({+ level: "info",+ source: "plugin-event",+ message: "Observed plugin demo event",+ data: event,+ });+ });+}++async function registerJobs(ctx: PluginContext): Promise<void> {+ ctx.jobs.register(JOB_KEYS.heartbeat, async (job: PluginJobContext) => {+ const payload = {+ jobKey: job.jobKey,+ runId: job.runId,+ trigger: job.trigger,+ scheduledAt: job.scheduledAt,+ completedAt: new Date().toISOString(),+ };+ await writeInstanceState(ctx, "last-job-run", payload);+ pushRecord({+ level: "info",+ source: "jobs",+ message: "Kitchen Sink demo job ran",+ data: payload,+ });+ await ctx.metrics.write("jobs.demo_heartbeat", 1, { trigger: job.trigger });+ });+}++const plugin: PaperclipPlugin = definePlugin({+ async setup(ctx) {+ currentContext = ctx;+ runtimeLaunchers.set(RUNTIME_LAUNCHER.id, RUNTIME_LAUNCHER);+ ctx.launchers.register(RUNTIME_LAUNCHER);+ pushRecord({+ level: "info",+ source: "setup",+ message: "Kitchen Sink plugin setup complete",+ data: { pluginId: PLUGIN_ID },+ });+ await registerEventHandlers(ctx);+ await registerJobs(ctx);+ await registerDataHandlers(ctx);+ await registerActionHandlers(ctx);+ await registerToolHandlers(ctx);+ },++ async onHealth(): Promise<PluginHealthDiagnostics> {+ const ctx = currentContext;+ const config = ctx ? await getConfig(ctx) : DEFAULT_CONFIG;+ return {+ status: "ok",+ message: "Kitchen Sink plugin ready",+ details: {+ recordsTracked: recentRecords.length,+ runtimeLaunchers: runtimeLaunchers.size,+ processDemosEnabled: config.enableProcessDemos === true,+ workspaceDemosEnabled: config.enableWorkspaceDemos !== false,+ },+ };+ },++ async onConfigChanged(newConfig) {+ pushRecord({+ level: "info",+ source: "config",+ message: "Kitchen Sink config changed",+ data: newConfig,+ });+ },++ async onValidateConfig(config) {+ const errors: string[] = [];+ const warnings: string[] = [];+ const typed = config as KitchenSinkConfig;+ if (typed.httpDemoUrl && typeof typed.httpDemoUrl !== "string") {+ errors.push("httpDemoUrl must be a string");+ }+ if (typed.allowedCommands && !Array.isArray(typed.allowedCommands)) {+ errors.push("allowedCommands must be an array");+ }+ if (Array.isArray(typed.allowedCommands)) {+ const allowed = new Set<string>(SAFE_COMMANDS.map((command) => command.key));+ const invalid = typed.allowedCommands.filter((value) => typeof value !== "string" || !allowed.has(value));+ if (invalid.length > 0) {+ errors.push(`allowedCommands contains unsupported values: ${invalid.join(", ")}`);+ }+ }+ if (typed.enableProcessDemos) {+ warnings.push("Process demos run local child processes and are intended only for trusted development environments.");+ }+ return {+ ok: errors.length === 0,+ warnings,+ errors,+ };+ },++ async onWebhook(input: PluginWebhookInput) {+ const payload = {+ endpointKey: input.endpointKey,+ requestId: input.requestId,+ rawBody: input.rawBody,+ parsedBody: input.parsedBody,+ receivedAt: new Date().toISOString(),+ };+ const ctx = currentContext;+ if (ctx) {+ await writeInstanceState(ctx, "last-webhook", payload);+ }+ pushRecord({+ level: "info",+ source: "webhook",+ message: `Received webhook ${input.endpointKey}`,+ data: payload,+ });+ if (input.endpointKey !== WEBHOOK_KEYS.demo) {+ throw new Error(`Unsupported webhook endpoint "${input.endpointKey}"`);+ }+ },++ async onShutdown() {+ pushRecord({+ level: "warning",+ source: "shutdown",+ message: "Kitchen Sink plugin shutting down",+ });+ },+});++export default plugin;+runWorker(plugin, import.meta.url);diff --git a/packages/plugins/examples/plugin-kitchen-sink-example/tsconfig.json b/packages/plugins/examples/plugin-kitchen-sink-example/tsconfig.jsonnew file mode 100644index 0000000000..3482c1738c--- /dev/null+++ b/packages/plugins/examples/plugin-kitchen-sink-example/tsconfig.json@@ -0,0 +1,10 @@+{+ "extends": "../../../../tsconfig.json",+ "compilerOptions": {+ "outDir": "dist",+ "rootDir": "src",+ "lib": ["ES2023", "DOM"],+ "jsx": "react-jsx"+ },+ "include": ["src"]+}diff --git a/server/src/routes/plugins.ts b/server/src/routes/plugins.tsindex 0237741215..95215d899a 100644--- a/server/src/routes/plugins.ts+++ b/server/src/routes/plugins.ts@@ -131,6 +131,14 @@ const BUNDLED_PLUGIN_EXAMPLES: AvailablePluginExample[] = [localPath: "packages/plugins/examples/plugin-file-browser-example",tag: "example",},+ {+ packageName: "@paperclipai/plugin-kitchen-sink-example",+ pluginKey: "paperclip-kitchen-sink-example",+ displayName: "Kitchen Sink (Example)",+ description: "Reference plugin that demonstrates the current Paperclip plugin API surface, bridge flows, UI extension surfaces, jobs, webhooks, tools, streams, and trusted local workspace/process demos.",+ localPath: "packages/plugins/examples/plugin-kitchen-sink-example",+ tag: "example",+ },];function listBundledPluginExamples(): AvailablePluginExample[] {diff --git a/ui/src/components/CommentThread.tsx b/ui/src/components/CommentThread.tsxindex fa123d3178..8e042acf9d 100644--- a/ui/src/components/CommentThread.tsx+++ b/ui/src/components/CommentThread.tsx@@ -10,6 +10,7 @@ import { MarkdownEditor, type MarkdownEditorRef, type MentionOption } from "./Maimport { StatusBadge } from "./StatusBadge";import { AgentIcon } from "./AgentIconPicker";import { formatDateTime } from "../lib/utils";+import { PluginSlotOutlet } from "@/plugins/slots";interface CommentWithRunMeta extends IssueComment {runId?: string | null;@@ -32,6 +33,8 @@ interface CommentReassignment {interface CommentThreadProps {comments: CommentWithRunMeta[];linkedRuns?: LinkedRunItem[];+ companyId?: string | null;+ projectId?: string | null;onAdd: (body: string, reopen?: boolean, reassignment?: CommentReassignment) => Promise<void>;issueStatus?: string;agentMap?: Map<string, Agent>;@@ -118,10 +121,14 @@ type TimelineItem =const TimelineList = memo(function TimelineList({timeline,agentMap,+ companyId,+ projectId,highlightCommentId,}: {timeline: TimelineItem[];agentMap?: Map<string, Agent>;+ companyId?: string | null;+ projectId?: string | null;highlightCommentId?: string | null;}) {if (timeline.length === 0) {@@ -180,6 +187,22 @@ const TimelineList = memo(function TimelineList({<Identity name="You" size="sm" />)}<span className="flex items-center gap-1.5">+ {companyId ? (+ <PluginSlotOutlet+ slotTypes={["commentContextMenuItem"]}+ entityType="comment"+ context={{+ companyId,+ projectId: projectId ?? null,+ entityId: comment.id,+ entityType: "comment",+ parentEntityId: comment.issueId,+ }}+ className="flex flex-wrap items-center gap-1.5"+ itemClassName="inline-flex"+ missingBehavior="placeholder"+ />+ ) : null}<ahref={`#comment-${comment.id}`}className="text-xs text-muted-foreground hover:text-foreground hover:underline transition-colors"@@ -190,6 +213,24 @@ const TimelineList = memo(function TimelineList({</span></div><MarkdownBody className="text-sm">{comment.body}</MarkdownBody>+ {companyId ? (+ <div className="mt-2 space-y-2">+ <PluginSlotOutlet+ slotTypes={["commentAnnotation"]}+ entityType="comment"+ context={{+ companyId,+ projectId: projectId ?? null,+ entityId: comment.id,+ entityType: "comment",+ parentEntityId: comment.issueId,+ }}+ className="space-y-2"+ itemClassName="rounded-md"+ missingBehavior="placeholder"+ />+ </div>+ ) : null}{comment.runId && (<div className="mt-2 pt-2 border-t border-border/60">{comment.runAgentId ? (@@ -216,6 +257,8 @@ const TimelineList = memo(function TimelineList({export function CommentThread({comments,linkedRuns = [],+ companyId,+ projectId,onAdd,issueStatus,agentMap,@@ -351,7 +394,13 @@ export function CommentThread({<div className="space-y-4"><h3 className="text-sm font-semibold">Comments & Runs ({timeline.length})</h3>- <TimelineList timeline={timeline} agentMap={agentMap} highlightCommentId={highlightCommentId} />+ <TimelineList+ timeline={timeline}+ agentMap={agentMap}+ companyId={companyId}+ projectId={projectId}+ highlightCommentId={highlightCommentId}+ />{liveRunSlot}diff --git a/ui/src/components/InstanceSidebar.tsx b/ui/src/components/InstanceSidebar.tsxindex 0b396ef9c4..5c9dcd54d9 100644--- a/ui/src/components/InstanceSidebar.tsx+++ b/ui/src/components/InstanceSidebar.tsx@@ -1,7 +1,16 @@+import { useQuery } from "@tanstack/react-query";import { Clock3, Puzzle, Settings } from "lucide-react";+import { NavLink } from "@/lib/router";+import { pluginsApi } from "@/api/plugins";+import { queryKeys } from "@/lib/queryKeys";import { SidebarNavItem } from "./SidebarNavItem";export function InstanceSidebar() {+ const { data: plugins } = useQuery({+ queryKey: queryKeys.plugins.all,+ queryFn: () => pluginsApi.list(),+ });+return (<aside className="w-60 h-full min-h-0 border-r border-border bg-background flex flex-col"><div className="flex items-center gap-2 px-3 h-12 shrink-0">@@ -15,6 +24,26 @@ export function InstanceSidebar() {<div className="flex flex-col gap-0.5"><SidebarNavItem to="/instance/settings/heartbeats" label="Heartbeats" icon={Clock3} end /><SidebarNavItem to="/instance/settings/plugins" label="Plugins" icon={Puzzle} />+ {(plugins ?? []).length > 0 ? (+ <div className="ml-4 mt-1 flex flex-col gap-0.5 border-l border-border/70 pl-3">+ {(plugins ?? []).map((plugin) => (+ <NavLink+ key={plugin.id}+ to={`/instance/settings/plugins/${plugin.id}`}+ className={({ isActive }) =>+ [+ "rounded-md px-2 py-1.5 text-xs transition-colors",+ isActive+ ? "bg-accent text-foreground"+ : "text-muted-foreground hover:bg-accent/50 hover:text-foreground",+ ].join(" ")+ }+ >+ {plugin.manifestJson.displayName ?? plugin.packageName}+ </NavLink>+ ))}+ </div>+ ) : null}</div></nav></aside>diff --git a/ui/src/components/Sidebar.tsx b/ui/src/components/Sidebar.tsxindex 0cc46d8755..b8742deef9 100644--- a/ui/src/components/Sidebar.tsx+++ b/ui/src/components/Sidebar.tsx@@ -21,6 +21,7 @@ import { heartbeatsApi } from "../api/heartbeats";import { queryKeys } from "../lib/queryKeys";import { useInboxBadge } from "../hooks/useInboxBadge";import { Button } from "@/components/ui/button";+import { PluginSlotOutlet } from "@/plugins/slots";export function Sidebar() {const { openNewIssue } = useDialog();@@ -38,6 +39,11 @@ export function Sidebar() {document.dispatchEvent(new KeyboardEvent("keydown", { key: "k", metaKey: true }));}+ const pluginContext = {+ companyId: selectedCompanyId,+ companyPrefix: selectedCompany?.issuePrefix ?? null,+ };+return (<aside className="w-60 h-full min-h-0 border-r border-border bg-background flex flex-col">{/* Top bar: Company name (bold) + Search — aligned with top sections (no visible border) */}@@ -80,6 +86,13 @@ export function Sidebar() {badgeTone={inboxBadge.failedRuns > 0 ? "danger" : "default"}alert={inboxBadge.failedRuns > 0}/>+ <PluginSlotOutlet+ slotTypes={["sidebar"]}+ context={pluginContext}+ className="flex flex-col gap-0.5"+ itemClassName="text-[13px] font-medium"+ missingBehavior="placeholder"+ /></div><SidebarSection label="Work">@@ -97,6 +110,14 @@ export function Sidebar() {<SidebarNavItem to="/activity" label="Activity" icon={History} /><SidebarNavItem to="/company/settings" label="Settings" icon={Settings} /></SidebarSection>++ <PluginSlotOutlet+ slotTypes={["sidebarPanel"]}+ context={pluginContext}+ className="flex flex-col gap-3"+ itemClassName="rounded-lg border border-border p-3"+ missingBehavior="placeholder"+ /></nav></aside>);diff --git a/ui/src/main.tsx b/ui/src/main.tsxindex 4fe0da4883..5486bd124e 100644--- a/ui/src/main.tsx+++ b/ui/src/main.tsx@@ -15,6 +15,7 @@ import { ToastProvider } from "./context/ToastContext";import { ThemeProvider } from "./context/ThemeContext";import { TooltipProvider } from "@/components/ui/tooltip";import { initPluginBridge } from "./plugins/bridge-init";+import { PluginLauncherProvider } from "./plugins/launchers";import "@mdxeditor/editor/style.css";import "./index.css";@@ -47,9 +48,11 @@ createRoot(document.getElementById("root")!).render(<BreadcrumbProvider><SidebarProvider><PanelProvider>- <DialogProvider>- <App />- </DialogProvider>+ <PluginLauncherProvider>+ <DialogProvider>+ <App />+ </DialogProvider>+ </PluginLauncherProvider></PanelProvider></SidebarProvider></BreadcrumbProvider>diff --git a/ui/src/pages/IssueDetail.tsx b/ui/src/pages/IssueDetail.tsxindex 9a43f26a65..02c5c8dbcd 100644--- a/ui/src/pages/IssueDetail.tsx+++ b/ui/src/pages/IssueDetail.tsx@@ -24,6 +24,8 @@ import { StatusIcon } from "../components/StatusIcon";import { PriorityIcon } from "../components/PriorityIcon";import { StatusBadge } from "../components/StatusBadge";import { Identity } from "../components/Identity";+import { PluginSlotMount, PluginSlotOutlet, usePluginSlots } from "@/plugins/slots";+import { PluginLauncherOutlet } from "@/plugins/launchers";import { Separator } from "@/components/ui/separator";import { Popover, PopoverTrigger, PopoverContent } from "@/components/ui/popover";import { Button } from "@/components/ui/button";@@ -168,6 +170,7 @@ export function IssueDetail() {queryFn: () => issuesApi.get(issueId!),enabled: !!issueId,});+ const resolvedCompanyId = issue?.companyId ?? selectedCompanyId;const { data: comments } = useQuery({queryKey: queryKeys.issues.comments(issueId!),@@ -257,6 +260,21 @@ export function IssueDetail() {companyId: selectedCompanyId,userId: currentUserId,});+ const { slots: issuePluginDetailSlots } = usePluginSlots({+ slotTypes: ["detailTab"],+ entityType: "issue",+ companyId: resolvedCompanyId,+ enabled: !!resolvedCompanyId,+ });+ const issuePluginTabItems = useMemo(+ () => issuePluginDetailSlots.map((slot) => ({+ value: `plugin:${slot.pluginKey}:${slot.id}`,+ label: slot.displayName,+ slot,+ })),+ [issuePluginDetailSlots],+ );+ const activePluginTab = issuePluginTabItems.find((item) => item.value === detailTab) ?? null;const agentMap = useMemo(() => {const map = new Map<string, Agent>();@@ -678,6 +696,47 @@ export function IssueDetail() {/></div>+ <PluginSlotOutlet+ slotTypes={["toolbarButton", "contextMenuItem"]}+ entityType="issue"+ context={{+ companyId: issue.companyId,+ projectId: issue.projectId ?? null,+ entityId: issue.id,+ entityType: "issue",+ }}+ className="flex flex-wrap gap-2"+ itemClassName="inline-flex"+ missingBehavior="placeholder"+ />++ <PluginLauncherOutlet+ placementZones={["toolbarButton"]}+ entityType="issue"+ context={{+ companyId: issue.companyId,+ projectId: issue.projectId ?? null,+ entityId: issue.id,+ entityType: "issue",+ }}+ className="flex flex-wrap gap-2"+ itemClassName="inline-flex"+ />++ <PluginSlotOutlet+ slotTypes={["taskDetailView"]}+ entityType="issue"+ context={{+ companyId: issue.companyId,+ projectId: issue.projectId ?? null,+ entityId: issue.id,+ entityType: "issue",+ }}+ className="space-y-3"+ itemClassName="rounded-lg border border-border p-3"+ missingBehavior="placeholder"+ />+<div className="space-y-3"><div className="flex items-center justify-between gap-2"><h3 className="text-sm font-medium text-muted-foreground">Attachments</h3>@@ -766,12 +825,19 @@ export function IssueDetail() {<ActivityIcon className="h-3.5 w-3.5" />Activity</TabsTrigger>+ {issuePluginTabItems.map((item) => (+ <TabsTrigger key={item.value} value={item.value}>+ {item.label}+ </TabsTrigger>+ ))}</TabsList><TabsContent value="comments"><CommentThreadcomments={commentsWithRunMeta}linkedRuns={timelineRuns}+ companyId={issue.companyId}+ projectId={issue.projectId}issueStatus={issue.status}agentMap={agentMap}draftKey={`paperclip:issue-comment-draft:${issue.id}`}@@ -844,6 +910,21 @@ export function IssueDetail() {</div>)}</TabsContent>++ {activePluginTab && (+ <TabsContent value={activePluginTab.value}>+ <PluginSlotMount+ slot={activePluginTab.slot}+ context={{+ companyId: issue.companyId,+ projectId: issue.projectId ?? null,+ entityId: issue.id,+ entityType: "issue",+ }}+ missingBehavior="placeholder"+ />+ </TabsContent>+ )}</Tabs>{linkedApprovals && linkedApprovals.length > 0 && (diff --git a/ui/src/pages/ProjectDetail.tsx b/ui/src/pages/ProjectDetail.tsxindex 8b8c027db2..42bb5b86bc 100644--- a/ui/src/pages/ProjectDetail.tsx+++ b/ui/src/pages/ProjectDetail.tsx@@ -19,7 +19,8 @@ import { PageSkeleton } from "../components/PageSkeleton";import { PageTabBar } from "../components/PageTabBar";import { projectRouteRef, cn } from "../lib/utils";import { Tabs } from "@/components/ui/tabs";-import { PluginSlotMount, usePluginSlots } from "@/plugins/slots";+import { PluginLauncherOutlet } from "@/plugins/launchers";+import { PluginSlotMount, PluginSlotOutlet, usePluginSlots } from "@/plugins/slots";/* ── Top-level tab types ── */@@ -405,6 +406,37 @@ export function ProjectDetail() {/></div>+ <PluginSlotOutlet+ slotTypes={["toolbarButton", "contextMenuItem"]}+ entityType="project"+ context={{+ companyId: resolvedCompanyId ?? null,+ companyPrefix: companyPrefix ?? null,+ projectId: project.id,+ projectRef: canonicalProjectRef,+ entityId: project.id,+ entityType: "project",+ }}+ className="flex flex-wrap gap-2"+ itemClassName="inline-flex"+ missingBehavior="placeholder"+ />++ <PluginLauncherOutlet+ placementZones={["toolbarButton"]}+ entityType="project"+ context={{+ companyId: resolvedCompanyId ?? null,+ companyPrefix: companyPrefix ?? null,+ projectId: project.id,+ projectRef: canonicalProjectRef,+ entityId: project.id,+ entityType: "project",+ }}+ className="flex flex-wrap gap-2"+ itemClassName="inline-flex"+ />+<Tabs value={activeTab ?? "list"} onValueChange={(value) => handleTabChange(value as ProjectTab)}><PageTabBaritems={[diff --git a/ui/src/plugins/slots.tsx b/ui/src/plugins/slots.tsxindex 0b1e39fbe2..d0e0551572 100644--- a/ui/src/plugins/slots.tsx+++ b/ui/src/plugins/slots.tsx@@ -257,11 +257,11 @@ function getShimBlobUrl(specifier: "react" | "react-dom" | "react-dom/client" |case "sdk-ui":source = `const SDK = globalThis.__paperclipPluginBridge__?.sdkUi ?? {};- const { usePluginData, usePluginAction, useHostContext,+ const { usePluginData, usePluginAction, useHostContext, usePluginStream,MetricCard, StatusBadge, DataTable, TimeseriesChart,MarkdownBlock, KeyValueList, ActionBar, LogView, JsonTree,Spinner, ErrorBoundary } = SDK;- export { usePluginData, usePluginAction, useHostContext,+ export { usePluginData, usePluginAction, useHostContext, usePluginStream,MetricCard, StatusBadge, DataTable, TimeseriesChart,MarkdownBlock, KeyValueList, ActionBar, LogView, JsonTree,Spinner, ErrorBoundary };