mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-11-24 14:20:12 +01:00
feat(connections): live setup progress from the person's own agent (#22626)
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work > - Several setup screens offer "Set it up with your agent": a prompt the person pastes into their own agent (Claude Code, Codex) to do the setup on their computer. AWS role setup is the newest > - Once the prompt is copied, the setup page goes quiet: the person cannot see what their agent is doing or when it is done, and has to switch windows to find out > - The agent already runs commands, so it can report its progress back if we give it a safe place to send it > - This pull request adds a live checklist the agent fills in: the page creates it, the prompt gives the agent curl commands with a token, and the page shows every update as it happens > - The benefit is a setup that shows its own progress, and a reusable piece any "Set it up with your agent" screen can use ## Linked Issues or Issue Description Refs #22233 (the AWS setup screen this extends). **Subsystem affected** Connections (agent-guided setup), live updates, a new public agent API, UI. **Problem or motivation** After a person copies a setup prompt into their own agent, Paperclip shows nothing until they come back and paste a result. There is no way for the agent to say what it is doing. **Proposed solution** A setup checklist a person's own agent writes to, shown live on the setup page. The agent's requests need no Paperclip sign-in, so they carry a narrow, expiring bearer token. Paperclip Cloud needs no front-door change: it already forwards `/api` requests that carry an `Authorization` header to the workspace without Cloud identity (its machine-request lane), and these always do. **Alternatives considered** - Polling the page instead of live events: slower and adds load to every open setup page. The page uses the existing live-event channel, with a 20-second backup refresh while the agent works. - Putting the token in the URL: URLs end up in logs. The token goes in the `Authorization` header. - Letting the agent set the role ARN itself: the person still pastes it (as decided for #22233). The agent's finish summary shows the ARN to copy. ## What Changed - `packages/db`: new `agent_setup_progress` table (company-scoped, purpose and subject, token hash, items, status, summary, update count, expiry). Migration `0501` is idempotent. - `packages/shared`: `agent-setup-progress` types, limits and validators; new live event type `agent_setup_progress.updated`. - `server`: - `agentSetupProgressService`: create (random `pcsp_` token, only its SHA-256 kept), read, and the agent's set-checklist, update-item and finish. Tokens are compared in constant time; a write is refused after expiry (6 hours) or 300 updates, and concurrent writes are guarded by the update counter. Finishing `done` ticks off open steps. - Routes: board-only `POST /api/companies/{companyId}/agent-setup-progress` and `GET /api/agent-setup-progress/{id}`; agent routes `PUT …/checklist`, `POST …/items/{key}` and `POST …/finish` mounted with the other public routes. Activity entries for created, started and finished. - Each agent write publishes `agent_setup_progress.updated`; the live-events socket forwards it with only the checklist ID. - OpenAPI entries for all five routes. - `ui`: - Reusable `ui/src/components/AgentSetupProgress.tsx`: `useAgentSetupProgress` (creates one checklist per setup and follows it), `agentSetupProgressInstructions` (the prompt section with the agent's curl commands) and `AgentSetupProgressPanel` (waiting, working, done and failed states, using the task status glyphs). - `LiveUpdatesProvider` refreshes the checklist on its live event. - AWS role step: one step (no numbering) with the prompt, the live checklist and the Role ARN field. The prompt starts with the progress instructions and asks the agent to put the role ARN in its finish summary. - Docs: `docs/api/agent-setup-progress.md` (API and how to add it to another page) and the AWS setup section. - Storybook: AWS step in waiting, working, done and failed states, and the panel on its own. ## Verification - `server/src/__tests__/agent-setup-progress.test.ts` (real routes, embedded Postgres): set, update and finish with the prompt's token; only the hash is stored; four live events carry the checklist ID; activity entries. Refusals: missing token, wrong token, another checklist's token (401), bad key (400), unknown item (404), update limit (429), expired (410). Company boundary: another company's member gets 403 on read and create. - `live-events-toast.test.ts`: the socket delivers the event with only `{ progressId }`. It failed before the socket fix (red/green), which an end-to-end run found. - `AgentSetupProgress.test.tsx`: the prompt section's exact commands; the hook creates one checklist and the panel follows waiting → working → done on live refreshes. - `AwsRoleSetup.test.tsx`: the step creates the checklist for its connection, waits for the agent, and the prompt leads with progress reporting. - Totals: shared 1362, server (new, OpenAPI, live events, AWS) 101, UI (components, connections, apps, live updates) 1469. Typecheck clean for db, shared, server and UI (except Storybook's generated catalog, not built in this worktree). - End to end on a local instance: Playwright opened the real AWS setup step, read the prompt, sent the agent's requests with its token, and the page showed each update within 1.5 seconds (inside the 20-second backup refresh, so from live events) through "Your agent set up AWS" with the role ARN summary. No page errors. - Not run yet: Paperclip Cloud staging (after deploy) and an agent running the prompt on its own. ## Risks - New anonymous routes. The token is the only credential: 32 random bytes, stored as a hash, scoped to one checklist, six hours, 300 updates. Text from the agent is shown as plain text (no links or markup), so the worst a leaked token can do is change one checklist's wording until it expires. - One new table and migration (idempotent). - Live delivery is per server process, like every other live event; the 20-second refresh covers a missed event. > For core feature work, check [`ROADMAP.md`](ROADMAP.md) first and discuss it in `#dev` before opening the PR. Feature PRs that overlap with planned core work may need to be redirected — check the roadmap first. See `CONTRIBUTING.md`. ## Model Used - Claude Opus 5.5 (`claude-opus-5-5`) in Claude Code, with tool use (shell, file edits, Storybook and Playwright screenshots, the in-app browser against a local dev server). ## 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 - [ ] All Paperclip CI gates are green - [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [x] I will address all Greptile and reviewer comments before requesting merge 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> Co-authored-by: Paperclip <noreply@paperclip.ing>
This commit is contained in:
36 files changed
+2580
-41
No files matched your search
@@ -0,0 +1,251 @@
|
||||
import { randomUUID } from "node:crypto";
|
||||
import { afterAll, beforeAll, describe, expect, it, vi } from "vitest";
|
||||
import express from "express";
|
||||
import request from "supertest";
|
||||
import { eq, inArray } from "drizzle-orm";
|
||||
import { activityLog, agentSetupProgress, companies, companyMemberships, createDb, principalPermissionGrants, toolApplications, toolConnections } from "@paperclipai/db";
|
||||
import { AGENT_SETUP_PROGRESS_LIMITS, type AgentSetupProgressHandoff, type LiveEvent } from "@paperclipai/shared";
|
||||
import { startEmbeddedPostgresTestDatabase } from "./helpers/embedded-postgres.js";
|
||||
import { agentSetupProgressAgentRoutes, agentSetupProgressBoardRoutes } from "../routes/agent-setup-progress.js";
|
||||
import { subscribeCompanyLiveEvents } from "../services/live-events.js";
|
||||
import { agentSetupProgressService } from "../services/agent-setup-progress.js";
|
||||
import { errorHandler } from "../middleware/error-handler.js";
|
||||
|
||||
const userId = "setup-progress-user";
|
||||
|
||||
describe("agent setup progress", () => {
|
||||
let fixture: Awaited<ReturnType<typeof startEmbeddedPostgresTestDatabase>>;
|
||||
let db: ReturnType<typeof createDb>;
|
||||
|
||||
beforeAll(async () => {
|
||||
vi.stubEnv("PAPERCLIP_PUBLIC_URL", "https://acme.paperclip.app");
|
||||
fixture = await startEmbeddedPostgresTestDatabase("agent-setup-progress-");
|
||||
db = createDb(fixture.connectionString);
|
||||
}, 120_000);
|
||||
afterAll(async () => {
|
||||
await fixture?.cleanup();
|
||||
vi.unstubAllEnvs();
|
||||
});
|
||||
|
||||
async function company() {
|
||||
const [row] = await db.insert(companies).values({ name: `Setup ${randomUUID()}`, issuePrefix: `S${randomUUID().slice(0, 5)}` }).returning();
|
||||
await db.insert(companyMemberships).values({ companyId: row!.id, principalType: "user", principalId: userId, status: "active", membershipRole: "admin" });
|
||||
const [application] = await db.insert(toolApplications).values({ companyId: row!.id, name: "AWS", type: "mcp_http" }).returning();
|
||||
const [connection] = await db.insert(toolConnections).values({
|
||||
companyId: row!.id, applicationId: application!.id, name: "AWS", uid: `aws-${randomUUID()}`, transport: "mcp_remote", createdByUserId: userId,
|
||||
}).returning();
|
||||
return { ...row!, connectionId: connection!.id, applicationId: application!.id };
|
||||
}
|
||||
|
||||
/** The real app splits these: the agent's routes need no sign-in, the board's do. */
|
||||
function app(boardCompanyIds: string[], actorUserId = userId) {
|
||||
const server = express();
|
||||
server.use(express.json());
|
||||
server.use(agentSetupProgressAgentRoutes(db));
|
||||
const api = express.Router();
|
||||
api.use((req, _res, next) => {
|
||||
req.actor = { type: "board", userId: actorUserId, source: "session", companyIds: boardCompanyIds, isInstanceAdmin: false } as Express.Request["actor"];
|
||||
next();
|
||||
});
|
||||
api.use(agentSetupProgressBoardRoutes(db));
|
||||
server.use("/api", api);
|
||||
server.use(errorHandler);
|
||||
return server;
|
||||
}
|
||||
|
||||
const path = (url: string) => new URL(url).pathname;
|
||||
|
||||
it("lets the agent set and tick off its checklist with the prompt's token, live, then finish", async () => {
|
||||
const org = await company();
|
||||
const server = app([org.id]);
|
||||
const created = await request(server).post(`/api/companies/${org.id}/agent-setup-progress`)
|
||||
.send({ purpose: "aws_connection", subjectId: org.connectionId }).expect(201);
|
||||
const handoff = created.body as AgentSetupProgressHandoff;
|
||||
expect(handoff.progress).toMatchObject({ status: "waiting", items: [], purpose: "aws_connection", subjectId: org.connectionId });
|
||||
expect(handoff.urls.checklist).toBe(`https://acme.paperclip.app/api/agent-setup-progress/${handoff.progress.id}/checklist`);
|
||||
expect(handoff.urls.item).toContain("/items/{key}");
|
||||
expect(handoff.token).toMatch(/^pcsp_/);
|
||||
// Only the token's hash is stored.
|
||||
const [stored] = await db.select().from(agentSetupProgress).where(eq(agentSetupProgress.id, handoff.progress.id));
|
||||
expect(stored!.tokenHash).not.toContain(handoff.token);
|
||||
|
||||
const events: LiveEvent[] = [];
|
||||
const stop = subscribeCompanyLiveEvents(org.id, (event) => events.push(event));
|
||||
const auth = { Authorization: `Bearer ${handoff.token}` };
|
||||
await request(server).put(path(handoff.urls.checklist)).set(auth).send({ items: [
|
||||
{ key: "check-account", title: "Check the AWS account" },
|
||||
{ key: "deploy-stack", title: "Create the role" },
|
||||
] }).expect(200);
|
||||
const item = (key: string) => path(handoff.urls.item.replace("{key}", key));
|
||||
await request(server).post(item("check-account")).set(auth).send({ status: "done", detail: "Account 123456789012" }).expect(200);
|
||||
const working = await request(server).post(item("deploy-stack")).set(auth).send({ status: "in_progress" }).expect(200);
|
||||
expect(working.body).toMatchObject({ status: "in_progress", items: [
|
||||
{ key: "check-account", status: "done", detail: "Account 123456789012" },
|
||||
{ key: "deploy-stack", status: "in_progress", detail: null },
|
||||
] });
|
||||
// Every step ticked off is still in progress: only the finish carries the summary, and the page keeps refreshing until it.
|
||||
// A detail is kept when omitted and cleared with null, so a retry can drop an earlier error.
|
||||
const keptDetail = await request(server).post(item("check-account")).set(auth).send({ status: "done" }).expect(200);
|
||||
expect(keptDetail.body.items[0].detail).toBe("Account 123456789012");
|
||||
await request(server).post(item("deploy-stack")).set(auth).send({ status: "failed", detail: "Access denied" }).expect(200);
|
||||
const cleared = await request(server).post(item("deploy-stack")).set(auth).send({ status: "in_progress", detail: null }).expect(200);
|
||||
expect(cleared.body.items[1].detail).toBeNull();
|
||||
const ticked = await request(server).post(item("deploy-stack")).set(auth).send({ status: "done" }).expect(200);
|
||||
expect(ticked.body.status).toBe("in_progress");
|
||||
const finished = await request(server).post(path(handoff.urls.finish)).set(auth)
|
||||
.send({ status: "done", summary: "Role ARN: arn:aws:iam::123456789012:role/paperclip-conn-1" }).expect(200);
|
||||
// Finishing done ticks off what is left.
|
||||
expect(finished.body).toMatchObject({ status: "done", summary: "Role ARN: arn:aws:iam::123456789012:role/paperclip-conn-1",
|
||||
items: [{ status: "done" }, { status: "done" }] });
|
||||
stop();
|
||||
const progressEvents = events.filter((event) => event.type === "agent_setup_progress.updated");
|
||||
expect(progressEvents).toHaveLength(8);
|
||||
expect(progressEvents.every((event) => event.payload.progressId === handoff.progress.id)).toBe(true);
|
||||
|
||||
const read = await request(server).get(`/api/agent-setup-progress/${handoff.progress.id}`).expect(200);
|
||||
expect(read.body.status).toBe("done");
|
||||
const actions = (await db.select().from(activityLog).where(eq(activityLog.entityId, handoff.progress.id))).map((row) => row.action).sort();
|
||||
// Every change is on the activity history, and no entry holds the token.
|
||||
expect(actions).toEqual([
|
||||
"agent_setup_progress.created", "agent_setup_progress.finished",
|
||||
"agent_setup_progress.item_updated", "agent_setup_progress.item_updated", "agent_setup_progress.item_updated",
|
||||
"agent_setup_progress.item_updated", "agent_setup_progress.item_updated", "agent_setup_progress.item_updated",
|
||||
"agent_setup_progress.started",
|
||||
]);
|
||||
const history = await db.select().from(activityLog).where(eq(activityLog.entityId, handoff.progress.id));
|
||||
expect(JSON.stringify(history)).not.toContain(handoff.token);
|
||||
});
|
||||
|
||||
it("refuses a missing or wrong token, an unknown item, an expired checklist and too many updates", async () => {
|
||||
const org = await company();
|
||||
const server = app([org.id]);
|
||||
const handoff = (await request(server).post(`/api/companies/${org.id}/agent-setup-progress`).send({ purpose: "aws_connection", subjectId: org.connectionId }).expect(201)).body as AgentSetupProgressHandoff;
|
||||
const checklist = path(handoff.urls.checklist);
|
||||
const items = { items: [{ key: "step-1", title: "Step one" }] };
|
||||
await request(server).put(checklist).send(items).expect(401);
|
||||
await request(server).put(checklist).set({ Authorization: "Bearer pcsp_wrong" }).send(items).expect(401);
|
||||
// A real token for another checklist opens nothing else.
|
||||
const other = (await request(server).post(`/api/companies/${org.id}/agent-setup-progress`).send({ purpose: "aws_connection", subjectId: org.connectionId }).expect(201)).body as AgentSetupProgressHandoff;
|
||||
await request(server).put(checklist).set({ Authorization: `Bearer ${other.token}` }).send(items).expect(401);
|
||||
|
||||
const auth = { Authorization: `Bearer ${handoff.token}` };
|
||||
await request(server).put(checklist).set(auth).send({ items: [{ key: "Bad Key", title: "x" }] }).expect(400);
|
||||
await request(server).put(checklist).set(auth).send(items).expect(200);
|
||||
await request(server).post(path(handoff.urls.item.replace("{key}", "nope"))).set(auth).send({ status: "done" }).expect(404);
|
||||
|
||||
await db.update(agentSetupProgress).set({ updateCount: AGENT_SETUP_PROGRESS_LIMITS.maxUpdates }).where(eq(agentSetupProgress.id, handoff.progress.id));
|
||||
await request(server).put(checklist).set(auth).send(items).expect(429);
|
||||
await db.update(agentSetupProgress).set({ updateCount: 0, expiresAt: new Date(Date.now() - 1000) }).where(eq(agentSetupProgress.id, handoff.progress.id));
|
||||
await request(server).put(checklist).set(auth).send(items).expect(410);
|
||||
});
|
||||
|
||||
it("finishes as failed, keeps finished final, never loses a concurrent update, and cleans up old checklists", async () => {
|
||||
const org = await company();
|
||||
const server = app([org.id]);
|
||||
const create = async () => (await request(server).post(`/api/companies/${org.id}/agent-setup-progress`).send({ purpose: "aws_connection", subjectId: org.connectionId }).expect(201)).body as AgentSetupProgressHandoff;
|
||||
const handoff = await create();
|
||||
const auth = { Authorization: `Bearer ${handoff.token}` };
|
||||
const item = (key: string) => path(handoff.urls.item.replace("{key}", key));
|
||||
await request(server).put(path(handoff.urls.checklist)).set(auth).send({ items: [
|
||||
{ key: "a", title: "A" }, { key: "b", title: "B" }, { key: "c", title: "C" },
|
||||
] }).expect(200);
|
||||
|
||||
// Concurrent writes either land or answer 409 to be sent again: none is silently lost.
|
||||
const results = await Promise.all(["a", "b", "c"].map((key) => request(server).post(item(key)).set(auth).send({ status: "in_progress" })));
|
||||
expect(results.every((res) => res.status === 200 || res.status === 409)).toBe(true);
|
||||
const [afterRace] = await db.select().from(agentSetupProgress).where(eq(agentSetupProgress.id, handoff.progress.id));
|
||||
expect(afterRace!.updateCount).toBe(1 + results.filter((res) => res.status === 200).length);
|
||||
expect(afterRace!.items.filter((entry) => entry.status === "in_progress")).toHaveLength(results.filter((res) => res.status === 200).length);
|
||||
|
||||
await request(server).post(item("b")).set(auth).send({ status: "failed", detail: "No permission" }).expect(200);
|
||||
const failed = await request(server).post(path(handoff.urls.finish)).set(auth).send({ status: "failed", summary: "Stopped: no permission" }).expect(200);
|
||||
expect(failed.body).toMatchObject({ status: "failed", summary: "Stopped: no permission" });
|
||||
expect(failed.body.items.find((entry: { key: string }) => entry.key === "b")).toMatchObject({ status: "failed", detail: "No permission" });
|
||||
// A late or retried write cannot reopen a finished setup.
|
||||
const late = await request(server).post(item("a")).set(auth).send({ status: "done" }).expect(409);
|
||||
expect(late.body.details).toMatchObject({ code: "agent_setup_progress_finished" });
|
||||
await request(server).post(path(handoff.urls.finish)).set(auth).send({ status: "done" }).expect(409);
|
||||
|
||||
// Finishing done is the agent's verdict: every step is ticked off, including one that failed along the way.
|
||||
const second = await create();
|
||||
const auth2 = { Authorization: `Bearer ${second.token}` };
|
||||
await request(server).put(path(second.urls.checklist)).set(auth2).send({ items: [{ key: "a", title: "A" }, { key: "b", title: "B" }] }).expect(200);
|
||||
await request(server).post(path(second.urls.item.replace("{key}", "a"))).set(auth2).send({ status: "failed" }).expect(200);
|
||||
const done = await request(server).post(path(second.urls.finish)).set(auth2).send({ status: "done" }).expect(200);
|
||||
expect(done.body.items.map((entry: { status: string }) => entry.status)).toEqual(["done", "done"]);
|
||||
|
||||
// Checklists a day past expiry are removed as new ones are created; recent ones stay.
|
||||
await db.update(agentSetupProgress).set({ expiresAt: new Date(Date.now() - 25 * 3600_000) }).where(eq(agentSetupProgress.id, handoff.progress.id));
|
||||
await db.update(agentSetupProgress).set({ expiresAt: new Date(Date.now() - 3600_000) }).where(eq(agentSetupProgress.id, second.progress.id));
|
||||
// Another company's long-expired checklist is never touched by this company's cleanup.
|
||||
const other = await company();
|
||||
const foreign = (await request(app([other.id])).post(`/api/companies/${other.id}/agent-setup-progress`).send({ purpose: "aws_connection", subjectId: other.connectionId }).expect(201)).body as AgentSetupProgressHandoff;
|
||||
await db.update(agentSetupProgress).set({ expiresAt: new Date(Date.now() - 48 * 3600_000) }).where(eq(agentSetupProgress.id, foreign.progress.id));
|
||||
await create();
|
||||
expect(await db.select().from(agentSetupProgress).where(eq(agentSetupProgress.id, foreign.progress.id))).toHaveLength(1);
|
||||
expect(await db.select().from(agentSetupProgress).where(eq(agentSetupProgress.id, handoff.progress.id))).toHaveLength(0);
|
||||
expect(await db.select().from(agentSetupProgress).where(eq(agentSetupProgress.id, second.progress.id))).toHaveLength(1);
|
||||
});
|
||||
|
||||
it("clears long-expired checklists across companies once at startup, and keeps the rest", async () => {
|
||||
const first = await company();
|
||||
const second = await company();
|
||||
const make = async (org: Awaited<ReturnType<typeof company>>) => ((await request(app([org.id])).post(`/api/companies/${org.id}/agent-setup-progress`)
|
||||
.send({ purpose: "aws_connection", subjectId: org.connectionId }).expect(201)).body as AgentSetupProgressHandoff).progress.id;
|
||||
const oldA = await make(first);
|
||||
const oldB = await make(second);
|
||||
const recent = await make(second);
|
||||
await db.update(agentSetupProgress).set({ expiresAt: new Date(Date.now() - 48 * 3600_000) }).where(inArray(agentSetupProgress.id, [oldA, oldB]));
|
||||
await db.update(agentSetupProgress).set({ expiresAt: new Date(Date.now() - 3600_000) }).where(eq(agentSetupProgress.id, recent));
|
||||
// Batches of one: the sweep keeps going until no old checklist is left, not just one batch.
|
||||
expect(await agentSetupProgressService(db).sweepExpired({ batchSize: 1 })).toBeGreaterThanOrEqual(2);
|
||||
const left = (await db.select({ id: agentSetupProgress.id }).from(agentSetupProgress).where(inArray(agentSetupProgress.id, [oldA, oldB, recent]))).map((row) => row.id);
|
||||
expect(left).toEqual([recent]);
|
||||
});
|
||||
|
||||
it("does not let a cache keep the agent's token", async () => {
|
||||
const org = await company();
|
||||
const res = await request(app([org.id])).post(`/api/companies/${org.id}/agent-setup-progress`).send({ purpose: "aws_connection", subjectId: org.connectionId }).expect(201);
|
||||
expect(res.headers["cache-control"]).toBe("no-store");
|
||||
expect(res.headers.pragma).toBe("no-cache");
|
||||
});
|
||||
|
||||
it("keeps checklists inside their company", async () => {
|
||||
const org = await company();
|
||||
const outsider = await company();
|
||||
const handoff = (await request(app([org.id])).post(`/api/companies/${org.id}/agent-setup-progress`).send({ purpose: "aws_connection", subjectId: org.connectionId }).expect(201)).body as AgentSetupProgressHandoff;
|
||||
// Another company's checklist answers exactly like a missing one.
|
||||
const hidden = await request(app([outsider.id])).get(`/api/agent-setup-progress/${handoff.progress.id}`).expect(404);
|
||||
const missing = await request(app([outsider.id])).get(`/api/agent-setup-progress/${randomUUID()}`).expect(404);
|
||||
expect(hidden.body).toEqual(missing.body);
|
||||
await request(app([outsider.id])).post(`/api/companies/${org.id}/agent-setup-progress`).send({ purpose: "aws_connection", subjectId: org.connectionId }).expect(403);
|
||||
|
||||
// Inside the company: only someone who may configure the connection starts its setup,
|
||||
// and only the person who started it reads the checklist back.
|
||||
const viewerId = `viewer-${randomUUID()}`;
|
||||
await db.insert(companyMemberships).values({ companyId: org.id, principalType: "user", principalId: viewerId, status: "active", membershipRole: "viewer" });
|
||||
await request(app([org.id], viewerId)).post(`/api/companies/${org.id}/agent-setup-progress`).send({ purpose: "aws_connection", subjectId: org.connectionId }).expect(403);
|
||||
// A manager whose permission covers just this connection may set it up; one scoped to another connection may not.
|
||||
const scopedId = `scoped-${randomUUID()}`;
|
||||
const elsewhereId = `elsewhere-${randomUUID()}`;
|
||||
const [otherConnection] = await db.insert(toolConnections).values({
|
||||
companyId: org.id, applicationId: org.applicationId, name: "Other", uid: `other-${randomUUID()}`, transport: "mcp_remote", createdByUserId: userId,
|
||||
}).returning();
|
||||
await db.insert(companyMemberships).values([scopedId, elsewhereId].map((principalId) => ({ companyId: org.id, principalType: "user", principalId, status: "active", membershipRole: "member" })));
|
||||
await db.insert(principalPermissionGrants).values([
|
||||
{ companyId: org.id, principalType: "user", principalId: scopedId, permissionKey: "tools:manage_connections", scope: { connectionIds: [org.connectionId] } },
|
||||
{ companyId: org.id, principalType: "user", principalId: elsewhereId, permissionKey: "tools:manage_connections", scope: { connectionIds: [otherConnection!.id] } },
|
||||
]);
|
||||
await request(app([org.id], scopedId)).post(`/api/companies/${org.id}/agent-setup-progress`).send({ purpose: "aws_connection", subjectId: org.connectionId }).expect(201);
|
||||
await request(app([org.id], elsewhereId)).post(`/api/companies/${org.id}/agent-setup-progress`).send({ purpose: "aws_connection", subjectId: org.connectionId }).expect(403);
|
||||
const otherMember = await request(app([org.id], viewerId)).get(`/api/agent-setup-progress/${handoff.progress.id}`).expect(404);
|
||||
expect(otherMember.body).toEqual(missing.body);
|
||||
const own = await request(app([org.id])).get(`/api/agent-setup-progress/${handoff.progress.id}`).expect(200);
|
||||
expect(own.body.createdByUserId).toBeUndefined();
|
||||
// A checklist always names a real connection of this company.
|
||||
await request(app([org.id])).post(`/api/companies/${org.id}/agent-setup-progress`).send({ purpose: "aws_connection" }).expect(422);
|
||||
await request(app([org.id])).post(`/api/companies/${org.id}/agent-setup-progress`).send({ purpose: "aws_connection", subjectId: outsider.connectionId }).expect(404);
|
||||
// A malformed id is a clean not-found, never a server error.
|
||||
await request(app([org.id])).post(`/api/companies/${org.id}/agent-setup-progress`).send({ purpose: "aws_connection", subjectId: "abc" }).expect(404);
|
||||
});
|
||||
});
|
||||
@@ -218,6 +218,27 @@ describe("authenticated activity notifications", () => {
|
||||
}
|
||||
});
|
||||
|
||||
it("delivers an agent setup progress update to the page with only the checklist id", async () => {
|
||||
const server = createServer();
|
||||
setupLiveEventsWebSocketServer(server, database() as never, { deploymentMode: "authenticated",
|
||||
resolveCloudActor: async () => ({ userId: "viewer", companyIds: ["company"] }) });
|
||||
server.listen(0, "127.0.0.1");
|
||||
await once(server, "listening");
|
||||
const socket = new WebSocket(`ws://127.0.0.1:${(server.address() as { port: number }).port}/api/companies/company/events/ws`);
|
||||
try {
|
||||
await once(socket, "open");
|
||||
const message = once(socket, "message");
|
||||
publishLiveEvent({ companyId: "company", type: "agent_setup_progress.updated", payload: { progressId: "progress-1", token: "never-sent" } });
|
||||
const [data] = await message;
|
||||
const event = JSON.parse(data.toString());
|
||||
expect(event).toMatchObject({ type: "agent_setup_progress.updated", payload: { progressId: "progress-1" } });
|
||||
expect(event.payload).toEqual({ progressId: "progress-1" });
|
||||
} finally {
|
||||
socket.terminate();
|
||||
await new Promise<void>(resolve => server.close(() => resolve()));
|
||||
}
|
||||
});
|
||||
|
||||
it("uses the persisted local-board user identity for local task eligibility", async () => {
|
||||
vi.mocked(taskToastEligible).mockImplementation(async (_db, _event, userId) => userId === "local-board");
|
||||
const server = createServer();
|
||||
|
||||
@@ -119,6 +119,7 @@ const apiPrefixes: Record<string, string> = {
|
||||
"user-profiles.ts": "/api",
|
||||
"workspace-preferences.ts": "/api",
|
||||
"workload-identity.ts": "/api",
|
||||
"agent-setup-progress.ts": "/api",
|
||||
};
|
||||
|
||||
const ROUTE_LITERAL_PATTERN =
|
||||
@@ -216,6 +217,7 @@ function normalizeExpressPath(routePath: string) {
|
||||
function resolveMountedPath(file: string, prefix: string, routePath: string) {
|
||||
if (file === "connection-event-wake.ts") return routePath;
|
||||
if (file === "workload-identity.ts" && routePath.startsWith("/oidc/")) return routePath;
|
||||
if (file === "agent-setup-progress.ts" && routePath.startsWith("/api/")) return routePath;
|
||||
if (file === "public-mcp.ts" && (routePath.startsWith("/mcp/oauth/") || routePath.startsWith("/.well-known/"))) return routePath;
|
||||
if (
|
||||
(file === "chat-channels.ts" || file === "email.ts") &&
|
||||
@@ -425,6 +427,21 @@ describe("openapi routes", () => {
|
||||
expect(operation.requestBody.content).toHaveProperty("application/json");
|
||||
expect(spec.paths).not.toHaveProperty("/api/routine-triggers/public/{publicId}/sentry-run-failures");
|
||||
});
|
||||
it("documents the agent's setup progress routes as needing the checklist's bearer token", () => {
|
||||
const spec = buildOpenApiSpec() as any;
|
||||
expect(spec.components.securitySchemes.AgentSetupTokenAuth).toMatchObject({ type: "http", scheme: "bearer" });
|
||||
for (const [path, method] of [
|
||||
["/api/agent-setup-progress/{id}/checklist", "put"],
|
||||
["/api/agent-setup-progress/{id}/items/{key}", "post"],
|
||||
["/api/agent-setup-progress/{id}/finish", "post"],
|
||||
] as const) {
|
||||
const operation = spec.paths[path][method];
|
||||
expect(operation.security, `${method} ${path}`).toEqual([{ AgentSetupTokenAuth: [] }]);
|
||||
expect(operation["x-paperclip-authorization"]).toEqual({ actor: "setup_token" });
|
||||
expect(operation.responses).toHaveProperty("401");
|
||||
}
|
||||
expect(spec.paths["/api/agent-setup-progress/{id}"].get["x-paperclip-authorization"]).toEqual({ actor: "board" });
|
||||
});
|
||||
it("documents connected-app skill review as board only and file reads as agent-run only", () => {
|
||||
const spec = buildOpenApiSpec() as any;
|
||||
const files = spec.paths["/api/agents/me/mcp-skills/{skillId}/files"].get;
|
||||
|
||||
@@ -140,6 +140,7 @@ import { routineSuggestionRoutes } from "./routes/routine-suggestions.js";
|
||||
import { environmentRoutes } from "./routes/environments.js";
|
||||
import { tailscaleConnectionRoutes } from "./routes/tailscale-connections.js";
|
||||
import { workloadIdentityPublicRoutes, workloadIdentityRoutes } from "./routes/workload-identity.js";
|
||||
import { agentSetupProgressAgentRoutes, agentSetupProgressBoardRoutes } from "./routes/agent-setup-progress.js";
|
||||
import { setWorkloadIdentityConfiguredPublicOrigin } from "./services/workload-identity.js";
|
||||
import { executionWorkspaceRoutes } from "./routes/execution-workspaces.js";
|
||||
import { goalRoutes } from "./routes/goals.js";
|
||||
@@ -623,6 +624,8 @@ export async function createApp(
|
||||
// Outside clouds fetch these anonymously to verify connection identity tokens.
|
||||
setWorkloadIdentityConfiguredPublicOrigin(opts.authPublicBaseUrl);
|
||||
app.use(workloadIdentityPublicRoutes(db));
|
||||
// A person's own agent reports setup progress with the bearer token from its setup prompt.
|
||||
app.use(agentSetupProgressAgentRoutes(db));
|
||||
// Connection-intent tools carry their own short-lived, run-bound bearer and
|
||||
// must be reachable by remote adapters that intentionally do not receive an
|
||||
// agent API key. Every request revalidates the active heartbeat row.
|
||||
@@ -872,6 +875,7 @@ export async function createApp(
|
||||
api.use(routineRoutes(db, { pluginWorkerManager: workerManager }));
|
||||
api.use(tailscaleConnectionRoutes(db));
|
||||
api.use(workloadIdentityRoutes(db));
|
||||
api.use(agentSetupProgressBoardRoutes(db));
|
||||
api.use(routineSuggestionRoutes(db, { pluginWorkerManager: workerManager }));
|
||||
api.use(
|
||||
environmentRoutes(db, {
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { tailscaleNetworks } from "./services/connectors/tailscale/network.js";
|
||||
import { agentSetupProgressService } from "./services/agent-setup-progress.js";
|
||||
import type { IdleDeadlineOwners } from "./services/idle-deadline-types.js";
|
||||
import { closeProcessRunAdmission, isProcessRunAdmissionClosed } from "./services/heartbeat/run-admission.js";
|
||||
import { registerReattachPhaseWork } from "./services/heartbeat/reattach-phase.js";
|
||||
@@ -2050,6 +2051,8 @@ async function startServerWithDatabaseTeardown(
|
||||
() => !isIdleTaskDrainActive() && !isWarmStandby() && !heartbeatSchedulerStopped).ready);
|
||||
await step("approval_queue_seeding", () => registerApprovalQueueSeedingWork(deliveryWork, approvalQueueSeedingService(db as any),
|
||||
() => !isIdleTaskDrainActive() && !isWarmStandby() && !heartbeatSchedulerStopped).ready);
|
||||
// Once per start, not a recurring scan: clear agent setup checklists a day past expiry.
|
||||
await step("agent_setup_progress_cleanup", () => agentSetupProgressService(db).sweepExpired());
|
||||
await step("approval_retention", () => registerApprovalRetentionWork(deliveryWork, approvalRetentionService(db as any),
|
||||
() => !isIdleTaskDrainActive() && !isWarmStandby() && !heartbeatSchedulerStopped).ready);
|
||||
await step("join_request_retention", () => registerJoinRequestRetentionWork(deliveryWork, joinRequestRetentionService(db as any),
|
||||
|
||||
@@ -391,6 +391,8 @@ export function setupLiveEventsWebSocketServer(
|
||||
if (event.type === "agent.status") return { ...event, payload: { agentId: payload.agentId, status: payload.status } };
|
||||
if (event.type === "agent.runtime_state.updated") return { ...event, payload: { agentId: payload.agentId } };
|
||||
if (event.type === "external_object.updated") return { ...event, payload: { externalObjectId: payload.externalObjectId } };
|
||||
// Only the id: reading the checklist itself goes through the board-only API.
|
||||
if (event.type === "agent_setup_progress.updated") return { ...event, payload: { progressId: payload.progressId } };
|
||||
if (event.type.startsWith("plugin.")) return event;
|
||||
return null;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,115 @@
|
||||
import { Router, type Request, type Response } from "express";
|
||||
import { and, eq } from "drizzle-orm";
|
||||
import { toolConnections } from "@paperclipai/db";
|
||||
import type { Db } from "@paperclipai/db";
|
||||
import { z } from "zod";
|
||||
import {
|
||||
agentSetupItemKeyPattern,
|
||||
createAgentSetupProgressSchema,
|
||||
finishAgentSetupSchema,
|
||||
setAgentSetupChecklistSchema,
|
||||
updateAgentSetupItemSchema,
|
||||
type CreateAgentSetupProgress,
|
||||
} from "@paperclipai/shared";
|
||||
import { notFound, unprocessable } from "../errors.js";
|
||||
import { connectionManagementGuard } from "./connection-management-authz.js";
|
||||
import { validate } from "../middleware/validate.js";
|
||||
import { agentSetupProgressService } from "../services/agent-setup-progress.js";
|
||||
import { workloadIdentityPublicOrigin } from "../services/workload-identity.js";
|
||||
import { assertBoard, assertCompanyAccess, getAccessibleResource, getActorInfo } from "./authz.js";
|
||||
|
||||
const idSchema = z.string().uuid();
|
||||
|
||||
/**
|
||||
* The agent's side of a setup checklist. A person's own agent (outside
|
||||
* Paperclip) calls these with the bearer token from the setup prompt; they
|
||||
* need no Paperclip sign-in, so the token is the only credential and it can
|
||||
* only write to this one checklist.
|
||||
*/
|
||||
export function agentSetupProgressAgentRoutes(db: Db) {
|
||||
const router = Router();
|
||||
const service = agentSetupProgressService(db);
|
||||
const progressId = (req: Request) => {
|
||||
const parsed = idSchema.safeParse(req.params.id);
|
||||
if (!parsed.success) throw notFound("Setup progress not found");
|
||||
return parsed.data;
|
||||
};
|
||||
router.put("/api/agent-setup-progress/:id/checklist", validate(setAgentSetupChecklistSchema), async (req, res) => {
|
||||
res.setHeader("Cache-Control", "no-store");
|
||||
res.json(await service.setChecklist(progressId(req), req.header("authorization"), req.body));
|
||||
});
|
||||
router.post("/api/agent-setup-progress/:id/items/:key", validate(updateAgentSetupItemSchema), async (req, res) => {
|
||||
res.setHeader("Cache-Control", "no-store");
|
||||
const key = String(req.params.key);
|
||||
if (!agentSetupItemKeyPattern.test(key)) throw notFound("Checklist item not found");
|
||||
res.json(await service.updateItem(progressId(req), key, req.header("authorization"), req.body));
|
||||
});
|
||||
router.post("/api/agent-setup-progress/:id/finish", validate(finishAgentSetupSchema), async (req, res) => {
|
||||
res.setHeader("Cache-Control", "no-store");
|
||||
res.json(await service.finish(progressId(req), req.header("authorization"), req.body));
|
||||
});
|
||||
return router;
|
||||
}
|
||||
|
||||
/** The address the agent should call: the instance's public address, else the one the page used. */
|
||||
function agentOrigin(req: Request) {
|
||||
return workloadIdentityPublicOrigin() ?? `${req.protocol}://${req.get("host")}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* The page's side. A checklist describes the setup of one thing (for AWS, one
|
||||
* connection), so only someone who may configure that thing creates one, and
|
||||
* only the person who started the setup reads it back.
|
||||
*/
|
||||
export function agentSetupProgressBoardRoutes(db: Db) {
|
||||
const router = Router();
|
||||
const service = agentSetupProgressService(db);
|
||||
|
||||
// Same rule as the AWS setup screen: the connection-management check for configuring this
|
||||
// connection, which honours permissions granted for just this connection.
|
||||
const configureConnection = connectionManagementGuard(db, "tool")("connections:configure", "POST /companies/:companyId/agent-setup-progress");
|
||||
|
||||
async function assertCanSetUpSubject(req: Request, res: Response, companyId: string, body: CreateAgentSetupProgress) {
|
||||
if (body.purpose !== "aws_connection") return;
|
||||
if (!body.subjectId) throw unprocessable("Name the connection being set up.", { code: "agent_setup_progress_subject_required" });
|
||||
// A connection id is a UUID; anything else is simply not a connection (and must not reach the uuid column).
|
||||
if (!idSchema.safeParse(body.subjectId).success) throw notFound("Tool connection not found");
|
||||
const [connection] = await db.select({ id: toolConnections.id }).from(toolConnections)
|
||||
.where(and(eq(toolConnections.id, body.subjectId), eq(toolConnections.companyId, companyId)));
|
||||
if (!connection) throw notFound("Tool connection not found");
|
||||
req.params.connectionId = connection.id;
|
||||
await new Promise<void>((resolve, reject) => {
|
||||
void configureConnection(req, res, (error?: unknown) => (error ? reject(error) : resolve()));
|
||||
});
|
||||
}
|
||||
router.post("/companies/:companyId/agent-setup-progress", validate(createAgentSetupProgressSchema), async (req, res) => {
|
||||
assertBoard(req);
|
||||
const companyId = idSchema.parse(req.params.companyId);
|
||||
assertCompanyAccess(req, companyId);
|
||||
const body = req.body as CreateAgentSetupProgress;
|
||||
await assertCanSetUpSubject(req, res, companyId, body);
|
||||
const { actorId } = getActorInfo(req);
|
||||
// The response carries the agent's token: never cache it.
|
||||
res.setHeader("Cache-Control", "no-store");
|
||||
res.setHeader("Pragma", "no-cache");
|
||||
res.status(201).json(await service.create({
|
||||
companyId, purpose: body.purpose, subjectId: body.subjectId ?? null, userId: actorId, origin: agentOrigin(req),
|
||||
}));
|
||||
});
|
||||
router.get("/agent-setup-progress/:id", async (req, res) => {
|
||||
assertBoard(req);
|
||||
const id = idSchema.safeParse(req.params.id);
|
||||
// Another company's checklist, or another person's, answers exactly like a missing one.
|
||||
const progress = await getAccessibleResource(req, res, id.success ? service.get(id.data) : null, "Setup progress not found");
|
||||
if (!progress) return;
|
||||
const { actorId } = getActorInfo(req);
|
||||
const unrestricted = req.actor.source === "local_implicit" || req.actor.isInstanceAdmin;
|
||||
if (!unrestricted && progress.createdByUserId !== actorId) {
|
||||
res.status(404).json({ error: "Setup progress not found" });
|
||||
return;
|
||||
}
|
||||
const { createdByUserId: _creator, ...visible } = progress;
|
||||
res.json(visible);
|
||||
});
|
||||
return router;
|
||||
}
|
||||
@@ -1,3 +1,4 @@
|
||||
import { createAgentSetupProgressSchema, setAgentSetupChecklistSchema, updateAgentSetupItemSchema, finishAgentSetupSchema } from "@paperclipai/shared";
|
||||
import { catalogTeamInstallSchema, catalogTeamPreviewSchema, updateWorkspacePreferenceSchema, issueDocumentBatchQuerySchema } from "@paperclipai/shared";
|
||||
import { MUSE_ASSET_VERSION, museStopBoundarySchema, museDetectorCleanupAttestationSchema, createGrokInvitationSchema, configureGrokRoutineSchema, verifyGrokRoutineSchema, recoverGrokRoutineSchema, pairGrokBindingSchema, stopGrokWorkSchema, retryGrokDeliverySchema, updateFastResponseSchema } from "@paperclipai/shared";
|
||||
import { slackTestMessageSchema, slackTestMessageResultSchema, slackManagerAuthorizationSchema, slackSetupOptionsSchema, slackManagedProvisionSchema, slackManagedResultSchema, slackRegistrationSchema, slackSetupActionSchema, slackInstallAuthorizationSchema, slackRegistrationStateSchema, slackAppConfigurationSchema, slackAvatarStateSchema, slackAccountStateSchema } from "@paperclipai/shared";
|
||||
@@ -1363,6 +1364,7 @@ type OpenApiAuthLevel =
|
||||
| "agent_run"
|
||||
| "agent_heartbeat"
|
||||
| "runtime_tools"
|
||||
| "agent_setup_token"
|
||||
| "authenticated"
|
||||
| "board"
|
||||
| "instance_admin";
|
||||
@@ -1372,6 +1374,7 @@ const BOARD_API_KEY_AUTH_SCHEME = "BoardApiKeyAuth";
|
||||
const AGENT_BEARER_AUTH_SCHEME = "AgentBearerAuth";
|
||||
const AGENT_RUN_AUTH_SCHEME = "AgentRunAuth";
|
||||
const RUNTIME_TOOLS_BEARER_AUTH_SCHEME = "RuntimeToolsBearerAuth";
|
||||
const AGENT_SETUP_TOKEN_AUTH_SCHEME = "AgentSetupTokenAuth";
|
||||
|
||||
function securityRequirement(name: string): Record<string, string[]> {
|
||||
return { [name]: [] };
|
||||
@@ -1399,6 +1402,13 @@ const RUNTIME_TOOLS_OPERATIONS = new Set([
|
||||
"POST /runtime-tools/connections/request",
|
||||
]);
|
||||
|
||||
/** A person's own agent reports setup progress with the checklist's bearer token, not a Paperclip sign-in (routes/agent-setup-progress.ts). */
|
||||
const AGENT_SETUP_TOKEN_OPERATIONS = new Set([
|
||||
"PUT /api/agent-setup-progress/{id}/checklist",
|
||||
"POST /api/agent-setup-progress/{id}/items/{key}",
|
||||
"POST /api/agent-setup-progress/{id}/finish",
|
||||
]);
|
||||
|
||||
const PUBLIC_OPERATIONS = new Set([
|
||||
"GET /api/agent-avatars/{version}/{palette}/{file}",
|
||||
"GET /api/health",
|
||||
@@ -1473,6 +1483,9 @@ const BOARD_ONLY_OPERATIONS = new Set([
|
||||
// Workload identity status and key rotation are board-only (assertBoard in routes/workload-identity.ts).
|
||||
"GET /api/companies/{companyId}/workload-identity",
|
||||
"POST /api/companies/{companyId}/workload-identity/rotation",
|
||||
// Setup progress checklists are created and read by board members (assertBoard in routes/agent-setup-progress.ts).
|
||||
"POST /api/companies/{companyId}/agent-setup-progress",
|
||||
"GET /api/agent-setup-progress/{id}",
|
||||
"POST /api/companies/{companyId}/chats/{agentRef}/onboarding",
|
||||
"POST /api/companies/{companyId}/chats/{agentRef}/onboarding/greeting",
|
||||
"PATCH /api/agents/{id}/permission-grants",
|
||||
@@ -1657,6 +1670,7 @@ const INSTANCE_ADMIN_OPERATIONS = new Set([
|
||||
]);
|
||||
|
||||
const CREATED_OPERATIONS = new Set([
|
||||
"POST /api/companies/{companyId}/agent-setup-progress",
|
||||
"POST /api/adapters/install",
|
||||
"POST /api/companies/{companyId}/agent-hires",
|
||||
"POST /api/companies/{companyId}/agents",
|
||||
@@ -1758,6 +1772,7 @@ function resolveOperationAuthLevel(
|
||||
if (path === "/api/companies/{companyId}/grok-invitations"
|
||||
|| /^\/api\/companies\/\{companyId\}\/agents\/\{agentId\}\/grok-binding(?:\/(?:routine|verify|retry|stop|recover))?$/.test(path)) return "board";
|
||||
if (PUBLIC_OPERATIONS.has(key)) return "public";
|
||||
if (AGENT_SETUP_TOKEN_OPERATIONS.has(key)) return "agent_setup_token";
|
||||
if (key === "POST /api/companies/{companyId}/agent-commentary") return "agent_heartbeat";
|
||||
if (key === "POST /api/agents/me/chat/messages") return "agent_heartbeat";
|
||||
// An approved connected-app skill's file: an agent in an active run only.
|
||||
@@ -1817,6 +1832,12 @@ function applyDocumentFixups(document: any): any {
|
||||
description:
|
||||
"Scoped token bound to an active heartbeat run and presented in the Authorization bearer header. The GitHub credential endpoint requires the distinct github_credentials scope.",
|
||||
},
|
||||
[AGENT_SETUP_TOKEN_AUTH_SCHEME]: {
|
||||
type: "http",
|
||||
scheme: "bearer",
|
||||
bearerFormat: "Setup checklist token (pcsp_…)",
|
||||
description: "The token from a setup prompt, presented in the Authorization bearer header. It updates only its own setup checklist, until the checklist finishes or expires.",
|
||||
},
|
||||
[AGENT_RUN_AUTH_SCHEME]: {
|
||||
type: "http",
|
||||
scheme: "bearer",
|
||||
@@ -1839,6 +1860,8 @@ function applyDocumentFixups(document: any): any {
|
||||
operation.security = [securityRequirement(AGENT_BEARER_AUTH_SCHEME)];
|
||||
} else if (authLevel === "runtime_tools") {
|
||||
operation.security = RUNTIME_TOOLS_SECURITY;
|
||||
} else if (authLevel === "agent_setup_token") {
|
||||
operation.security = [securityRequirement(AGENT_SETUP_TOKEN_AUTH_SCHEME)];
|
||||
} else if (authLevel === "authenticated") {
|
||||
operation.security = AUTHENTICATED_SECURITY;
|
||||
} else {
|
||||
@@ -1856,6 +1879,8 @@ function applyDocumentFixups(document: any): any {
|
||||
? { actor: "agent", heartbeatBound: true }
|
||||
: authLevel === "runtime_tools"
|
||||
? { actor: "runtime_tools", heartbeatBound: true }
|
||||
: authLevel === "agent_setup_token"
|
||||
? { actor: "setup_token" }
|
||||
: authLevel === "authenticated"
|
||||
? { actor: "board_or_agent" }
|
||||
: { actor: "public" };
|
||||
@@ -1866,7 +1891,8 @@ function applyDocumentFixups(document: any): any {
|
||||
}
|
||||
|
||||
const key = operationKey(method, path);
|
||||
if (authLevel !== "public") {
|
||||
// The setup token is only ever valid or not (401); it has no permissions to be refused.
|
||||
if (authLevel !== "public" && authLevel !== "agent_setup_token") {
|
||||
const responses = (operation.responses ??= {}) as Record<
|
||||
string,
|
||||
unknown
|
||||
@@ -9770,6 +9796,64 @@ registry.registerPath({
|
||||
}).strict()) }).strict()), ...workloadIdentityPublicNotFound },
|
||||
});
|
||||
|
||||
const agentSetupItem = z.object({
|
||||
key: z.string(), title: z.string(), status: z.enum(["pending", "in_progress", "done", "failed"]), detail: z.string().nullable(),
|
||||
}).strict();
|
||||
const agentSetupProgressDoc = z.object({
|
||||
id: z.string().uuid(), companyId: z.string().uuid(), purpose: z.string(), subjectId: z.string().nullable(),
|
||||
status: z.enum(["waiting", "in_progress", "done", "failed"]), items: z.array(agentSetupItem), summary: z.string().nullable(),
|
||||
expiresAt: z.string().datetime(), createdAt: z.string().datetime(), updatedAt: z.string().datetime(),
|
||||
}).strict();
|
||||
const agentSetupProgressId = z.object({ id: z.string().uuid() });
|
||||
const agentSetupAgentErrors = {
|
||||
400: r.badRequest, 401: { description: "The bearer token is missing or does not open this checklist" },
|
||||
404: r.notFound, 409: { description: "Another update changed the checklist at the same time; send it again" },
|
||||
410: { description: "The checklist's token expired" }, 429: { description: "The checklist reached its update limit" },
|
||||
};
|
||||
|
||||
registry.registerPath({
|
||||
method: "post", path: "/api/companies/{companyId}/agent-setup-progress", tags: ["agent-setup-progress"],
|
||||
summary: "Create a setup checklist for a person's own agent",
|
||||
description: "Board only. For aws_connection, subjectId must be a connection of this company that the caller may configure. Creates an empty checklist and returns it with a bearer token (shown once; only its hash is kept) and the URLs the agent uses to set the checklist, update items and finish. The token works for six hours and can only write to this checklist.",
|
||||
request: { params: z.object({ companyId: z.string().uuid() }), body: { content: { "application/json": { schema: createAgentSetupProgressSchema } } } },
|
||||
responses: {
|
||||
201: r.ok(z.object({ progress: agentSetupProgressDoc, token: z.string(), urls: z.object({ checklist: z.string().url(), item: z.string(), finish: z.string().url() }).strict() }).strict()),
|
||||
400: r.badRequest, 401: r.unauthorized, 403: r.forbidden,
|
||||
},
|
||||
});
|
||||
|
||||
registry.registerPath({
|
||||
method: "get", path: "/api/agent-setup-progress/{id}", tags: ["agent-setup-progress"],
|
||||
summary: "Read a setup checklist",
|
||||
description: "Board only, for the person who started the setup; anyone else gets 404. Updates also arrive as agent_setup_progress.updated live events.",
|
||||
request: { params: agentSetupProgressId },
|
||||
responses: { 200: r.ok(agentSetupProgressDoc), 401: r.unauthorized, 403: r.forbidden, 404: r.notFound },
|
||||
});
|
||||
|
||||
registry.registerPath({
|
||||
method: "put", path: "/api/agent-setup-progress/{id}/checklist", tags: ["agent-setup-progress"],
|
||||
summary: "Set the agent's setup checklist",
|
||||
description: "Called by the person's own agent with Authorization: Bearer <token>; no Paperclip sign-in. Replaces the checklist (1 to 20 items, keys of lowercase letters, numbers, - and _).",
|
||||
request: { params: agentSetupProgressId, body: { content: { "application/json": { schema: setAgentSetupChecklistSchema } } } },
|
||||
responses: { 200: r.ok(agentSetupProgressDoc), ...agentSetupAgentErrors },
|
||||
});
|
||||
|
||||
registry.registerPath({
|
||||
method: "post", path: "/api/agent-setup-progress/{id}/items/{key}", tags: ["agent-setup-progress"],
|
||||
summary: "Update one step of the agent's setup checklist",
|
||||
description: "Called by the person's own agent with Authorization: Bearer <token>. Sets the item's status (pending, in_progress, done or failed) and an optional one-line detail.",
|
||||
request: { params: agentSetupProgressId.extend({ key: z.string() }), body: { content: { "application/json": { schema: updateAgentSetupItemSchema } } } },
|
||||
responses: { 200: r.ok(agentSetupProgressDoc), ...agentSetupAgentErrors },
|
||||
});
|
||||
|
||||
registry.registerPath({
|
||||
method: "post", path: "/api/agent-setup-progress/{id}/finish", tags: ["agent-setup-progress"],
|
||||
summary: "Finish the agent's setup",
|
||||
description: "Called by the person's own agent with Authorization: Bearer <token>. done ticks off any open items; failed keeps them. An optional summary is shown on the setup page.",
|
||||
request: { params: agentSetupProgressId, body: { content: { "application/json": { schema: finishAgentSetupSchema } } } },
|
||||
responses: { 200: r.ok(agentSetupProgressDoc), ...agentSetupAgentErrors },
|
||||
});
|
||||
|
||||
registry.registerPath({
|
||||
method: "get", path: "/api/companies/{companyId}/workload-identity", tags: ["workload-identity"],
|
||||
summary: "Company workload identity issuer and key states",
|
||||
|
||||
@@ -0,0 +1,220 @@
|
||||
import { createHash, randomBytes, timingSafeEqual } from "node:crypto";
|
||||
import { and, eq, inArray, lt, sql } from "drizzle-orm";
|
||||
import type { Db } from "@paperclipai/db";
|
||||
import { agentSetupProgress, type AgentSetupProgressItemRecord } from "@paperclipai/db";
|
||||
import {
|
||||
AGENT_SETUP_PROGRESS_LIMITS,
|
||||
type AgentSetupProgress,
|
||||
type AgentSetupProgressHandoff,
|
||||
type AgentSetupProgressPurpose,
|
||||
type AgentSetupProgressStatus,
|
||||
type FinishAgentSetup,
|
||||
type SetAgentSetupChecklist,
|
||||
type UpdateAgentSetupItem,
|
||||
} from "@paperclipai/shared";
|
||||
import { HttpError, conflict, notFound, unprocessable } from "../errors.js";
|
||||
import { logActivity } from "./activity-log.js";
|
||||
import { publishLiveEvent } from "./live-events.js";
|
||||
|
||||
/**
|
||||
* Checklists that a person's own agent fills in while it sets something up for
|
||||
* them (see `@paperclipai/shared` agent-setup-progress). The board creates one
|
||||
* and gets a token for the agent; the agent's writes are checked against the
|
||||
* token's hash and pushed to the page as a live event.
|
||||
*/
|
||||
|
||||
type Row = typeof agentSetupProgress.$inferSelect;
|
||||
|
||||
const hashToken = (token: string) => createHash("sha256").update(token).digest("hex");
|
||||
|
||||
function toProgress(row: Row): AgentSetupProgress {
|
||||
return {
|
||||
id: row.id,
|
||||
companyId: row.companyId,
|
||||
purpose: row.purpose as AgentSetupProgressPurpose,
|
||||
subjectId: row.subjectId,
|
||||
status: row.status,
|
||||
items: row.items,
|
||||
summary: row.summary,
|
||||
expiresAt: row.expiresAt.toISOString(),
|
||||
createdAt: row.createdAt.toISOString(),
|
||||
updatedAt: row.updatedAt.toISOString(),
|
||||
};
|
||||
}
|
||||
|
||||
/** The agent's URLs: the item URL keeps `{key}` for the agent to fill in. */
|
||||
export function agentSetupProgressUrls(origin: string, id: string): AgentSetupProgressHandoff["urls"] {
|
||||
const base = `${origin.replace(/\/+$/, "")}/api/agent-setup-progress/${id}`;
|
||||
return { checklist: `${base}/checklist`, item: `${base}/items/{key}`, finish: `${base}/finish` };
|
||||
}
|
||||
|
||||
/**
|
||||
* Until the agent finishes, a checklist with steps is in progress, even with every step ticked off:
|
||||
* only the finish carries the summary (such as the role ARN), and the page keeps refreshing until then.
|
||||
*/
|
||||
function statusFor(items: AgentSetupProgressItemRecord[]): AgentSetupProgressStatus {
|
||||
return items.length === 0 ? "waiting" : "in_progress";
|
||||
}
|
||||
|
||||
export function agentSetupProgressService(db: Db, options: { now?: () => Date } = {}) {
|
||||
const now = options.now ?? (() => new Date());
|
||||
|
||||
function publish(row: Row) {
|
||||
publishLiveEvent({ companyId: row.companyId, type: "agent_setup_progress.updated", payload: { progressId: row.id } });
|
||||
}
|
||||
|
||||
/** The row the agent's token opens, still open for writes. Any mismatch reads as not found. */
|
||||
async function openForAgent(id: string, authorization: string | undefined): Promise<Row> {
|
||||
const token = /^Bearer\s+(\S+)$/i.exec(authorization ?? "")?.[1];
|
||||
const [row] = token ? await db.select().from(agentSetupProgress).where(eq(agentSetupProgress.id, id)) : [];
|
||||
const expected = row ? Buffer.from(row.tokenHash, "hex") : null;
|
||||
const given = token ? Buffer.from(hashToken(token), "hex") : null;
|
||||
if (!row || !expected || !given || expected.length !== given.length || !timingSafeEqual(expected, given)) {
|
||||
throw new HttpError(401, "This setup progress link is not valid. Copy the setup prompt from Paperclip again.", { code: "agent_setup_progress_unauthorized" });
|
||||
}
|
||||
if (row.expiresAt.getTime() <= now().getTime()) {
|
||||
throw new HttpError(410, "This setup progress link expired. Copy the setup prompt from Paperclip again.", { code: "agent_setup_progress_expired" });
|
||||
}
|
||||
if (row.status === "done" || row.status === "failed") {
|
||||
// Finished is final: a late or retried update must not make the page show work in progress again.
|
||||
throw conflict("This setup already finished.", { code: "agent_setup_progress_finished" });
|
||||
}
|
||||
if (row.updateCount >= AGENT_SETUP_PROGRESS_LIMITS.maxUpdates) {
|
||||
throw new HttpError(429, "This setup checklist has had too many updates.", { code: "agent_setup_progress_update_limit" });
|
||||
}
|
||||
return row;
|
||||
}
|
||||
|
||||
/** Saves the agent's change; the update counter guards against two writes racing. */
|
||||
async function save(
|
||||
row: Row,
|
||||
change: { items: AgentSetupProgressItemRecord[]; status?: AgentSetupProgressStatus; summary?: string | null },
|
||||
activity: { action: string; details: Record<string, unknown> },
|
||||
) {
|
||||
const [saved] = await db.update(agentSetupProgress).set({
|
||||
items: change.items,
|
||||
status: change.status ?? statusFor(change.items),
|
||||
...(change.summary !== undefined ? { summary: change.summary } : {}),
|
||||
updateCount: sql`${agentSetupProgress.updateCount} + 1`,
|
||||
updatedAt: now(),
|
||||
}).where(and(eq(agentSetupProgress.id, row.id), eq(agentSetupProgress.updateCount, row.updateCount))).returning();
|
||||
if (!saved) throw conflict("The checklist changed at the same time. Send the update again.", { code: "agent_setup_progress_conflict" });
|
||||
// Every change the agent makes is on the activity history; the token never is.
|
||||
await logActivity(db, {
|
||||
companyId: row.companyId, actorType: "system", actorId: "agent-setup", action: activity.action,
|
||||
entityType: "agent_setup_progress", entityId: row.id, details: { purpose: row.purpose, ...activity.details },
|
||||
});
|
||||
publish(saved);
|
||||
return toProgress(saved);
|
||||
}
|
||||
|
||||
return {
|
||||
async create(input: {
|
||||
companyId: string;
|
||||
purpose: AgentSetupProgressPurpose;
|
||||
subjectId?: string | null;
|
||||
userId: string | null;
|
||||
origin: string;
|
||||
}): Promise<AgentSetupProgressHandoff> {
|
||||
// Expired checklists are only history: as a company makes a new one, drop its own that are a day
|
||||
// past expiry, a few at a time. Another company's rows are never touched.
|
||||
const stale = await db.select({ id: agentSetupProgress.id }).from(agentSetupProgress)
|
||||
.where(and(
|
||||
eq(agentSetupProgress.companyId, input.companyId),
|
||||
lt(agentSetupProgress.expiresAt, new Date(now().getTime() - 24 * 60 * 60 * 1000)),
|
||||
)).limit(100);
|
||||
if (stale.length > 0) {
|
||||
await db.delete(agentSetupProgress).where(and(
|
||||
eq(agentSetupProgress.companyId, input.companyId),
|
||||
inArray(agentSetupProgress.id, stale.map((row) => row.id)),
|
||||
));
|
||||
}
|
||||
const token = `pcsp_${randomBytes(32).toString("base64url")}`;
|
||||
const [row] = await db.insert(agentSetupProgress).values({
|
||||
companyId: input.companyId,
|
||||
purpose: input.purpose,
|
||||
subjectId: input.subjectId ?? null,
|
||||
tokenHash: hashToken(token),
|
||||
createdByUserId: input.userId,
|
||||
expiresAt: new Date(now().getTime() + AGENT_SETUP_PROGRESS_LIMITS.lifetimeMs),
|
||||
}).returning();
|
||||
await logActivity(db, {
|
||||
companyId: input.companyId,
|
||||
actorType: "user",
|
||||
actorId: input.userId ?? "board",
|
||||
action: "agent_setup_progress.created",
|
||||
entityType: "agent_setup_progress",
|
||||
entityId: row!.id,
|
||||
details: { purpose: input.purpose, subjectId: input.subjectId ?? null },
|
||||
});
|
||||
return { progress: toProgress(row!), token, urls: agentSetupProgressUrls(input.origin, row!.id) };
|
||||
},
|
||||
|
||||
/**
|
||||
* Removes checklists more than a day past expiry, across companies. Runs once at server start
|
||||
* (reconstructing cleanup from the rows, never as a recurring scan), so companies that stopped
|
||||
* using agent setup do not keep dead rows; creating a checklist also cleans its own company.
|
||||
*/
|
||||
async sweepExpired(options: { batchSize?: number; maxBatches?: number } = {}): Promise<number> {
|
||||
// Batches keep each delete small; the cap keeps a very large backlog from holding up startup
|
||||
// (whatever is left goes at the next start, or as each company creates a checklist).
|
||||
const batchSize = options.batchSize ?? 1000;
|
||||
const maxBatches = options.maxBatches ?? 50;
|
||||
const cutoff = new Date(now().getTime() - 24 * 60 * 60 * 1000);
|
||||
let removed = 0;
|
||||
for (let batch = 0; batch < maxBatches; batch += 1) {
|
||||
const stale = await db.select({ id: agentSetupProgress.id }).from(agentSetupProgress)
|
||||
.where(lt(agentSetupProgress.expiresAt, cutoff)).limit(batchSize);
|
||||
if (stale.length === 0) break;
|
||||
await db.delete(agentSetupProgress).where(inArray(agentSetupProgress.id, stale.map((row) => row.id)));
|
||||
removed += stale.length;
|
||||
if (stale.length < batchSize) break;
|
||||
}
|
||||
return removed;
|
||||
},
|
||||
|
||||
/** The checklist and who started it (for the read check; not part of the API response). */
|
||||
async get(id: string): Promise<(AgentSetupProgress & { createdByUserId: string | null }) | null> {
|
||||
const [row] = await db.select().from(agentSetupProgress).where(eq(agentSetupProgress.id, id));
|
||||
return row ? { ...toProgress(row), createdByUserId: row.createdByUserId } : null;
|
||||
},
|
||||
|
||||
async setChecklist(id: string, authorization: string | undefined, input: SetAgentSetupChecklist) {
|
||||
const row = await openForAgent(id, authorization);
|
||||
const items = input.items.map((item) => ({
|
||||
key: item.key, title: item.title, status: item.status ?? "pending", detail: item.detail ?? null,
|
||||
}));
|
||||
return save(row, { items, summary: null }, {
|
||||
action: row.items.length === 0 ? "agent_setup_progress.started" : "agent_setup_progress.checklist_replaced",
|
||||
details: { itemCount: items.length },
|
||||
});
|
||||
},
|
||||
|
||||
async updateItem(id: string, key: string, authorization: string | undefined, input: UpdateAgentSetupItem) {
|
||||
const row = await openForAgent(id, authorization);
|
||||
if (!row.items.some((item) => item.key === key)) {
|
||||
throw notFound(`The checklist has no item "${key}". Set the checklist first, then update its items by key.`);
|
||||
}
|
||||
const items = row.items.map((item) => item.key === key
|
||||
// Omitted keeps the detail; null clears it.
|
||||
? { ...item, status: input.status, detail: input.detail === undefined ? item.detail : input.detail }
|
||||
: item);
|
||||
return save(row, { items }, { action: "agent_setup_progress.item_updated", details: { key, status: input.status } });
|
||||
},
|
||||
|
||||
async finish(id: string, authorization: string | undefined, input: FinishAgentSetup) {
|
||||
const row = await openForAgent(id, authorization);
|
||||
if (row.items.length === 0 && input.status === "done") {
|
||||
throw unprocessable("Set the checklist before finishing.", { code: "agent_setup_progress_empty" });
|
||||
}
|
||||
// The agent's finish is the verdict: done ticks off every step (it recovered from any that failed),
|
||||
// so a finished setup never shows open or failed steps; failed keeps the steps as they were.
|
||||
const items = input.status === "done"
|
||||
? row.items.map((item) => ({ ...item, status: "done" as const }))
|
||||
: row.items;
|
||||
return save(row, { items, status: input.status, summary: input.summary ?? null }, {
|
||||
action: "agent_setup_progress.finished", details: { status: input.status },
|
||||
});
|
||||
},
|
||||
};
|
||||
}
|
||||
Reference in new issue
Block a user