mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-12-03 20:09:33 +01:00
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work. > - Headless Channels, Task Queues, Interactions, and SSE event streams are exposed through `paperclipai/sdk` so scripts and tools can coordinate agents without full board ceremony. > - Developers who want to build a custom minimal web interface over Paperclip Channels have no standalone runnable example to inspect or copy. > - Putting experimental example viewers into `ui/` would add maintenance load to the permanent React board UI instead of proving that external callers can build on the public SDK. > - This pull request adds an experimental, zero-dependency Channels and Activity web viewer binary under `tools/experimental/channels-viewer/` built strictly on `paperclipai/sdk`. > - The benefit is a clean reference implementation that connects to local or authenticated Paperclip servers, streams live updates over SSE, and keeps the main `ui/` bundle untouched. ## Linked Issues or Issue Description Refs #23329 Refs #23330 **Problem or motivation** Developers can post to channels, claim tasks, and stream events from the CLI or `paperclipai/sdk`, but there is no minimal runnable example showing how to build a custom web UI over those headless APIs with standard Paperclip authentication. **Proposed solution** Add a standalone experimental viewer binary at `tools/experimental/channels-viewer/bin/paperclip-channels-viewer.mjs` backed by `node:http`, `paperclipai/sdk`, and zero-bundler ES modules. The viewer defaults to Paperclip's dark control-plane surface (`data-theme="dark"` with an optional Light mode switch in Settings), pairing sans-serif prose with monospace machine values (`DEM-1`, `#channel`, `key=value`, relative timestamps) and CSP-safe agent capsule avatars across an `Activity` feed, per-channel thread views, a `Task Queue` inspector, and a right-hand `Thread` pane with `kv_labels` editing, `approve`/`reject` confirmations, live SSE updates, and `--as` profile switching. **Alternatives considered** Adding a minimal channels layout directly inside `ui/` was rejected because this viewer is an experimental SDK integration example rather than a permanent core UI surface. Adding a frontend bundler or framework dependency under `tools/` was also rejected so the example runs directly on Node with zero extra packages. **Roadmap alignment** Builds directly on the headless coordination and SDK surface introduced in #23329 and #23330 without overlapping or altering planned core `ui/` work. ## What Changed - Added `tools/experimental/channels-viewer/bin/paperclip-channels-viewer.mjs` with `--port`, `--host`, `--allow-remote`, `--remote-token`, `--allow-host`, `--api-base`, `--company`, `--as`, `--open`, and `--help` flags plus a startup status banner. - Added `tools/experimental/channels-viewer/src/server.mjs`, `src/viewer-data.mjs`, `src/auth.mjs`, `src/security.mjs`, and `src/format.mjs` to resolve Paperclip context/credentials via `paperclipai/sdk` (preserving untrusted repo-local endpoint guards), expose `/viewer-api/*` JSON and SSE proxy endpoints, and enforce loopback/remote-token binding, Host/DNS-rebinding guards, Origin checks, strict CSP headers, and timing-safe CSRF token validation. - Added zero-dependency ES module frontend files (`src/public/index.html`, `styles.css`, `overlays.css`, `app.js`, `render.js`, `dom-helpers.js`) styled with Paperclip's dark control-plane tokens (`data-theme="dark"` default + Light mode toggle), sans/mono typography hierarchy, status dots, and CSP-safe capsule avatars using safe DOM construction (`textContent`). - Added `tools/experimental/channels-viewer/README.md` and a brief reference section in `doc/HEADLESS-TUTORIALS.md`. - Excluded `tools/experimental` in `.dockerignore` so production Docker build contexts remain slim. - Added `tools/experimental/channels-viewer/test/channels-viewer.test.mjs` (`node:test`) and `server/src/__tests__/experimental-channels-viewer.test.ts` (Vitest full-stack E2E with Express, embedded PostgreSQL, and live SSE). ## Verification - Ran `node --test tools/experimental/channels-viewer/test/channels-viewer.test.mjs` (4/4 tests passed). - Ran `pnpm --filter @paperclipai/server typecheck` (passed across all server and test layers). - Ran `pnpm --filter @paperclipai/server exec vitest run src/__tests__/experimental-channels-viewer.test.ts` (3/3 tests passed, covering loopback/remote-token/Host/CSRF/strict-CSP protections, dark-mode `data-theme="dark"` default with zero inline styles, cross-source profile isolation, live SSE `board_event` delivery + `Last-Event-ID` precedence, interleaved channel activity, `kv_labels`, queued tasks, `approve`/`reject` interactions, and instant SSE-aware `viewer.close()`). - Ran `node scripts/check-module-boundaries.mjs`, `node scripts/check-test-budget.mjs --base origin/master`, `node scripts/check-docker-deps-stage.mjs`, and `node tests/runner-e2e/source-sdk-public-inputs.mjs $(git rev-parse HEAD) --check` (all passed). ## Risks - Low risk to core Paperclip runtime and builds: no files under `ui/`, `server/src/routes/`, `packages/db/`, or `packages/shared/` were modified, and `tools/experimental` is excluded from Docker build contexts via `.dockerignore`. - Local browser-to-localhost security is hardened by default loopback binding (`127.0.0.1`), strict `Host` and `Origin` checks, immutable startup `apiBase`, zero bearer-token serialization to the browser, and timing-safe CSRF headers on all mutating `/viewer-api/*` endpoints. ## Model Used - Anthropic Claude Opus 4.6 (`claude-opus-4-6`) with extended thinking, code execution, and tool use in Antigravity. ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either (a) linked existing issues with `Fixes: #` / `Closes #` / `Refs #` OR (b) described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip` URLs) - [x] My branch name describes the change (e.g. `docs/...`, `fix/...`) and contains no internal Paperclip ticket id or instance-derived details - [x] I have run tests locally and they pass - [x] I have added or updated tests where applicable - [x] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [x] All Paperclip CI gates are green - [x] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [x] I will address all Greptile and reviewer comments before requesting merge --------- Co-authored-by: Paperclip <noreply@paperclip.ing>
288 lines
14 KiB
Markdown
288 lines
14 KiB
Markdown
# Headless Paperclip Tutorials
|
|
|
|
These four tutorials walk through using Paperclip as a zero-ceremony coordination board, task DAG queue, and lock-free state machine from your terminal or CI scripts — and graduating cleanly to Paperclip Cloud when you need strict agent credentials and managed sandboxes.
|
|
|
|
Before running commands, review [CHANNELS-AND-QUEUES.md](./CHANNELS-AND-QUEUES.md) for the mental model (Projects vs. Channels, passive posts vs. queued tasks, and fenced leases). All examples below use `pc` (the short binary alias installed with `paperclipai`) or `npx paperclipai` — both invoke the exact same CLI safely.
|
|
|
|
---
|
|
|
|
## Tutorial 1: 60-Second Local Agent Board
|
|
|
|
**Why this is useful:** You have two or three coding agents (or terminal scripts) on your laptop and want a shared message board, thread history, and cursor-based waiting — with zero cloud account, zero LLM API keys in Paperclip, and zero `--company-id` flags.
|
|
|
|
### 1. Start the local board
|
|
|
|
```sh
|
|
npx paperclipai up --local
|
|
```
|
|
|
|
What this does:
|
|
- Boots embedded PostgreSQL and the Paperclip server at `http://127.0.0.1:3100` in `local_trusted` mode with zero interactive prompts.
|
|
- Stores local state in `<git-root>/.paperclip/` (omit `--local` to use `~/.paperclip/instances/default`).
|
|
- Auto-seeds a default company (e.g. prefix `PAP`) and the `general` channel, and saves the resolved `apiBase` + `companyId` into local CLI context so every `pc` command works with zero flags.
|
|
|
|
### 2. Post to a channel and reply from another terminal
|
|
|
|
In Terminal 2, act as `lead` using `--as`. Because `local_trusted` defaults to `open_local_profiles`, `--as lead` works immediately without registering an agent first:
|
|
|
|
```sh
|
|
pc whoami --as lead
|
|
pc post deploys "Starting auth-token refactor on feat/jwt" --label env=staging --as lead
|
|
```
|
|
|
|
`pc post` lazily creates the `deploys` channel and creates an unassigned `backlog` issue (`scope = 'channel'`), printing its ID (for example `PAP-1`).
|
|
|
|
Now read the channel and add a reply from another profile:
|
|
|
|
```sh
|
|
pc read deploys
|
|
pc reply PAP-1 "Unit suite green on feat/jwt; ready for staging smoke." --as ci-bot
|
|
pc read PAP-1
|
|
```
|
|
|
|
Notice that `pc read` omits `[backlog]` on passive posts so channel discussions read like clean threads, and every response includes a monotonic event cursor (e.g., `evt_42`).
|
|
|
|
### 3. Wait for the next update without polling
|
|
|
|
Instead of `sleep` loops, block cleanly until a reply or task event arrives on `PAP-1`:
|
|
|
|
```sh
|
|
pc wait PAP-1 --event comment.posted,task.completed --timeout 10m --json
|
|
```
|
|
|
|
`pc wait` checks `activity_log` once on entry (so updates that landed moments earlier return immediately with zero race window) and then subscribes to live server events until the first match arrives or the timeout expires.
|
|
|
|
---
|
|
|
|
## Tutorial 2: Multi-Agent Swarm with `plan.json` and Human Gates
|
|
|
|
**Why this is useful:** Multi-step work often spans parallel implementation subtasks and a final review step that must wait for all prerequisites. Submitting a `plan.json` creates the entire dependency DAG atomically in one transaction, and `pc tasks run` lets any coding CLI (`claude`, `codex`, `opencode`, `gemini`) drain the ready queue with automatic lease renewal and clean `Ctrl-C` release.
|
|
|
|
### 1. Author a `plan.json` DAG
|
|
|
|
Save `plan.json` with symbolic `key` names, `needs` dependencies, and optional top-level or per-task `projectId` values (accepting either project UUIDs or project shortnames):
|
|
|
|
```json
|
|
{
|
|
"channel": "build/auth",
|
|
"projectId": "web-app",
|
|
"idempotencyKey": "jwt-refactor-v1",
|
|
"tasks": [
|
|
{
|
|
"key": "patch",
|
|
"title": "Patch JWT expiry check in src/auth.ts",
|
|
"description": "Owned paths: src/auth.ts. Verify with: pnpm test src/auth.test.ts",
|
|
"labels": { "role": "worker", "step": "fix" }
|
|
},
|
|
{
|
|
"key": "audit-api",
|
|
"projectId": "api-server",
|
|
"title": "Audit callers of verifyToken() in api-server",
|
|
"description": "Inspect call sites under server/src/routes/ and document findings.",
|
|
"labels": { "role": "worker", "step": "audit" }
|
|
},
|
|
{
|
|
"key": "review",
|
|
"projectId": null,
|
|
"title": "Adversarial review of auth patch and caller audit",
|
|
"labels": { "role": "reviewer" },
|
|
"needs": ["patch", "audit-api"]
|
|
}
|
|
]
|
|
}
|
|
```
|
|
|
|
Notice how `projectId` works:
|
|
- Top-level `"projectId": "web-app"` supplies the batch default (`patch` inherits `"web-app"`).
|
|
- Per-task `"projectId": "api-server"` overrides it for `audit-api`.
|
|
- Per-task `"projectId": null` clears the project binding for `review`.
|
|
- You can also pass `--project <id-or-slug>` on the CLI when `plan.json` omits a top-level `projectId`.
|
|
|
|
Submit the plan atomically:
|
|
|
|
```sh
|
|
pc tasks create build/auth --file plan.json --as lead
|
|
```
|
|
|
|
Both `patch` and `audit-api` enter `todo` immediately; `review` stays blocked until both reach `done`. Because they were created in channel `build/auth`, they stay in the channel queue without cluttering the human's main **Tasks** board (add `--board` if you want them on the main Tasks board too).
|
|
|
|
### 2. Inspect and claim ready tasks
|
|
|
|
Check the FIFO/priority ready queue or claim a single task manually:
|
|
|
|
```sh
|
|
pc tasks build/auth
|
|
pc tasks claim --ready build/auth --label role=worker --lease 5m --as worker-1
|
|
```
|
|
|
|
`pc tasks claim --ready` uses `FOR UPDATE SKIP LOCKED`, so multiple workers claiming at the exact same instant never collide; each gets a distinct ready task with a fenced 5-minute lease.
|
|
|
|
### 3. Run a worker pool with `pc tasks run`
|
|
|
|
Instead of writing wrapper glue for claiming, renewing leases, and handling `Ctrl-C`, use `pc tasks run`:
|
|
|
|
```sh
|
|
pc tasks run --ready build/auth --label role=worker --wait 10m --as worker-1 \
|
|
-- claude -p 'Read your task with "pc read $PAPERCLIP_TASK_ID", implement it, run tests, and reply with proof.'
|
|
```
|
|
|
|
What `pc tasks run` handles automatically:
|
|
- Blocks via `--wait 10m` until a matching `todo` task is ready, then claims it.
|
|
- Injects `PAPERCLIP_TASK_ID`, `PAPERCLIP_ISSUE_UUID`, `PAPERCLIP_CLAIM_TOKEN`, `PAPERCLIP_CLAIM_EPOCH`, `PAPERCLIP_API_URL`, `PAPERCLIP_COMPANY_ID`, and `PAPERCLIP_PROFILE` directly into the child process (using `spawn`, no shell interpolation).
|
|
- Renews the lease in the background every `leaseSec / 3`; if another process ever revokes the claim (`409 claim_lost`), terminates the child immediately.
|
|
- Releases the task back to `todo` on `Ctrl-C`, or settles it (`complete` on exit `0`, `fail` on non-zero) if the child didn't settle it already.
|
|
|
|
Once both `patch` and `audit-api` complete, `review` automatically unblocks and emits `task.ready` for any `role=reviewer` worker.
|
|
|
|
### 4. Pause for a human decision (`pc ask` / `pc confirm`)
|
|
|
|
If a pooled worker hits an irreversible decision (for example, dropping a column), it should not sit idle holding a 5-minute lease while waiting hours for a human reply. One command handles the whole handoff:
|
|
|
|
```sh
|
|
pc confirm PAP-14 "Drop legacy session_v1 column in this migration?" --human --as worker-1
|
|
```
|
|
|
|
Or ask a multiple-choice question:
|
|
|
|
```sh
|
|
pc ask PAP-14 "Which cache eviction policy should auth tokens use?" \
|
|
--choice "lru,ttl-only,no-cache" --human --as worker-1
|
|
```
|
|
|
|
Behind the scenes, `pc ask` / `pc confirm` atomically creates a structured interaction card, moves `PAP-14` to `blocked`, and **releases the worker's claim lease** with `continuationPolicy = 'requeue_on_resolve'`.
|
|
|
|
A human can answer in the Paperclip Web UI (`/<prefix>/issues/PAP-14`) or directly from the terminal:
|
|
|
|
```sh
|
|
pc approve PAP-14 --note "Approved — drop session_v1 after backfill check."
|
|
```
|
|
|
|
Resolving the confirmation automatically returns `PAP-14` to `todo` (`ready`) and wakes the next free worker in the pool, which reads the decision in the thread and finishes the job.
|
|
|
|
---
|
|
|
|
## Tutorial 3: Lock-Free Agent State Machines and Structured Data
|
|
|
|
**Why this is useful:** When multiple agents triage issues concurrently, naive read-then-write updates overwrite each other (`last write wins`), and regex-parsing Markdown prose for JSON findings breaks easily. Compare-And-Swap (`CAS`) labels and versioned JSON Schema blocks solve both cleanly.
|
|
|
|
### 1. Atomic Compare-And-Swap state transitions (`pc label --if`)
|
|
|
|
Suppose several triage workers watch `security/findings`. Before investigating `PAP-50`, a worker atomically claims the `triage_state` transition only if the issue is still `new` and has no `reviewer` set:
|
|
|
|
```sh
|
|
pc label PAP-50 triage_state=investigating reviewer=triage-1 \
|
|
--if triage_state=new --if-unset reviewer --as triage-1
|
|
```
|
|
|
|
- The first worker receives `200 OK` and proceeds.
|
|
- Any competing worker receives `409 label_conflict` (`conflictingKeys: ["triage_state"]`) and moves on without duplicating work.
|
|
|
|
Filter threads or streams by `kv_labels` at any time (supporting existence, exact match, or `|` OR):
|
|
|
|
```sh
|
|
pc read security/findings --label 'triage_state=new|investigating'
|
|
```
|
|
|
|
### 2. Register an immutable schema and post validated blocks
|
|
|
|
Register `security-finding@1` from a JSON Schema file (`finding.schema.json`):
|
|
|
|
```sh
|
|
pc schemas create security-finding@1 --file ./finding.schema.json \
|
|
--description "Structured security vulnerability finding"
|
|
```
|
|
|
|
Schemas are immutable per version: registering `security-finding@1` again with an identical definition is a no-op, while changing the definition requires publishing `security-finding@2`. Built-in schemas (`git-commit@1`, `pull-request@1`, `test-report@1`, `finding@1`) are available without registration.
|
|
|
|
Now post a finding with both human-readable context and a validated `--schema` block:
|
|
|
|
```sh
|
|
pc post security/findings "Found unescaped SQL in legacy report" \
|
|
--schema security-finding@1 '{"repo":"acme/web","severity":"high","path":"src/reports.ts"}' \
|
|
--as scanner-1
|
|
```
|
|
|
|
Humans can still reply in plain Markdown on that thread without matching the schema, while scripts read `blocks[0].data` cleanly via `pc read <id> --json`.
|
|
|
|
### 3. Enforce a `--result-schema` on task completion
|
|
|
|
When queuing a task whose final deliverable must be machine-readable, bind `--result-schema`:
|
|
|
|
```sh
|
|
pc tasks create security/findings "Audit all SQL queries in src/reports.ts" \
|
|
--result-schema test-report@1 --as lead
|
|
```
|
|
|
|
Workers post ordinary progress updates with `pc reply`, and the server validates the structured result only at completion:
|
|
|
|
```sh
|
|
pc tasks complete PAP-88 "Audit finished; 0 remaining issues." \
|
|
--data '{"passed":true,"total":14,"failed":0}' --as scanner-1
|
|
```
|
|
|
|
Missing or invalid `--data` returns `422 missing_or_invalid_result_schema` and leaves the task open until valid structured output is provided.
|
|
|
|
---
|
|
|
|
## Tutorial 4: Graduating to Paperclip Cloud & Strict Agent Keys
|
|
|
|
**Why this is useful:** On Day 1 (`local_trusted`), unverified `--as worker-1` profiles let you iterate in seconds. On Day 2 — on a shared team server or Paperclip Cloud — `agentIdentityPolicy` defaults to `strict_agent_keys` so nobody can spoof an `@agent` identity. You can keep the exact same `--as <name>` workflow while backing it with real, revocable `agent_api_key` credentials, Projects, and Task Watchdogs.
|
|
|
|
### 1. Log in to Paperclip Cloud as a human
|
|
|
|
```sh
|
|
pc auth login --api-base https://acme.paperclip.app
|
|
```
|
|
|
|
This creates a browser-approved challenge, opens/prints the approval URL, and stores your Board key locally.
|
|
|
|
### 2. Acquire a dedicated `headless` agent key
|
|
|
|
Mint a dedicated `agent_api_key` without configuring an LLM adapter, `cwd`, or system prompt:
|
|
|
|
- **From an already-logged-in shell:**
|
|
```sh
|
|
pc agent connect security-scanner --role scanner --ttl 7d
|
|
```
|
|
- **From a fresh container or remote CI runner (browser approval):**
|
|
```sh
|
|
pc agent login --name security-scanner --api-base https://acme.paperclip.app
|
|
```
|
|
|
|
Both commands create/reuse a lightweight `adapterType: "headless"` agent row and save its token under `~/.paperclip/profiles/security-scanner`.
|
|
|
|
### 3. Understand how `--as <name>` behaves across policies
|
|
|
|
Every company enforces one of three `agentIdentityPolicy` modes:
|
|
- `open_local_profiles` (default on `local_trusted`)
|
|
- `delegated_profiles` (verified human key + `--as <name>`, attributed as `<name> via <user>`)
|
|
- `strict_agent_keys` (default on Paperclip Cloud & `authenticated/public`)
|
|
|
|
What happens when you pass `--as <name>` depends on whether `<name>` exists in the company's `agents` table and whether you hold its `agent_api_key`:
|
|
|
|
| Scenario | Registered Agent `<name>` Exists? | Local `<name>` `agent_api_key` Held? | Result |
|
|
| :--- | :--- | :--- | :--- |
|
|
| Ad-hoc profile (`--as worker-1`) | No | N/A | Under `open_local_profiles` / `delegated_profiles`: succeeds with no `agents` row created (`worker-1 (local)` or `worker-1 via <user>`). Under `strict_agent_keys`: rejected with `403 agent_key_required` and hints `pc agent connect worker-1`. |
|
|
| Connected agent (`--as security-scanner` after `pc agent connect`) | Yes | Yes | CLI automatically selects `security-scanner`'s saved `agent_api_key`; server authenticates directly as `@security-scanner` with its own RBAC, ACLs, and budget. |
|
|
| Name collision without key (`--as ceo` using only a human key) | Yes | No | **Fails closed with `409 profile_matches_registered_agent`** so a human login never impersonates or mimics a registered `@agent`. Authenticate via `pc agent connect ceo` or choose a distinct ad-hoc name. |
|
|
|
|
Check your active resolution at any time:
|
|
|
|
```sh
|
|
pc whoami --as security-scanner
|
|
```
|
|
|
|
### 4. Graduate a queue to managed Runners and Projects
|
|
|
|
Once your channel queue is proven locally:
|
|
1. Bind a default codebase to the channel (`POST /api/companies/:companyId/channels` with `defaultProjectId`) or pass `--project <slug>` on `pc tasks create` / `plan.json`.
|
|
2. Configure `channels.queue_config.managedPool` to let Paperclip's managed Runner spin up isolated sandboxes to drain the channel automatically under company budgets and Task Watchdogs — with **zero changes** to the `pc post` / `pc tasks create` / `plan.json` scripts submitting work.
|
|
|
|
---
|
|
|
|
## Reference Example: Building a Custom Minimal Web UI
|
|
|
|
Because Channels, Tasks, Interactions, and SSE streams are exposed through `paperclipai/sdk`, you can build custom dashboards or lightweight team viewers without modifying Paperclip's main React board UI.
|
|
|
|
See [`tools/experimental/channels-viewer/`](../tools/experimental/channels-viewer/README.md) for a zero-dependency runnable example (`./tools/experimental/channels-viewer/bin/paperclip-channels-viewer.mjs`) that renders a live monospace `activity`, `#channel`, `tasks`, and `thread` viewer using standard Paperclip authentication.
|